82 lines
2.3 KiB
TypeScript
82 lines
2.3 KiB
TypeScript
"use client";
|
|
|
|
import {
|
|
useActionState,
|
|
useRef,
|
|
useEffect,
|
|
useState,
|
|
useCallback,
|
|
} from "react";
|
|
import { updateNameAction, type UpdateNameState } from "./actions";
|
|
|
|
const initialState: UpdateNameState = null;
|
|
|
|
export function EditableName({ currentName }: Readonly<{ currentName: string }>) {
|
|
const [editing, setEditing] = useState(false);
|
|
const [state, action, pending] = useActionState(
|
|
updateNameAction,
|
|
initialState,
|
|
);
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
|
|
// Focus input when entering edit mode
|
|
useEffect(() => {
|
|
if (editing) {
|
|
inputRef.current?.focus();
|
|
inputRef.current?.select();
|
|
}
|
|
}, [editing]);
|
|
|
|
const handleEdit = useCallback(() => setEditing(true), []);
|
|
|
|
if (!editing) {
|
|
return (
|
|
<div className="mt-3 flex items-center gap-3">
|
|
<h2 className="text-xl font-semibold text-neutral-900">
|
|
{currentName}
|
|
</h2>
|
|
<button
|
|
type="button"
|
|
onClick={handleEdit}
|
|
className="rounded-md px-2 py-1 text-xs font-medium text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900"
|
|
>
|
|
Edit
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<form action={action} className="mt-3">
|
|
<div className="flex items-start gap-2">
|
|
<input
|
|
ref={inputRef}
|
|
name="name"
|
|
type="text"
|
|
defaultValue={currentName}
|
|
required
|
|
maxLength={50}
|
|
className="w-64 rounded-lg border border-neutral-300 bg-white px-3 py-1.5 text-lg font-semibold text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
|
/>
|
|
<button
|
|
type="submit"
|
|
disabled={pending}
|
|
className="rounded-lg bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
|
>
|
|
{pending ? "..." : "Save"}
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => setEditing(false)}
|
|
className="rounded-lg border border-neutral-300 px-3 py-1.5 text-sm font-medium text-neutral-700 transition hover:bg-neutral-50"
|
|
>
|
|
Cancel
|
|
</button>
|
|
</div>
|
|
{state && "error" in state && (
|
|
<p className="mt-1 text-xs text-red-600">{state.error}</p>
|
|
)}
|
|
</form>
|
|
);
|
|
}
|