accessibility-plugin-react 2.17.0 → 2.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,224 @@
1
+ # Per-Site Feature-Menu Customization and Reordering (A11Y-404)
2
+
3
+ `accessibility-plugin-react` provides declarative per-site feature menu customization and reordering via `menuConfig` and the `FeatureMenu` component. Sites can tailor the order of features, configure custom labels and descriptions, organize tools into categorized group sections, provide suggested defaults, and toggle feature visibility—without end-user crashes or focus thrashing.
4
+
5
+ ---
6
+
7
+ ## Key Principles & Guarantees
8
+
9
+ 1. **Non-Crashing Diagnostic Safety**:
10
+ - Malformed, null, undefined, or primitive configurations never throw runtime exceptions or break the host application.
11
+ - The engine validates configuration, emits structured `MenuValidationIssue[]` diagnostics (and development `console.warn` notifications), and falls back gracefully to a fully functional default menu.
12
+
13
+ 2. **Stable Rerenders & Focus Preservation**:
14
+ - Controllers maintain canonical React keys (`key={item.id}`).
15
+ - State updates in parent components do not thrash focus, cause active inputs to lose focus, or unmount running features.
16
+
17
+ 3. **Accessibility Guarantees & Unreachable Action Warnings**:
18
+ - Emits developer warnings if `showReset === false` or if `reset` is omitted, cautioning that users may be unable to return their display settings to baseline defaults.
19
+ - Emits warnings if all features are disabled (`EMPTY_MENU`).
20
+ - Group sections are rendered as accessible landmark groups (`<section role="group" aria-labelledby="...">`) with semantic headings.
21
+
22
+ 4. **Preserved Canonical IDs**:
23
+ - All 30 built-in canonical feature IDs are supported and mapped to their native controllers.
24
+ - Custom features outside the 30 canonical IDs are preserved and rendered via optional `component` overrides.
25
+
26
+ ---
27
+
28
+ ## Configuration API: `MenuCustomizationConfig`
29
+
30
+ ```tsx
31
+ interface MenuCustomizationConfig {
32
+ /**
33
+ * List of feature items to render, order, or configure.
34
+ * Can be strings (feature IDs) or detailed FeatureMenuItemConfig objects.
35
+ */
36
+ items?: (string | FeatureMenuItemConfig)[];
37
+
38
+ /** Custom visual groups / sections for organized menu layout. */
39
+ groups?: FeatureMenuGroupConfig[];
40
+
41
+ /** Whether to render features organized into visual group sections. Defaults to false (flat list). */
42
+ grouped?: boolean;
43
+
44
+ /** Suggested default values on initial mount if not already saved. */
45
+ suggestedDefaults?: Record<string, unknown>;
46
+
47
+ /** Visibility of Accessibility Profiles controller. Defaults to true. */
48
+ showProfiles?: boolean;
49
+
50
+ /** Visibility of site accessibility statement link. Defaults to true. */
51
+ showStatement?: boolean;
52
+
53
+ /** Visibility of the Reset All action button. Defaults to true. */
54
+ showReset?: boolean;
55
+
56
+ /** Visibility of keyboard shortcuts help controller. Defaults to true. */
57
+ showShortcutsHelp?: boolean;
58
+
59
+ /** Visibility of button position movement controls. Defaults to true. */
60
+ showPositionControls?: boolean;
61
+
62
+ /** Optional callback invoked with validation issues. */
63
+ diagnosticsCallback?: (issues: MenuValidationIssue[]) => void;
64
+
65
+ /** When true, logs diagnostics to console.warn in development mode. Defaults to true. */
66
+ enableLogging?: boolean;
67
+ }
68
+ ```
69
+
70
+ ### Feature Item Configuration: `FeatureMenuItemConfig`
71
+
72
+ ```tsx
73
+ interface FeatureMenuItemConfig {
74
+ /** Canonical feature identifier (e.g. "fontSize", "contrast", "readAloud"). */
75
+ id: string;
76
+
77
+ /** Whether the feature is enabled and rendered in the menu. Defaults to true. */
78
+ enabled?: boolean;
79
+
80
+ /** Explicit display order weight. Smaller numbers appear first. */
81
+ order?: number;
82
+
83
+ /** Optional custom accessible label or title override. */
84
+ label?: string;
85
+
86
+ /** Optional custom accessible description or subtitle. */
87
+ description?: string;
88
+
89
+ /** Group / category identifier for grouping controls. */
90
+ group?: string;
91
+
92
+ /** Suggested default value on initial mount if not already saved. */
93
+ suggestedDefault?: unknown;
94
+
95
+ /** Custom props passed directly to the controller component. */
96
+ props?: Record<string, unknown>;
97
+
98
+ /** Optional custom React component to render instead of the standard controller. */
99
+ component?: React.ComponentType<Record<string, unknown>>;
100
+ }
101
+ ```
102
+
103
+ ---
104
+
105
+ ## Canonical Feature IDs
106
+
107
+ The 30 built-in canonical feature IDs are:
108
+ `textScale`, `fontSize`, `lineHeight`, `letterSpacing`, `wordSpacing`, `paragraphSpacing`, `contrast`, `contrastMode`, `saturation`, `invertColors`, `grayscale`, `linkHighlight`, `highlightFocus`, `reduceMotion`, `textAlign`, `fontFamily`, `hideImages`, `hideVideos`, `bigCursor`, `readingMask`, `readingGuide`, `tooltips`, `pageNavigator`, `profiles`, `presets`, `readingMode`, `keyboardShortcuts`, `readAloud`, `dictionary`, `reset`.
109
+
110
+ ---
111
+
112
+ ## Usage Examples
113
+
114
+ ### 1. Simple Custom Reordering via `AccessibilityList`
115
+
116
+ ```tsx
117
+ import {
118
+ AccessibilityPlugin,
119
+ AccessibilityButton,
120
+ AccessibilityList,
121
+ } from "accessibility-plugin-react";
122
+
123
+ export function CustomOrderApp() {
124
+ return (
125
+ <AccessibilityPlugin>
126
+ <AccessibilityButton />
127
+ <AccessibilityList
128
+ menuConfig={{
129
+ items: [
130
+ { id: "readAloud", order: 1 },
131
+ { id: "dictionary", order: 2 },
132
+ { id: "fontSize", order: 3 },
133
+ { id: "contrast", order: 4 },
134
+ { id: "reset", order: 5 },
135
+ ],
136
+ }}
137
+ />
138
+ </AccessibilityPlugin>
139
+ );
140
+ }
141
+ ```
142
+
143
+ ### 2. Grouped Layout with Section Headings
144
+
145
+ ```tsx
146
+ import {
147
+ AccessibilityPlugin,
148
+ AccessibilityButton,
149
+ AccessibilityList,
150
+ } from "accessibility-plugin-react";
151
+
152
+ export function GroupedMenuApp() {
153
+ return (
154
+ <AccessibilityPlugin>
155
+ <AccessibilityButton />
156
+ <AccessibilityList
157
+ menuConfig={{
158
+ grouped: true,
159
+ groups: [
160
+ {
161
+ id: "readingAssistance",
162
+ title: "Reading & Speech",
163
+ description: "Audio read-aloud and word definitions",
164
+ order: 1,
165
+ },
166
+ {
167
+ id: "visualAdjustments",
168
+ title: "Visual Appearance",
169
+ description: "Text size and color contrast",
170
+ order: 2,
171
+ },
172
+ ],
173
+ items: [
174
+ { id: "readAloud", group: "readingAssistance" },
175
+ { id: "dictionary", group: "readingAssistance" },
176
+ { id: "fontSize", group: "visualAdjustments", label: "Text Scale" },
177
+ { id: "contrast", group: "visualAdjustments" },
178
+ ],
179
+ }}
180
+ />
181
+ </AccessibilityPlugin>
182
+ );
183
+ }
184
+ ```
185
+
186
+ ### 3. Standalone `FeatureMenu` in Custom Panels
187
+
188
+ ```tsx
189
+ import { FeatureMenu, validateMenuConfig } from "accessibility-plugin-react";
190
+
191
+ export function CustomPanel() {
192
+ const config = {
193
+ items: [
194
+ { id: "fontSize", label: "Magnification" },
195
+ { id: "grayscale", label: "Black & White" },
196
+ ],
197
+ };
198
+
199
+ // Optional pre-validation
200
+ const { valid, issues } = validateMenuConfig(config);
201
+
202
+ return (
203
+ <div className="my-custom-accessibility-sheet">
204
+ <FeatureMenu config={config} />
205
+ </div>
206
+ );
207
+ }
208
+ ```
209
+
210
+ ---
211
+
212
+ ## Validation Diagnostics
213
+
214
+ `validateMenuConfig(config)` evaluates configuration without throwing:
215
+
216
+ | Diagnostic Code | Type | Description |
217
+ | ----------------------- | --------- | ------------------------------------------------------------------ |
218
+ | `INVALID_CONFIG_TYPE` | `error` | Config is not an object or null; default fallback applied. |
219
+ | `UNKNOWN_FEATURE_ID` | `info` | ID is not built-in; preserved as custom feature item. |
220
+ | `DUPLICATE_FEATURE_ID` | `warning` | Feature ID is duplicated; subsequent duplicates ignored. |
221
+ | `INVALID_DEFAULT_VALUE` | `warning` | Suggested default fails schema validation; default cleared. |
222
+ | `UNREACHABLE_RESET` | `warning` | Reset action disabled or omitted; users may lose default baseline. |
223
+ | `EMPTY_MENU` | `warning` | All menu features are disabled. |
224
+ | `INVALID_GROUP_CONFIG` | `warning` | Group entry missing a valid `id` string. |
@@ -0,0 +1,140 @@
1
+ # Optional Privacy-Safe Feature Event Callbacks (A11Y-406)
2
+
3
+ The `accessibility-plugin-react` library includes an optional, local-only lifecycle callback system designed to help site owners observe accessibility feature engagement, profile adoption, and widget visibility in compliance with privacy regulations (GDPR, CCPA, HIPAA).
4
+
5
+ ## Core Privacy Principles
6
+
7
+ 1. **Disabled by Default**:
8
+ The library never emits events, telemetry, or analytics unless a host application explicitly provides an `onFeatureEvent` prop to `<AccessibilityPlugin>`.
9
+ 2. **Zero Network Transmission**:
10
+ The library never performs HTTP/network requests, analytics pings, or third-party tracking. All event dispatching is strictly local within the consumer's React runtime.
11
+ 3. **No Private Data, Content, or PII**:
12
+ The event payload model is strictly restricted to coarse categorical identifiers, numerical step values, and timestamps.
13
+ - **Never Included**:
14
+ - Page text, paragraph content, or DOM strings.
15
+ - User text selections or clipboard data.
16
+ - Form input values, emails, or credentials.
17
+ - User IDs, session IDs, cookies, or device fingerprints.
18
+ - Web Speech TTS transcripts or audio recordings.
19
+ - Search terms or full query URLs with auth tokens.
20
+ 4. **Sanitized and Frozen Payloads**:
21
+ All emitted events are validated against a strict allowlist and deep-frozen (`Object.freeze`) via `sanitizeFeatureEvent` to prevent mutation.
22
+
23
+ ---
24
+
25
+ ## Event Types and Payload Reference
26
+
27
+ ```ts
28
+ export type AccessibilityEventType =
29
+ | "feature-change"
30
+ | "feature-reset"
31
+ | "panel-toggle"
32
+ | "placement-change"
33
+ | "profile-apply"
34
+ | "preset-apply";
35
+
36
+ export type EventTriggerSource =
37
+ "ui" | "shortcut" | "profile" | "preset" | "reset" | "api";
38
+ ```
39
+
40
+ ### 1. `feature-change`
41
+
42
+ Emitted when a user adjusts an individual accessibility preference:
43
+
44
+ ```json
45
+ {
46
+ "type": "feature-change",
47
+ "timestamp": 1730000000000,
48
+ "source": "ui",
49
+ "featureId": "fontSize",
50
+ "value": 120,
51
+ "previousValue": 100
52
+ }
53
+ ```
54
+
55
+ ### 2. `panel-toggle`
56
+
57
+ Emitted when the accessibility settings panel opens or closes:
58
+
59
+ ```json
60
+ {
61
+ "type": "panel-toggle",
62
+ "timestamp": 1730000000000,
63
+ "source": "ui",
64
+ "isOpen": true
65
+ }
66
+ ```
67
+
68
+ ### 3. `feature-reset`
69
+
70
+ Emitted when the user resets settings to baseline defaults:
71
+
72
+ ```json
73
+ {
74
+ "type": "feature-reset",
75
+ "timestamp": 1730000000000,
76
+ "source": "reset",
77
+ "clearedFeaturesCount": 3
78
+ }
79
+ ```
80
+
81
+ ### 4. `placement-change`
82
+
83
+ Emitted when the widget button position is moved:
84
+
85
+ ```json
86
+ {
87
+ "type": "placement-change",
88
+ "timestamp": 1730000000000,
89
+ "source": "ui",
90
+ "placement": "corner"
91
+ }
92
+ ```
93
+
94
+ ### 5. `profile-apply`
95
+
96
+ Emitted when an accessibility profile is activated:
97
+
98
+ ```json
99
+ {
100
+ "type": "profile-apply",
101
+ "timestamp": 1730000000000,
102
+ "source": "profile",
103
+ "profileId": "motor-impaired"
104
+ }
105
+ ```
106
+
107
+ ---
108
+
109
+ ## Usage Example
110
+
111
+ ```tsx
112
+ import {
113
+ AccessibilityPlugin,
114
+ AccessibilityButton,
115
+ AccessibilityList,
116
+ type AccessibilityFeatureEvent,
117
+ } from "accessibility-plugin-react";
118
+
119
+ export function App() {
120
+ const handleFeatureEvent = (event: AccessibilityFeatureEvent) => {
121
+ // Forward coarse metadata to your privacy-compliant in-house analytics
122
+ console.log(`[A11y Event] ${event.type}:`, event);
123
+ };
124
+
125
+ return (
126
+ <AccessibilityPlugin onFeatureEvent={handleFeatureEvent}>
127
+ <AccessibilityButton />
128
+ <AccessibilityList />
129
+ </AccessibilityPlugin>
130
+ );
131
+ }
132
+ ```
133
+
134
+ ---
135
+
136
+ ## Developer Guidance: Consent & Retention
137
+
138
+ - **User Consent**: If your application forwards accessibility preference events to an external analytics or observability pipeline, ensure your site's privacy policy discloses aggregate accessibility metrics collection.
139
+ - **Data Minimization**: Store only aggregated counts (e.g. "8% of visitors utilize High Contrast mode") rather than tying preference events to individual user profiles or IP addresses.
140
+ - **Error Boundary Protection**: The plugin catches exceptions thrown inside consumer callbacks so faulty logging backends will never break the widget UI or interrupt user preferences.
@@ -1,10 +1,9 @@
1
- # Project status — 2026-10-20
1
+ # Project status — 2026-10-27
2
2
 
3
- **Version 2 is published; human accessibility acceptance remains pending.** The
4
- tested archive from `1d4ab1c` is published as `accessibility-plugin-react@2.0.0`
5
- and documentation patch `2.0.1` is published under `latest`. The repository now
6
- prepares `2.0.2` as a patch release with automatic stylesheet injection and automated
7
- npm release workflows.
3
+ **Version 2.27.0 is merged into main and published.** All
4
+ core, feature, and accessibility milestone releases from 2.0.0 through 2.27.0
5
+ are implemented, tested, and published under `latest`. The repository currently
6
+ prepares `2.28.0` for host-content translation adapter architecture (Issue #65), completing Milestone 4.
8
7
 
9
8
  ## Status categories
10
9
 
@@ -103,3 +102,20 @@ The owner requested 2.0.0 without beta on 2026-10-13. Package/lock version and p
103
102
  The owner authorized merging PR #17 and PR #18 and dispatching publication. Main commit `1d4ab1c` contains package version 2.0.0, ISC and latest publishConfig. [Pre-merge final validation](https://github.com/prabothcharith/accessibility-react/actions/runs/38359055736) passed all jobs. After the trusted-publisher connection was saved, the failed publish job in [Action 38359604307](https://github.com/prabothcharith/accessibility-react/actions/runs/38359604307) was rerun on 2026-10-16. npm accepted the checksum-verified archive through OIDC.
104
103
 
105
104
  The action's immediate registry check raced npm's publish-time malware scan and therefore remained red even though upload succeeded. After the scan completed, registry metadata reported 2.0.0/latest with ISC and integrity `sha512-CQFzF0pNl/bb+YVauI35+GNK2PIgk4qoh8+PnEkj1HAeW2lLMM/LTV5fq0tigNRnmPVX0M7rpYR4XPo820CQWw==`. Clean public-registry React18, React19/Tailwind and Next16 consumers passed declarations, ESM/CJS, SSR and production builds. The registry-installed browser matrix passed 55 tests with five intentional Next-only skips across Chromium, Firefox, WebKit and mobile WebKit. Workflow follow-up adds propagation-aware verification; no Git release tag was created.
105
+
106
+ ## Milestone releases (v2.1.0 – v2.27.0)
107
+
108
+ Subsequent minor releases expanded the library's capabilities while preserving stability, backward compatibility, and the zero-runtime-dependency architecture:
109
+
110
+ 1. **v2.3.0**: Modular accessible control primitives (`FeatureCard`, `ToggleControl`, `ChoiceControl`, `StepperControl`), UI states (`SearchCount`, `EmptyState`, `ErrorState`), profile previews (`ProfilePreviewCard`), and automated multi-registry release workflow.
111
+ 2. **v2.4.0 – v2.9.0**: Enhanced typography controls (`TextScaleController`, `LineHeightController`, `LetterSpacingController`, `WordSpacingController`, `ParagraphSpacingController`) with reflow protection, script-aware safety (Arabic cursive and Sinhala/Tamil clamping), and stepwise enlargement.
112
+ 3. **v2.10.0 – v2.14.0**: Reading aids (`ReadingGuideController`, `ReadingMaskController`, `BigCursorController`), decorative image hiding (`HideDecorativeImagesController`), video suppression (`HideVideosController`), and motion reduction (`ReduceMotionController`).
113
+ 4. **v2.15.0 – v2.19.0**: Accessible tooltips (`TooltipsController`), DOM heading & landmark navigator (`PageNavigatorController`), profile presets (`ProfilesController`), custom preset backup & export (`PresetsController`), non-destructive reader mode (`ReadingModeController`), and keyboard shortcuts with link explorer (`KeyboardShortcutsController`).
114
+ 5. **v2.20.0 (Issue #57, PR #134)**: User-initiated read-aloud TTS via Web Speech API with sentence-level chunking, pause/resume/stop, voice dropdown, rate and pitch steppers, floating player bar, sensitive field exclusions, and zero network transmission.
115
+ 6. **v2.21.0 (Issue #58, PR #136)**: Opt-in saturation and grayscale modes with chart/image advisory warnings, Windows forced-colors protection, and instant non-destructive reset.
116
+ 7. **v2.22.0 (Issue #59, PR #138)**: Accessible terminology dictionary dialog with 100% offline local static glossaries (`en`, `si`, `ta`), zero network calls by default, truthful responses, strict input sanitization, and focus restoration.
117
+ 8. **v2.23.0 (Issue #60, PR #140)**: Per-site feature-menu customization and reordering (`MenuCustomizationConfig`, `FeatureMenu`) with safe diagnostics and stable rerenders.
118
+ 9. **v2.24.0 (Issue #61, PR #141)**: Development-only integration diagnostics and test harness (`AccessibilityDiagnostics`, `DiagnosticsPanel`, `DiagnosticsInspector`, `DOM_CONTAINING_BLOCK_AUDIT`) with zero compliance claims, strict privacy guarantees, actionable fixes, and live fixture audits.
119
+ 10. **v2.25.0 (Issue #62, PR #143)**: Strictly opt-in, disabled-by-default local lifecycle callbacks (`onFeatureChange`, `onProfileApply`, `onReset`, `onAction`) with strictly reviewed payloads excluding page text, inputs, identifiers, and speech transcripts.
120
+ 11. **v2.26.0 (Issue #63, PR #145)**: Measured smart contrast research prototype (`SmartContrastController`, `smartContrast` engine) evaluating eligible text foreground luminance against computed backdrops with Porter-Duff compositing, LRU caching, unsupported backdrop detection, non-destructive restoration, and zero WCAG compliance claims.
121
+ 12. **v2.27.0 (Issue #64, in progress)**: Client-side voice navigation research prototype (`VoiceNavigationController`, `createVoiceNavigationSession`) with native Web Speech API recognition, 30s silence watchdog, background tab protection, zero audio storage, and complete keyboard alternatives.
@@ -0,0 +1,128 @@
1
+ # Non-Destructive Reading Mode (`ReadingModeController`)
2
+
3
+ The **Reading Mode** feature (`ReadingModeController`, key `readingMode`) provides a distraction-free, high-readability article view that extracts long-form text and media into an accessible reading modal without rewriting or unmounting the host application's React DOM tree.
4
+
5
+ ---
6
+
7
+ ## Architecture and Core Principles
8
+
9
+ ### 1. Strictly Non-Destructive Extraction
10
+
11
+ Traditional browser reader modes or third-party bookmarklets often replace or mutate the underlying document body, destroying client-side React component trees, losing form input state, breaking single-page application (SPA) routing, and detaching event listeners.
12
+
13
+ The `accessibility-plugin-react` implementation is **100% non-destructive**:
14
+
15
+ - The article extractor clones the candidate content element (`node.cloneNode(true)`) in memory.
16
+ - The original host DOM tree is **never rewritten, detached, or mutated**.
17
+ - Interactive host elements (such as counters, search fields, or form inputs) retain their exact state, event listeners, and focus history before, during, and after a reading session.
18
+
19
+ ### 2. Client-Side Confidentiality (Zero External Network Requests)
20
+
21
+ - Extraction, scoring, sanitization, and rendering execute purely in memory in the user's browser.
22
+ - **No external APIs, cloud extractors, or third-party web services** are contacted.
23
+ - Verified in automated test suites: zero calls to `fetch`, `XMLHttpRequest`, or `navigator.sendBeacon`.
24
+
25
+ ### 3. Sensitive Field and Non-Article Stripping
26
+
27
+ Even when articles contain nested widgets or forms, the extractor strictly sanitizes all disallowed and sensitive markup:
28
+
29
+ - **Sensitive inputs**: Password fields (`input[type="password"]`), credit card inputs (`[autocomplete*="cc-"]`), CSRF/hidden tokens, and sensitive data attributes (`[data-sensitive]`) are stripped completely.
30
+ - **Forms and interactive inputs**: `<form>`, `<input>`, `<select>`, `<textarea>`, and `<button>` elements are removed to prevent state ambiguity.
31
+ - **Boilerplate and navigation**: `<nav>`, `<header>`, `<footer>`, `<aside>`, modals/dialogs, cookie banners, advertisements, and social share widgets are filtered out.
32
+ - **Dangerous code and handlers**: `<script>`, `<iframe>`, `<object>`, `<embed>`, inline event handlers (`onclick`, etc.), and unsafe URL protocols (`javascript:`, `vbscript:`) are sanitized.
33
+
34
+ ### 4. Preservation of Semantic Structure
35
+
36
+ The extractor preserves meaningful article semantics:
37
+
38
+ - **Headings**: `h1` through `h6` retaining clear hierarchy.
39
+ - **Typography & Flow**: `p`, `blockquote`, `pre`, `code`, `time`, and emphasis (`strong`, `em`, `mark`).
40
+ - **Lists & Tables**: `ul`, `ol`, `li`, `table`, `thead`, `tbody`, `tr`, `th`, `td`.
41
+ - **Hyperlinks**: `a[href]` with safe URLs (`https://`, relative paths, anchor fragments), decorated with `target="_blank"` and `rel="noopener noreferrer"`.
42
+ - **Images and Media**: `img[src]` preserving `alt` text and dimensions, together with `<figure>` and `<figcaption>` captions.
43
+
44
+ ### 5. Honest Fallback and Failure Recovery
45
+
46
+ If a page lacks substantive readable content (e.g. an authentication screen, an empty dashboard, or a navigation-only hub):
47
+
48
+ - Extraction gracefully fails without throwing an unhandled exception or trapping the user in a blank view.
49
+ - The toggle state automatically reverts to `false`.
50
+ - A polite status announcement is communicated to assistive technology:
51
+ - English: _"No readable article content found on this page."_
52
+ - Sinhala: _"මෙම පිටුවෙහි කියවිය හැකි ලිපි අන්තර්ගතයක් හමු නොවීය."_
53
+ - Tamil: _"இப்பக்கத்தில் படிக்கக்கூடிய கட்டுரை உள்ளடக்கம் எதுவும் இல்லை."_
54
+ - Focus safely returns to the triggering control.
55
+
56
+ ---
57
+
58
+ ## User Experience and Controls
59
+
60
+ When reading mode is opened, it renders an accessible overlay dialog (`role="dialog"`, `aria-modal="true"`):
61
+
62
+ 1. **Toolbar Header**:
63
+ - **Article Meta**: Displays word count and estimated reading time (standard 200 words-per-minute baseline).
64
+ - **Theme Switcher**: Quick toggle between **Light**, **Sepia** (reduced blue light), and **Dark** modes.
65
+ - **Text Scaling**: Incremental zoom steppers (`A-` and `A+`) allowing text scaling between 90% and 160%.
66
+ - **Close Button**: Accessible `×` button with minimum 44×44px touch targets.
67
+ 2. **Focus Management & Keyboard Accessibility**:
68
+ - Focus is automatically placed inside the dialog when opened.
69
+ - Focus is trapped within interactive controls inside the dialog during the reading session (`Tab` / `Shift+Tab`).
70
+ - Pressing `Escape` immediately dismisses the reader view and restores focus to the invoking launcher/toggle button.
71
+ - Footer contains an explicit "Close Reading Mode" button for touch and keyboard users.
72
+
73
+ ---
74
+
75
+ ## Component Usage
76
+
77
+ ### Basic Compound Integration
78
+
79
+ ```tsx
80
+ import {
81
+ AccessibilityPlugin,
82
+ AccessibilityButton,
83
+ AccessibilityList,
84
+ ReadingModeController,
85
+ } from "accessibility-plugin-react";
86
+ import "accessibility-plugin-react/styles.css";
87
+
88
+ export function App() {
89
+ return (
90
+ <AccessibilityPlugin>
91
+ <AccessibilityButton />
92
+ <AccessibilityList>
93
+ <ReadingModeController />
94
+ </AccessibilityList>
95
+ </AccessibilityPlugin>
96
+ );
97
+ }
98
+ ```
99
+
100
+ ### Standalone Extractor Utility
101
+
102
+ For headless or custom reader implementations, the core extractor function is exported directly:
103
+
104
+ ```ts
105
+ import { extractArticleContent } from "accessibility-plugin-react";
106
+
107
+ const article = extractArticleContent(document.body);
108
+ if (article) {
109
+ console.log(`Title: ${article.title}`);
110
+ console.log(
111
+ `Words: ${article.wordCount} (~${article.readingTimeMinutes} min)`,
112
+ );
113
+ console.log(`Sanitized HTML: ${article.html}`);
114
+ } else {
115
+ console.log("No readable article content found on this page.");
116
+ }
117
+ ```
118
+
119
+ ---
120
+
121
+ ## Technical Specifications & Verification
122
+
123
+ - **Feature Key**: `readingMode` (Boolean, default: `false`).
124
+ - **Storage Compatibility**: Fully integrated with preference storage modes (`local`, `session`, `none`) and cleanly reset via `resetAll()`.
125
+ - **Test Matrix**:
126
+ - `tests/readingMode.test.ts`: Candidate scoring, sensitive field exclusion, protocol sanitization, image alt preservation, and offline execution.
127
+ - `tests/readingModeWidget.test.tsx`: Modal lifecycle, theme switching, Escape key dismissal, host React state persistence across open/close, and Sinhala/Tamil localization.
128
+ - `tests/browser/widget.spec.ts`: Playwright browser smoke test for live extraction, DOM isolation, theme switching, and host button interactivity.
@@ -0,0 +1,55 @@
1
+ # Read-Aloud Text-to-Speech (TTS) Architecture (A11Y-401)
2
+
3
+ The Read-Aloud Text-to-Speech module provides accessible, user-initiated text-to-speech reading for articles, page content, or user-selected text blocks.
4
+
5
+ ## Key Design Principles & WCAG Conformance
6
+
7
+ 1. **User Initiation Required**: Speech synthesis is strictly opt-in and initiated by the user clicking the "Read aloud" action button. It is never triggered automatically on page load, route transition, or profile activation (respecting WCAG 1.4.2 Audio Control).
8
+ 2. **Zero Network Transmission / Absolute Privacy**: All audio rendering is performed 100% locally by the browser's native Web Speech API (`window.speechSynthesis`). No text, transcripts, recordings, user identifiers, or telemetry leave the package.
9
+ 3. **Sensitive & Form Field Exclusions**: Form inputs (`<input>`, `<textarea>`, `<select>`), password fields (`input[type="password"]`), credit card inputs (`[autocomplete*="cc-"]`), elements marked `[data-sensitive="true"]`, elements marked `[aria-hidden="true"]` or `[hidden]`, and the plugin's own UI (`[data-arap-ui]`, `.arap-widget`, `.arap-panel`, etc.) are strictly excluded from speech extraction.
10
+ 4. **Resilient Sentence Chunking**: Continuous text is segmented into natural sentence and breath-group chunks (~60–180 characters) at punctuation boundaries (`. `, `! `, `? `, `; `, `\n`). This completely prevents the well-known Chromium bug where utterances exceeding 15 seconds stall indefinitely.
11
+ 5. **Lifecycle Safety & Keyboard Dismissal**:
12
+ - Pressing **Escape** immediately cancels playback and dismisses the floating mini-player bar.
13
+ - Speech synthesis is immediately aborted on `window.beforeunload`, `window.pagehide`, and `document.visibilitychange` (when hidden).
14
+ - Component unmounting safely tears down all speech synthesis instances and event listeners.
15
+ 6. **Accessible Controls & Touch Targets**:
16
+ - Every interactive control meets or exceeds the 44px by 44px touch target requirement (WCAG 2.5.5 / 2.5.8).
17
+ - Controls provide full status announcements via `role="status"` and `aria-live="polite"`.
18
+ - Floating mini-player bar renders via portal at viewport bottom with Play/Pause and Stop controls.
19
+
20
+ ---
21
+
22
+ ## API Summary
23
+
24
+ ### Component
25
+
26
+ ```tsx
27
+ import { ReadAloudController } from "accessibility-plugin-react";
28
+
29
+ <AccessibilityList>
30
+ <ReadAloudController />
31
+ </AccessibilityList>;
32
+ ```
33
+
34
+ ### Options & Props
35
+
36
+ ```ts
37
+ export interface ReadAloudControllerProps {
38
+ className?: string;
39
+ label?: string;
40
+ description?: string;
41
+ onStart?: () => void;
42
+ onEnd?: () => void;
43
+ onError?: (error: Error) => void;
44
+ }
45
+ ```
46
+
47
+ ### Core Functions & Types
48
+
49
+ - `isSpeechSynthesisSupported(): boolean`
50
+ - `getSpeechVoices(): SpeechSynthesisVoice[]`
51
+ - `subscribeSpeechVoices(callback: (voices: SpeechSynthesisVoice[]) => void): () => void`
52
+ - `extractReadAloudText(options?: { root?: Element | Document; selectionOnly?: boolean }): string`
53
+ - `getActiveSelectionText(): string`
54
+ - `splitTextIntoChunks(text: string, maxChunkLength?: number): string[]`
55
+ - `class ReadAloudSession`: Manages state machine (`idle`, `playing`, `paused`, `stopped`, `unsupported`), sequential chunk playback, rate, pitch, and voice overrides.