Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useCommitOnBlur.ts

49 lines1.5 KB

1import { type ChangeEvent, type KeyboardEvent, useEffect, useRef, useState } from "react";
2​
3/**
4 * Buffer text input locally so keystrokes don't cause a settings-wide
5 * re-render (and optionally a server RPC round-trip) on every character.
6 * `onCommit` fires on blur and on Enter.
7 *
8 * The draft resynchronizes from the upstream `value` only when the input
9 * is not focused, so an external push (e.g. an optimistic settings
10 * update from the user's own commit, or a reset to defaults) doesn't
11 * clobber an in-progress edit.
12 *
13 * Returns a bag of props that should be spread onto an `<Input>`:
14 *
15 * const bag = useCommitOnBlur(instance.displayName ?? "", (next) => {...});
16 * <Input {...bag} placeholder="e.g. Work" />
17 */
18export function useCommitOnBlur(value: string, onCommit: (next: string) => void) {
19 const [draft, setDraft] = useState(value);
20 const focusedRef = useRef(false);
21​
22 useEffect(() => {
23 if (!focusedRef.current) {
24 setDraft(value);
25 }
26 }, [value]);
27​
28 return {
29 value: draft,
30 onChange: (event: ChangeEvent<HTMLInputElement>) => {
31 setDraft(event.target.value);
32 },
33 onFocus: () => {
34 focusedRef.current = true;
35 },
36 onBlur: () => {
37 focusedRef.current = false;
38 if (draft !== value) {
39 onCommit(draft);
40 }
41 },
42 onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => {
43 if (event.key === "Enter") {
44 event.preventDefault();
45 (event.target as HTMLInputElement).blur();
46 }
47 },
48 };