UNPKG

2.5 kBTypeScriptView Raw
1import React, { memo, type CSSProperties } from "react";
2import { assert } from "tsafe/assert";
3import type { Equals } from "tsafe";
4import { cx } from "./tools/cx";
5import { fr } from "./fr";
6import { ToggleSwitch } from "./ToggleSwitch";
7import type { ToggleSwitchProps } from "./ToggleSwitch";
8import { useAnalyticsId } from "./tools/useAnalyticsId";
9
10export type ToggleSwitchGroupProps = {
11 id?: string;
12 className?: string;
13 /** Default: true */
14 showCheckedHint?: ToggleSwitchProps["showCheckedHint"];
15 /** Default: right */
16 labelPosition?: ToggleSwitchProps["labelPosition"];
17 classes?: Partial<Record<"root" | "li", string>>;
18 /** Needs at least one ToggleSwitch */
19 toggles: [ToggleSwitchPropsWithoutSharedProps, ...ToggleSwitchPropsWithoutSharedProps[]];
20 style?: CSSProperties;
21};
22
23/** @see <https://components.react-dsfr.codegouv.studio/?path=/docs/components-toggleswitchgroup> */
24export const ToggleSwitchGroup = memo<ToggleSwitchGroupProps>(props => {
25 const {
26 id: id_props,
27 className,
28 toggles,
29 showCheckedHint = true,
30 labelPosition = "right",
31 classes = {},
32 style,
33 ...rest
34 } = props;
35
36 assert<Equals<keyof typeof rest, never>>();
37
38 const id = useAnalyticsId({
39 "defaultIdPrefix": "fr-toggle",
40 "explicitlyProvidedId": id_props
41 });
42
43 return (
44 <ul
45 id={id}
46 className={cx(fr.cx("fr-toggle__list"), classes.root, className)}
47 style={style}
48 {...rest}
49 >
50 {toggles.map((toggleSwitchProps, i) => (
51 <li key={i} className={classes.li}>
52 <ToggleSwitch
53 {...toggleSwitchProps}
54 showCheckedHint={showCheckedHint}
55 labelPosition={labelPosition}
56 />
57 </li>
58 ))}
59 </ul>
60 );
61});
62
63export default ToggleSwitchGroup;
64
65type ToggleSwitchPropsWithoutSharedProps =
66 | ToggleSwitchPropsWithoutSharedProps.Controlled
67 | ToggleSwitchPropsWithoutSharedProps.Uncontrolled;
68
69namespace ToggleSwitchPropsWithoutSharedProps {
70 export type Common = Omit<ToggleSwitchProps, "showCheckedHint" | "labelPosition">;
71
72 export type Uncontrolled = Common &
73 Omit<ToggleSwitchProps.Uncontrolled, keyof ToggleSwitchProps.Common>;
74 export type Controlled = Common &
75 Omit<ToggleSwitchProps.Controlled, keyof ToggleSwitchProps.Common>;
76}