1"use client";
2
3import {
4 RadioGroup,
5 RadioGroupItem,
6} from "@/components/ui/radio-group";
7import { cn } from "@/lib/utils";
8import {
9 type ComponentProps,
10 createContext,
11 type HTMLAttributes,
12 useContext,
13} from "react";
14import {
15 Field,
16 FieldContent,
17 FieldDescription,
18 FieldLabel,
19 FieldTitle,
20} from "@/components/ui/field";
21
22export type ChoiceboxProps = ComponentProps<typeof RadioGroup>;
23
24export const Choicebox = ({ className, ...props }: ChoiceboxProps) => (
25 <RadioGroup className={cn("w-full", className)} {...props} />
26);
27
28type ChoiceboxItemContextValue = {
29 value: ChoiceboxItemProps["value"];
30 id?: ChoiceboxItemProps["id"];
31};
32
33const ChoiceboxItemContext = createContext<ChoiceboxItemContextValue | null>(
34 null
35);
36
37const useChoiceboxItemContext = () => {
38 const context = useContext(ChoiceboxItemContext);
39
40 if (!context) {
41 throw new Error(
42 "useChoiceboxItemContext must be used within a ChoiceboxItem"
43 );
44 }
45
46 return context;
47};
48
49export type ChoiceboxItemProps = ComponentProps<typeof RadioGroupItem>;
50
51export const ChoiceboxItem = ({
52 className,
53 children,
54 value,
55 id,
56}: ChoiceboxItemProps) => (
57 <ChoiceboxItemContext.Provider value={{ value, id }}>
58 <FieldLabel htmlFor={id}>
59 <Field className={className} orientation="horizontal">
60 {children}
61 </Field>
62 </FieldLabel>
63 </ChoiceboxItemContext.Provider>
64);
65
66export type ChoiceboxItemHeaderProps = ComponentProps<typeof FieldContent>;
67
68export const ChoiceboxItemHeader = ({
69 className,
70 ...props
71}: ChoiceboxItemHeaderProps) => (
72 <FieldContent className={className} {...props} />
73);
74
75export type ChoiceboxItemTitleProps = ComponentProps<typeof FieldTitle>;
76
77export const ChoiceboxItemTitle = ({
78 className,
79 ...props
80}: ChoiceboxItemTitleProps) => <FieldTitle className={className} {...props} />;
81
82export type ChoiceboxItemSubtitleProps = HTMLAttributes<HTMLSpanElement>;
83
84export const ChoiceboxItemSubtitle = ({
85 className,
86 ...props
87}: ChoiceboxItemSubtitleProps) => (
88 <span
89 className={cn("font-normal text-muted-foreground text-xs", className)}
90 {...props}
91 />
92);
93
94export type ChoiceboxItemDescriptionProps = ComponentProps<
95 typeof FieldDescription
96>;
97
98export const ChoiceboxItemDescription = ({
99 className,
100 ...props
101}: ChoiceboxItemDescriptionProps) => (
102 <FieldDescription className={className} {...props} />
103);
104
105export type ChoiceboxIndicatorProps = Partial<
106 ComponentProps<typeof RadioGroupItem>
107>;
108
109export const ChoiceboxIndicator = (props: ChoiceboxIndicatorProps) => {
110 const context = useChoiceboxItemContext();
111
112 return <RadioGroupItem {...props} value={context.value} />;
113};
114