Debian Codegraph @

a11y-plugin/src/index.ts

raw
1 import { HookHandler, Visit } from 'swup';
2 import Plugin from '@swup/plugin';
3
4 import 'focus-options-polyfill';
5
6 import { Announcer, getPageAnnouncement } from './announcements.js';
7 import { focusAutofocusElement, focusElement } from './focus.js';
8 import { prefersReducedMotion } from './util.js';
9
10 export interface VisitA11y {
11 /** How to announce the new content after it inserted */
12 announce: string | false | undefined;
13 /** The element to focus after the content is replaced */
14 focus: string | false;
15 }
16
17 declare module 'swup' {
18 export interface Visit {
19 /** Accessibility settings for this visit */
20 a11y: VisitA11y;
21 }
22 export interface HookDefinitions {
23 'content:announce': undefined;
24 'content:focus': undefined;
25 }
26 export interface Swup {
27 /**
28 * Announce something programmatically
29 */
30 announce?: SwupA11yPlugin['announce'];
31 }
32 }
33
34 /** Templates for announcements of the new page content. */
35 export type Announcements = {
36 /** How to announce the new page. */
37 visit: string;
38 /** How to read a page url. Used as fallback if no heading was found. */
39 url: string;
40 };
41
42 /** Translations of announcements, keyed by language. */
43 export type AnnouncementTranslations = {
44 [lang: string]: Announcements;
45 };
46
47 export type Options = {
48 /** The selector for finding headings inside the main content area. */
49 headingSelector: string;
50 /** Whether to skip animations for users that prefer reduced motion. */
51 respectReducedMotion: boolean;
52 /** How to announce the new page title and url. */
53 announcements: Announcements | AnnouncementTranslations;
54 /** Whether to focus elements with an [autofocus] attribute after navigation. */
55 autofocus: boolean;
56 };
57
58 export default class SwupA11yPlugin extends Plugin {
59 name = 'SwupA11yPlugin';
60
61 requires = { swup: '>=4' };
62
63 defaults: Options = {
64 headingSelector: 'h1',
65 respectReducedMotion: true,
66 autofocus: false,
67 announcements: {
68 visit: 'Navigated to: {title}',
69 url: 'New page at {url}'
70 }
71 };
72
73 options: Options;
74
75 /**
76 * The announcer instance for reading new page content.
77 */
78 announcer: Announcer;
79
80 /**
81 * The delay before announcing new page content.
82 * Why 100ms? see research at https://github.com/swup/a11y-plugin/pull/50
83 */
84 announcementDelay: number = 100;
85
86 /**
87 * The selector for the main content area of the page, to focus after navigation.
88 */
89 rootSelector: string = 'body';
90
91 constructor(options: Partial<Options> = {}) {
92 super();
93
94 // Merge default options with user defined options
95 this.options = { ...this.defaults, ...options };
96
97 // Create announcer instance for announcing new page content
98 this.announcer = new Announcer();
99 }
100
101 mount() {
102 // Prepare new hooks
103 this.swup.hooks.create('content:announce');
104 this.swup.hooks.create('content:focus');
105
106 // Prepare visit by adding a11y settings to visit object
107 this.before('visit:start', this.prepareVisit);
108
109 // Mark page as busy during transitions
110 this.on('visit:start', this.markAsBusy);
111 this.on('visit:end', this.unmarkAsBusy);
112
113 // Focus new page content after visit completes
114 this.on('visit:end', this.focusContent);
115
116 // Announce new page title after visit completes
117 this.on('visit:end', this.announceContent);
118
119 // Move focus start point when clicking on-page anchors
120 this.on('scroll:anchor', this.handleAnchorScroll);
121
122 // Disable transition and scroll animations if user prefers reduced motion
123 this.before('visit:start', this.disableAnimations);
124 this.before('link:self', this.disableAnimations);
125 this.before('link:anchor', this.disableAnimations);
126
127 // Announce something programmatically
128 this.swup.announce = this.announce.bind(this);
129 }
130
131 unmount() {
132 this.swup.announce = undefined;
133 }
134
135 async announce(message: string): Promise<void> {
136 await this.announcer.announce(message);
137 }
138
139 markAsBusy() {
140 document.documentElement.setAttribute('aria-busy', 'true');
141 }
142
143 unmarkAsBusy() {
144 document.documentElement.removeAttribute('aria-busy');
145 }
146
147 prepareVisit(visit: Visit) {
148 visit.a11y = {
149 announce: undefined,
150 focus: this.rootSelector
151 };
152 }
153
154 announceContent(visit: Visit) {
155 this.swup.hooks.callSync('content:announce', visit, undefined, (visit) => {
156 // Allow customizing announcement before this hook
157 if (typeof visit.a11y.announce === 'undefined') {
158 visit.a11y.announce = this.getPageAnnouncement();
159 }
160
161 if (!visit.a11y.announce) return;
162
163 this.announcer.announce(visit.a11y.announce, this.announcementDelay);
164 });
165 }
166
167 focusContent(visit: Visit) {
168 this.swup.hooks.callSync('content:focus', visit, undefined, (visit) => {
169 if (!visit.a11y.focus) return;
170
171 // Found and focused [autofocus] element? Return early
172 if (this.options.autofocus && focusAutofocusElement() === true) return;
173
174 // Otherwise, find and focus actual content container
175 focusElement(visit.a11y.focus);
176 });
177 }
178
179 handleAnchorScroll: HookHandler<'scroll:anchor'> = (visit, { hash }) => {
180 const anchor = this.swup.getAnchorElement(hash);
181 if (anchor instanceof HTMLElement) {
182 focusElement(anchor);
183 }
184 };
185
186 getPageAnnouncement(): string | undefined {
187 const { headingSelector, announcements } = this.options;
188 return getPageAnnouncement({ headingSelector, announcements });
189 }
190
191 disableAnimations(visit: Visit) {
192 if (this.options.respectReducedMotion && prefersReducedMotion()) {
193 visit.animation.animate = false;
194 // @ts-expect-error: animate is undefined unless Scroll Plugin installed
195 visit.scroll.animate = false;
196 }
197 }
198 }