Skip to content

Commit

Permalink
Added basic focus functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
scmmmh committed Sep 7, 2023
1 parent e5b63f7 commit 78e3c35
Showing 1 changed file with 52 additions and 3 deletions.
55 changes: 52 additions & 3 deletions museum_map/server/frontend/src/simple-svelte-router/Route.svelte
Original file line number Diff line number Diff line change
@@ -1,12 +1,44 @@
<script lang="ts">
import { onDestroy } from "svelte";
import { onDestroy, tick } from "svelte";
import { location } from "./store";
import type { RouterLocation } from "./store";
export let path: string;
let pathComponents: string[] = [];
let matches = false;
let startMarker: HTMLElement | null = null;
let endMarker: HTMLElement | null = null;
/**
* Focus on the first hX element we find
*/
function focusElement() {
console.log(startMarker, endMarker);
if (startMarker && endMarker) {
let element = startMarker.nextElementSibling as HTMLElement;
let found = false;
while (element !== null && element !== endMarker) {
console.log(element);
const heading = element.querySelector("h1,h2,h3,h4,h5,h6");
if (heading !== null) {
(heading as HTMLElement).setAttribute("tabindex", "-1");
(heading as HTMLElement).focus();
found = true;
break;
}
element = element.nextElementSibling as HTMLElement;
}
if (!found) {
console.error("No heading found for post-navigation focus");
}
}
}
/**
* Check if the current location matches the path for this Route
*
* @param location The current location
*/
function checkMatch(location: RouterLocation) {
matches = true;
for (let idx = 0; idx < pathComponents.length; idx++) {
Expand All @@ -28,18 +60,35 @@
}
}
/**
* Process a location change.
*
* First check for matches and if there is one, then call the focus handling.
*
* @param location The current location
*/
function process(location: RouterLocation) {
const oldMatches = matches;
checkMatch(location);
if (!oldMatches && matches) {
tick().then(focusElement);
}
}
$: {
pathComponents = path.substring(1).split("/");
checkMatch($location);
process($location);
}
const locationUnsubscribe = location.subscribe((location) => {
checkMatch(location);
process(location);
});
onDestroy(locationUnsubscribe);
</script>

{#if matches}
<div bind:this={startMarker} />
<slot />
<div bind:this={endMarker} />
{/if}

0 comments on commit 78e3c35

Please sign in to comment.