/** * Where the page is: its address's path (`/sessions/s3`, `/activity/events`), * kept with the History API. The hub answers every such path with the page * (src/web.rs), so an address can be shared, reloaded and opened in a tab. * * `here()` is that path without its slashes: `sessions/s3`, and '' for Home. */ /** The page's place: `sessions/s3`, `workspace`, '' for Home. */ export const here = (): string => location.pathname.replace(/^\/+|\/+$/g, '') /** A place's address, for a link: `sessions/s3` → `/sessions/s3`. */ export const href = (place: string): string => `/${place.replace(/^[#/]+/, '')}` /** * Go to a place. The change is told as a `popstate`, as the browser tells Back and * Forward, so one listener follows them all; going where the page is changes nothing. */ export function go(place: string, opts: {replace?: boolean} = {}) { const to = href(place) if (to === location.pathname) return if (opts.replace) history.replaceState(null, '', to) else history.pushState(null, '', to) window.dispatchEvent(new PopStateEvent('popstate')) } /** An old `#`-address (`#sessions/s3`, `#/setup/`) as the path it is now. */ export function fromHash(hash: string): string | null { const h = hash.replace(/^#\/?/, '') return h ? href(h) : null } /** * Start following the address: an old `#` link (a bookmark, a notification, a setup * link sent before) is rewritten to its path, and a click on a link to a place of * the page goes there in this window instead of loading the page again. A link * opened in another tab (a modifier key, the middle button, `target`) is left to * the browser. */ export function startRouting() { const old = fromHash(location.hash) if (old) history.replaceState(null, '', old + location.search) document.addEventListener('click', (e) => { if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return const a = (e.target as Element | null)?.closest?.('a') if (!a || (a.target && a.target !== '_self') || a.hasAttribute('download')) return const url = new URL(a.href, location.href) if (url.origin !== location.origin || url.pathname.startsWith('/v1/')) return e.preventDefault() go(url.pathname) }) }