@yamada-ui/react
Version:
React UI components of the Yamada, by the Yamada, for the Yamada built with React and Emotion
75 lines (71 loc) • 2.2 kB
JavaScript
"use client";
import { createContext as createContext$1 } from "../../utils/context.js";
import { useUpdateEffect } from "../../utils/effect.js";
import { utils_exports } from "../../utils/index.js";
import { useControllableState } from "../../hooks/use-controllable-state/index.js";
import { useCallback, useRef } from "react";
//#region src/components/toggle/use-toggle-group.ts
const [ToggleGroupContext, useToggleGroupContext] = createContext$1({
name: "ToggleGroupContext",
strict: false
});
const useToggleGroup = ({ defaultValue, disabled, readOnly, value: valueProp, onChange: onChangeProp,...rest }) => {
const onChangeMapRef = useRef(/* @__PURE__ */ new Map());
const [value, setValue] = useControllableState({
defaultValue,
value: valueProp,
onChange: onChangeProp
});
const onReset = useCallback((targetValue) => {
onChangeMapRef.current.forEach((onChange$1, value$1) => {
if (targetValue?.includes(value$1)) onChange$1(true);
else onChange$1(false);
});
}, []);
const onChange = useCallback((value$1) => {
if ((0, utils_exports.isUndefined)(value$1)) return;
setValue((prev) => {
if ((0, utils_exports.isArray)(prev)) if (prev.includes(value$1)) {
const nextValue = prev.filter((prevValue) => prevValue !== value$1);
onReset(nextValue);
return nextValue;
} else {
const nextValue = [...prev, value$1];
onReset(nextValue);
return nextValue;
}
else if (value$1 === prev) {
onReset();
return;
} else {
onReset([value$1]);
return value$1;
}
});
}, [setValue, onReset]);
useUpdateEffect(() => {
onReset(!(0, utils_exports.isUndefined)(valueProp) ? (0, utils_exports.toArray)(valueProp) : void 0);
setValue(valueProp);
}, [valueProp]);
return {
disabled,
readOnly,
value,
getGroupProps: useCallback((props) => ({
"data-disabled": (0, utils_exports.dataAttr)(disabled),
"data-readonly": (0, utils_exports.dataAttr)(readOnly),
role: "group",
...rest,
...props
}), [
disabled,
readOnly,
rest
]),
onChange,
onChangeMapRef
};
};
//#endregion
export { ToggleGroupContext, useToggleGroup, useToggleGroupContext };
//# sourceMappingURL=use-toggle-group.js.map