Svelte action that does things when keys are pressed:
import type { Action } from "svelte/action"
export const keys: Action<HTMLElement, boolean> = (node, active?: boolean) => {
function listener(event: KeyboardEvent & { currentTarget: EventTarget & Window }) {
if(!active){ // <- always initial value
return;
}
const target = event.target as HTMLElement
if(target instanceof HTMLInputElement){
return;
}
// do things with node...
}
window.addEventListener("keydown", listener, true)
return {
destroy() {
window.removeEventListener("keydown", listener, true)
}
}
}
it’s used in components like this:
<div use:keys={someLocalStateVar} ...
Problem is that the active
argument which corresponds to someLocalStateVar
does not change when the state changes.
Is there a way to make it reactive in the action?