From 1af39169bd815086c799312d8332552f99049c14 Mon Sep 17 00:00:00 2001 From: praboth charith - GBS - CLI Date: Mon, 16 Nov 2026 12:16:40 +0530 Subject: [PATCH 1/6] feat(fonts): bundle Manrope font asset and sync UI typography (#189) --- NOTICE | 9 +- docs/CSP.md | 15 ++- docs/SECURITY_AUDIT.md | 18 ++-- examples/next-app/next.config.mjs | 2 +- package.json | 3 +- scripts/build-css.mjs | 30 +++++- scripts/check-package.mjs | 15 +++ src/core/AccessibilityPlugin.tsx | 10 ++ src/core/DiagnosticsHarness.tsx | 6 +- src/core/WidgetPortal.tsx | 10 +- src/core/types.ts | 1 + .../fonts/Manrope-VariableFont_wght.ttf | Bin 0 -> 164596 bytes src/styles/fonts/OFL.txt | 93 ++++++++++++++++++ tsup.config.ts | 6 ++ 14 files changed, 196 insertions(+), 22 deletions(-) create mode 100644 src/styles/fonts/Manrope-VariableFont_wght.ttf create mode 100644 src/styles/fonts/OFL.txt diff --git a/NOTICE b/NOTICE index 16fa5d5..0987d91 100644 --- a/NOTICE +++ b/NOTICE @@ -11,9 +11,12 @@ https://github.com/prabothcharith/accessibility-plugin Third-Party Assets & Licensure: - Zero Runtime Dependencies: This library has no runtime dependencies outside of peer dependencies on React and React DOM. -- Fonts: No third-party binary font files (.woff, .woff2, .ttf) are bundled. All font - presets utilize client-system font stacks (e.g. system-ui, -apple-system, sans-serif) - with fallback declarations. +- Fonts: The plugin bundles the variable Manrope typeface + (`src/styles/fonts/Manrope-VariableFont_wght.ttf` -> `dist/fonts/Manrope-VariableFont_wght.ttf` + and inlined `@font-face` data URI in JS bundles) as the default UI font, + licensed under the SIL Open Font License 1.1 (`OFL.txt` included alongside + the font asset). Additional font presets (`legible`, `dyslexia-option`) + utilize client-system font stacks with zero external network font requests. - Icons: All decorative icons are authored directly as inline SVG elements under the package's ISC License. - Dictionaries: Built-in glossaries (English, Sinhala, Tamil) are compiled in-tree diff --git a/docs/CSP.md b/docs/CSP.md index 76a24e1..df7fdc2 100644 --- a/docs/CSP.md +++ b/docs/CSP.md @@ -37,6 +37,15 @@ This guide explains how `accessibility-plugin-react` operates under Content Secu ``` If `data:` is omitted from `img-src`, the browser will fall back to native system cursors. +### D. Bundled Manrope UI Typography (`font-src`) + +- **Default UI font:** The library bundles the variable **Manrope** typeface locally (`dist/fonts/Manrope-VariableFont_wght.ttf` for standalone CSS imports, and inlined `data:font/ttf;base64,...` within the runtime injected styles in `dist/index.mjs` / `dist/index.js`) with zero external font CDN calls. +- **Recommended directive:** + ```text + font-src 'self' data:; + ``` + If `data:` is omitted from `font-src`, import `accessibility-plugin-react/style.css` so your bundler serves `dist/fonts/Manrope-VariableFont_wght.ttf` from `'self'`. + --- ## 2. Next.js App Router Strict CSP Recipe @@ -54,7 +63,7 @@ const cspHeader = ` style-src 'self' 'unsafe-inline'; style-src-attr 'unsafe-inline'; img-src 'self' data:; - font-src 'self'; + font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; @@ -106,7 +115,7 @@ export function middleware(request: NextRequest) { style-src 'self' 'nonce-${nonce}'; style-src-attr 'unsafe-inline'; img-src 'self' data:; - font-src 'self'; + font-src 'self' data:; base-uri 'self'; form-action 'self'; ` @@ -159,7 +168,7 @@ For Vite applications, configure CSP headers either through your production web style-src 'self' 'unsafe-inline'; style-src-attr 'unsafe-inline'; img-src 'self' data:; - font-src 'self'; + font-src 'self' data:; " /> diff --git a/docs/SECURITY_AUDIT.md b/docs/SECURITY_AUDIT.md index bc9abdb..7d75269 100644 --- a/docs/SECURITY_AUDIT.md +++ b/docs/SECURITY_AUDIT.md @@ -6,14 +6,14 @@ This document provides a comprehensive security review, dependency audit, Conten ## 1. Executive summary and audit results -| Audit Area | Standard / Requirement | Current Verification Result | Status | -| :------------------- | :---------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------ | :------- | -| **Dependencies** | 0 runtime dependencies; peerDependencies only | Clean `package.json`; 0 runtime dependencies. Only peer dependencies: React (`^18.3.1 \|\| ^19.0.0`) and React DOM. | **PASS** | -| **Vulnerabilities** | `npm audit` 0 findings across direct and transitive tooling | `npm audit` returns 0 vulnerabilities across all installed packages. | **PASS** | -| **Script Injection** | No dynamic code execution (`eval`, `new Function`) | Automated AST scan verifies 0 instances of `eval` or `Function` constructors across all `src/` modules. | **PASS** | -| **Network Requests** | No unauthorized telemetry, tracking, or background calls | 0 `fetch()`, 0 `XMLHttpRequest`, 0 `navigator.sendBeacon`, 0 `WebSocket` calls. | **PASS** | -| **Data Residency** | All state stored locally; zero external exfiltration | Preferences persist strictly in `localStorage` under `react-accessibility-plugin:state`. Zero cloud sync. | **PASS** | -| **Licensing** | Permissive ISC license; clean IP attribution | Dedicated `LICENSE` and `NOTICE` files committed; zero GPL/copyleft or proprietary binary assets. | **PASS** | +| Audit Area | Standard / Requirement | Current Verification Result | Status | +| :------------------- | :---------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | +| **Dependencies** | 0 runtime dependencies; peerDependencies only | Clean `package.json`; 0 runtime dependencies. Only peer dependencies: React (`^18.3.1 \|\| ^19.0.0`) and React DOM. | **PASS** | +| **Vulnerabilities** | `npm audit` 0 findings across direct and transitive tooling | `npm audit` returns 0 vulnerabilities across all installed packages. | **PASS** | +| **Script Injection** | No dynamic code execution (`eval`, `new Function`) | Automated AST scan verifies 0 instances of `eval` or `Function` constructors across all `src/` modules. | **PASS** | +| **Network Requests** | No unauthorized telemetry, tracking, or background calls | 0 `fetch()`, 0 `XMLHttpRequest`, 0 `navigator.sendBeacon`, 0 `WebSocket` calls. | **PASS** | +| **Data Residency** | All state stored locally; zero external exfiltration | Preferences persist strictly in `localStorage` under `react-accessibility-plugin:state`. Zero cloud sync. | **PASS** | +| **Licensing** | Permissive ISC license + SIL OFL 1.1 font attribution | Dedicated `LICENSE` and `NOTICE` files committed; bundles SIL OFL 1.1 `Manrope-VariableFont_wght.ttf` with zero GPL/copyleft or proprietary binary assets. | **PASS** | --- @@ -78,6 +78,6 @@ Features that inspect or transform DOM elements (such as host translation, read - **License**: Released under the open-source **ISC License** (permissive, GPL-compatible). - **Attribution**: Derived from the original vanilla JavaScript accessibility plugin; attribution is documented in `NOTICE` and `README.md`. - **Assets**: - - **Fonts**: No binary font files (`.woff`, `.woff2`, `.ttf`) are bundled. Presets rely entirely on standard system font stacks. + - **Fonts**: Bundles the open-source variable **Manrope** font (`Manrope-VariableFont_wght.ttf`) under the **SIL Open Font License 1.1** (`dist/fonts/OFL.txt` and `NOTICE`), with offline client-system fallback stacks for legible and dyslexia presets. Zero external Google Fonts or remote CDN requests. - **Icons**: Authored in-tree as native inline SVG icons under ISC. - **Glossary Data**: Built-in dictionary entries (English, Sinhala, Tamil) are compiled in-tree under ISC for offline accessibility lookup. diff --git a/examples/next-app/next.config.mjs b/examples/next-app/next.config.mjs index 7abaf57..93946de 100644 --- a/examples/next-app/next.config.mjs +++ b/examples/next-app/next.config.mjs @@ -5,7 +5,7 @@ const cspHeader = ` style-src 'self' 'unsafe-inline'; style-src-attr 'unsafe-inline'; img-src 'self' data:; - font-src 'self'; + font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; diff --git a/package.json b/package.json index 1baafef..7287288 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,8 @@ } }, "./dist/style.css": "./dist/style.css", - "./style.css": "./dist/style.css" + "./style.css": "./dist/style.css", + "./fonts/*": "./dist/fonts/*" }, "files": [ "dist", diff --git a/scripts/build-css.mjs b/scripts/build-css.mjs index ea2dc59..84be8e8 100644 --- a/scripts/build-css.mjs +++ b/scripts/build-css.mjs @@ -1,3 +1,29 @@ -import { copyFile, mkdir } from "node:fs/promises"; -await mkdir("dist", { recursive: true }); +import { copyFile, cp, mkdir, readFile, writeFile } from "node:fs/promises"; +import assert from "node:assert/strict"; + +await mkdir("dist/fonts", { recursive: true }); await copyFile("src/styles/tailwind.css", "dist/style.css"); +await cp("src/styles/fonts", "dist/fonts", { recursive: true }); + +// tsup injects CSS as a raw string without resolving font url() assets; inline base64 +// into the runtime JS bundles while leaving dist/style.css referencing dist/fonts/. +const ttfBytes = await readFile( + "src/styles/fonts/Manrope-VariableFont_wght.ttf", +); +const fontDataUri = `data:font/ttf;base64,${ttfBytes.toString("base64")}`; +const fontUrlPattern = + /url\(\s*(?:"\.\/fonts\/Manrope-VariableFont_wght\.ttf"|'\.\/fonts\/Manrope-VariableFont_wght\.ttf'|\.\/fonts\/Manrope-VariableFont_wght\.ttf)\s*\)/g; + +for (const bundleFile of ["dist/index.mjs", "dist/index.js"]) { + const source = await readFile(bundleFile, "utf8"); + assert( + fontUrlPattern.test(source), + `Expected Manrope font URL placeholder in ${bundleFile}`, + ); + fontUrlPattern.lastIndex = 0; + await writeFile( + bundleFile, + source.replace(fontUrlPattern, `url(${fontDataUri})`), + "utf8", + ); +} diff --git a/scripts/check-package.mjs b/scripts/check-package.mjs index 6778fcd..d24b578 100644 --- a/scripts/check-package.mjs +++ b/scripts/check-package.mjs @@ -27,6 +27,8 @@ for (const file of [ "dist/index.d.ts", "dist/index.d.mts", "dist/style.css", + "dist/fonts/Manrope-VariableFont_wght.ttf", + "dist/fonts/OFL.txt", "LICENSE", "NOTICE", ]) @@ -43,8 +45,21 @@ for (const file of ["dist/index.mjs", "dist/index.js"]) { `Missing automatic CSS injection: ${file}`, ); assert(bundle.includes(".arap-root"), `Missing bundled widget CSS: ${file}`); + assert(bundle.includes("Manrope"), `Missing bundled Manrope font: ${file}`); + assert( + bundle.includes("data:font/ttf;base64,"), + `Missing inlined Manrope data URI in ${file}`, + ); + assert( + !bundle.includes("./fonts/Manrope-VariableFont_wght.ttf"), + `Relative Manrope font URL leaked into ${file}`, + ); } const css = await readFile("dist/style.css", "utf8"); +assert( + css.includes("./fonts/Manrope-VariableFont_wght.ttf"), + "Standalone dist/style.css should reference ./fonts/Manrope-VariableFont_wght.ttf", +); assert( !/(^|\})\s*(html|body|:root|\*)\s*\{/.test(css), "Global reset detected", diff --git a/src/core/AccessibilityPlugin.tsx b/src/core/AccessibilityPlugin.tsx index 4b95db2..9e25391 100644 --- a/src/core/AccessibilityPlugin.tsx +++ b/src/core/AccessibilityPlugin.tsx @@ -314,6 +314,14 @@ export function AccessibilityPlugin({ : undefined) || undefined; + const rawFont = getFeatureState("fontFamily", "default"); + const activeFont = + rawFont === "legible" || + rawFont === "dyslexia-option" || + rawFont === "dyslexia" + ? rawFont + : "default"; + useBuiltinEffects(active, handleDisable, { effectScope, nonce }); const value = useMemo( () => ({ @@ -334,6 +342,7 @@ export function AccessibilityPlugin({ locale: effectiveLocale, statementUrl, largeControls, + activeFont, effectScope, nonce, }), @@ -355,6 +364,7 @@ export function AccessibilityPlugin({ effectiveLocale, statementUrl, largeControls, + activeFont, effectScope, nonce, ], diff --git a/src/core/DiagnosticsHarness.tsx b/src/core/DiagnosticsHarness.tsx index 6c12c43..0067252 100644 --- a/src/core/DiagnosticsHarness.tsx +++ b/src/core/DiagnosticsHarness.tsx @@ -1,6 +1,7 @@ "use client"; -import React, { useCallback, useEffect, useState } from "react"; +import React, { useCallback, useContext, useEffect, useState } from "react"; +import { AccessibilityContext } from "./AccessibilityContext"; import { type DiagnosticIssue, type DiagnosticsConfig, @@ -30,6 +31,7 @@ export function DiagnosticsHarness({ process.env && process.env.NODE_ENV === "production"; + const ctx = useContext(AccessibilityContext); const [isOpen, setIsOpen] = useState(defaultOpen); const [activeCategory, setActiveCategory] = useState("all"); const [report, setReport] = useState(() => { @@ -90,6 +92,8 @@ export function DiagnosticsHarness({
{!isOpen ? (
+ {isDesktopResizable && ( +
+ )}
); } diff --git a/src/core/controls/FeatureGroup.tsx b/src/core/controls/FeatureGroup.tsx new file mode 100644 index 0000000..a985acf --- /dev/null +++ b/src/core/controls/FeatureGroup.tsx @@ -0,0 +1,120 @@ +"use client"; + +import { useId, useState, type ReactNode } from "react"; + +export interface FeatureGroupProps { + id?: string; + title: string; + description?: string; + badge?: string; + collapsible?: boolean; + defaultExpanded?: boolean; + expanded?: boolean; + onExpandedChange?: (expanded: boolean) => void; + className?: string; + role?: "group" | "region"; + "data-group"?: string; + children: ReactNode; +} + +export function FeatureGroup({ + id, + title, + description, + badge, + collapsible = false, + defaultExpanded = true, + expanded: controlledExpanded, + onExpandedChange, + className = "", + role, + "data-group": dataGroup, + children, +}: FeatureGroupProps) { + const autoId = useId(); + const baseId = id ?? `arap-group-${autoId}`; + const headingId = `${baseId}-heading`; + const contentId = `${baseId}-content`; + + const [internalExpanded, setInternalExpanded] = useState(defaultExpanded); + const isControlled = controlledExpanded !== undefined; + const isExpanded = collapsible + ? isControlled + ? controlledExpanded + : internalExpanded + : true; + + const handleToggle = () => { + const next = !isExpanded; + if (!isControlled) { + setInternalExpanded(next); + } + onExpandedChange?.(next); + }; + + return ( +
+ {collapsible ? ( +

+ +

+ ) : ( +
+
+
+

+ {title} +

+ {badge && {badge}} +
+ {description &&

{description}

} +
+
+ )} + + +
+ ); +} + +export default FeatureGroup; diff --git a/src/core/controls/ModalDialog.tsx b/src/core/controls/ModalDialog.tsx new file mode 100644 index 0000000..96a5fb8 --- /dev/null +++ b/src/core/controls/ModalDialog.tsx @@ -0,0 +1,207 @@ +"use client"; + +import { + useEffect, + useId, + useRef, + type ReactNode, + type RefObject, +} from "react"; +import { WidgetPortal } from "../WidgetPortal"; + +export interface ModalDialogProps { + isOpen: boolean; + onClose: () => void; + id?: string; + title: string; + subtitle?: string; + icon?: ReactNode; + closeLabel?: string; + size?: "md" | "lg" | "full"; + trapFocus?: boolean; + lockScroll?: boolean; + closeOnBackdrop?: boolean; + ariaModal?: boolean; + disableEscapeClose?: boolean; + initialFocusRef?: RefObject; + returnFocusTo?: RefObject; + footer?: ReactNode; + className?: string; + children: ReactNode; +} + +const FOCUSABLE_SELECTOR = + 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'; + +export function ModalDialog({ + isOpen, + onClose, + id, + title, + subtitle, + icon, + closeLabel = "Close", + size = "full", + trapFocus = true, + lockScroll = true, + closeOnBackdrop = true, + ariaModal = true, + disableEscapeClose = false, + initialFocusRef, + returnFocusTo, + footer, + className = "", + children, +}: ModalDialogProps) { + const autoId = useId(); + const titleId = `${id ?? autoId}-title`; + const descId = subtitle ? `${id ?? autoId}-desc` : undefined; + const dialogRef = useRef(null); + const closeBtnRef = useRef(null); + const onCloseRef = useRef(onClose); + const wasOpenRef = useRef(false); + + useEffect(() => { + onCloseRef.current = onClose; + }, [onClose]); + + useEffect(() => { + if (isOpen && !wasOpenRef.current) { + wasOpenRef.current = true; + const focusTimer = window.setTimeout(() => { + if (initialFocusRef?.current) { + initialFocusRef.current.focus(); + } else if (closeBtnRef.current) { + closeBtnRef.current.focus(); + } else { + dialogRef.current?.focus(); + } + }, 20); + return () => window.clearTimeout(focusTimer); + } + + if (!isOpen && wasOpenRef.current) { + wasOpenRef.current = false; + const target = returnFocusTo?.current; + if (target && target.isConnected) { + target.focus(); + } + } + }, [isOpen, initialFocusRef, returnFocusTo]); + + useEffect(() => { + if (!isOpen || !lockScroll || typeof document === "undefined") return; + const prevOverflow = document.body.style.overflow; + document.body.style.overflow = "hidden"; + return () => { + document.body.style.overflow = prevOverflow; + }; + }, [isOpen, lockScroll]); + + useEffect(() => { + if (!isOpen) return; + + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") { + if (disableEscapeClose) return; + event.preventDefault(); + event.stopPropagation(); + onCloseRef.current(); + return; + } + + if (trapFocus && event.key === "Tab") { + const dialog = dialogRef.current; + if (!dialog) return; + + const focusable = Array.from( + dialog.querySelectorAll(FOCUSABLE_SELECTOR), + ).filter( + (el) => el.offsetParent !== null || el === document.activeElement, + ); + + if (focusable.length === 0) return; + + const first = focusable[0]; + const last = focusable[focusable.length - 1]; + + if (event.shiftKey && document.activeElement === first) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } else if (!dialog.contains(document.activeElement)) { + event.preventDefault(); + first.focus(); + } + } + }; + + document.addEventListener("keydown", handleKeyDown, { capture: true }); + return () => { + document.removeEventListener("keydown", handleKeyDown, { capture: true }); + }; + }, [isOpen, trapFocus, disableEscapeClose]); + + if (!isOpen) return null; + + return ( + +
{ + if (closeOnBackdrop && e.target === e.currentTarget) { + onClose(); + } + }} + > + +
+
+ ); +} + +export default ModalDialog; diff --git a/src/core/controls/ProfilePreviewCard.tsx b/src/core/controls/ProfilePreviewCard.tsx index 40d855d..b5bde97 100644 --- a/src/core/controls/ProfilePreviewCard.tsx +++ b/src/core/controls/ProfilePreviewCard.tsx @@ -16,6 +16,78 @@ export interface ProfilePreviewCardProps { style?: CSSProperties; } +export function formatPreferenceKey(key: string): string { + switch (key) { + case "fontScale": + case "fontSize": + return "Font Size"; + case "fontFamily": + return "Font Family"; + case "lineHeight": + return "Line Height"; + case "letterSpacing": + return "Letter Spacing"; + case "wordSpacing": + return "Word Spacing"; + case "paragraphSpacing": + return "Paragraph Spacing"; + case "contrastMode": + case "contrast": + return "Contrast"; + case "reduceMotion": + return "Reduce Motion"; + case "textAlign": + return "Text Align"; + case "highlightLinks": + case "linkHighlight": + return "Highlight Links"; + case "highlightFocus": + case "focusOutline": + return "Focus Outline"; + case "cursorSize": + case "bigCursor": + return "Big Cursor"; + case "readerMode": + case "readingMode": + return "Reading Mode"; + case "readingGuide": + return "Reading Guide"; + case "readingMask": + return "Reading Mask"; + case "saturation": + return "Saturation"; + case "grayscale": + return "Grayscale"; + case "hideDecorativeImages": + case "hideImages": + return "Hide Images"; + case "hideVideos": + return "Hide Videos"; + case "tooltips": + case "accessibleTooltips": + return "Tooltips"; + default: { + const spaced = key.replace(/([A-Z])/g, " $1").trim(); + return spaced.charAt(0).toUpperCase() + spaced.slice(1); + } + } +} + +export function formatPreferenceValue( + key: keyof AccessibilityPreferences, + val: unknown, +): string { + if (typeof val === "boolean") return val ? "On" : "Off"; + if (key === "fontScale" && typeof val === "number") + return `${Math.round(val * 100)}%`; + if (key === "lineHeight" && typeof val === "number") + return `${Math.round(val * 100)}%`; + if (val === null || val === undefined) return "Original"; + const str = String(val); + if (str === "dyslexia-option" || str === "dyslexia") return "Dyslexia"; + return str.includes("-") ? str.replace(/-/g, " ") : str; +} + export function ProfilePreviewCard({ profile, isActive, @@ -29,48 +101,6 @@ export function ProfilePreviewCard({ profile.settings, ) as (keyof AccessibilityPreferences)[]; - const formatKeyName = (key: string): string => { - switch (key) { - case "fontScale": - return "Font Size"; - case "lineHeight": - return "Line Height"; - case "contrastMode": - return "Contrast"; - case "reduceMotion": - return "Reduce Motion"; - case "textAlign": - return "Text Align"; - case "highlightLinks": - return "Highlight Links"; - case "highlightFocus": - return "Highlight Focus"; - case "cursorSize": - return "Cursor Size"; - case "readerMode": - return "Reading Mode"; - case "saturation": - return "Saturation"; - case "hideDecorativeImages": - return "Hide Images"; - default: - return key.replace(/([A-Z])/g, " $1").trim(); - } - }; - - const formatSettingValue = ( - key: keyof AccessibilityPreferences, - val: unknown, - ): string => { - if (typeof val === "boolean") return val ? "On" : "Off"; - if (key === "fontScale" && typeof val === "number") - return `${Math.round(val * 100)}%`; - if (key === "lineHeight" && typeof val === "number") - return `${Math.round(val * 100)}%`; - if (val === null || val === undefined) return "Original"; - return String(val); - }; - return (
- {formatKeyName(key)}:{" "} - {formatSettingValue(key, val)} + {formatPreferenceKey(key)}:{" "} + {formatPreferenceValue(key, val)} ); })} @@ -112,7 +142,7 @@ export function ProfilePreviewCard({ {isActive ? ( {/* Accessible Modal Dialog */} - {isOpen && ( -
{ - if (e.target === e.currentTarget) { - handleClose(); - } - }} - > + } + closeLabel={strings.dictionaryCloseDialog ?? "Close dictionary"} + size="full" + lockScroll={false} + initialFocusRef={searchInputRef} + returnFocusTo={triggerRef} + > +
+ {/* Live status announcements */} - {/* Live status announcements */} -
- {liveStatus} + {/* Search Form */} +
+
+ setSearchTerm(e.target.value)} + aria-label={ + strings.dictionarySearchPlaceholder ?? + "Type a word to look up..." + } + maxLength={50} + autoComplete="off" + spellCheck="false" + /> + {searchTerm && ( + + )}
- - {/* Search Form */} - -
- setSearchTerm(e.target.value)} - aria-label={ - strings.dictionarySearchPlaceholder ?? - "Type a word to look up..." - } - maxLength={50} - autoComplete="off" - spellCheck="false" - /> - {searchTerm && ( - - )} -
- -
- - {/* Content Area */} -
- {result?.found && result.entry && ( -
-
-

{result.entry.word}

- {result.entry.phonetic && ( - - {result.entry.phonetic} - - )} - {result.entry.partOfSpeech && ( - - {result.entry.partOfSpeech} - - )} - - {result.entry.source === "local" - ? (strings.dictionarySourceLocal ?? "Built-in Glossary") - : (provider?.name ?? - strings.dictionarySourceProvider ?? - "Configured Provider")} + + + + {/* Content Area */} +
+ {result?.found && result.entry && ( +
+
+

{result.entry.word}

+ {result.entry.phonetic && ( + + {result.entry.phonetic} -
- -

- {result.entry.definition} -

- - {result.entry.example && ( -
- - {strings.dictionaryExampleLabel ?? "Example"}: - {" "} - “{result.entry.example}” -
)} -
- )} - - {result && !result.found && ( -
-

- {result.error ?? - (strings.dictionaryStatusNotFound - ? strings.dictionaryStatusNotFound( - result.term ?? searchTerm, - ) - : `No definition found for "${result.term ?? searchTerm}".`)} -

- - {result.suggestions && result.suggestions.length > 0 && ( -
-

- {strings.dictionarySuggestionsTitle ?? "Did you mean:"} -

-
- {result.suggestions.map((suggestion) => ( - - ))} -
-
+ {result.entry.partOfSpeech && ( + + {result.entry.partOfSpeech} + )} + + {result.entry.source === "local" + ? (strings.dictionarySourceLocal ?? "Built-in Glossary") + : (provider?.name ?? + strings.dictionarySourceProvider ?? + "Configured Provider")} + +
+ +

+ {result.entry.definition} +

+ + {result.entry.example && ( +
+ + {strings.dictionaryExampleLabel ?? "Example"}: + {" "} + “{result.entry.example}” +
+ )} +
+ )} + + {result && !result.found && ( +
+

+ {result.error ?? + (strings.dictionaryStatusNotFound + ? strings.dictionaryStatusNotFound( + result.term ?? searchTerm, + ) + : `No definition found for "${result.term ?? searchTerm}".`)} +

+ + {result.suggestions && result.suggestions.length > 0 && ( +
+

+ {strings.dictionarySuggestionsTitle ?? "Did you mean:"} +

+
+ {result.suggestions.map((suggestion) => ( + + ))} +
+
+ )} +
+ )} + + {!result && ( +
+

+ {strings.dictionaryDescription ?? + "Look up definitions and accessibility terminology"} +

+
+

+ Popular terms: +

+
+ {[ + "accessibility", + "contrast", + "dyslexia", + "voice", + "wcag", + "screen reader", + ].map((chip) => ( + + ))} +
- )} - - {!result && ( -
-

- {strings.dictionaryDescription ?? - "Look up definitions and accessibility terminology"} -

-

- {provider - ? `Using ${provider.name}. Queries are rate-limited and sanitized.` - : "Using local offline glossary. Zero network transmission."} -

-
- )} -
+

+ {provider + ? `Using ${provider.name}. Queries are rate-limited and sanitized.` + : "Using local offline glossary. Zero network transmission."} +

+
+ )}
- )} +
); } diff --git a/src/features/FeatureMenu.tsx b/src/features/FeatureMenu.tsx index 46bffbd..fd20565 100644 --- a/src/features/FeatureMenu.tsx +++ b/src/features/FeatureMenu.tsx @@ -1,6 +1,7 @@ "use client"; import React, { useMemo } from "react"; +import { FeatureGroup } from "../core/controls/FeatureGroup"; import { type MenuCustomizationConfig, type NormalizedMenuItem, @@ -154,26 +155,34 @@ export function FeatureMenu({ if (groupItems.length === 0) return null; - const headingId = `arap-grp-${group.id}`; + if (group.title) { + return ( + +
+ {groupItems.map((item) => renderItem(item))} +
+
+ ); + } return (
- {group.title && ( -
-

- {group.title} -

- {group.description && ( -

{group.description}

- )} -
- )}
{groupItems.map((item) => renderItem(item))}
diff --git a/src/features/KeyboardShortcutsController.tsx b/src/features/KeyboardShortcutsController.tsx index 6b34e00..62d94e8 100644 --- a/src/features/KeyboardShortcutsController.tsx +++ b/src/features/KeyboardShortcutsController.tsx @@ -1,17 +1,9 @@ "use client"; -import { - useState, - useEffect, - useRef, - useContext, - useId, - type ReactNode, - useSyncExternalStore, -} from "react"; -import { createPortal } from "react-dom"; +import { useState, useEffect, useRef, useContext, useId } from "react"; import { AccessibilityContext } from "../core/AccessibilityContext"; import { FeatureIcon } from "../core/FeatureIcon"; +import { ModalDialog } from "../core/controls/ModalDialog"; import { resolveLocaleStrings } from "../core/i18n"; import { useAccessibility } from "../core/useAccessibility"; import { @@ -29,8 +21,6 @@ export interface KeyboardShortcutsControllerProps { description?: string; } -const emptySubscribe = () => () => {}; - export function KeyboardShortcutsController({ className = "", label, @@ -55,16 +45,10 @@ export function KeyboardShortcutsController({ const [isError, setIsError] = useState(false); const triggerRef = useRef(null); - const dialogRef = useRef(null); const remapInputRef = useRef(null); - const previousActiveElement = useRef(null); - - const titleId = useId(); - const isClient = useSyncExternalStore( - emptySubscribe, - () => true, - () => false, - ); + const enabledCheckboxId = useId(); + const searchInputId = useId(); + const remapInputId = useId(); const controllerLabel = label ?? strings.shortcutsTitle ?? "Keyboard Shortcuts"; @@ -76,10 +60,6 @@ export function KeyboardShortcutsController({ const closeLabel = strings.shortcutsClose ?? "Close Keyboard Shortcuts"; const handleOpen = () => { - if (typeof document !== "undefined") { - previousActiveElement.current = - document.activeElement as HTMLElement | null; - } setStatusMessage(null); setRemapTargetId(null); setIsOpen(true); @@ -89,65 +69,8 @@ export function KeyboardShortcutsController({ setIsOpen(false); setRemapTargetId(null); setStatusMessage(null); - if (previousActiveElement.current) { - previousActiveElement.current.focus(); - } else { - triggerRef.current?.focus(); - } }; - const handleCloseRef = useRef(handleClose); - useEffect(() => { - handleCloseRef.current = handleClose; - }); - - // Focus management and Escape key in dialog - useEffect(() => { - if (!isOpen || !dialogRef.current) return; - - dialogRef.current.focus(); - - const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === "Escape") { - event.stopPropagation(); - if (remapTargetId) { - setRemapTargetId(null); - setStatusMessage("Remapping cancelled."); - setIsError(false); - } else { - handleCloseRef.current(); - } - return; - } - - if (event.key === "Tab") { - const dialog = dialogRef.current; - if (!dialog) return; - - const focusable = dialog.querySelectorAll( - 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])', - ); - if (focusable.length === 0) return; - - const first = focusable[0]; - const last = focusable[focusable.length - 1]; - - if (event.shiftKey && document.activeElement === first) { - event.preventDefault(); - last.focus(); - } else if (!event.shiftKey && document.activeElement === last) { - event.preventDefault(); - first.focus(); - } - } - }; - - document.addEventListener("keydown", handleKeyDown, { capture: true }); - return () => { - document.removeEventListener("keydown", handleKeyDown, { capture: true }); - }; - }, [isOpen, remapTargetId]); - // Focus remap input when remap mode activates useEffect(() => { if (remapTargetId && remapInputRef.current) { @@ -297,278 +220,249 @@ export function KeyboardShortcutsController({ { id: "tools", label: "Tools" }, ]; - const dialogPortal: ReactNode = - isClient && isOpen && typeof document !== "undefined" - ? createPortal( -
{ - if (e.target === e.currentTarget) { - handleClose(); - } - }} + return ( + <> +
+
+ + + + {controllerLabel} + {controllerDescription} + + + +
+
+ + } + closeLabel={closeLabel} + size="full" + lockScroll={false} + disableEscapeClose={Boolean(remapTargetId)} + returnFocusTo={triggerRef} + footer={ +
+ +
+ } + > +
+ {/* Global shortcut toggle switch */} +
+ +
+ + {/* Filter controls */} +
-
-
-

- - {controllerLabel} -

-

- {controllerDescription} -

-
+ {categories.map((c) => ( -
- - {/* Global shortcut toggle switch */} -
- -
- - {/* Filter controls */} -
-
- {categories.map((c) => ( - - ))} -
- -
- setSearch(e.target.value)} - aria-label="Filter shortcuts" - /> -
-
- - {/* Status announcement */} - {statusMessage && ( -
- {statusMessage} -
- )} - - {/* Remap Active Input Card */} - {remapTargetId && ( -
-
- - Remapping:{" "} - {stringMap[ - DEFAULT_SHORTCUTS.find((s) => s.id === remapTargetId) - ?.labelKey || "" - ] ?? remapTargetId} - - -
- - - Press your new combination or Escape to cancel. Reserved - browser keys (e.g. Ctrl+U, Ctrl+R) are protected. - -
- )} - - {/* Shortcuts List */} -
- {filteredShortcuts.length === 0 ? ( -
- No shortcuts match your search. -
- ) : ( -
    - {filteredShortcuts.map((shortcut) => { - const activeKey = resolveActiveShortcut( - shortcut.id, - customShortcuts, - ); - const keyParts = activeKey.split("+"); - const isCustom = Boolean(customShortcuts?.[shortcut.id]); - - return ( -
  • -
    - - {stringMap[shortcut.labelKey] ?? shortcut.id} - {isCustom && ( - - Custom - - )} - - - {stringMap[shortcut.descriptionKey] ?? ""} - -
    - -
    -
    - {keyParts.map((kp, idx) => ( - - {kp} - {idx < keyParts.length - 1 && " + "} - - ))} -
    - - {shortcut.allowRemap && ( - - )} -
    -
  • - ); - })} -
- )} -
+ ))} +
- {/* Footer */} -
+
+ setSearch(e.target.value)} + aria-label="Filter shortcuts" + /> + {search && ( + )} +
+
+ + {/* Status announcement */} + {statusMessage && ( +
+ {statusMessage} +
+ )} + + {/* Remap Active Input Card */} + {remapTargetId && ( +
+
+ + Remapping:{" "} + {stringMap[ + DEFAULT_SHORTCUTS.find((s) => s.id === remapTargetId) + ?.labelKey || "" + ] ?? remapTargetId} +
+ + + Press your new combination or Escape to cancel. Reserved browser + keys (e.g. Ctrl+U, Ctrl+R) are protected. +
-
, - document.body, - ) - : null; - - return ( - <> -
- - - - {controllerLabel} - - {controllerDescription} - - - - -
+ )} - {dialogPortal} + {/* Shortcuts List */} +
+ {filteredShortcuts.length === 0 ? ( +
+ No shortcuts match your search. +
+ ) : ( +
    + {filteredShortcuts.map((shortcut) => { + const activeKey = resolveActiveShortcut( + shortcut.id, + customShortcuts, + ); + const keyParts = activeKey.split("+"); + const isCustom = Boolean(customShortcuts?.[shortcut.id]); + + return ( +
  • +
    + + {stringMap[shortcut.labelKey] ?? shortcut.id} + {isCustom && ( + + Custom + + )} + + + {stringMap[shortcut.descriptionKey] ?? ""} + +
    + +
    +
    + {keyParts.map((kp, idx) => ( + + {kp} + {idx < keyParts.length - 1 && " + "} + + ))} +
    + + {shortcut.allowRemap && ( + + )} +
    +
  • + ); + })} +
+ )} +
+
+
); } diff --git a/src/features/PageNavigatorController.tsx b/src/features/PageNavigatorController.tsx index 5451c67..718f8b4 100644 --- a/src/features/PageNavigatorController.tsx +++ b/src/features/PageNavigatorController.tsx @@ -1,7 +1,8 @@ "use client"; -import { useState, useEffect, useRef, useCallback } from "react"; +import { useState, useEffect, useRef, useCallback, useId } from "react"; import { FeatureIcon } from "../core/FeatureIcon"; +import { ModalDialog } from "../core/controls/ModalDialog"; import { scanHeadings, scanLandmarks, @@ -40,6 +41,9 @@ export function PageNavigatorController({ const [landmarks, setLandmarks] = useState([]); const [links, setLinks] = useState([]); const [search, setSearch] = useState(""); + const [activeNavKey, setActiveNavKey] = useState(null); + const [navStatus, setNavStatus] = useState(""); + const searchInputId = useId(); const triggerRef = useRef(null); const dialogRef = useRef(null); @@ -52,6 +56,7 @@ export function PageNavigatorController({ const handleOpen = () => { refreshStructure(); + setNavStatus(""); setIsOpen(true); }; @@ -66,14 +71,13 @@ export function PageNavigatorController({ return subscribePageStructure(refreshStructure); }, [isOpen, refreshStructure]); - // Focus management when opening dialog - useEffect(() => { - if (isOpen) { - dialogRef.current?.focus(); - } - }, [isOpen]); - - const handleNavigate = (element: HTMLElement) => { + const handleNavigate = ( + element: HTMLElement, + navKey: string, + announceText: string, + ) => { + setActiveNavKey(navKey); + setNavStatus(`Navigated to ${announceText}`); navigateToElement(element, { onComplete: () => { if (closeOnNavigate) { @@ -109,37 +113,21 @@ export function PageNavigatorController({ role="group" aria-label={label} > -
+
- {label} + {label} {description && ( - - {description} - + {description} )}
- {isOpen && ( + } + closeLabel="Close Page Navigator" + size="full" + trapFocus={false} + lockScroll={false} + ariaModal={false} + initialFocusRef={dialogRef} + returnFocusTo={triggerRef} + >
setSearch(e.target.value)} aria-label={`Filter ${activeTab}`} /> + {search && ( + + )}
+ {navStatus && ( +
+ {navStatus} +
+ )} +
{activeTab === "headings" && (
) : (
    - {filteredHeadings.map((h, i) => ( -
  • - -
  • - ))} + + + {h.text} + + + + ); + })}
)}
@@ -300,25 +335,36 @@ export function PageNavigatorController({
) : (
    - {filteredLandmarks.map((l, i) => ( -
  • - -
  • - ))} + + + {l.label} + + + + ); + })}
)}
@@ -338,53 +384,61 @@ export function PageNavigatorController({
) : (
    - {filteredLinks.map((lnk, i) => ( -
  • - -
  • - ))} + + + ); + })}
)}
)} - )} + ); } diff --git a/src/features/PresetsController.tsx b/src/features/PresetsController.tsx index 4c542c6..5d119f4 100644 --- a/src/features/PresetsController.tsx +++ b/src/features/PresetsController.tsx @@ -3,6 +3,11 @@ import { useContext, useId, useRef, useState, type ChangeEvent } from "react"; import { FeatureIcon } from "../core/FeatureIcon"; import { EmptyState } from "../core/controls/FeatureStatusState"; +import { ModalDialog } from "../core/controls/ModalDialog"; +import { + formatPreferenceKey, + formatPreferenceValue, +} from "../core/controls/ProfilePreviewCard"; import { usePresets } from "../core/usePresets"; import { AccessibilityContext } from "../core/AccessibilityContext"; import { resolveLocaleStrings } from "../core/i18n"; @@ -32,6 +37,7 @@ export function PresetsController({ const [errorMessage, setErrorMessage] = useState(""); const dialogId = "arap-presets-dialog"; const nameInputId = useId(); + const fileInputId = useId(); const fileInputRef = useRef(null); const triggerRef = useRef(null); @@ -110,76 +116,19 @@ export function PresetsController({ } }; - const formatKeyName = (key: string): string => { - switch (key) { - case "fontScale": - return "Font Size"; - case "lineHeight": - return "Line Height"; - case "contrastMode": - return "Contrast"; - case "reduceMotion": - return "Reduce Motion"; - case "textAlign": - return "Text Align"; - case "highlightLinks": - return "Highlight Links"; - case "highlightFocus": - return "Highlight Focus"; - case "cursorSize": - return "Cursor Size"; - case "readerMode": - return "Reading Mode"; - case "saturation": - return "Saturation"; - case "hideDecorativeImages": - return "Hide Images"; - default: - return key.replace(/([A-Z])/g, " $1").trim(); - } - }; - - const formatSettingValue = ( - key: keyof AccessibilityPreferences, - val: unknown, - ): string => { - if (typeof val === "boolean") return val ? "On" : "Off"; - if (key === "fontScale" && typeof val === "number") - return `${Math.round(val * 100)}%`; - if (key === "lineHeight" && typeof val === "number") - return `${Math.round(val * 100)}%`; - if (val === null || val === undefined) return "Original"; - return String(val); - }; - return (
-
+
- {effectiveLabel} + {effectiveLabel} {description && ( - + {presets.length > 0 ? `${presets.length} custom preset${presets.length === 1 ? "" : "s"} saved` : description} @@ -189,101 +138,61 @@ export function PresetsController({
- {isOpen && ( + setIsOpen(false)} + id="arap-presets-modal" + title={effectiveLabel} + subtitle={description} + icon={} + closeLabel="Close presets dialog" + size="full" + lockScroll={false} + returnFocusTo={triggerRef} + >
{ - if (e.key === "Escape") { - e.stopPropagation(); - setIsOpen(false); - triggerRef.current?.focus(); - } - }} > {/* Live Status and Error Announcements */} -
+
{statusMessage && ( -
+
✓ {statusMessage}
)} {errorMessage && ( -
+
⚠ {errorMessage}
)}
{/* Save Current Configuration as New Preset */} -
-