Skip to content

Commit

Permalink
refactor: use mergeProps in toggle
Browse files Browse the repository at this point in the history
  • Loading branch information
malangcat committed Jan 4, 2025
1 parent 485d73a commit 14bc878
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
12 changes: 10 additions & 2 deletions packages/react-headless/toggle/src/Toggle.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { mergeProps } from "@seed-design/dom-utils";
import { Primitive, type PrimitiveProps } from "@seed-design/react-primitive";
import type * as React from "react";
import { forwardRef } from "react";
Expand All @@ -10,10 +11,17 @@ export interface ToggleRootProps
React.HTMLAttributes<HTMLButtonElement> {}

export const ToggleRoot = forwardRef<HTMLButtonElement, ToggleRootProps>((props, ref) => {
const api = useToggle(props);
const { pressed, defaultPressed, onPressedChange, disabled, ...otherProps } = props;
const api = useToggle({
pressed,
defaultPressed,
onPressedChange,
disabled,
});
const mergedProps = mergeProps(api.rootProps, otherProps);
return (
<ToggleProvider value={api}>
<Primitive.button ref={ref} {...api.rootProps} {...api.restProps} />
<Primitive.button ref={ref} {...mergedProps} />
</ToggleProvider>
);
});
Expand Down
8 changes: 1 addition & 7 deletions packages/react-headless/toggle/src/useToggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,11 @@ export function useToggleState(props: UseToggleStateProps) {

export interface UseToggleProps extends UseToggleStateProps {
disabled?: boolean;

onClick?: React.MouseEventHandler<HTMLButtonElement>;
}

export type UseToggleReturn = ReturnType<typeof useToggle>;

export function useToggle(props: UseToggleProps) {
const { pressed, defaultPressed, disabled, onPressedChange, onClick, ...restProps } = props;
const { toggle, isPressed } = useToggleState(props);

const stateProps = elementProps({
Expand All @@ -52,16 +49,13 @@ export function useToggle(props: UseToggleProps) {
isPressed,
toggle,

restProps,
stateProps,
rootProps: buttonProps({
...stateProps,
"aria-pressed": isPressed,
onClick(event) {
onClick() {
if (props.disabled) return;
toggle();
// FIXME: temporal workaround, should be replaced with `mergeProps()` or getRootProps() pattern.
onClick?.(event);
},
}),
};
Expand Down

0 comments on commit 14bc878

Please sign in to comment.