summaryrefslogtreecommitdiffstats
path: root/src/components/molecules/forms/radio-group.tsx
blob: 64bdaa0a685b5ba37958529bdcaed5bd7e778929 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import Fieldset, {
  type FieldsetProps,
} from '@components/molecules/forms/fieldset';
import useStateChange from '@utils/hooks/use-state-change';
import { ChangeEvent, FC, MouseEvent, SetStateAction, useState } from 'react';
import LabelledBooleanField, {
  type LabelledBooleanFieldProps,
} from './labelled-boolean-field';
import styles from './radio-group.module.scss';

export type RadioGroupCallbackProps = {
  choices: {
    new: string;
    prev: string;
  };
  updateChoice: (value: SetStateAction<string>) => void;
};

export type RadioGroupCallback = (props: RadioGroupCallbackProps) => void;

export type RadioGroupOption = Pick<
  LabelledBooleanFieldProps,
  'id' | 'label' | 'name' | 'value'
>;

export type RadioGroupProps = Pick<
  FieldsetProps,
  'bodyClassName' | 'className' | 'legend' | 'legendClassName' | 'Tooltip'
> &
  Pick<LabelledBooleanFieldProps, 'labelPosition' | 'labelSize'> & {
    /**
     * Set additional classnames to the radio group wrapper when kind is toggle.
     */
    groupClassName?: string;
    /**
     * The default option value.
     */
    initialChoice: string;
    /**
     * The radio group kind. Default: regular.
     */
    kind?: 'regular' | 'toggle';
    /**
     * The legend position. Default: inline.
     */
    legendPosition?: FieldsetProps['legendPosition'];
    /**
     * A callback function to execute when choice is changed.
     */
    onChange?: RadioGroupCallback;
    /**
     * A callback function to execute when clicking on a choice.
     */
    onClick?: RadioGroupCallback;
    /**
     * Set additional classnames to the labelled field wrapper.
     */
    optionClassName?: string;
    /**
     * The options.
     */
    options: RadioGroupOption[];
  };

/**
 * RadioGroup component
 *
 * Render a group of labelled radio buttons.
 */
const RadioGroup: FC<RadioGroupProps> = ({
  className,
  groupClassName = '',
  initialChoice,
  kind = 'regular',
  labelPosition,
  labelSize,
  legendPosition = 'inline',
  onChange,
  optionClassName = '',
  options,
  ...props
}) => {
  const [selectedChoice, setSelectedChoice] =
    useStateChange<string>(initialChoice);
  const isToggle = kind === 'toggle';
  const alignmentModifier = `wrapper--${legendPosition}`;
  const toggleModifier = isToggle ? 'wrapper--toggle' : 'wrapper--regular';

  /**
   * Update the selected choice on click or change event.
   */
  const updateChoice = (
    e:
      | ChangeEvent<HTMLInputElement>
      | MouseEvent<HTMLInputElement, globalThis.MouseEvent>
  ) => {
    const input = e.target as HTMLInputElement;
    onChange &&
      onChange({
        choices: { new: input.value, prev: selectedChoice },
        updateChoice: setSelectedChoice,
      });
    if (e.type === 'change') setSelectedChoice(input.value);
  };

  /**
   * Retrieve an array of radio buttons.
   *
   * @returns {JSX.Element[]} The radio buttons.
   */
  const getOptions = (): JSX.Element[] => {
    return options.map((option) => (
      <LabelledBooleanField
        key={option.id}
        checked={selectedChoice === option.value}
        className={`${styles.option} ${optionClassName}`}
        fieldClassName={styles.radio}
        hidden={isToggle}
        labelClassName={styles.label}
        labelPosition={kind === 'toggle' ? 'right' : labelPosition}
        labelSize={labelSize}
        onChange={updateChoice}
        onClick={updateChoice}
        type="radio"
        {...option}
      />
    ));
  };

  return (
    <Fieldset
      className={`${styles.wrapper} ${styles[alignmentModifier]} ${styles[toggleModifier]} ${className}`}
      legendPosition={legendPosition}
      role="radiogroup"
      {...props}
    >
      {isToggle ? (
        <span className={`${styles.toggle} ${groupClassName}`}>
          {getOptions()}
        </span>
      ) : (
        getOptions()
      )}
    </Fieldset>
  );
};

export default RadioGroup;