{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-multi-select",
  "type": "registry:ui",
  "title": "react-tw/multi-select.tsx",
  "description": "Carbon `MultiSelect` / `FilterableMultiSelect` as a React + Tailwind component: the look of 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": [
    "@purpurabog/ui@^2.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/core-field",
    "@kanok-ui/core-listbox",
    "@kanok-ui/core-multi-select",
    "@kanok-ui/tw-field",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-list",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/multi-select.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/multi-select.tsx",
      "content": "import { useId, type CSSProperties, type HTMLAttributes, type ReactNode, type Ref } from 'react';\nimport type { TextFilter } from '../core/listbox.ts';\nimport type { SelectionFeedback } from '../core/multi-select.ts';\nimport { MultiSelect as MultiSelectPrimitive } from '@purpurabog/ui/headless';\nimport { FieldLabel, FieldMessageLine, StatusIcon, fluidBoxClasses, fluidControlClasses, fluidLabelClasses, useFluid, useFieldDisabled, fieldMessage, fieldBoxClasses, fieldDisabledEdge, fieldDisabledFill, fieldReadOnlyEdge, fieldLabelClasses, useRequiredError, fieldInvalidRing, fieldInvalidRingWithin, fieldTextSize } from './field.tsx';\nimport { useTranslation } from './lib/i18n.ts';\nimport type { FieldMessage } from '../core/field.ts';\nimport { cn } from './lib/utils.ts';\nimport { controlsPadding, EmptyRow, FieldControls, ListRows, ListStatus, listMenuClasses, listRowClasses, type ListItem, type ListOption } from './list.tsx';\n\n/**\n * Carbon `MultiSelect` / `FilterableMultiSelect` as a React + Tailwind component: the look of\n * `<ui-multi-select>` on the headless `MultiSelect` (the rules of core/multi-select, traced on\n * Carbon React): a list of\n * checkboxes that stays open while toggling; chosen rows move to the top when the list reopens\n * (`selectionFeedback`); a count tag with a clear-all ×; an optional \"Select all\" row (mixed when\n * some are chosen). `filterable` turns the field into a text box that narrows the list.\n */\nexport interface MultiSelectProps extends Omit<HTMLAttributes<HTMLElement>, 'label' | 'hideLabel' | 'items' | 'value' | 'defaultValue' | 'onChange' | 'onInputChange' | 'inputValue' | 'placeholder' | 'size' | 'direction' | 'selectionFeedback' | 'selectAll' | 'filterable' | 'filter' | 'loading' | 'helperText' | 'invalid' | 'invalidText' | 'warn' | 'warnText' | 'disabled' | 'readOnly' | 'required' | 'name' | 'id' | 'lang' | 'fluid' | 'onMenuChange' | 'className'> {\n    label: ReactNode;\n    hideLabel?: boolean;\n    items: ListItem[];\n    value?: string[];\n    defaultValue?: string[];\n    onChange?: (value: string[]) => void;\n    /** Filterable: every keystroke (with `filter=\"none\"` the list is yours to fill, e.g. from a server), and the text emptied. */\n    onInputChange?: (text: string) => void;\n    /** Filterable: what the text box shows, controlled (Lit `inputValue`). */\n    inputValue?: string;\n    placeholder?: string;\n    size?: 'sm' | 'md' | 'lg';\n    direction?: 'bottom' | 'top';\n    selectionFeedback?: SelectionFeedback;\n    /** A \"Select all\" row before the options. */\n    selectAll?: boolean;\n    filterable?: boolean;\n    filter?: TextFilter;\n    /** The options are on their way: \"Searching…\" when `filterable` (a server search), else \"Loading…\"; the keys pick nothing. */\n    loading?: boolean;\n    /** After the list opens or closes (Carbon React `onMenuChange`), e.g. to load the options on first open. */\n    onMenuChange?: (open: boolean) => void;\n    helperText?: ReactNode;\n    invalid?: boolean;\n    invalidText?: ReactNode;\n    warn?: boolean;\n    warnText?: ReactNode;\n    disabled?: boolean;\n    readOnly?: boolean;\n    required?: boolean;\n    name?: string;\n    id?: string;\n    lang?: string;\n    /** Carbon `FluidMultiSelect`: the label inside a 64px box (also set by `FluidForm`); the open list keeps its row height. */\n    fluid?: boolean;\n    className?: string;\n    /** The field: the trigger button, or the text box when `filterable`. */\n    ref?: Ref<HTMLElement>;\n}\n\nconst ROW = { sm: 'var(--ui-field-height-sm)', md: 'var(--ui-field-height-md)', lg: 'var(--ui-field-height-lg)' } as const;\n\n/** A list row's leading checkbox. */\nconst rowLead = (option: ListOption, selected: boolean) => <RowBox checked={selected} disabled={option.disabled} twoLine={!!option.description} />;\n\nfunction RowBox({ checked, mixed, disabled, twoLine }: Readonly<{ checked: boolean; mixed?: boolean; disabled?: boolean; twoLine?: boolean }>) {\n    return (\n        <span\n            aria-hidden=\"true\"\n            className={cn(\n                // the checkbox settings (--ui-checkbox-*), as Checkbox\n                'relative me-[22px] box-border block size-4 flex-none rounded-xs border border-solid border-[var(--ui-checkbox-border,var(--ui-ink))] bg-transparent',\n                \"after:absolute after:start-[3px] after:top-[-0.5px] after:box-border after:h-[5px] after:w-[9px] after:origin-bottom-right after:border-0 after:border-b-[1.5px] after:border-l-[1.5px] after:border-solid after:border-[var(--ui-checkbox-mark,var(--ui-icon-inverse))] after:content-['']\",\n                'after:[transform:scale(0)_rotate(-45deg)]',\n                (checked || mixed) && 'border-[var(--ui-checkbox-checked,var(--ui-ink))] bg-[var(--ui-checkbox-checked,var(--ui-ink))]',\n                checked && 'after:[transform:scale(1)_rotate(-45deg)]',\n                mixed && 'after:top-1 after:w-2 after:border-b-2 after:border-l-0 after:[transform:scale(1)_rotate(0deg)]',\n                disabled && 'border-ink-disabled',\n                // a two-line row: Carbon centres the box on both lines; a design can pin it to the label (--ui-option-box-*)\n                twoLine && 'self-[var(--ui-option-box-align,auto)] mt-[var(--ui-option-box-offset,0px)]',\n                'forced-colors:border-[FieldText]',\n            )}\n        />\n    );\n}\n\n/** The ids that describe the field (the count, the message), space-separated; none when empty. */\nconst joinIds = (...ids: (string | false | null | undefined)[]) => ids.filter(Boolean).join(' ') || undefined;\n\ninterface EmptyState {\n    filterable: boolean;\n    loading: boolean;\n    count: number;\n}\n\n/** The open list's only row, if any: \"Searching…\" (a filterable list loading) / \"Loading…\" / \"No matching items\" (filterable, nothing found). */\nfunction emptyText({ filterable, loading, count }: EmptyState, t: { searching: string; noResults: string; loadingOptions: string }) {\n    if (loading) return filterable ? t.searching : t.loadingOptions;\n    return filterable && count === 0 ? t.noResults : '';\n}\n\n/** What the open list says to screen readers: the same as its only row (a disabled row is never announced). */\nfunction listStatus(state: EmptyState & { open: boolean }, t: { searching: string; noResults: string; loadingOptions: string }) {\n    return state.open ? emptyText(state, t) : '';\n}\n\n/** Filterable, the label is the text box's; otherwise it names the button (with the value). */\nfunction MultiLabel({ fieldId, filterable, hidden, disabled, fluid, children }: Readonly<{ fieldId: string; filterable: boolean; hidden: boolean; disabled: boolean; fluid: boolean; children: ReactNode }>) {\n    if (filterable) {\n        return (\n            <FieldLabel htmlFor={fieldId} hidden={hidden} disabled={disabled} fluid={fluid}>\n                <span id={`${fieldId}-label`}>{children}</span>\n            </FieldLabel>\n        );\n    }\n    return (\n        <span id={`${fieldId}-label`} className={hidden ? 'sr-only' : cn(fieldLabelClasses, disabled && 'text-ink-disabled', fluid && fluidLabelClasses)}>\n            {children}\n        </span>\n    );\n}\n\ninterface CountTagProps {\n    id: string;\n    fluid: boolean;\n    labels: { selectedCount: (count: number) => string; clearAll: string };\n}\n\n/** The count of chosen options with its × (Carbon ListBoxSelection); fluid: on the value's line, 30px down. Nothing while none is chosen. */\nfunction CountTag({ id, fluid, labels }: Readonly<CountTagProps>) {\n    const { count, filterable, interactive } = MultiSelectPrimitive.useMultiSelectContext();\n    if (count === 0) return null;\n    let fluidPlace = '';\n    if (fluid) fluidPlace = filterable ? 'mt-[30px] mb-0' : 'top-[30px] bottom-auto my-0';\n    return (\n        <span className={cn('my-auto flex h-6 items-center rounded-pill bg-[var(--ui-count-tag-background,var(--ui-ink))] ps-2 type-caption text-[var(--ui-count-tag-ink,var(--ui-inverse-ink))]', filterable ? 'static ms-4 me-2 flex-none' : 'absolute inset-y-0 start-4', !interactive && 'pe-2', fluidPlace)}>\n            <span aria-hidden=\"true\">{count}</span>\n            <span className=\"sr-only\" id={id}>\n                {labels.selectedCount(count)}\n            </span>\n            {interactive ? (\n                <MultiSelectPrimitive.Clear\n                    aria-label={labels.clearAll}\n                    className=\"grid size-6 cursor-pointer place-items-center rounded-pill border-0 bg-transparent p-0 text-inherit transition-[background-color] duration-(--ui-duration-fast) ease-carbon hover:bg-[var(--ui-count-tag-hover,var(--ui-secondary-hover))] focus-visible:outline-[length:var(--ui-focus-width,2px)] focus-visible:[outline-offset:var(--ui-focus-offset,-2px)] focus-visible:outline-focus [&_svg]:size-4 [&_svg]:fill-current forced-colors:[&_svg]:fill-[FieldText]\"\n                >\n                    <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n                        <path d=\"m12 4.7-.7-.7L8 7.3 4.7 4l-.7.7L7.3 8 4 11.3l.7.7L8 8.7l3.3 3.3.7-.7L8.7 8z\" />\n                    </svg>\n                </MultiSelectPrimitive.Clear>\n            ) : null}\n        </span>\n    );\n}\n\n/** The chevron (turned while open) after the status icon; fluid: 34px down and 12px from the end, the status icon in the message row. */\nfunction MultiChevron({ kind, fluid, readOnly, disabled }: Readonly<{ kind: FieldMessage['kind'] | undefined; fluid: boolean; readOnly: boolean; disabled: boolean }>) {\n    const { open } = MultiSelectPrimitive.useMultiSelectContext();\n    return (\n        <span className={cn('pointer-events-none absolute inset-y-0 end-4 flex items-center gap-2', fluid && 'end-3 items-start pt-[34px]')} aria-hidden=\"true\">\n            <StatusIcon kind={kind} className={fluid ? 'absolute end-1 top-[calc(100%+8px)]' : undefined} />\n            <svg className={cn('size-4 fill-ink transition-transform duration-(--ui-duration-fast) ease-carbon forced-colors:fill-[FieldText]', open && '[transform:rotate(180deg)]', readOnly && 'fill-ink-subtle', disabled && 'fill-ink-disabled')} viewBox=\"0 0 16 16\">\n                <path d=\"M8 11 3 6l.7-.7L8 9.6l4.3-4.3.7.7z\" />\n            </svg>\n        </span>\n    );\n}\n\n/** Filterable: the field box holding the tag, the text box and the controls (it keeps its own fill and outline, as <ui-multi-select>). */\nfunction filterBoxClasses({ open, showError, disabled, readOnly, fluid }: { open: boolean; showError: boolean; disabled: boolean; readOnly: boolean; fluid: boolean }) {\n    return cn(\n        fieldBoxClasses,\n        'relative box-border flex h-(--list-row) items-center outline-[length:var(--ui-field-focus-width,2px)] [outline-offset:calc(-1*var(--ui-field-focus-width,2px))] outline-transparent hover:bg-ghost-hover focus-within:outline-focus focus-within:[box-shadow:var(--ui-field-focus-halo,none)]',\n        // Carbon multi-select--filterable: the outline at fast-01 (the hover fill switches at once)\n        'transition-[outline-color] duration-(--ui-duration-fast) ease-carbon',\n        open && 'outline-focus [box-shadow:var(--ui-field-focus-halo,none)] hover:bg-[var(--ui-field-open-background,var(--ui-ghost-hover))]',\n        showError && fieldInvalidRingWithin,\n        disabled && cn(fieldDisabledEdge, fieldDisabledFill),\n        readOnly && cn('bg-[var(--ui-field-readonly-background,transparent)]', fieldReadOnlyEdge),\n        'forced-colors:border forced-colors:border-[FieldText] forced-colors:focus-within:outline-[Highlight]',\n        // fluid: 64px, the text under the label\n        fluid && 'h-16 items-start',\n    );\n}\n\nfunction filterInputClasses({ showClearText, hasStatus, hasValue, fluid }: { showClearText: boolean; hasStatus: boolean; hasValue: boolean; fluid: boolean }) {\n    return cn(\n        'm-0 box-border h-full min-w-0 flex-1 border-0 bg-transparent ps-4 text-ink type-body-sm outline-none placeholder:text-ink-placeholder placeholder:opacity-100',\n        controlsPadding(showClearText, hasStatus),\n        hasValue && 'ps-0',\n        'disabled:cursor-not-allowed disabled:text-ink-disabled',\n        fluid && cn('pt-[33px] pb-[13px]', showClearText ? 'pe-24' : 'pe-16'),\n        fieldTextSize,\n    );\n}\n\ninterface TriggerLook {\n    hasValue: boolean;\n    showError: boolean;\n    statusKind: FieldMessage['kind'] | undefined;\n    disabled: boolean;\n    readOnly: boolean;\n    fluid: boolean;\n}\n\n/** The button field; the count tag takes 72px at its start. */\nfunction triggerClasses({ hasValue, showError, statusKind, disabled, readOnly, fluid }: TriggerLook) {\n    return cn(\n        'm-0 box-border flex h-(--list-row) w-full cursor-pointer items-center gap-2 ps-4 pe-12 text-start',\n        fieldBoxClasses,\n        'text-ink type-body-sm',\n        // open, the field keeps its fill under the pointer (--ui-field-open-background; Carbon: the hover fill)\n        'outline-[length:var(--ui-field-focus-width,2px)] [outline-offset:calc(-1*var(--ui-field-focus-width,2px))] outline-transparent hover:bg-ghost-hover aria-expanded:hover:bg-[var(--ui-field-open-background,var(--ui-ghost-hover))] focus:outline-focus focus:[box-shadow:var(--ui-field-focus-halo,none)] aria-expanded:outline-focus aria-expanded:[box-shadow:var(--ui-field-focus-halo,none)]',\n        // Carbon list-box: all at fast-01; the hover fill is what changes\n        'transition-[background-color] duration-(--ui-duration-fast) ease-carbon',\n        hasValue && 'ps-[72px]',\n        showError && fieldInvalidRing,\n        statusKind && 'pe-16',\n        disabled && cn('cursor-not-allowed text-ink-disabled', fieldDisabledEdge, fieldDisabledFill),\n        readOnly && cn('cursor-default bg-[var(--ui-field-readonly-background,transparent)]', fieldReadOnlyEdge),\n        'forced-colors:border forced-colors:border-solid forced-colors:border-[FieldText] forced-colors:focus:outline-[Highlight]',\n        fluid && cn('h-16 pt-[33px] pe-12 pb-[13px] hover:bg-transparent', hasValue ? 'ps-[72px]' : 'ps-4', fluidControlClasses(statusKind, readOnly)),\n    );\n}\n\n/** \"Select all\": checked when every shown option is, mixed when some are. */\nfunction SelectAllRow({ label }: Readonly<{ label: string }>) {\n    const { allState } = MultiSelectPrimitive.useMultiSelectContext();\n    return (\n        <MultiSelectPrimitive.SelectAll data-option=\"\" className={cn(listRowClasses, 'border-0 border-b border-solid border-b-hairline')}>\n            <RowBox checked={allState === 'all'} mixed={allState === 'some'} />\n            <span className=\"truncate\">{label}</span>\n        </MultiSelectPrimitive.SelectAll>\n    );\n}\n\nexport function MultiSelect({ label, hideLabel, items, value, defaultValue = [], onChange, onInputChange, inputValue, placeholder = '', size = 'md', direction = 'bottom', selectionFeedback = 'top-after-reopen', selectAll, filterable, filter = 'contains', loading = false, onMenuChange, helperText, invalid, invalidText, warn, warnText, disabled: ownDisabled, readOnly, required, name, id, lang, fluid: fluidProp, className, ref, ...rest }: Readonly<MultiSelectProps>) {\n    const disabled = useFieldDisabled(ownDisabled);\n    const t = useTranslation(lang).list;\n    const autoId = useId();\n    const fieldId = id ?? autoId;\n    const interactive = !disabled && !readOnly;\n    // nothing chosen on a submit attempt: the required message, until a choice is made\n    const requiredError = useRequiredError(onChange);\n    const { message, content } = fieldMessage({ interactive, invalid: invalid || requiredError.missing, invalidText: invalid ? invalidText : undefined, fallbackError: requiredError.missing ? t.required : '', warn, warnText, helperText });\n    const showError = message?.kind === 'error';\n    const hasStatus = !!message && message.kind !== 'helper';\n    const fluid = useFluid(fluidProp);\n    const statusKind = hasStatus ? message.kind : undefined;\n    const look: FieldLook = { fieldId, placeholder, showError, statusKind, messageKind: message?.kind, hasMessage: !!message, fluid, labels: t };\n    return (\n        <MultiSelectPrimitive.Root items={items} value={value} defaultValue={defaultValue} onValueChange={requiredError.onValueChange} onInvalid={requiredError.onInvalid} onInputValueChange={onInputChange} inputValue={inputValue} selectionFeedback={selectionFeedback} selectAll={!!selectAll} filterable={!!filterable} filter={filter} loading={loading} onOpenChange={onMenuChange} disabled={disabled} readOnly={readOnly} required={required} invalid={showError} name={name} id={fieldId}>\n            <div style={{ '--list-row': ROW[size] } as CSSProperties} className={cn('block font-sans', fluid && fluidBoxClasses(statusKind, readOnly), className)}>\n                <MultiLabel fieldId={fieldId} filterable={!!filterable} hidden={!!hideLabel} disabled={disabled} fluid={fluid}>\n                    {label}\n                </MultiLabel>\n                {filterable ? <FilterField {...rest} ref={ref as Ref<HTMLInputElement>} look={look} /> : <TriggerField {...rest} ref={ref as Ref<HTMLButtonElement>} look={look} />}\n                <FieldMessageLine id={`${fieldId}-message`} message={message} content={content} disabled={disabled} fluid={fluid} />\n                <MultiSelectPrimitive.Popup side={direction} className={listMenuClasses}>\n                    {(shown) => <MultiRows items={shown} labels={t} />}\n                </MultiSelectPrimitive.Popup>\n                <MultiStatus labels={t} />\n            </div>\n        </MultiSelectPrimitive.Root>\n    );\n}\n\n/** What the field parts need from the props. */\ninterface FieldLook {\n    fieldId: string;\n    placeholder: string;\n    showError: boolean;\n    statusKind: FieldMessage['kind'] | undefined;\n    messageKind: FieldMessage['kind'] | undefined;\n    hasMessage: boolean;\n    fluid: boolean;\n    labels: { selectedCount: (count: number) => string; clearAll: string; clear: string; closeList: string; openList: string };\n}\n\n/** The count and the message describe the field. */\nfunction useDescribedBy(look: FieldLook) {\n    const { count } = MultiSelectPrimitive.useMultiSelectContext();\n    return joinIds(count > 0 && `${look.fieldId}-count`, look.hasMessage && `${look.fieldId}-message`);\n}\n\n/** Filterable: a text box in the field (after the count tag), with × and the chevron button. */\nfunction FilterField({ look, ...rest }: Readonly<HTMLAttributes<HTMLElement> & { look: FieldLook; ref?: Ref<HTMLInputElement> }>) {\n    const { open, count, text, interactive, disabled, readOnly } = MultiSelectPrimitive.useMultiSelectContext();\n    const describedBy = useDescribedBy(look);\n    const showClearText = interactive && text !== '';\n    return (\n        <MultiSelectPrimitive.Anchor className={filterBoxClasses({ open, showError: look.showError, disabled, readOnly, fluid: look.fluid })}>\n            <CountTag id={`${look.fieldId}-count`} fluid={look.fluid} labels={look.labels} />\n            <MultiSelectPrimitive.Input\n                {...rest}\n                aria-describedby={describedBy}\n                placeholder={look.placeholder || undefined}\n                className={filterInputClasses({ showClearText, hasStatus: !!look.statusKind, hasValue: count > 0, fluid: look.fluid })}\n            />\n            <FieldControls\n                status={look.statusKind ? <StatusIcon kind={look.statusKind} className={look.fluid ? 'absolute end-4 top-[50px]' : undefined} /> : null}\n                clearLabel={look.labels.clear}\n                Clear={showClearText ? MultiSelectPrimitive.ClearText : undefined}\n                toggleLabel={open ? look.labels.closeList : look.labels.openList}\n                Toggle={MultiSelectPrimitive.Toggle}\n                open={open}\n                disabled={disabled}\n                readOnly={readOnly}\n                fluid={look.fluid}\n            />\n        </MultiSelectPrimitive.Anchor>\n    );\n}\n\n/** The field is a button that opens the list; the count tag and the chevron sit over it. */\nfunction TriggerField({ look, ...rest }: Readonly<HTMLAttributes<HTMLElement> & { look: FieldLook; ref?: Ref<HTMLButtonElement> }>) {\n    const { count, disabled, readOnly } = MultiSelectPrimitive.useMultiSelectContext();\n    const describedBy = useDescribedBy(look);\n    return (\n        <MultiSelectPrimitive.Anchor className=\"relative\">\n            <MultiSelectPrimitive.Trigger\n                {...rest}\n                aria-describedby={describedBy}\n                className={triggerClasses({ hasValue: count > 0, showError: look.showError, statusKind: look.statusKind, disabled, readOnly, fluid: look.fluid })}\n            >\n                <MultiSelectPrimitive.Value placeholder={look.placeholder} className=\"truncate text-ink-muted\" />\n            </MultiSelectPrimitive.Trigger>\n            <CountTag id={`${look.fieldId}-count`} fluid={look.fluid} labels={look.labels} />\n            <MultiChevron kind={look.messageKind} fluid={look.fluid} readOnly={readOnly} disabled={disabled} />\n        </MultiSelectPrimitive.Anchor>\n    );\n}\n\n/** The open list: \"Select all\", then \"Searching…\" / \"Loading…\" / \"No results\" or the options with their checkboxes. */\nfunction MultiRows({ items, labels }: Readonly<{ items: ListItem[]; labels: { searching: string; noResults: string; loadingOptions: string; selectAll: string } }>) {\n    const { filterable, loading, rows, value } = MultiSelectPrimitive.useMultiSelectContext();\n    const empty = emptyText({ filterable, loading, count: rows.length }, labels);\n    return (\n        <>\n            <SelectAllRow label={labels.selectAll} />\n            {empty ? <EmptyRow>{empty}</EmptyRow> : <ListRows items={items} isSelected={(o) => value.includes(o.value)} lead={rowLead} />}\n        </>\n    );\n}\n\n/** What the open list says to screen readers. */\nfunction MultiStatus({ labels }: Readonly<{ labels: { searching: string; noResults: string; loadingOptions: string } }>) {\n    const { filterable, open, loading, rows } = MultiSelectPrimitive.useMultiSelectContext();\n    return <ListStatus>{listStatus({ filterable, open, loading, count: rows.length }, labels)}</ListStatus>;\n}\n"
    }
  ]
}
