Skip to content

Commit

Permalink
fix pin input issues and add new test
Browse files Browse the repository at this point in the history
  • Loading branch information
huntabyte committed Nov 1, 2024
1 parent 33be869 commit b49832a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
17 changes: 17 additions & 0 deletions packages/bits-ui/src/lib/bits/pin-input/pin-input.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,25 @@ class PinInputRootState {
});
}

keysToIgnore = [
"Backspace",
"Delete",
"ArrowLeft",
"ArrowRight",
"ArrowUp",
"ArrowDown",
"Home",
"End",
"Escape",
"Enter",
"Tab",
"Shift",
"Control",
];

#onkeydown = (e: KeyboardEvent) => {
const key = e.key;
if (this.keysToIgnore.includes(key)) return;
if (key && this.#regexPattern && !this.#regexPattern.test(key)) {
e.preventDefault();
}
Expand Down
21 changes: 20 additions & 1 deletion packages/tests/src/tests/pin-input/pin-input.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { render, waitFor } from "@testing-library/svelte/svelte5";
import { axe } from "jest-axe";
import { describe, it, vi } from "vitest";
import type { PinInput } from "bits-ui";
import { type PinInput, REGEXP_ONLY_DIGITS } from "bits-ui";
import { getTestKbd, setupUserEvents } from "../utils.js";
import PinInputTest from "./pin-input-test.svelte";

Expand Down Expand Up @@ -153,4 +153,23 @@ describe("pin Input", () => {
expect(mockComplete).toHaveBeenCalledTimes(1);
expect(mockComplete).toHaveBeenCalledWith("123456");
});

it("should ignore keys that do not match the pattern", async () => {
const { user, hiddenInput } = setup({
pattern: REGEXP_ONLY_DIGITS,
});

await user.click(hiddenInput);
await user.keyboard("123");
expect(hiddenInput).toHaveValue("123");

await user.keyboard(kbd.BACKSPACE);
await user.keyboard(kbd.BACKSPACE);
await user.keyboard(kbd.BACKSPACE);
expect(hiddenInput).toHaveValue("");
await user.keyboard("$");
expect(hiddenInput).toHaveValue("");
await user.keyboard("1$");
expect(hiddenInput).toHaveValue("1");
});
});

0 comments on commit b49832a

Please sign in to comment.