Skip to content

Commit

Permalink
fix(focus-key): action should reflection updated options (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
metonym authored Feb 8, 2022
1 parent cc69416 commit 9dc48a1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 6 deletions.
24 changes: 24 additions & 0 deletions demo/FocusKeyActionUpdates.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<script>
import { focusKey } from "svelte-focus-key";
let selectText = false;
let key = "k";
let value = "text";
</script>

<input
use:focusKey={{ key, selectText }}
placeholder={'Press "k" to focus'}
bind:value
/>

<div>
<button
on:click={() => {
key = key === "/" ? "k" : "/";
selectText = !selectText;
}}
>
Toggle options
</button>
</div>
14 changes: 10 additions & 4 deletions src/focus-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ export function focusKey(
element: HTMLInputElement | HTMLTextAreaElement,
options: FocusKeyOptions = {}
) {
const key = options.key || "/";
const keys = Array.isArray(key) ? key : [key];
const selectText = options.selectText === true;
let key = options.key || "/";
let keys = Array.isArray(key) ? key : [key];
let selectText = options.selectText === true;

const keydown = (e: KeyboardEvent) => {
if (
keys.some((key) => key === e.key) &&
element != null &&
document.activeElement?.tagName === "BODY" &&
document.activeElement !== element
) {
Expand All @@ -26,6 +26,12 @@ export function focusKey(
document.body.addEventListener("keydown", keydown);

return {
update(options: FocusKeyOptions = {}) {
key = options.key || "/";
keys = Array.isArray(key) ? key : [key];
selectText = options.selectText === true;
element.selectionStart = element.selectionEnd;
},
destroy() {
document.body.removeEventListener("keydown", keydown);
},
Expand Down
3 changes: 1 addition & 2 deletions tests/focus-key.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { tick } from "svelte";
import { test, expect, describe, afterEach } from "vitest";
import userEvent from "@testing-library/user-event";
import { focusKey } from "../src";
Expand Down Expand Up @@ -49,7 +48,7 @@ describe("focus-key", () => {
expect(document.activeElement).not.toEqual(input);
});

test("Multiple focus keys", async () => {
test("Multiple focus keys", () => {
document.body.innerHTML = `
<input />
`;
Expand Down

0 comments on commit 9dc48a1

Please sign in to comment.