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(fields): Add toggle component #1018

Merged
merged 6 commits into from
Feb 8, 2024
Merged
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
41 changes: 28 additions & 13 deletions src/fields/MultiRadio.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import classnames from 'classnames'
import { equals } from 'ramda'
import { useCallback, useMemo, type CSSProperties } from 'react'
import { useCallback, useMemo, type CSSProperties, type ReactNode } from 'react'
import { Radio } from 'rsuite'
import styled, { css } from 'styled-components'

import { FieldError } from '../elements/FieldError'
import { Fieldset } from '../elements/Fieldset'
import { useFieldUndefineEffect } from '../hooks/useFieldUndefineEffect'
import { useKey } from '../hooks/useKey'
import { getRsuiteDataFromOptions } from '../utils/getRsuiteDataFromOptions'
import { getRsuiteValueFromOptionValue } from '../utils/getRsuiteValueFromOptionValue'
import { normalizeString } from '../utils/normalizeString'

import type { Option, OptionValueType } from '../types/definitions'
Expand All @@ -26,7 +28,9 @@ export type MultiRadioProps<OptionValue extends OptionValueType = string> = {
label: string
name: string
onChange?: ((nextValue: OptionValue | undefined) => Promisable<void>) | undefined
optionValueKey?: keyof OptionValue | undefined
options: Option<OptionValue>[]
renderMenuItem?: (label: string, value: OptionValue) => ReactNode
style?: CSSProperties | undefined
value?: OptionValue | undefined
}
Expand All @@ -44,6 +48,8 @@ export function MultiRadio<OptionValue extends OptionValueType = string>({
name,
onChange,
options,
optionValueKey,
renderMenuItem,
style,
value
}: MultiRadioProps<OptionValue>) {
Expand All @@ -52,15 +58,18 @@ export function MultiRadio<OptionValue extends OptionValueType = string>({
const hasError = useMemo(() => Boolean(controlledError), [controlledError])
const key = useKey([value, disabled, name])

const rsuiteData = useMemo(() => getRsuiteDataFromOptions(options, optionValueKey), [options, optionValueKey])
const selectedRsuiteValue = useMemo(
() => getRsuiteValueFromOptionValue(value, optionValueKey) ?? '',
[value, optionValueKey]
)

const handleChange = useCallback(
(nextOptionValue: OptionValue, isChecked: boolean) => {
(nextValue: OptionValue) => {
if (!onChange) {
return
}

const nextCheckedOptionValue = isChecked ? nextOptionValue : undefined

onChange(nextCheckedOptionValue)
onChange(nextValue)
},
[onChange]
)
Expand All @@ -78,16 +87,17 @@ export function MultiRadio<OptionValue extends OptionValueType = string>({
style={style}
>
<Box key={key} $hasError={hasError} $isInline={isInline} $isReadOnly={isReadOnly}>
{options.map(option => (
{rsuiteData.map(rsuiteDataItem => (
<Radio
key={JSON.stringify(option.value)}
checked={equals(option.value, value)}
disabled={!!option.isDisabled || disabled}
key={JSON.stringify(rsuiteDataItem.value)}
checked={equals(rsuiteDataItem.value, selectedRsuiteValue)}
disabled={!!rsuiteDataItem.isDisabled || disabled}
name={name}
onChange={(_: any, isChecked: boolean) => handleChange(option.value, isChecked)}
onChange={() => handleChange(rsuiteDataItem.optionValue)}
readOnly={isReadOnly}
value={selectedRsuiteValue}
>
{option.label}
{renderMenuItem ? renderMenuItem(rsuiteDataItem.label, rsuiteDataItem.optionValue) : rsuiteDataItem.label}
</Radio>
))}
</Box>
Expand All @@ -106,7 +116,6 @@ const Box = styled.div<{
display: flex;
flex-direction: ${p => (p.$isInline ? 'row' : 'column')};
font-weight: 500;
outline: ${p => (p.$hasError ? `1px solid ${p.theme.color.maximumRed}` : 0)};

> .rs-radio {
* {
Expand All @@ -122,6 +131,12 @@ const Box = styled.div<{
left: 2px;
top: 3px !important;
}
.rs-radio-inner:before {
border-color: ${p => (p.$hasError ? p.theme.color.maximumRed : p.theme.color.gunMetal)};
}
.rs-radio-inner:after {
border-color: ${p => (p.$hasError ? p.theme.color.maximumRed : p.theme.color.gunMetal)};
}
}
}

Expand Down
109 changes: 109 additions & 0 deletions src/fields/Toggle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import classNames from 'classnames'
import { useMemo } from 'react'
import { Toggle as RsuiteToggle, type ToggleProps as RSuiteToggleProps } from 'rsuite'
import styled from 'styled-components'

import { Field } from '../elements/Field'
import { FieldError } from '../elements/FieldError'
import { Label } from '../elements/Label'
import { useKey } from '../hooks/useKey'
import { normalizeString } from '../utils/normalizeString'

export type ToggleProps = Omit<RSuiteToggleProps, 'onChange'> & {
dataCy?: string
error?: string | undefined
isChecked: boolean
isErrorMessageHidden?: boolean | undefined
isLabelHidden?: boolean | undefined
label: string
name: string
onChange: (isChecked: boolean) => void
}
export function Toggle({
className,
dataCy,
error,
isChecked,
isErrorMessageHidden = false,
isLabelHidden,
label,
onChange,
style,
...originalProps
}: ToggleProps) {
const controlledClassName = useMemo(() => classNames('Field-Toggle', className), [className])
const controlledError = useMemo(() => normalizeString(error), [error])

const hasError = useMemo(() => Boolean(controlledError), [controlledError])
const key = useKey([isChecked, originalProps.disabled, originalProps.name])

return (
<Field className={controlledClassName} style={style}>
<Label
disabled={originalProps.disabled}
hasError={hasError}
htmlFor={originalProps.name}
isHidden={isLabelHidden}
>
{label}
</Label>
<StyledToggle
key={key}
$hasError={hasError}
checked={isChecked}
data-cy={dataCy}
onChange={onChange}
{...originalProps}
/>
{!isErrorMessageHidden && hasError && <FieldError>{controlledError}</FieldError>}
</Field>
)
}

const StyledToggle = styled(RsuiteToggle)<{ $hasError?: boolean }>`
.rs-toggle-presentation {
background-color: transparent;
border: 1px solid ${p => (p.$hasError ? p.theme.color.maximumRed : p.theme.color.charcoal)};

&:after {
background-color: ${p => (p.$hasError ? p.theme.color.maximumRed : p.theme.color.charcoal)};
top: 2px;
}
&:hover {
border: 1px solid ${p => p.theme.color.blueYonder};
&:after {
background-color: ${p => p.theme.color.blueYonder};
}
}
}

&.rs-toggle-disabled .rs-toggle-presentation {
background-color: ${p => p.theme.color.white};
border: 1px solid ${p => p.theme.color.lightGray};
box-shadow: none;
&:after {
background-color: ${p => p.theme.color.lightGray};
}
}

&.rs-toggle-checked.rs-toggle-disabled .rs-toggle-presentation {
background-color: ${p => p.theme.color.lightGray};
border: 1px solid ${p => p.theme.color.lightGray};
box-shadow: none;
&:after {
background-color: ${p => p.theme.color.gainsboro};
}
}

&.rs-toggle-checked .rs-toggle-presentation {
background-color: ${p => (p.$hasError ? p.theme.color.maximumRed : p.theme.color.charcoal)};
border: 1px solid transparent;
&:after {
background-color: ${p => p.theme.color.white};
}
&:hover {
border: 1px solid transparent;
background-color: ${p => p.theme.color.blueYonder};
}
}
`
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export { CoordinatesInput } from './fields/CoordinatesInput'
export { Select } from './fields/Select'
export { Textarea } from './fields/Textarea'
export { TextInput } from './fields/TextInput'
export { Toggle } from './fields/Toggle'

export { FormikSearch } from './formiks/FormikSearch'
export { FormikCheckbox } from './formiks/FormikCheckbox'
Expand Down Expand Up @@ -193,6 +194,7 @@ export type { CoordinatesInputProps } from './fields/CoordinatesInput'
export type { SelectProps } from './fields/Select'
export type { TextareaProps } from './fields/Textarea'
export type { TextInputProps } from './fields/TextInput'
export type { ToggleProps } from './fields/Toggle'

export type { FormikSearchProps } from './formiks/FormikSearch'
export type { FormikCheckboxProps } from './formiks/FormikCheckbox'
Expand Down
1 change: 1 addition & 0 deletions src/types/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,6 @@ export type Option<OptionValue extends OptionValueType = string> = Omit<ItemData
label: string
value: OptionValue
}

// `symbol` should never happen, we add it here to simplify other declarations related this type
export type OptionValueType = boolean | number | string | symbol | Record<string, any>
54 changes: 51 additions & 3 deletions stories/fields/MultiRadio.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { useState } from 'react'
import { useState, type FunctionComponent } from 'react'

import { Output } from '../../.storybook/components/Output'
import { generateStoryDecorator } from '../../.storybook/components/StoryDecorator'
import { MultiRadio, useFieldControl } from '../../src'
import { Icon as MonitorUiIcon, MultiRadio, useFieldControl } from '../../src'

import type { MultiRadioProps } from '../../src'
import type { IconProps, MultiRadioProps, Option } from '../../src'
import type { Meta } from '@storybook/react'

const args: MultiRadioProps = {
Expand All @@ -25,6 +25,34 @@ const args: MultiRadioProps = {
value: undefined
}

type InterestPointOptionValueType = {
Icon: FunctionComponent<IconProps>
value: string
}

const OPTIONS_WITH_ICONS: Array<Option<InterestPointOptionValueType>> = [
{
label: 'Moyen de contrôle',
value: {
value: 'CONTROL_ENTITY',
Icon: MonitorUiIcon.ControlUnit
}
},
{
label: 'Navire de pêche',
value: {
value: 'FISHING_VESSEL',
Icon: MonitorUiIcon.FleetSegment
}
},
{
label: 'Autre point',
value: {
value: 'OTHER',
Icon: MonitorUiIcon.Info
}
}
]
const meta: Meta<MultiRadioProps> = {
title: 'Fields/MultiRadio',
component: MultiRadio,
Expand All @@ -51,6 +79,10 @@ export function _MultiRadio(props: MultiRadioProps) {

const { controlledOnChange, controlledValue } = useFieldControl(props.value, setOutputValue)

const [outputValueWithIcon, setOutputValueWithIcons] = useState<InterestPointOptionValueType | undefined>(
OPTIONS_WITH_ICONS[2]?.value
)

return (
<>
<div style={{ marginBottom: '32px' }}>
Expand All @@ -65,6 +97,22 @@ export function _MultiRadio(props: MultiRadioProps) {
onChange={controlledOnChange}
value="FIRST_OPTION"
/>
<div style={{ marginTop: '32px' }}>
<MultiRadio
{...props}
label="Multiradio with icons"
onChange={nextOptionValue => setOutputValueWithIcons(nextOptionValue)}
options={OPTIONS_WITH_ICONS}
optionValueKey="value"
renderMenuItem={(label, value) => (
<>
<value.Icon />
{label}
</>
)}
value={outputValueWithIcon}
/>
</div>
</>
)
}
Loading
Loading