Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 29x 19x 19x 19x 19x 38x 38x 38x 29x 29x 30x 30x | import { Box, Stack } from "@mui/material";
import { useFormContext, useWatch } from "react-hook-form";
import { ReactNode } from "react";
import GiveText from "@shared/Text/GiveText";
import GiveTabs from "@shared/Tabs/GiveTabs";
import GiveSwitch from "@shared/Switch/GiveSwitch";
type ToggleSwitch = {
title: string;
name: string;
description: string;
icon?: ReactNode;
};
type Props = {
switches: ToggleSwitch[];
endElement?: ReactNode;
label?: string;
useToggle?: boolean;
};
export const GiveToggleGroup = ({
switches,
endElement,
label = "Options",
useToggle,
}: Props) => {
const methods = useFormContext();
const { watch, setValue, control } = methods;
const values = watch();
return (
<>
<Stack direction="row" justifyContent="space-between">
<GiveText variant="bodyS">{label}</GiveText>
{endElement ?? null}
</Stack>
<Stack gap="16px" pt="16px">
{switches.map(({ title, name, description, icon }) => {
// Use useWatch to ensure the component re-renders when the form is reset
// This needed for proper UI updates when handleClearFilters is called
const watchedValue = useWatch({ control, name });
const switchValue = watchedValue ?? values[name];
return (
<Stack
key={name}
direction="row"
justifyContent="space-between"
gap={2}
>
<Stack direction="row" gap={1}>
<Box width="24px">{icon}</Box>
<Stack gap={useToggle ? 1 : 0}>
<GiveText variant="bodyS">{title}</GiveText>
<GiveText variant="bodyXS" color="secondary">
{description}
</GiveText>
</Stack>
</Stack>
{useToggle ? (
<GiveSwitch
checked={Boolean(switchValue)}
onChange={(e) => {
const isChecked = e.target.checked;
setValue(name, isChecked ? true : undefined); //for toggle off we set undefined to not send the filter
}}
/>
) : (
<NewToggleButton
value={switchValue}
onYes={() => setValue(name, switchValue ? undefined : true)}
onNo={() =>
setValue(name, switchValue === false ? undefined : false)
}
/>
)}
</Stack>
);
})}
</Stack>
</>
);
};
const toggleTabs = [
{ value: "yes", label: "Yes" },
{ value: "no", label: "No" },
];
type NewToggleButtonProps = {
value: boolean | undefined;
onYes(): void;
onNo(): void;
};
const NewToggleButton = ({ value, onYes, onNo }: NewToggleButtonProps) => {
const selectedTab =
value === true ? "yes" : value === false ? "no" : undefined;
return (
<GiveTabs
selected={selectedTab}
items={toggleTabs}
onClick={(val) => {
if (val === "yes") onYes();
else if (val === "no") onNo();
}}
type="segmented"
tabSx={{
padding: "4px 16px",
}}
/>
);
};
|