Skip to content

Commit

Permalink
feat(front): adds focusTrap action and implementation on PageNav (#711)
Browse files Browse the repository at this point in the history
Closes: #711
  • Loading branch information
dgrebb committed Oct 11, 2023
1 parent 71abcfc commit 4562e1e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
32 changes: 32 additions & 0 deletions front/src/lib/_utils/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Traps the focus within the given node when enabled.
*
* @param {Node} node - The node within which to trap the focus.
* @param {boolean} enabled - Whether the focus trap is enabled.
* @returns {boolean} - Returns false if the focus trap is not enabled.
*/
export const focusTrap = (node, enabled) => {
if (!enabled) return false;
var focusableEls = node.querySelectorAll(
'a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled])'
);
var firstFocusableEl = focusableEls[0];
var lastFocusableEl = focusableEls[focusableEls.length - 1];

node.addEventListener('keydown', function (e) {
var isTab = e.key === 'Tab' || e.keyCode === 9;
var isEsc = e.key === 'Escape' || e.keyCode === 27;
if (isTab) {
var activeElement = document.activeElement;
var focusElement = e.shiftKey ? firstFocusableEl : lastFocusableEl;
if (activeElement === focusElement) {
e.preventDefault();
(e.shiftKey ? lastFocusableEl : firstFocusableEl).focus();
}
} else if (isEsc) {
const miniNavToggle = document.getElementById('page-navigation-checkbox');
miniNavToggle.checked = false;
miniNavToggle.focus();
}
});
};
4 changes: 2 additions & 2 deletions front/src/lib/components/PageNav.svelte
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<script>
import { onMount } from 'svelte';
import TableOfContents from '@components/content/TableOfContents.svelte';
import ClosePageNav from '@components/icons/ClosePageNav.svelte';
import { categoryClick, relatedClick } from '@utils/uiHelpers.js';
import { focusTrap } from '@utils/actions.js';
import ListIcon from '~icons/gg/list';
export let contents = false;
Expand Down Expand Up @@ -44,7 +44,7 @@
<ClosePageNav classList="page-navigation-close" />
</label>
{/if}
<div class="page-navigation-list">
<div class="page-navigation-list" use:focusTrap={mini}>
{#if contents && contents.length}
<h2>Table of Contents</h2>
<TableOfContents
Expand Down

0 comments on commit 4562e1e

Please sign in to comment.