import React, { ClipboardEvent, FocusEvent, HTMLAttributes, KeyboardEvent, ReactNode, forwardRef, isValidElement, useId, useMemo, useRef, useState, } from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import { useChipSet } from '../chip-set/useChipSet' import { useForkedRef } from '../../hooks' import { isRTL } from '../../utils' type ChipClassName = string | ((value: string) => string) export interface CChipInputProps extends Omit< HTMLAttributes, 'onChange' | 'onInput' | 'onSelect' > { /** * Declarative `CChip` children used as the initial chips. Their values seed the uncontrolled value when `defaultValue` is not provided (parity with the vanilla Chip Input). */ children?: ReactNode /** * Adds custom classes to chips rendered by the React Chip Input component. Accepts a static className or a resolver function based on chip value. */ chipClassName?: ChipClassName /** * Adds custom classes to the React Chip Input component root element. */ className?: string /** * Creates a new chip when the React Chip Input component loses focus with a pending value. */ createOnBlur?: boolean /** * Sets the initial uncontrolled values rendered by the React Chip Input component. */ defaultValue?: string[] /** * Disables the React Chip Input component and prevents adding, removing, or selecting chips. */ disabled?: boolean /** * Renders the chips as filter chips, each showing a leading check icon while selected. Implies `selectable`. */ filter?: boolean /** * Sets the `id` of the internal text input rendered by the React Chip Input component. */ id?: string /** * Renders an inline label inside the React Chip Input component container. */ label?: ReactNode /** * Sets the maximum number of chips that can be created in the React Chip Input component. */ maxChips?: number | null /** * Sets the name of the hidden input used by the React Chip Input component for form submission. */ name?: string /** * Callback fired when the React Chip Input component adds a new chip. */ onAdd?: (value: string) => void /** * Callback fired when the value list of the React Chip Input component changes. */ onChange?: (values: string[]) => void /** * Callback fired when the internal text input value changes in the React Chip Input component. */ onInput?: (value: string) => void /** * Callback fired when the React Chip Input component removes a chip. */ onRemove?: (value: string) => void /** * Callback fired when the selected chip values change in the React Chip Input component. */ onSelect?: (selected: string[]) => void /** * Sets placeholder text for the internal input of the React Chip Input component. */ placeholder?: string /** * Makes the React Chip Input component readonly while keeping values visible. */ readOnly?: boolean /** * Displays remove buttons on chips managed by the React Chip Input component. */ removable?: boolean /** * Enables chip selection behavior in the React Chip Input component. */ selectable?: boolean /** * Sets how many chips can be selected at once in the React Chip Input component. */ selectionMode?: 'single' | 'multiple' /** * Sets the separator character used to create chips while typing or pasting in the React Chip Input component. */ separator?: string | null /** * Sets the size of the React Chip Input component to small or large. */ size?: 'sm' | 'lg' /** * Controls the values rendered by the React Chip Input component. * * @controllable onChange */ value?: string[] } const resolveChipClassName = (chipClassName: ChipClassName | undefined, value: string) => { if (!chipClassName) { return } if (typeof chipClassName === 'function') { const resolvedClassName = chipClassName(value) return typeof resolvedClassName === 'string' ? resolvedClassName : undefined } return chipClassName } const uniqueValues = (values: string[]) => [ ...new Set(values.map((value) => value.trim()).filter(Boolean)), ] // Initial chip values can be supplied declaratively as CChip children (parity // with the vanilla ChipInput, which reads existing .chip elements on init). const valuesFromChildren = (children: ReactNode): string[] => { const values: string[] = [] React.Children.forEach(children, (child) => { if (!isValidElement(child)) { return } const { value, children: childContent } = child.props as { value?: string children?: ReactNode } const chipValue = value ?? (typeof childContent === 'string' ? childContent : undefined) if (chipValue) { values.push(chipValue) } }) return values } export const CChipInput = forwardRef( ( { children, className, chipClassName, createOnBlur = true, defaultValue = [], disabled, filter, id, label, maxChips = null, name, onAdd, onChange, onInput, onRemove, onSelect, placeholder = '', readOnly, removable = true, selectable, selectionMode, separator = ',', size, value, ...rest }, ref ) => { const isControlled = value !== undefined const [_values, setValues] = useState(() => uniqueValues(defaultValue.length > 0 ? defaultValue : valuesFromChildren(children)) ) const [inputValue, setInputValue] = useState('') const inputRef = useRef(null) const generatedName = useId() const values = useMemo( () => uniqueValues(isControlled ? (value as string[]) : _values), [isControlled, value, _values] ) // Build CChipInput on the same engine as CChipSet: selection coordination, // roving focus, and chip prop injection all live in useChipSet. CChipInput // owns the chip list and adds the text-input layer on top. const { rootRef, clearSelection, getFocusableChips, handleKeyDown, renderChipsFromData } = useChipSet({ ariaRemoveLabel: undefined, disabled, filter, removable: Boolean(removable && !disabled && !readOnly), selectable, selectionMode, restoreFocusOnRemove: false, onSelectionChange: onSelect, onRemoveChip: (chipValue) => remove(chipValue), }) const forkedRef = useForkedRef(ref, rootRef) const emitValuesChange = (nextValues: string[]) => { if (!isControlled) { setValues(nextValues) } onChange?.(nextValues) } const canAddMore = maxChips === null || values.length < maxChips const add = (rawValue: string) => { if (disabled || readOnly) { return false } const normalizedValue = String(rawValue).trim() if (!normalizedValue || values.includes(normalizedValue) || !canAddMore) { return false } const nextValues = [...values, normalizedValue] emitValuesChange(nextValues) onAdd?.(normalizedValue) return true } const remove = (valueToRemove: string) => { if (disabled || readOnly) { return false } if (!values.includes(valueToRemove)) { return false } // Selection is cleaned up by useChipSet; here we just drop the value. emitValuesChange(values.filter((item) => item !== valueToRemove)) onRemove?.(valueToRemove) inputRef.current?.focus() return true } const createFromInput = () => { if (add(inputValue)) { setInputValue('') } } const focusLastChip = () => { const chips = getFocusableChips() chips[chips.length - 1]?.focus() } const handleInputKeyDown = (event: KeyboardEvent) => { switch (event.key) { case 'Enter': { event.preventDefault() createFromInput() break } case 'Backspace': case 'Delete': { if (inputValue === '') { event.preventDefault() focusLastChip() } break } case 'ArrowLeft': case 'ArrowRight': { // The arrow pointing toward the chips (left in LTR, right in RTL) jumps // to the last chip when the caret is at the start of the input. const towardChipsKey = isRTL(rootRef.current) ? 'ArrowRight' : 'ArrowLeft' if ( event.key === towardChipsKey && event.currentTarget.selectionStart === 0 && event.currentTarget.selectionEnd === 0 ) { event.preventDefault() focusLastChip() } break } case 'Escape': { setInputValue('') event.currentTarget.blur() break } // No default } } const handleInputChange = (value: string) => { if (disabled || readOnly) { return } if (separator && value.includes(separator)) { const parts = value.split(separator) const chipsToAdd = uniqueValues(parts.slice(0, -1)) const nextValues = [...values] for (const chipValue of chipsToAdd) { if (maxChips !== null && nextValues.length >= maxChips) { break } if (!nextValues.includes(chipValue)) { nextValues.push(chipValue) onAdd?.(chipValue) } } if (nextValues.length !== values.length) { emitValuesChange(nextValues) } const tail = parts[parts.length - 1] || '' setInputValue(tail) onInput?.(tail) return } setInputValue(value) onInput?.(value) } const handlePaste = (event: ClipboardEvent) => { if (disabled || readOnly || !separator) { return } const pastedData = event.clipboardData.getData('text') if (!pastedData.includes(separator)) { return } event.preventDefault() const chipsToAdd = uniqueValues(pastedData.split(separator)) const nextValues = [...values] for (const chipValue of chipsToAdd) { if (maxChips !== null && nextValues.length >= maxChips) { break } if (!nextValues.includes(chipValue)) { nextValues.push(chipValue) onAdd?.(chipValue) } } if (nextValues.length !== values.length) { emitValuesChange(nextValues) } setInputValue('') onInput?.('') } const handleInputBlur = (event: FocusEvent) => { if (!createOnBlur) { return } if ((event.relatedTarget as HTMLElement | null)?.closest('.chip')) { return } createFromInput() } const handleContainerKeyDown = (event: KeyboardEvent) => { if (event.target === inputRef.current) { return } // The arrow past the last chip moves focus into the text field (mirrored in RTL). if (event.key === (isRTL(rootRef.current) ? 'ArrowLeft' : 'ArrowRight')) { const chips = getFocusableChips() const lastChip = chips[chips.length - 1] if (lastChip?.contains(event.target as Node)) { event.preventDefault() inputRef.current?.focus() return } } if (handleKeyDown(event)) { return } if (event.key.length === 1) { inputRef.current?.focus() } } const handleContainerClick = (event: React.MouseEvent) => { if (event.target === rootRef.current) { inputRef.current?.focus() } } const inputSize = Math.max(placeholder.length, inputValue.length, 1) return (
{label && ( )} {renderChipsFromData( values.map((chipValue) => ({ value: chipValue, label: chipValue, className: resolveChipClassName(chipClassName, chipValue), ariaRemoveLabel: `Remove ${chipValue}`, })) )} handleInputChange(event.target.value)} onKeyDown={handleInputKeyDown} onPaste={handlePaste} onFocus={clearSelection} ref={inputRef} />
) } ) CChipInput.propTypes = { children: PropTypes.node, chipClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), className: PropTypes.string, createOnBlur: PropTypes.bool, defaultValue: PropTypes.array, disabled: PropTypes.bool, filter: PropTypes.bool, id: PropTypes.string, label: PropTypes.node, maxChips: PropTypes.number, name: PropTypes.string, onAdd: PropTypes.func, onChange: PropTypes.func, onInput: PropTypes.func, onRemove: PropTypes.func, onSelect: PropTypes.func, placeholder: PropTypes.string, readOnly: PropTypes.bool, removable: PropTypes.bool, selectable: PropTypes.bool, selectionMode: PropTypes.oneOf(['single', 'multiple']), separator: PropTypes.string, size: PropTypes.oneOf(['sm', 'lg']), value: PropTypes.array, } CChipInput.displayName = 'CChipInput'