Hash routes with keyboard shortcuts
Hash routes with a parameter, a keyboard shortcut per view, and the new view announced.
Apache-2.0Runs on this page
Package: @awacloud/fw
Three hash-routed views plus a parameterised one, a keyboard shortcut for each, and the new view's heading announced to assistive technology.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
A small app served as static files: the URL hash selects the view, links are ordinary anchors, the back button works, and power users get modifier shortcuts that do not depend on the keyboard layout and do not collide with the browser's own.
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - Add a
ROUTE.on(name, pattern, handler)line per view;:paramcaptures a segment,*restthe tail.
What it shows
route.on(name, pattern, fn),route.start(),route.go(path)(resolvingfalsewhen nothing matches),route.active()androute.current().keybindings.create({ target: document }),bind('Ctrl+Shift+2', fn, { preventDefault: true })andattach(); digits and letters match by physical key, so the shortcut is the same on every layout.- After each view change, focus moves to the new heading (
tabindex="-1", focusable by script only) anda11y.announce(heading)speaks it, since the router itself does neither; the first view at load keeps the focus where the browser put it. route.onneeds its pattern: a name alone is not a route.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { route } from '@awacloud/fw/dom/utils/route.js';
import { keybindings } from '@awacloud/fw/dom/utils/keybindings.js';
import { a11y } from '@awacloud/fw/dom/utils/a11y.js';
fw.runtime.registerAllDeep([route, keybindings, a11y]);
export const ROUTE = fw.runtime.resolve('route');
const A11Y = fw.runtime.resolve('a11y');
const title = /** @type {HTMLElement} */ (document.getElementById('view-title'));
const body = /** @type {HTMLElement} */ (document.getElementById('view-body'));
/** False until the first view is shown: the page's first render must not steal the focus. */
let started = false;
/**
* Render a view, move the focus to its heading and announce it: a hash
* router does neither on its own, while a real page load would.
* @param {string} heading
* @param {string} text
*/
export function showView(heading, text) {
title.textContent = heading;
body.textContent = text;
if (started) title.focus(); // the heading has tabindex="-1": focusable by script only
A11Y.announce(heading, 'polite');
}
// Every route has a name, a pattern (`:param` captures a segment) and a handler.
ROUTE.on('home', '/', () => showView('Home', 'Pick a view from the menu, or press Ctrl+Shift+1, 2 or 3.'));
ROUTE.on('about', '/about', () => showView('About', 'A three-view page routed by the URL hash.'));
ROUTE.on('contact', '/contact', () => showView('Contact', 'Write to hello at example dot org.'));
ROUTE.on('docs', '/docs/:topic', (params) => {
showView(`Docs: ${params.topic}`, `You asked for the "${params.topic}" topic.`);
});
/**
* Navigate; an unknown path leaves no active route, so the page says so.
* @param {string} path
* @returns {Promise<boolean>} whether a route matched
*/
export async function go(path) {
const matched = await ROUTE.go(path);
if (!matched) showView('Not found', `No view at ${path}.`);
return matched;
}
// Keyboard shortcuts: modifier-based (WCAG 2.1.4) and matched on the physical
// key so they survive keyboard layouts. Check yours against the browsers and
// screen readers your users have: no combination is free everywhere.
export const keys = fw.runtime.resolve('keybindings').create({ target: document });
keys.bind('Ctrl+Shift+1', () => go('/'), { preventDefault: true });
keys.bind('Ctrl+Shift+2', () => go('/about'), { preventDefault: true });
keys.bind('Ctrl+Shift+3', () => go('/contact'), { preventDefault: true });
keys.attach();
// Install the hashchange listener and dispatch the current hash once.
ROUTE.start();
if (!ROUTE.active()) await go('/');
started = true;index.html
<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fw · Hash routes with keyboard shortcuts</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Hash routes with keyboard shortcuts</h1>
<nav aria-label="Views">
<a href="#/">Home</a> <kbd>Ctrl+Shift+1</kbd> ·
<a href="#/about">About</a> <kbd>Ctrl+Shift+2</kbd> ·
<a href="#/contact">Contact</a> <kbd>Ctrl+Shift+3</kbd> ·
<a href="#/docs/routing">Docs: routing</a>
</nav>
<section aria-labelledby="view-title">
<h2 id="view-title" tabindex="-1"></h2>
<p id="view-body"></p>
</section>
</main>
</body>
</html>