Skip to content

Commit

Permalink
feat: Controlled InputToggle
Browse files Browse the repository at this point in the history
  • Loading branch information
tihuan committed Apr 5, 2024
1 parent c86af1d commit e309af5
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { BADGE } from "@geometricpanda/storybook-addon-badges";
import { InputToggle } from "./stories/default";
import { INPUT_TOGGLE_EXCLUDED_CONTROLS } from "./constants";
import { LivePreviewDemo } from "./stories/livePreview";
import { ControlledDemo } from "./stories/controlled";

export default {
argTypes: {
Expand Down Expand Up @@ -43,6 +44,20 @@ export const LivePreview = {
render: (args: Args) => <LivePreviewDemo {...args} />,
};

// Controlled

export const Controlled = {
parameters: {
controls: {
exclude: INPUT_TOGGLE_EXCLUDED_CONTROLS,
},
snapshot: {
skip: true,
},
},
render: (args: Args) => <ControlledDemo {...args} />,
};

// Test

export const Test = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Args } from "@storybook/react";
import { useState } from "react";
import RawInputToggle from "src/core/InputToggle";

export const ControlledDemo = (props: Args): JSX.Element => {
const [isChecked, setIsChecked] = useState(true);

function handleChange() {
setIsChecked((currentChecked) => !currentChecked);
}

return (
<RawInputToggle {...props} checked={isChecked} onChange={handleChange} />
);
};
14 changes: 10 additions & 4 deletions packages/components/src/core/InputToggle/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,25 @@ import { InputToggleExtraProps, Toggle } from "./style";
* @see https://mui.com/material-ui/react-switch/
*/
const InputToggle = (props: InputToggleExtraProps) => {
const isControlled = props.checked !== undefined;

const [checked, setChecked] = useState<boolean>(false);

const finalChecked = isControlled ? props.checked : checked;

const { offLabel = "Off", onChange, onLabel = "On", ...rest } = props;
const labelValue = checked ? onLabel : offLabel;

const labelValue = finalChecked ? onLabel : offLabel;

const handleChange = (e: React.ChangeEvent) => {
setChecked(!checked);
if (onChange) onChange(e);
setChecked((currentChecked) => !currentChecked);

onChange?.(e);
};

return (
<Toggle
checked={checked}
checked={finalChecked}
color="primary"
onChange={handleChange}
value={labelValue}
Expand Down

0 comments on commit e309af5

Please sign in to comment.