-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckboxGroup.tsx
More file actions
71 lines (62 loc) · 2.06 KB
/
Copy pathCheckboxGroup.tsx
File metadata and controls
71 lines (62 loc) · 2.06 KB
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
import React from 'react'
import { Checkbox } from '../Checkbox'
import { Label } from '../Label'
interface CheckboxGroupContextValue {
name: string
value: string[]
onValueChange: (value: string[]) => void
disabled?: boolean
}
const CheckboxGroupContext = React.createContext<CheckboxGroupContextValue | null>(null)
function useCheckboxGroup() {
const ctx = React.useContext(CheckboxGroupContext)
if (!ctx) {
throw new Error('CheckboxGroupItem must be used within CheckboxGroup')
}
return ctx
}
export interface CheckboxGroupProps extends React.HTMLAttributes<HTMLDivElement> {
name: string
value: string[]
onValueChange: (value: string[]) => void
disabled?: boolean
}
export const CheckboxGroup = ({ name, value, onValueChange, disabled, children, ...props }: CheckboxGroupProps) => (
<CheckboxGroupContext.Provider value={{ name, value, onValueChange, disabled }}>
{/* biome-ignore lint/a11y/useSemanticElements: <fieldset> would force consumer styling; role="group" preserves headless flexibility */}
<div role="group" {...props}>
{children}
</div>
</CheckboxGroupContext.Provider>
)
export interface CheckboxGroupItemProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'children'> {
value: string
disabled?: boolean
children: React.ReactNode
}
export const CheckboxGroupItem = ({ value, disabled, children, ...props }: CheckboxGroupItemProps) => {
const ctx = useCheckboxGroup()
const id = `${ctx.name}-${value}`
const isDisabled = disabled ?? ctx.disabled
const checked = ctx.value.includes(value)
const handleCheckedChange = (checkedState: boolean | 'indeterminate') => {
if (checkedState === true) {
ctx.onValueChange([...ctx.value, value])
} else {
ctx.onValueChange(ctx.value.filter((v) => v !== value))
}
}
return (
<div {...props}>
<Checkbox
id={id}
name={ctx.name}
value={value}
checked={checked}
onCheckedChange={handleCheckedChange}
disabled={isDisabled}
/>
<Label htmlFor={id}>{children}</Label>
</div>
)
}