Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(components): Add labelPosition prop on Switch #2452

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 40 additions & 29 deletions packages/components/src/Switch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const SIZE = 18

export interface SwitchProps
extends Assign<React.ComponentPropsWithRef<'input'>, BoxOwnProps> {
labelPosition?: 'start' | 'end',
label?: string
}

Expand All @@ -23,7 +24,7 @@ export interface SwitchProps
*/
export const Switch: ForwardRef<HTMLInputElement, SwitchProps> =
React.forwardRef(function Switch(
{ className, label, sx, variant = 'switch', ...rest },
{ className, label, sx, labelPosition = 'end', variant = 'switch', ...rest },
ref
) {
const __css: ThemeUICSSObject = {
Expand All @@ -33,7 +34,6 @@ export const Switch: ForwardRef<HTMLInputElement, SwitchProps> =
borderRadius: SIZE,
height: SIZE + GUTTER * 2,
width: SIZE * 2 + GUTTER * 2,
mr: 2,
'input:disabled ~ &': {
opacity: 0.5,
cursor: 'not-allowed',
Expand All @@ -58,34 +58,45 @@ export const Switch: ForwardRef<HTMLInputElement, SwitchProps> =
},
}

// Inner really checkbox (but hidden)
const reallyHiddenCheckbox = (
<Box
ref={ref}
as="input"
type="checkbox"
aria-label={label}
{...rest}
sx={{
position: 'absolute',
opacity: 0,
zIndex: -1,
width: 1,
height: 1,
overflow: 'hidden',
}}
{...__internalProps({ __themeKey: 'forms' })}
/>
);

// Switch just for show
const switchForShow = (
<Box
css={{ padding: GUTTER }}
variant={variant}
className={className}
sx={sx}
{...__internalProps({ __themeKey: 'forms', __css })}
>
<Box />
</Box>
);

return (
<Label sx={{ cursor: 'pointer' }}>
<Box
ref={ref}
as="input"
type="checkbox"
aria-label={label}
{...rest}
sx={{
position: 'absolute',
opacity: 0,
zIndex: -1,
width: 1,
height: 1,
overflow: 'hidden',
}}
{...__internalProps({ __themeKey: 'forms' })}
/>
<Box
css={{ padding: GUTTER }}
variant={variant}
className={className}
sx={sx}
{...__internalProps({ __themeKey: 'forms', __css })}
>
<Box />
</Box>
<span>{label}</span>
<Label sx={{ cursor: 'pointer', gap: 2 }}>
{ labelPosition === 'start' && label ? <span>{label}</span> : null }
{reallyHiddenCheckbox}
{switchForShow}
{ labelPosition === 'end' && label ? <span>{label}</span> : null }
</Label>
)
})
Loading
Loading