diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c78f94..ee22521 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 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): + - Bundle SIL Open Font License 1.1 variable **Manrope** typeface locally (`dist/fonts/Manrope-VariableFont_wght.ttf` and inline data-URI `@font-face`), and synchronize `fontFamily` changes (`default`, `legible`, `dyslexia-option`) across `.arap-root`, panels, portals, modals, reading mode, playback bar, and accessible tooltips via `activeFont` / `data-arap-font` (#189). + - Add reusable `ModalDialog` and collapsible `FeatureGroup` primitives, default `"experimental"` collapsible group (`smartContrast`, `voiceNavigation`, `translation`), and move search-heavy views (`Profiles`, `Presets`, `Page Navigator`, `Dictionary`, `Keyboard Shortcuts`) into spacious responsive modals (#183, #195, #197). + - Widen default desktop panel to `460px` and add desktop-only (`>= 1024px` fine-pointer) transient pointer + keyboard panel resizing with clamped viewport bounds (#185, #186). + - Fix `.arap-btn-sm` stepper scoping, `.arap-feature-expandable` flex layout, unstyled `.arap-feature-btn`, duplicate search clear icons, duplicate footer close/revert controls, Read-Aloud `44px` mini-player targets, form-field `id`/`name` compliance, and primary blue CTA hierarchy (#182, #184, #191, #192, #196). + - Move Reading Guide and Reading Mask `↑`/`↓` nudge controls out of the panel into external `44px` `` floating buttons (`data-aid="guide"|"mask"`) so mobile/touch users can reposition overlays without reopening the widget panel (#199). + - Expand offline local dictionary glossaries (`"voice"`, `"voice navigation"`, `"read aloud"`, `"translation"`, `"keyboard"`, `"landmark"`, etc.) with fuzzy typo suggestions and truthful empty states (#188). + - Fix host-content translation boundaries (`[data-arap-ui]`, `.arap-root`, ` -

Decorative Images

+

Decorative & Informative Media

- Decorative images below are eligible to be hidden when the Hide - Images mode is activated: + Hide Images conceals purely decorative visuals below while keeping + informative diagrams visible. Hide Videos hides video players + while preserving layout space.

- + > + + Diagram showing 44px minimum target size and 7.2:1 contrast + +
+ +
) : ( -
+

Simulated Route: Long Article

This view simulates navigating to a reading-heavy page to test @@ -191,7 +285,13 @@ function App() { how the container adjusts naturally without layout truncation or unintended scrollbars.

-
+

Section 2: Semantic Landmarks & Reading Mode

+

+ Semantic landmarks and structured headings allow Page Navigator + and Reading Mode to isolate primary prose cleanly even when + toggling between dark mode, custom typography, and live routes. +

+ )} diff --git a/examples/next-app/app/components/AccessibilitySettings.tsx b/examples/next-app/app/components/AccessibilitySettings.tsx index 5ea4a88..b47d15f 100644 --- a/examples/next-app/app/components/AccessibilitySettings.tsx +++ b/examples/next-app/app/components/AccessibilitySettings.tsx @@ -4,7 +4,7 @@ import { AccessibilityPlugin, AccessibilityButton, AccessibilityList, - TextScaleController, + FeatureGroup, FontSizeController, LineHeightController, LetterSpacingController, @@ -12,11 +12,9 @@ import { ParagraphSpacingController, FontFamilyController, ContrastModeController, - ContrastController, SmartContrastController, SaturationController, InvertColorsController, - GrayscaleController, LinkHighlightController, HighlightFocusController, ReduceMotionController, @@ -47,38 +45,80 @@ export function AccessibilitySettings() { description="Adjust your display and reading preferences" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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-lock.json b/package-lock.json index 21f1d90..2bc85cd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "accessibility-plugin-react", - "version": "2.29.2", + "version": "2.30.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "accessibility-plugin-react", - "version": "2.29.2", + "version": "2.30.0", "license": "ISC", "devDependencies": { "@axe-core/playwright": "^4.13.0", diff --git a/package.json b/package.json index 1baafef..82924a4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "accessibility-plugin-react", - "version": "2.29.2", + "version": "2.30.0", "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", @@ -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/AccessibilityList.tsx b/src/core/AccessibilityList.tsx index 3de06e7..34b5b33 100644 --- a/src/core/AccessibilityList.tsx +++ b/src/core/AccessibilityList.tsx @@ -1,5 +1,14 @@ "use client"; -import { useContext, useEffect, useRef, useState } from "react"; +import { + useCallback, + useContext, + useEffect, + useRef, + useState, + useSyncExternalStore, + type KeyboardEvent as ReactKeyboardEvent, + type PointerEvent as ReactPointerEvent, +} from "react"; import { AccessibilityContext } from "./AccessibilityContext"; import { PanelActionsContext } from "./PanelActionsContext"; import { PositionControls } from "./PositionControls"; @@ -14,6 +23,25 @@ import { resolveLocaleStrings, isRtlLocale } from "./i18n"; import { FeatureMenu } from "../features/FeatureMenu"; import type { AccessibilityListProps } from "./types"; +const finePointerSubscribe = (callback: () => void) => { + if ( + typeof window === "undefined" || + typeof window.matchMedia !== "function" + ) { + return () => {}; + } + const mq = window.matchMedia("(pointer: fine) and (hover: hover)"); + mq.addEventListener?.("change", callback); + return () => mq.removeEventListener?.("change", callback); +}; + +const finePointerSnapshot = () => + typeof window !== "undefined" && typeof window.matchMedia === "function" + ? window.matchMedia("(pointer: fine) and (hover: hover)").matches + : true; + +const finePointerServerSnapshot = () => true; + function Panel({ children, footer, @@ -52,6 +80,119 @@ function Panel({ ctx.widgetPlacement?.kind === "corner" ? ctx.widgetPlacement.corner : defaultCorner(ctx.position); + + // Desktop-only resizable panel bounds (transient UI state; not persisted into storage) + const hasFinePointer = useSyncExternalStore( + finePointerSubscribe, + finePointerSnapshot, + finePointerServerSnapshot, + ); + + const isDesktopResizable = + viewport[0] >= 1024 && viewport[1] >= 520 && hasFinePointer; + const minPanelWidth = 380; + const maxPanelWidth = Math.min( + 720, + Math.max(minPanelWidth, viewport[0] - 48), + ); + const minPanelHeight = 420; + const maxPanelHeight = Math.max(minPanelHeight, viewport[1] - 48); + + const [panelSize, setPanelSize] = useState<{ + width: number; + height: number; + } | null>(null); + const [isResizing, setIsResizing] = useState(false); + + const clampPanelSize = useCallback( + (nextW: number, nextH: number) => ({ + width: Math.max( + minPanelWidth, + Math.min(maxPanelWidth, Math.round(nextW)), + ), + height: Math.max( + minPanelHeight, + Math.min(maxPanelHeight, Math.round(nextH)), + ), + }), + [maxPanelHeight, maxPanelWidth], + ); + + const effectivePanelSize = + isDesktopResizable && panelSize + ? clampPanelSize(panelSize.width, panelSize.height) + : null; + + const effectiveDesktopWidth = effectivePanelSize + ? effectivePanelSize.width + : 460; + const pointPlacementStyle = panelStyle( + ctx.widgetPlacement, + viewport, + triggerSize, + effectiveDesktopWidth, + ); + const isRightAnchored = + ctx.widgetPlacement?.kind === "point" ? false : corner.endsWith("right"); + const isTopAnchored = + ctx.widgetPlacement?.kind === "point" + ? Boolean(pointPlacementStyle?.top && pointPlacementStyle.top !== "auto") + : corner.startsWith("top"); + + const startPointerResize = (event: ReactPointerEvent) => { + if (!isDesktopResizable || !panel.current || event.button !== 0) return; + event.preventDefault(); + event.stopPropagation(); + const rect = panel.current.getBoundingClientRect(); + const startX = event.clientX; + const startY = event.clientY; + const startW = rect.width; + const startH = rect.height; + setIsResizing(true); + + const onMove = (moveEvent: PointerEvent) => { + const dx = moveEvent.clientX - startX; + const dy = moveEvent.clientY - startY; + const rawW = isRightAnchored ? startW - dx : startW + dx; + const rawH = isTopAnchored ? startH + dy : startH - dy; + setPanelSize(clampPanelSize(rawW, rawH)); + }; + + const onEnd = () => { + setIsResizing(false); + window.removeEventListener("pointermove", onMove); + window.removeEventListener("pointerup", onEnd); + window.removeEventListener("pointercancel", onEnd); + }; + + window.addEventListener("pointermove", onMove); + window.addEventListener("pointerup", onEnd); + window.addEventListener("pointercancel", onEnd); + }; + + const handleResizeKeyDown = (event: ReactKeyboardEvent) => { + if (!isDesktopResizable) return; + const step = event.shiftKey ? 48 : 24; + const rect = panel.current?.getBoundingClientRect(); + const currentW = effectivePanelSize?.width ?? rect?.width ?? 460; + const currentH = effectivePanelSize?.height ?? rect?.height ?? 560; + + if (event.key === "ArrowLeft" || event.key === "ArrowRight") { + event.preventDefault(); + const dir = event.key === "ArrowLeft" ? -1 : 1; + const deltaW = isRightAnchored ? -dir * step : dir * step; + setPanelSize(clampPanelSize(currentW + deltaW, currentH)); + } else if (event.key === "ArrowUp" || event.key === "ArrowDown") { + event.preventDefault(); + const dir = event.key === "ArrowUp" ? -1 : 1; + const deltaH = isTopAnchored ? dir * step : -dir * step; + setPanelSize(clampPanelSize(currentW, currentH + deltaH)); + } else if (event.key === "Home" || event.key === "Enter") { + event.preventDefault(); + setPanelSize(null); + } + }; + const previous = useRef(null); useEffect(() => { if (ctx.isOpen) { @@ -75,14 +216,23 @@ function Panel({
+ {isDesktopResizable && ( +
+ )}
); } 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 ? ( + + ) : ( +
+
+
+

+ {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 */} -
-