Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions lib/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,17 @@ export class Router {
private prefetched = new Set<string>();
private observer: IntersectionObserver;

// Announces the current page title to screen readers
private announcer: HTMLDivElement;

constructor(public opts?: FlamethrowerOptions) {
this.opts = { ...defaultOpts, ...(opts ?? {}) };

if (window?.history) {
document.addEventListener('click', (e) => this.onClick(e));
window.addEventListener('popstate', (e) => this.onPop(e));
this.prefetch();
this.announcePageChanged();
} else {
console.warn(
'flamethrower router not supported in this browser or environment'
Expand Down Expand Up @@ -214,6 +218,8 @@ export class Router {

window.dispatchEvent(new CustomEvent('flamethrower:router:end'));

this.announcePageChanged();

// delay for any js rendered links
setTimeout(() => {
this.prefetch();
Expand All @@ -228,4 +234,21 @@ export class Router {
return false;
}
}
/**
* Announces the current page title to screen readers
*/
private announcePageChanged(): void {
if (!this.announcer) {
this.announcer = document.createElement('div');
this.announcer.setAttribute('id', 'flamethrower-announcer');
this.announcer.setAttribute('aria-live', 'assertive');
this.announcer.setAttribute('aria-atomic', 'true');
this.announcer.setAttribute(
'style',
'position: absolute; left: 0; top: 0; clip: rect(0 0 0 0); clip-path: inset(50%); overflow: hidden; white-space: nowrap; width: 1px; height: 1px'
);
}
this.announcer.textContent = document.title;
document.body.appendChild(this.announcer);
}
}
15 changes: 14 additions & 1 deletion test/main.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,20 @@ test('prefetching works', async ({ page }) => {

// ensure no duplicates
preAbout = page.locator('link[href="/about"]');
await expect(preAbout).toHaveCount(1)
await expect(preAbout).toHaveCount(1);


});

test('page change announcer works', async ({ page }) => {
await page.goto('http://localhost:3000');

const announcer = page.locator('#flamethrower-announcer');

await expect(announcer).toHaveText('Flamethrower');

const about = page.locator('#about');
await about.click();

await expect(announcer).toHaveText('About');
});