| 1 |
import { Location } from 'swup'; |
| 2 |
import { AnnouncementTranslations, Options } from './index.js'; |
| 3 |
import { createElement, parseTemplate } from './util.js'; |
| 4 |
|
| 5 |
export class Announcer { |
| 6 |
id: string = 'swup-announcer'; |
| 7 |
style: string = `position:absolute;top:0;left:0;clip:rect(0 0 0 0);clip-path:inset(50%);overflow:hidden;white-space:nowrap;word-wrap:normal;width:1px;height:1px;`; |
| 8 |
region: HTMLElement; |
| 9 |
|
| 10 |
constructor() { |
| 11 |
this.region = this.getRegion() ?? this.createRegion(); |
| 12 |
} |
| 13 |
|
| 14 |
getRegion(): HTMLElement | null { |
| 15 |
return document.getElementById(this.id); |
| 16 |
} |
| 17 |
|
| 18 |
createRegion(): HTMLElement { |
| 19 |
const liveRegion = createElement( |
| 20 |
`<p aria-live="assertive" aria-atomic="true" id="${this.id}" style="${this.style}"></p>` |
| 21 |
); |
| 22 |
document.body.appendChild(liveRegion); |
| 23 |
return liveRegion; |
| 24 |
} |
| 25 |
|
| 26 |
announce(message: string, delay: number = 0): Promise<void> { |
| 27 |
return new Promise((resolve) => { |
| 28 |
setTimeout(() => { |
| 29 |
// Make each message unique to allow reading identical page titles twice in a row |
| 30 |
if (this.region.textContent === message) { |
| 31 |
message = `${message}.`; |
| 32 |
} |
| 33 |
// Clear before announcing |
| 34 |
this.region.textContent = ''; |
| 35 |
this.region.textContent = message; |
| 36 |
|
| 37 |
resolve(); |
| 38 |
}, delay); |
| 39 |
}); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
export type PageAnnouncementOptions = Pick<Options, 'headingSelector' | 'announcements'>; |
| 44 |
|
| 45 |
export function getPageAnnouncement({ |
| 46 |
headingSelector = 'h1', |
| 47 |
announcements = {} |
| 48 |
}: PageAnnouncementOptions): string | undefined { |
| 49 |
const lang = document.documentElement.lang || '*'; |
| 50 |
const { href, url, pathname: path } = Location.fromUrl(window.location.href); |
| 51 |
|
| 52 |
const templates = |
| 53 |
(announcements as AnnouncementTranslations)[lang] ?? |
| 54 |
(announcements as AnnouncementTranslations)['*'] ?? |
| 55 |
announcements; |
| 56 |
if (typeof templates !== 'object') return; |
| 57 |
|
| 58 |
// Look for first heading on page |
| 59 |
const headingEl = document.querySelector(headingSelector); |
| 60 |
if (!headingEl) { |
| 61 |
console.warn(`SwupA11yPlugin: No main heading (${headingSelector}) found on new page`); |
| 62 |
} |
| 63 |
|
| 64 |
// Get page heading from aria attribute or text content |
| 65 |
const heading = headingEl?.getAttribute('aria-label') || headingEl?.textContent; |
| 66 |
|
| 67 |
// Fall back to document title, then url if no title was found |
| 68 |
const title = heading || document.title || parseTemplate(templates.url, { href, url, path }); |
| 69 |
|
| 70 |
// Replace {variables} in template |
| 71 |
return parseTemplate(templates.visit, { title, href, url, path }); |
| 72 |
} |