{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-checkbox-group",
  "type": "registry:ui",
  "title": "react-tw/checkbox-group.tsx",
  "description": "Carbon checkbox group as a React + Tailwind component, the look of `<ui-checkbox-group>`: a `role=\"group\"` around Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [],
  "registryDependencies": [
    "@kanok-ui/tw-checkbox",
    "@kanok-ui/tw-field",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/checkbox-group.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/checkbox-group.tsx",
      "content": "import { useCallback, useEffect, useId, useMemo, useRef, useSyncExternalStore, type ComponentProps, type ReactNode, type RefObject } from 'react';\nimport { CheckboxGroupProvider, type CheckboxGroupState } from './checkbox.tsx';\nimport { FieldMessageLine, fieldLabelClasses, fieldMessage, useFieldDisabled, useGroupTouched } from './field.tsx';\nimport { useTranslation } from './lib/i18n.ts';\nimport { cn } from './lib/utils.ts';\n\n/**\n * Carbon checkbox group as a React + Tailwind component, the look of `<ui-checkbox-group>`: a `role=\"group\"` around\n * `Checkbox` or `SelectableTile` elements, named by its label, its helper / warning / error line as its description.\n * `required` means at least one: the form won't submit until one box is checked (the browser points at the first\n * box, as the web component does) and the error shows once the group is touched — focus left it, a box changed or a\n * submit found it empty. `disabled` / `readOnly` reach every box without overwriting each one's own; each box still\n * submits its own `name` / `value`.\n */\nexport interface CheckboxGroupProps extends Omit<ComponentProps<'div'>, 'children' | 'className'> {\n    /** Group label, the group's name (Lit `label`); `hideLabel` keeps it for screen readers only (Lit `hide-label`). */\n    label: ReactNode;\n    hideLabel?: boolean;\n    /** Lit `helper-text`: shown while there is no error or warning. */\n    helperText?: ReactNode;\n    /** Lit `invalid`: forces the error state. */\n    invalid?: boolean;\n    /** Lit `invalid-text`; unset, the required message. */\n    invalidText?: ReactNode;\n    /** Lit `warn`: a non-blocking warning, shown when there is no error. */\n    warn?: boolean;\n    /** Lit `warn-text`. */\n    warnText?: ReactNode;\n    /** Lit `orientation`: `horizontal` puts the boxes in a wrapping row, 16px apart. */\n    orientation?: 'vertical' | 'horizontal';\n    /** Lit `required`: at least one box checked, or the form won't submit. */\n    required?: boolean;\n    /** Lit `required-text`: the error for an empty required group; defaults to the translation's \"Select at least one option.\" */\n    requiredText?: string;\n    /** Lit `disabled`: every box disabled. */\n    disabled?: boolean;\n    /** Lit `readonly`: every box keeps its state. */\n    readOnly?: boolean;\n    lang?: string;\n    className?: string;\n    /** `Checkbox` or `SelectableTile` elements. */\n    children: ReactNode;\n}\n\nconst boxesIn = (box: HTMLElement | null) => [...(box?.querySelectorAll<HTMLInputElement>('input[type=\"checkbox\"]') ?? [])];\n\n/**\n * How many boxes in `box` are checked, read from the DOM (a box may be uncontrolled): again after each render, a\n * change and a form reset. While `missing` is set and none is checked, the first enabled box carries it as its custom\n * validity: the form won't submit and the browser points at that box, where `<ui-checkbox-group>` anchors its `valueMissing`.\n */\nfunction useCheckedCount(box: RefObject<HTMLDivElement | null>, missing: string) {\n    const subscribe = useCallback(\n        (onChange: () => void) => {\n            const el = box.current;\n            const form = el?.closest('form');\n            // after React puts a controlled box back to its prop; after the browser resets the boxes\n            const onBoxChange = () => queueMicrotask(onChange);\n            let timer: ReturnType<typeof setTimeout> | undefined;\n            const onReset = () => {\n                timer = setTimeout(onChange);\n            };\n            el?.addEventListener('change', onBoxChange);\n            form?.addEventListener('reset', onReset);\n            return () => {\n                el?.removeEventListener('change', onBoxChange);\n                form?.removeEventListener('reset', onReset);\n                clearTimeout(timer);\n            };\n        },\n        [box],\n    );\n    // a new function each render, so React reads the boxes again once each render is on the page\n    const count = useSyncExternalStore(subscribe, () => boxesIn(box.current).filter((b) => b.checked).length, () => 0);\n    // the box holding the message, so a box's own custom validity is never cleared\n    const holder = useRef<HTMLInputElement | null>(null);\n    useEffect(() => {\n        const next = count === 0 && missing ? (boxesIn(box.current).find((b) => !b.disabled) ?? null) : null;\n        if (holder.current && holder.current !== next) holder.current.setCustomValidity('');\n        next?.setCustomValidity(missing);\n        holder.current = next;\n    });\n    useEffect(() => () => holder.current?.setCustomValidity(''), []);\n    return count;\n}\n\nexport function CheckboxGroup({ label, hideLabel, helperText, invalid, invalidText, warn, warnText, orientation = 'vertical', required = false, requiredText, disabled: ownDisabled, readOnly = false, lang, className, children, ...rest }: Readonly<CheckboxGroupProps>) {\n    const disabled = useFieldDisabled(ownDisabled);\n    const t = useTranslation(lang).field;\n    const id = useId();\n    const requiredMessage = requiredText || t.requiredAtLeastOne;\n    // the validation message, as Lit: the error text when it is text, else the required message\n    const missing = required && !disabled ? (typeof invalidText === 'string' && invalidText) || requiredMessage : '';\n    const optionsRef = useRef<HTMLDivElement>(null);\n    const count = useCheckedCount(optionsRef, missing);\n    const { touched, handlers } = useGroupTouched(optionsRef);\n    const interactive = !disabled && !readOnly;\n    const empty = required && count === 0;\n    const { message, content } = fieldMessage({ interactive, invalid: !!invalid || (touched && empty), invalidText, warn, warnText, helperText, fallbackError: requiredMessage });\n    const showError = message?.kind === 'error';\n    const messageId = message ? `${id}-message` : undefined;\n    const state = useMemo<CheckboxGroupState>(() => ({ disabled, readOnly, invalid: showError, describedBy: showError ? messageId : undefined }), [disabled, readOnly, showError, messageId]);\n    return (\n        <div {...rest} className={cn('block font-sans', className)}>\n            <div id={`${id}-label`} className={hideLabel ? 'sr-only' : cn(fieldLabelClasses, disabled && 'text-ink-disabled')}>\n                {label}\n            </div>\n            <div /* NOSONAR: as <ui-checkbox-group>: a group named by the label above it, laid out like the Lit one */\n                ref={optionsRef}\n                role=\"group\"\n                aria-labelledby={`${id}-label`}\n                aria-describedby={messageId}\n                className={cn('flex flex-col', orientation === 'horizontal' && 'flex-row flex-wrap gap-4')}\n                onChange={handlers.onChange}\n                onInvalid={handlers.onInvalid}\n                onBlur={handlers.onBlur}\n            >\n                <CheckboxGroupProvider value={state}>{children}</CheckboxGroupProvider>\n            </div>\n            <FieldMessageLine id={`${id}-message`} message={message} content={content} disabled={disabled} withIcon />\n        </div>\n    );\n}\n"
    }
  ]
}
