Spaces:
Sleeping
Sleeping
File size: 1,289 Bytes
1dd9186 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import { useEffect, useRef, useState } from 'react';
function toDraftValue(value, fallback = '') {
if (value === undefined || value === null) {
return fallback;
}
return String(value);
}
function useDraftValue(value, fallback, onCommit) {
const [draft, setDraft] = useState(() => toDraftValue(value, fallback));
const isEditingRef = useRef(false);
const externalValue = toDraftValue(value, fallback);
useEffect(() => {
if (!isEditingRef.current && draft !== externalValue) {
setDraft(externalValue);
}
}, [draft, externalValue]);
const change = (nextValue) => {
setDraft(nextValue);
onCommit(nextValue);
};
return {
value: draft,
onFocus: () => {
isEditingRef.current = true;
},
onBlur: () => {
isEditingRef.current = false;
onCommit(draft);
},
onChange: (event) => change(event.target.value),
};
}
export function NodeDraftInput({ value, fallback = '', onCommit, ...props }) {
const draftProps = useDraftValue(value, fallback, onCommit);
return <input {...props} {...draftProps} />;
}
export function NodeDraftTextarea({ value, fallback = '', onCommit, ...props }) {
const draftProps = useDraftValue(value, fallback, onCommit);
return <textarea {...props} {...draftProps} />;
}
|