rsuite
Version:
A suite of react components
58 lines (57 loc) • 1.46 kB
JavaScript
'use client';
import { useRef } from 'react';
import { contains, ownerDocument } from 'dom-lib';
import { useIsomorphicLayoutEffect, useUpdateEffect, useEventCallback } from "../internals/hooks/index.js";
import { RSUITE_PICKER_TYPE } from "../internals/symbols.js";
const useFocusEvent = ({
isEditing,
stateOnBlur,
onSave,
onCancel
}) => {
const ref = useRef(null);
const rootRef = useRef(null);
const isPicker = ref.current?.type === RSUITE_PICKER_TYPE;
const focus = () => {
if (isPicker) {
setTimeout(() => {
const picker = ref.current;
// Auto focus the search input
picker?.target?.focus?.();
// Open the picker
picker?.open?.();
}, 100);
} else {
ref.current?.focus?.();
}
};
const handleBlur = useEventCallback(event => {
if (event) {
const relatedTarget = event.relatedTarget ?? ownerDocument(event.currentTarget).activeElement;
if (rootRef.current && contains(rootRef.current, relatedTarget)) {
return;
}
}
if (stateOnBlur === 'save') {
onSave?.(event);
} else if (stateOnBlur === 'cancel') {
onCancel?.(event);
}
});
useIsomorphicLayoutEffect(() => {
if (isEditing) {
focus();
}
}, []);
useUpdateEffect(() => {
if (isEditing) {
focus();
}
}, [isEditing]);
return {
target: ref,
root: rootRef,
onBlur: handleBlur
};
};
export default useFocusEvent;