@yamada-ui/react
Version:
React UI components of the Yamada, by the Yamada, for the Yamada built with React and Emotion
106 lines (102 loc) • 2.97 kB
JavaScript
"use client";
import { visuallyHiddenAttributes } from "../../utils/dom.js";
import { mergeRefs } from "../../utils/ref.js";
import { utils_exports } from "../../utils/index.js";
import { useControllableState } from "../../hooks/use-controllable-state/index.js";
import { useFieldProps } from "../field/use-field-props.js";
import { useCallback, useId, useRef } from "react";
//#region src/components/switch/use-switch.ts
const useSwitch = (props = {}) => {
const uuid = useId();
const { props: { id = uuid, ref, name, checked: checkedProp, checkOnEnter = true, defaultChecked = false, disabled, readOnly, required, value, onChange: onChangeProp,...rest }, ariaProps, dataProps, eventProps } = useFieldProps(props);
const interactive = !(readOnly || disabled);
const inputRef = useRef(null);
const [checked, setChecked] = useControllableState({
defaultValue: defaultChecked,
value: checkedProp
});
const onChange = useCallback((ev) => {
if (!interactive) return ev.preventDefault();
setChecked(ev.target.checked);
onChangeProp?.(ev);
}, [
onChangeProp,
setChecked,
interactive
]);
const onKeyDown = useCallback((ev) => {
if (interactive && checkOnEnter && ev.key === "Enter") inputRef.current?.click();
}, [interactive, checkOnEnter]);
const getRootProps = useCallback((props$1 = {}) => ({
...dataProps,
htmlFor: id,
"data-checked": (0, utils_exports.dataAttr)(checked),
...rest,
...props$1
}), [
checked,
rest,
id,
dataProps
]);
const getTrackProps = useCallback((props$1 = {}) => ({
"data-checked": (0, utils_exports.dataAttr)(checked),
...dataProps,
...props$1
}), [checked, dataProps]);
const getThumbProps = useCallback((props$1 = {}) => ({
"data-checked": (0, utils_exports.dataAttr)(checked),
...dataProps,
...props$1
}), [checked, dataProps]);
return {
checked,
getInputProps: useCallback((props$1 = {}) => ({
...ariaProps,
...dataProps,
id,
type: "checkbox",
name,
style: visuallyHiddenAttributes.style,
checked,
disabled,
readOnly,
required,
role: "switch",
tabIndex: interactive ? 0 : -1,
value,
...props$1,
ref: mergeRefs(inputRef, props$1.ref, ref),
onBlur: (0, utils_exports.handlerAll)(eventProps.onBlur, props$1.onBlur),
onChange: (0, utils_exports.handlerAll)(props$1.onChange, onChange),
onFocus: (0, utils_exports.handlerAll)(eventProps.onFocus, props$1.onFocus),
onKeyDown: (0, utils_exports.handlerAll)(props$1.onKeyDown, onKeyDown)
}), [
ariaProps,
dataProps,
id,
name,
checked,
disabled,
readOnly,
required,
interactive,
value,
ref,
eventProps,
onChange,
onKeyDown
]),
getLabelProps: useCallback((props$1 = {}) => ({
...dataProps,
"data-checked": (0, utils_exports.dataAttr)(checked),
...props$1
}), [dataProps, checked]),
getRootProps,
getThumbProps,
getTrackProps
};
};
//#endregion
export { useSwitch };
//# sourceMappingURL=use-switch.js.map