The @svelte-put/shortcut package provides a Svelte action called use:shortcut that allows you to easily add keyboard shortcut event listeners to elements or the window.
To use it, import the shortcut action and pass a configuration object to the use: directive. A common pattern is to apply it to <svelte:window /> to listen for global shortcuts. The configuration object requires a trigger property which defines the key, optional modifiers, and the callback function to execute when the shortcut is pressed.
<script lang="ts">
import { shortcut, type ShortcutEventDetail } from '@svelte-put/shortcut';
function handleK(detail: ShortcutEventDetail) {
// detail.node is the element the action is attached to
console.log('attached node:', detail.node);
// detail.trigger contains the original configuration
console.log('original trigger config:', detail.trigger);
}
</script>
<svelte:window
use:shortcut={{
trigger: {
key: 'k',
modifier: ['ctrl', 'meta'],
callback: handleK,
},
}}
/>