Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions apps/web/src/hooks/useCommitOnBlur.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vite-plus/test";

import { shouldBlurCommitOnKeyDown } from "./useCommitOnBlur";

function keyEvent(overrides: {
key?: string;
keyCode?: number;
isComposing?: boolean;
}): Parameters<typeof shouldBlurCommitOnKeyDown>[0] {
return {
key: overrides.key ?? "Enter",
keyCode: overrides.keyCode ?? 13,
nativeEvent: { isComposing: overrides.isComposing ?? false },
};
}

describe("shouldBlurCommitOnKeyDown", () => {
it("commits on Enter after composition has finished", () => {
expect(shouldBlurCommitOnKeyDown(keyEvent({ key: "Enter" }))).toBe(true);
});

it("keeps focus during IME composition", () => {
expect(shouldBlurCommitOnKeyDown(keyEvent({ key: "Enter", isComposing: true }))).toBe(false);
expect(shouldBlurCommitOnKeyDown(keyEvent({ key: "Enter", keyCode: 229 }))).toBe(false);
});

it("ignores other keys", () => {
expect(shouldBlurCommitOnKeyDown(keyEvent({ key: "Escape" }))).toBe(false);
});
});
16 changes: 12 additions & 4 deletions apps/web/src/hooks/useCommitOnBlur.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ import { type ChangeEvent, type KeyboardEvent, useState } from "react";
* const bag = useCommitOnBlur(instance.displayName ?? "", (next) => {...});
* <Input {...bag} placeholder="e.g. Work" />
*/
export function shouldBlurCommitOnKeyDown(event: {
readonly key: string;
readonly keyCode: number;
readonly nativeEvent: { readonly isComposing?: boolean };
}): boolean {
if (event.nativeEvent.isComposing || event.keyCode === 229) return false;
return event.key === "Enter";
}

export function useCommitOnBlur(value: string, onCommit: (next: string) => void) {
const [draft, setDraft] = useState<string | null>(null);

Expand All @@ -34,10 +43,9 @@ export function useCommitOnBlur(value: string, onCommit: (next: string) => void)
}
},
onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
event.preventDefault();
(event.target as HTMLInputElement).blur();
}
if (!shouldBlurCommitOnKeyDown(event)) return;
event.preventDefault();
(event.target as HTMLInputElement).blur();
},
};
}
Loading