Skip to content

Commit

Permalink
Merge pull request #18 from OneBusAway/escape
Browse files Browse the repository at this point in the history
Closes the StopPane when the Escape key is pressed on the keyboard
  • Loading branch information
aaronbrethorst authored Jul 6, 2024
2 parents 36fe3d9 + 5a8528e commit f9e0e24
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/components/oba/StopPane.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { FontAwesomeIcon } from '@fortawesome/svelte-fontawesome';
import { faX } from '@fortawesome/free-solid-svg-icons';
import { createEventDispatcher } from 'svelte';
import { keybinding } from '$lib/keybinding';
import ArrivalDeparture from '../ArrivalDeparture.svelte';
export let stop;
Expand Down Expand Up @@ -71,7 +72,7 @@
<h1 class="text-lg text-white">Routes: {stop.name}</h1>
</div>
<div class="absolute -right-4 -top-6">
<button type="button" on:click={closePane}>
<button type="button" on:click={closePane} use:keybinding={{ code: 'Escape' }}>
<FontAwesomeIcon icon={faX} class="text-black dark:text-white" />
<span class="sr-only">Close</span>
</button>
Expand Down
40 changes: 40 additions & 0 deletions src/lib/keybinding.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Create a keybinding for an HTML element.
* @example
* <button use:keybinding={{code: 'Escape'}} on:click={yourEventHere}>
* Triggers a click on the button when the Escape key is pressed.
* </button>
* @param {HTMLElement} node The HTML element to bind to.
* @param {Object} params The keybinding parameters. See the example above.
* @returns {Object} An object with the update and destroy methods.
*/
export const keybinding = (node, params) => {
let handler;
const removeHandler = () => window.removeEventListener('keydown', handler);
const setHandler = () => {
removeHandler();
if (!params) {
return;
}

handler = (e) => {
if (
!!params.alt != e.altKey ||
!!params.shift != e.shiftKey ||
!!params.control != (e.ctrlKey || e.metaKey) ||
params.code != e.code
)
return;
e.preventDefault();
params.callback ? params.callback() : node.click();
};
window.addEventListener('keydown', handler);
};

setHandler();

return {
update: setHandler,
destroy: removeHandler
};
};

0 comments on commit f9e0e24

Please sign in to comment.