@eifi1/ui-kit 0.5.1 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -1
- package/dist/components/amount-input.d.ts +7 -0
- package/dist/components/autocomplete.d.ts +103 -0
- package/dist/components/autocomplete.js +260 -0
- package/dist/components/autocomplete.js.map +1 -0
- package/dist/components/calculator.d.ts +7 -0
- package/dist/components/checkbox.d.ts +9 -0
- package/dist/components/checkbox.js +7 -2
- package/dist/components/checkbox.js.map +1 -1
- package/dist/components/chip.d.ts +3 -2
- package/dist/components/chip.js +14 -1
- package/dist/components/chip.js.map +1 -1
- package/dist/components/choice-card.d.ts +100 -0
- package/dist/components/choice-card.js +170 -0
- package/dist/components/choice-card.js.map +1 -0
- package/dist/components/combobox-core.d.ts +76 -6
- package/dist/components/combobox-core.js +119 -49
- package/dist/components/combobox-core.js.map +1 -1
- package/dist/components/combobox.d.ts +12 -2
- package/dist/components/combobox.js +42 -17
- package/dist/components/combobox.js.map +1 -1
- package/dist/components/danger-confirm.d.ts +91 -0
- package/dist/components/danger-confirm.js +181 -0
- package/dist/components/danger-confirm.js.map +1 -0
- package/dist/components/dialog-frame.d.ts +84 -0
- package/dist/components/dialog-frame.js +86 -0
- package/dist/components/dialog-frame.js.map +1 -0
- package/dist/components/disclosure.d.ts +108 -0
- package/dist/components/disclosure.js +127 -0
- package/dist/components/disclosure.js.map +1 -0
- package/dist/components/entity-combobox.d.ts +17 -3
- package/dist/components/entity-combobox.js +25 -5
- package/dist/components/entity-combobox.js.map +1 -1
- package/dist/components/file-button.d.ts +161 -0
- package/dist/components/file-button.js +243 -0
- package/dist/components/file-button.js.map +1 -0
- package/dist/components/file-dropzone.d.ts +72 -23
- package/dist/components/file-dropzone.js +219 -94
- package/dist/components/file-dropzone.js.map +1 -1
- package/dist/components/icon-picker.d.ts +72 -0
- package/dist/components/icon-picker.js +104 -0
- package/dist/components/icon-picker.js.map +1 -0
- package/dist/components/mini-calendar.d.ts +3 -0
- package/dist/components/mini-calendar.js +4 -3
- package/dist/components/mini-calendar.js.map +1 -1
- package/dist/components/modal.d.ts +8 -1
- package/dist/components/modal.js +4 -2
- package/dist/components/modal.js.map +1 -1
- package/dist/components/multi-entity-combobox.d.ts +16 -3
- package/dist/components/multi-entity-combobox.js +25 -5
- package/dist/components/multi-entity-combobox.js.map +1 -1
- package/dist/components/number-field.d.ts +41 -1
- package/dist/components/number-field.js +42 -10
- package/dist/components/number-field.js.map +1 -1
- package/dist/components/number-input.d.ts +35 -2
- package/dist/components/number-input.js +35 -4
- package/dist/components/number-input.js.map +1 -1
- package/dist/components/numpad-sheet.d.ts +7 -0
- package/dist/components/search-field.d.ts +16 -0
- package/dist/components/search-field.js +29 -7
- package/dist/components/search-field.js.map +1 -1
- package/dist/components/signature-pad.d.ts +43 -1
- package/dist/components/signature-pad.js +74 -2
- package/dist/components/signature-pad.js.map +1 -1
- package/dist/components/swatch-picker.d.ts +69 -0
- package/dist/components/swatch-picker.js +75 -0
- package/dist/components/swatch-picker.js.map +1 -0
- package/dist/components/switch.d.ts +9 -0
- package/dist/components/switch.js +7 -2
- package/dist/components/switch.js.map +1 -1
- package/dist/components/tile-radio.d.ts +50 -0
- package/dist/components/tile-radio.js +140 -0
- package/dist/components/tile-radio.js.map +1 -0
- package/dist/components/toggle-group.d.ts +27 -5
- package/dist/components/toggle-group.js +22 -15
- package/dist/components/toggle-group.js.map +1 -1
- package/dist/components/ui.d.ts +150 -12
- package/dist/components/ui.js +196 -22
- package/dist/components/ui.js.map +1 -1
- package/dist/i18n/defaults.d.ts +7 -0
- package/dist/i18n/defaults.js +13 -2
- package/dist/i18n/defaults.js.map +1 -1
- package/dist/i18n/kit-labels.d.ts +38 -5
- package/dist/i18n/kit-labels.js +12 -4
- package/dist/i18n/kit-labels.js.map +1 -1
- package/dist/index.d.ts +16 -7
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -1
- package/dist/lib/table-text.d.ts +127 -0
- package/dist/lib/table-text.js +82 -0
- package/dist/lib/table-text.js.map +1 -0
- package/dist/rhf/form.d.ts +79 -0
- package/dist/rhf/form.js +143 -0
- package/dist/rhf/form.js.map +1 -0
- package/dist/rhf.d.ts +4 -0
- package/dist/rhf.js +3 -0
- package/dist/rhf.js.map +1 -0
- package/dist/shell/app-shell.js +3 -1
- package/dist/shell/app-shell.js.map +1 -1
- package/dist/table-text.d.ts +1 -0
- package/dist/table-text.js +3 -0
- package/dist/table-text.js.map +1 -0
- package/package.json +14 -1
- package/src/components/autocomplete.tsx +429 -0
- package/src/components/checkbox.tsx +16 -0
- package/src/components/chip.tsx +24 -2
- package/src/components/choice-card.tsx +305 -0
- package/src/components/combobox-core.tsx +228 -58
- package/src/components/combobox.tsx +58 -21
- package/src/components/danger-confirm.tsx +286 -0
- package/src/components/dialog-frame.tsx +179 -0
- package/src/components/disclosure.tsx +259 -0
- package/src/components/entity-combobox.tsx +41 -6
- package/src/components/file-button.tsx +458 -0
- package/src/components/file-dropzone.tsx +323 -117
- package/src/components/icon-picker.tsx +181 -0
- package/src/components/mini-calendar.tsx +7 -3
- package/src/components/modal.tsx +10 -2
- package/src/components/multi-entity-combobox.tsx +40 -6
- package/src/components/number-field.tsx +86 -10
- package/src/components/number-input.tsx +79 -2
- package/src/components/search-field.tsx +49 -6
- package/src/components/signature-pad.tsx +112 -0
- package/src/components/swatch-picker.tsx +141 -0
- package/src/components/switch.tsx +16 -0
- package/src/components/tile-radio.tsx +228 -0
- package/src/components/toggle-group.tsx +54 -18
- package/src/components/ui.tsx +400 -24
- package/src/i18n/defaults.ts +12 -1
- package/src/i18n/kit-labels.tsx +45 -5
- package/src/index.ts +19 -0
- package/src/lib/table-text.ts +265 -0
- package/src/rhf/form.tsx +300 -0
- package/src/rhf.ts +9 -0
- package/src/shell/app-shell.tsx +3 -1
- package/src/table-text.ts +8 -0
package/dist/components/chip.js
CHANGED
|
@@ -29,11 +29,24 @@ const TONE = {
|
|
|
29
29
|
info: {
|
|
30
30
|
idle: "border-[var(--info-border)] bg-[var(--info-bg)] text-[var(--info)]",
|
|
31
31
|
selected: "border-[var(--info)] bg-[var(--info-bg)] text-[var(--info)]"
|
|
32
|
+
},
|
|
33
|
+
// The money pair (Keksdose's direction toggle). Only the TEXT and the BORDER carry
|
|
34
|
+
// the tint, on the neutral chip's own surfaces: the money tokens are chosen for text
|
|
35
|
+
// contrast, and a filled amber pill beside an amber figure reads as one smear.
|
|
36
|
+
// `border-current` takes its hue from the text, so the two cannot drift apart.
|
|
37
|
+
income: {
|
|
38
|
+
idle: "border-current/40 bg-[var(--bg-surface-2)] text-[var(--money-income)]",
|
|
39
|
+
selected: "border-current bg-[var(--bg-active)] text-[var(--money-income)]"
|
|
40
|
+
},
|
|
41
|
+
expense: {
|
|
42
|
+
idle: "border-current/40 bg-[var(--bg-surface-2)] text-[var(--money-expense)]",
|
|
43
|
+
selected: "border-current bg-[var(--bg-active)] text-[var(--money-expense)]"
|
|
32
44
|
}
|
|
33
45
|
};
|
|
34
46
|
const SIZE = {
|
|
35
47
|
sm: { body: "gap-1 px-2 py-0.5 text-xs", icon: "size-3", remove: "size-3" },
|
|
36
|
-
md: { body: "gap-1.5 px-2.5 py-1 text-sm", icon: "size-3.5", remove: "size-3.5" }
|
|
48
|
+
md: { body: "gap-1.5 px-2.5 py-1 text-sm", icon: "size-3.5", remove: "size-3.5" },
|
|
49
|
+
lg: { body: "min-h-11 gap-2 px-4 py-2 text-sm", icon: "size-4", remove: "size-4" }
|
|
37
50
|
};
|
|
38
51
|
const CHIP_BASE = "inline-flex max-w-full items-center rounded-full border transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)] focus-visible:ring-offset-1 focus-visible:ring-offset-[var(--bg-surface)]";
|
|
39
52
|
const Chip = forwardRef(function Chip2({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/chip.tsx"],"sourcesContent":["import { forwardRef, useId, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent, MouseEvent, ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\nimport type { LucideIcon } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { FIELD_INVALID } from \"./ui\";\nimport { DEFAULT_COMMON_LABELS, useKitLabels, useKitLocale } from \"../i18n/kit-labels\";\n\n/**\n * A chip: a compact pill carrying one value.\n *\n * Three jobs, deliberately one component. A chip can be inert (a tag on a row), a link\n * (a jump to a section), or a toggle (a filter that is on or off) — and the difference is\n * which prop you pass, not which component you pick. Keeping them together is what stops\n * an app growing three near-identical pills that drift apart; it is the shape this kit\n * already uses for `Button`, which is a link when it is given an href.\n *\n * A chip is not a `Button`. It is smaller, it is rounded to a pill, and it reads as a\n * VALUE rather than as an action — which matters because a row of eight buttons says\n * \"choose one of eight things to do\" and a row of eight chips says \"here are eight\n * things\". Using `Button` for both is the mistake this exists to prevent.\n */\n\nexport type ChipTone = \"neutral\" | \"brand\" | \"danger\" | \"warning\" | \"success\" | \"info\";\nexport type ChipSize = \"sm\" | \"md\";\n\nconst TONE: Record<ChipTone, { idle: string; selected: string }> = {\n neutral: {\n idle: \"border-[var(--border)] bg-[var(--bg-surface-2)] text-[var(--text-secondary)]\",\n selected: \"border-[var(--border-strong)] bg-[var(--bg-active)] text-[var(--text-primary)]\",\n },\n brand: {\n idle: \"border-[var(--border)] bg-[var(--brand-bg)] text-[var(--brand-muted)]\",\n selected: \"border-[var(--brand)] bg-[var(--brand)] text-[var(--brand-contrast)]\",\n },\n danger: {\n idle: \"border-[var(--danger-border)] bg-[var(--danger-bg)] text-[var(--danger)]\",\n selected: \"border-[var(--danger)] bg-[var(--danger)] text-[var(--danger-contrast)]\",\n },\n warning: {\n idle: \"border-[var(--warning-border)] bg-[var(--warning-bg)] text-[var(--warning)]\",\n selected: \"border-[var(--warning)] bg-[var(--warning-bg)] text-[var(--warning)]\",\n },\n success: {\n idle: \"border-[var(--success-border)] bg-[var(--success-bg)] text-[var(--success)]\",\n selected: \"border-[var(--success)] bg-[var(--success-bg)] text-[var(--success)]\",\n },\n info: {\n idle: \"border-[var(--info-border)] bg-[var(--info-bg)] text-[var(--info)]\",\n selected: \"border-[var(--info)] bg-[var(--info-bg)] text-[var(--info)]\",\n },\n};\n\nconst SIZE: Record<ChipSize, { body: string; icon: string; remove: string }> = {\n sm: { body: \"gap-1 px-2 py-0.5 text-xs\", icon: \"size-3\", remove: \"size-3\" },\n md: { body: \"gap-1.5 px-2.5 py-1 text-sm\", icon: \"size-3.5\", remove: \"size-3.5\" },\n};\n\nconst CHIP_BASE =\n \"inline-flex max-w-full items-center rounded-full border transition-colors \" +\n // `focus-visible`, not `focus`: a chip commonly receives focus programmatically (the\n // ChipInput moves focus onto one after a removal) and a ring that appears on a\n // pointer click reads as a stuck selection.\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)] focus-visible:ring-offset-1 focus-visible:ring-offset-[var(--bg-surface)]\";\n\nexport interface ChipProps {\n children: ReactNode;\n tone?: ChipTone;\n size?: ChipSize;\n icon?: LucideIcon;\n /**\n * Marks the chip as the current one — `aria-current` on a link, `aria-pressed` on a\n * toggle.\n *\n * On a toggle, keep the LABEL the same in both states and let `selected` carry the\n * state. A label that flips with it (\"Skip this month\" / \"Ask again this month\") is\n * announced together with \"pressed\", and then says the opposite of what it does.\n */\n selected?: boolean;\n /** Renders the chip as a link. Mutually exclusive with `onClick`. */\n href?: string;\n /** Renders the chip as a toggle button. Mutually exclusive with `href`. Receives the\n * click, so a chip inside a clickable row can `stopPropagation()`. */\n onClick?: (event: MouseEvent<HTMLButtonElement>) => void;\n /** Renders a dismiss affordance. Works alongside `href`/`onClick` — see the note below. */\n onRemove?: () => void;\n /** Accessible name for the dismiss button. Default: `common.remove` from the\n * {@link UiKitProvider}, else \"Remove\". */\n removeLabel?: string;\n disabled?: boolean;\n className?: string;\n /**\n * Roving focus, for a container that manages a row of chips (see {@link ChipInput}).\n * A chip with no `href`/`onClick` is inert and unfocusable by default; give it a\n * `tabIndex` and a `role` and it becomes the thing arrow keys move between.\n */\n tabIndex?: number;\n role?: string;\n onKeyDown?: (e: KeyboardEvent<HTMLElement>) => void;\n onFocus?: () => void;\n /** Accessible name, when the visible text is not the whole story. */\n \"aria-label\"?: string;\n /** Any other ARIA attribute — `aria-describedby`, `aria-expanded`, `aria-controls`,\n * `aria-haspopup` — reaches the chip's interactive element. */\n [key: `aria-${string}`]: string | boolean | number | undefined;\n /** A test id, a `data-tour` anchor, or any other data attribute. */\n [key: `data-${string}`]: unknown;\n id?: string;\n /** A native tooltip. For anything a user must read, prefer the kit's `Tooltip`. */\n title?: string;\n}\n\n/**\n * Note on `onRemove` with `href`/`onClick`: a button cannot be nested inside a button or\n * a link, so when both are present the chip renders a wrapper holding TWO siblings — the\n * interactive body and the dismiss control. That is why the outer element is not always\n * the interactive one, and why the focus ring is drawn on the body rather than the\n * wrapper.\n */\nexport const Chip = forwardRef<HTMLElement, ChipProps>(function Chip(\n {\n children,\n tone = \"neutral\",\n size = \"md\",\n icon: Icon,\n selected = false,\n href,\n onClick,\n onRemove,\n removeLabel,\n disabled = false,\n className,\n tabIndex,\n role,\n onKeyDown,\n onFocus,\n ...rest\n },\n ref,\n) {\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS, { remove: removeLabel });\n const s = SIZE[size];\n const palette = TONE[tone];\n const interactive = !!href || !!onClick;\n const look = cn(\n CHIP_BASE,\n s.body,\n selected ? palette.selected : palette.idle,\n interactive && !disabled && \"cursor-pointer hover:brightness-[0.97] dark:hover:brightness-110\",\n disabled && \"cursor-default opacity-50\",\n className,\n );\n\n const body = (\n <>\n {Icon && <Icon className={cn(s.icon, \"shrink-0\")} aria-hidden />}\n <span className=\"min-w-0 truncate\">{children}</span>\n </>\n );\n\n const remove = onRemove ? (\n <button\n type=\"button\"\n // The name carries WHAT is being removed, not just \"Remove\" — a screen-reader user\n // tabbing a row of eight dismiss buttons otherwise hears the same word eight times\n // with no way to tell which one they are on.\n // Composed through `common.fieldValue` because the punctuation between the two\n // halves is the language's, not ours. A chip whose content is not plain text\n // has no value to name, and gets the bare verb rather than a dangling colon.\n aria-label={\n typeof children === \"string\" && children\n ? common.fieldValue(common.remove, children)\n : common.remove\n }\n onClick={(e) => {\n // The chip may itself be a link; removing it must not also follow it.\n e.preventDefault();\n e.stopPropagation();\n onRemove();\n }}\n disabled={disabled}\n className={cn(\n \"-mr-0.5 ml-0.5 shrink-0 rounded-full p-0.5 transition-colors\",\n \"hover:bg-[var(--bg-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)]\",\n disabled && \"pointer-events-none\",\n )}\n >\n <X className={s.remove} aria-hidden />\n </button>\n ) : null;\n\n // ── The three shapes.\n if (href && !disabled) {\n const link = (\n <a\n ref={ref as React.Ref<HTMLAnchorElement>}\n href={href}\n aria-current={selected ? \"true\" : undefined}\n className={cn(look, remove && \"pr-1.5\")}\n {...rest}\n >\n {body}\n {!remove && null}\n </a>\n );\n return remove ? (\n <span className=\"inline-flex items-center\">\n {link}\n {remove}\n </span>\n ) : (\n link\n );\n }\n\n if (onClick) {\n const button = (\n <button\n ref={ref as React.Ref<HTMLButtonElement>}\n type=\"button\"\n onClick={onClick}\n disabled={disabled}\n aria-pressed={selected}\n className={cn(look, remove && \"pr-1.5\")}\n {...rest}\n >\n {body}\n </button>\n );\n return remove ? (\n <span className=\"inline-flex items-center\">\n {button}\n {remove}\n </span>\n ) : (\n button\n );\n }\n\n return (\n <span\n ref={ref as React.Ref<HTMLSpanElement>}\n className={look}\n tabIndex={tabIndex}\n role={role}\n onKeyDown={onKeyDown}\n onFocus={onFocus}\n {...rest}\n >\n {body}\n {remove}\n </span>\n );\n});\n\n/* ── ChipInput ────────────────────────────────────────────────────────────── */\n\nexport interface ChipInputLabels {\n /** Announced after a value is added. Receives the value. */\n added: (value: string) => string;\n /** Announced after a value is removed. Receives the value. */\n removed: (value: string) => string;\n /** Accessible name for each chip's dismiss button. */\n remove: string;\n /** Shown when `max` is reached. Receives the limit. */\n atLimit: (max: number) => string;\n /** Shown when a duplicate is rejected. Receives the value. */\n duplicate: (value: string) => string;\n}\n\nexport const DEFAULT_CHIP_INPUT_LABELS: ChipInputLabels = {\n added: (v) => `${v} added`,\n removed: (v) => `${v} removed`,\n remove: \"Remove\",\n atLimit: (max) => `Limit of ${max} reached`,\n duplicate: (v) => `${v} is already in the list`,\n};\n\nexport function resolveChipInputLabels(labels?: Partial<ChipInputLabels>): ChipInputLabels {\n return labels ? { ...DEFAULT_CHIP_INPUT_LABELS, ...labels } : DEFAULT_CHIP_INPUT_LABELS;\n}\n\n/**\n * `onChange` is the field's own — the whole LIST, not a DOM event — so the wrapper\n * div's `onChange` is omitted rather than shadowed. `placeholder` is likewise this\n * component's, forwarded to the inner `<input>`; the div has none of its own.\n */\nexport interface ChipInputProps\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\" | \"placeholder\" | \"children\"> {\n value: string[];\n onChange: (next: string[]) => void;\n placeholder?: string;\n /** Visible label, rendered above the field. Without one, name the field with\n * `aria-label`. */\n label?: string;\n /**\n * @deprecated Pass `aria-label` instead — the DOM spelling the rest of this kit\n * now uses. Still honoured, and still second to `aria-label` when both are given.\n */\n ariaLabel?: string;\n /** Reject or rewrite a value on commit. Return a string to reject WITH that message. */\n validate?: (raw: string) => string | null;\n /** Characters that commit the current text, besides Enter. Default: comma. */\n separators?: string[];\n allowDuplicates?: boolean;\n max?: number;\n tone?: ChipTone;\n size?: ChipSize;\n disabled?: boolean;\n invalid?: boolean;\n /** Error text. Wires `aria-describedby` and implies `invalid`. */\n error?: ReactNode;\n labels?: Partial<ChipInputLabels>;\n className?: string;\n}\n\n/**\n * A field whose value is a LIST, entered as chips.\n *\n * The keyboard model is the whole component; the pills are the easy part. Per the WAI\n * pattern for a \"tag\" input:\n *\n * Enter, or any separator commit the typed text\n * Backspace on empty text move focus to the last chip (does NOT delete it)\n * ← → while on a chip move between chips\n * Backspace / Delete remove the focused chip, focus its neighbour\n * Escape clear what is typed but keep the committed chips\n * paste splits on the separators, so a pasted CSV becomes chips\n *\n * The Backspace-on-empty behaviour is the one worth arguing about. Deleting immediately\n * is more common and is a trap: it is a destructive action with no feedback on a key\n * people hit by reflex, and the value it destroys may have taken a while to type. Moving\n * focus first makes the second Backspace a deliberate one, and it is what lets a\n * keyboard user reach a chip at all.\n */\nexport function ChipInput({\n value,\n onChange,\n placeholder,\n label,\n ariaLabel,\n validate,\n separators = [\",\"],\n allowDuplicates = false,\n max,\n tone = \"neutral\",\n size = \"md\",\n disabled = false,\n invalid = false,\n error,\n labels,\n className,\n \"aria-label\": ariaLabelAttr,\n ...rest\n}: ChipInputProps) {\n // `labels` over the provider's `chipInput` over English — the same order\n // `resolveChipInputLabels` gives outside a provider.\n const text = useKitLabels(\"chipInput\", DEFAULT_CHIP_INPUT_LABELS, labels);\n // A batch of pasted values is announced as one list, joined the way the language\n // joins a list in a sentence (\"a, b and c added\") — hence the long conjunction,\n // where a trigger's summary would use the narrow one.\n const locale = useKitLocale();\n const [draft, setDraft] = useState(\"\");\n const [message, setMessage] = useState(\"\");\n const [focusedChip, setFocusedChip] = useState<number | null>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const chipRefs = useRef<Array<HTMLElement | null>>([]);\n const id = useId();\n const listId = `${id}-list`;\n const errorId = `${id}-error`;\n const isInvalid = invalid || !!error;\n\n const focusChip = (index: number | null) => {\n setFocusedChip(index);\n if (index === null) inputRef.current?.focus();\n else chipRefs.current[index]?.focus();\n };\n\n /**\n * Try to add every candidate, as ONE change.\n *\n * Batched rather than looped for a reason that bites immediately: `commit` closes over\n * `value`, so calling it once per pasted item makes every call compute its result from\n * the list as it was BEFORE the paste, and each `onChange` overwrites the last. A\n * pasted \"one,two,three\" left only \"three\". Accumulating locally and emitting once is\n * also the correct behaviour for an undo stack — a paste is one action.\n */\n const commitMany = (raws: string[]): { added: string[]; rejection: string | null } => {\n const next = [...value];\n const added: string[] = [];\n let rejection: string | null = null;\n\n for (const raw of raws) {\n const candidate = raw.trim();\n if (!candidate) continue;\n if (max !== undefined && next.length >= max) {\n rejection ??= text.atLimit(max);\n break;\n }\n if (!allowDuplicates && next.includes(candidate)) {\n rejection ??= text.duplicate(candidate);\n continue;\n }\n const invalidReason = validate?.(candidate);\n if (invalidReason) {\n rejection ??= invalidReason;\n continue;\n }\n next.push(candidate);\n added.push(candidate);\n }\n\n if (added.length) onChange(next);\n // A rejection is the more useful thing to say: \"three added\" is obvious from the\n // chips appearing, whereas \"already in the list\" is the only sign of what did not.\n const addedList = new Intl.ListFormat(locale, { type: \"conjunction\", style: \"long\" });\n setMessage(rejection ?? (added.length ? text.added(addedList.format(added)) : \"\"));\n return { added, rejection };\n };\n\n const commit = (raw: string): boolean => commitMany([raw]).added.length > 0;\n\n const removeAt = (index: number) => {\n const removed = value[index];\n onChange(value.filter((_, i) => i !== index));\n setMessage(text.removed(removed));\n // Focus the neighbour that takes its place, or the input when the list empties —\n // dropping focus to <body> here is how a keyboard user loses the field entirely.\n const next = index >= value.length - 1 ? null : index;\n requestAnimationFrame(() => focusChip(value.length - 1 === 0 ? null : next));\n };\n\n const onInputKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === \"Enter\") {\n // Only when there is something to commit: an empty Enter belongs to the form.\n if (draft.trim()) {\n e.preventDefault();\n if (commit(draft)) setDraft(\"\");\n }\n return;\n }\n if (separators.includes(e.key)) {\n e.preventDefault();\n if (commit(draft)) setDraft(\"\");\n return;\n }\n if (e.key === \"Escape\" && draft) {\n e.preventDefault();\n setDraft(\"\");\n return;\n }\n if (e.key === \"Backspace\" && !draft && value.length) {\n e.preventDefault();\n focusChip(value.length - 1);\n }\n };\n\n const onChipKeyDown = (e: KeyboardEvent<HTMLElement>, index: number) => {\n if (e.key === \"Backspace\" || e.key === \"Delete\") {\n e.preventDefault();\n removeAt(index);\n return;\n }\n if (e.key === \"ArrowLeft\" && index > 0) {\n e.preventDefault();\n focusChip(index - 1);\n return;\n }\n if (e.key === \"ArrowRight\") {\n e.preventDefault();\n focusChip(index === value.length - 1 ? null : index + 1);\n return;\n }\n if (e.key === \"Escape\") {\n e.preventDefault();\n focusChip(null);\n }\n };\n\n return (\n // The rest lands on the OUTER box — the thing a `data-tour` step or a test id\n // wants to point at — while the accessible name below goes on the `<input>`,\n // because that is what a screen-reader user actually lands in. Spreading the two\n // to the same element would have named a decorative wrapper and left the field\n // anonymous.\n <div {...rest} className={cn(\"space-y-1\", className)}>\n {label && (\n <label htmlFor={`${id}-input`} className=\"block text-sm text-[var(--text-secondary)]\">\n {label}\n </label>\n )}\n <div\n // `relative` so the live region below can be `sr-only` without escaping to the\n // initial containing block and inflating the document height.\n className={cn(\n \"relative flex flex-wrap items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--bg-surface)] px-2 py-1.5 shadow-sm\",\n \"focus-within:border-[var(--brand)] focus-within:ring-1 focus-within:ring-[var(--brand)]\",\n disabled && \"cursor-default bg-[var(--bg-surface-2)]\",\n isInvalid && FIELD_INVALID,\n )}\n onClick={() => !disabled && inputRef.current?.focus()}\n >\n {/* `display: contents` on the wrappers so the chips participate in the field's\n own flex wrap rather than forming a nested row. The list semantics are\n restored with explicit roles, because `contents` removes the ul/li boxes from\n the accessibility tree in several engines. */}\n {/* eslint-disable-next-line jsx-a11y/no-redundant-roles -- NOT redundant here: the\n `contents` display below removes the ul and li boxes from the box tree, and\n several engines drop the list semantics with them. The explicit role is what\n puts \"list, 3 items\" back. */}\n <ul id={listId} role=\"list\" className=\"contents\">\n {value.map((v, i) => (\n <li key={`${v}-${i}`} role=\"presentation\" className=\"contents\">\n <Chip\n ref={(el: HTMLElement | null) => {\n chipRefs.current[i] = el;\n }}\n tone={tone}\n size={size}\n disabled={disabled}\n removeLabel={text.remove}\n onRemove={disabled ? undefined : () => removeAt(i)}\n // A ROVING tabIndex: only the focused chip is tabbable, so Tab leaves\n // the field instead of walking through every value in it — the reason a\n // list of twenty tags is otherwise a twenty-stop detour for a keyboard.\n tabIndex={focusedChip === i ? 0 : -1}\n role=\"listitem\"\n aria-label={v}\n onKeyDown={(e) => onChipKeyDown(e, i)}\n onFocus={() => setFocusedChip(i)}\n data-chip-index={i}\n >\n {v}\n </Chip>\n </li>\n ))}\n </ul>\n <input\n id={`${id}-input`}\n ref={inputRef}\n value={draft}\n onChange={(e) => {\n setDraft(e.target.value);\n setMessage(\"\");\n }}\n onKeyDown={onInputKeyDown}\n onBlur={() => {\n // Commit on blur: a value typed and then clicked away from is a value the\n // user meant to add, and losing it silently is the commonest complaint\n // about this pattern.\n if (draft.trim() && commit(draft)) setDraft(\"\");\n }}\n onPaste={(e) => {\n const pasted = e.clipboardData.getData(\"text\");\n const pattern = new RegExp(`[${separators.map((s) => `\\\\${s}`).join(\"\")}\\n\\r]`);\n if (!pattern.test(pasted)) return;\n e.preventDefault();\n if (commitMany(pasted.split(pattern)).added.length) setDraft(\"\");\n }}\n placeholder={value.length ? undefined : placeholder}\n disabled={disabled}\n // A visible `label` is already wired through `htmlFor`, so adding a name\n // here would give the field two. Failing that, the DOM spelling wins and\n // the deprecated `ariaLabel` is the fallback.\n aria-label={label ? undefined : (ariaLabelAttr ?? ariaLabel)}\n aria-describedby={error ? errorId : undefined}\n aria-invalid={isInvalid || undefined}\n className=\"min-w-[6rem] flex-1 bg-transparent py-0.5 text-sm text-[var(--text-primary)] outline-none placeholder:text-[var(--text-placeholder)] disabled:cursor-default\"\n />\n {/* Additions, removals and rejections move no focus, so nothing would announce\n them. `sr-only-fixed` rather than `sr-only`: this sits inside a consumer's\n markup and must not extend the document height. */}\n <span role=\"status\" aria-live=\"polite\" aria-atomic className=\"sr-only-fixed\">\n {message}\n </span>\n </div>\n {error && (\n <p id={errorId} className=\"text-xs text-[var(--danger)]\">\n {error}\n </p>\n )}\n </div>\n );\n}\n"],"mappings":";AA0JI,mBACW,KADX;AA1JJ,SAAS,YAAY,OAAO,QAAQ,gBAAgB;AAEpD,SAAS,SAAS;AAElB,SAAS,UAAU;AACnB,SAAS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AAM,OAAO,CAAC,EAAE,MAAM,OAAQ,UAAS,EAAE;AAAA,gBACjE;AAAA,gBACA,aAAa,MAAM,SAAS,SAAY;AAAA,gBACxC;AAAA,gBAIA,cAAY,QAAQ,SAAa,iBAAiB;AAAA,gBAClD,oBAAkB,QAAQ,UAAU;AAAA,gBACpC,gBAAc,aAAa;AAAA,gBAC3B,WAAU;AAAA;AAAA,YACZ;AAAA,YAIA,oBAAC,UAAK,MAAK,UAAS,aAAU,UAAS,eAAW,MAAC,WAAU,iBAC1D,mBACH;AAAA;AAAA;AAAA,MACF;AAAA,MACC,SACC,oBAAC,OAAE,IAAI,SAAS,WAAU,gCACvB,iBACH;AAAA,OAEJ;AAAA;AAEJ;","names":["Chip"]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/chip.tsx"],"sourcesContent":["import { forwardRef, useId, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent, MouseEvent, ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\nimport type { LucideIcon } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { FIELD_INVALID } from \"./ui\";\nimport { DEFAULT_COMMON_LABELS, useKitLabels, useKitLocale } from \"../i18n/kit-labels\";\n\n/**\n * A chip: a compact pill carrying one value.\n *\n * Three jobs, deliberately one component. A chip can be inert (a tag on a row), a link\n * (a jump to a section), or a toggle (a filter that is on or off) — and the difference is\n * which prop you pass, not which component you pick. Keeping them together is what stops\n * an app growing three near-identical pills that drift apart; it is the shape this kit\n * already uses for `Button`, which is a link when it is given an href.\n *\n * A chip is not a `Button`. It is smaller, it is rounded to a pill, and it reads as a\n * VALUE rather than as an action — which matters because a row of eight buttons says\n * \"choose one of eight things to do\" and a row of eight chips says \"here are eight\n * things\". Using `Button` for both is the mistake this exists to prevent.\n */\n\nexport type ChipTone =\n | \"neutral\"\n | \"brand\"\n | \"danger\"\n | \"warning\"\n | \"success\"\n | \"info\"\n | \"income\"\n | \"expense\";\n/** `lg` is the 44px touch target (`min-h-11`) a phone surface wants; `md` is ~28px. */\nexport type ChipSize = \"sm\" | \"md\" | \"lg\";\n\nconst TONE: Record<ChipTone, { idle: string; selected: string }> = {\n neutral: {\n idle: \"border-[var(--border)] bg-[var(--bg-surface-2)] text-[var(--text-secondary)]\",\n selected: \"border-[var(--border-strong)] bg-[var(--bg-active)] text-[var(--text-primary)]\",\n },\n brand: {\n idle: \"border-[var(--border)] bg-[var(--brand-bg)] text-[var(--brand-muted)]\",\n selected: \"border-[var(--brand)] bg-[var(--brand)] text-[var(--brand-contrast)]\",\n },\n danger: {\n idle: \"border-[var(--danger-border)] bg-[var(--danger-bg)] text-[var(--danger)]\",\n selected: \"border-[var(--danger)] bg-[var(--danger)] text-[var(--danger-contrast)]\",\n },\n warning: {\n idle: \"border-[var(--warning-border)] bg-[var(--warning-bg)] text-[var(--warning)]\",\n selected: \"border-[var(--warning)] bg-[var(--warning-bg)] text-[var(--warning)]\",\n },\n success: {\n idle: \"border-[var(--success-border)] bg-[var(--success-bg)] text-[var(--success)]\",\n selected: \"border-[var(--success)] bg-[var(--success-bg)] text-[var(--success)]\",\n },\n info: {\n idle: \"border-[var(--info-border)] bg-[var(--info-bg)] text-[var(--info)]\",\n selected: \"border-[var(--info)] bg-[var(--info-bg)] text-[var(--info)]\",\n },\n // The money pair (Keksdose's direction toggle). Only the TEXT and the BORDER carry\n // the tint, on the neutral chip's own surfaces: the money tokens are chosen for text\n // contrast, and a filled amber pill beside an amber figure reads as one smear.\n // `border-current` takes its hue from the text, so the two cannot drift apart.\n income: {\n idle: \"border-current/40 bg-[var(--bg-surface-2)] text-[var(--money-income)]\",\n selected: \"border-current bg-[var(--bg-active)] text-[var(--money-income)]\",\n },\n expense: {\n idle: \"border-current/40 bg-[var(--bg-surface-2)] text-[var(--money-expense)]\",\n selected: \"border-current bg-[var(--bg-active)] text-[var(--money-expense)]\",\n },\n};\n\nconst SIZE: Record<ChipSize, { body: string; icon: string; remove: string }> = {\n sm: { body: \"gap-1 px-2 py-0.5 text-xs\", icon: \"size-3\", remove: \"size-3\" },\n md: { body: \"gap-1.5 px-2.5 py-1 text-sm\", icon: \"size-3.5\", remove: \"size-3.5\" },\n lg: { body: \"min-h-11 gap-2 px-4 py-2 text-sm\", icon: \"size-4\", remove: \"size-4\" },\n};\n\nconst CHIP_BASE =\n \"inline-flex max-w-full items-center rounded-full border transition-colors \" +\n // `focus-visible`, not `focus`: a chip commonly receives focus programmatically (the\n // ChipInput moves focus onto one after a removal) and a ring that appears on a\n // pointer click reads as a stuck selection.\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)] focus-visible:ring-offset-1 focus-visible:ring-offset-[var(--bg-surface)]\";\n\nexport interface ChipProps {\n children: ReactNode;\n tone?: ChipTone;\n size?: ChipSize;\n icon?: LucideIcon;\n /**\n * Marks the chip as the current one — `aria-current` on a link, `aria-pressed` on a\n * toggle.\n *\n * On a toggle, keep the LABEL the same in both states and let `selected` carry the\n * state. A label that flips with it (\"Skip this month\" / \"Ask again this month\") is\n * announced together with \"pressed\", and then says the opposite of what it does.\n */\n selected?: boolean;\n /** Renders the chip as a link. Mutually exclusive with `onClick`. */\n href?: string;\n /** Renders the chip as a toggle button. Mutually exclusive with `href`. Receives the\n * click, so a chip inside a clickable row can `stopPropagation()`. */\n onClick?: (event: MouseEvent<HTMLButtonElement>) => void;\n /** Renders a dismiss affordance. Works alongside `href`/`onClick` — see the note below. */\n onRemove?: () => void;\n /** Accessible name for the dismiss button. Default: `common.remove` from the\n * {@link UiKitProvider}, else \"Remove\". */\n removeLabel?: string;\n disabled?: boolean;\n className?: string;\n /**\n * Roving focus, for a container that manages a row of chips (see {@link ChipInput}).\n * A chip with no `href`/`onClick` is inert and unfocusable by default; give it a\n * `tabIndex` and a `role` and it becomes the thing arrow keys move between.\n */\n tabIndex?: number;\n role?: string;\n onKeyDown?: (e: KeyboardEvent<HTMLElement>) => void;\n onFocus?: () => void;\n /** Accessible name, when the visible text is not the whole story. */\n \"aria-label\"?: string;\n /** Any other ARIA attribute — `aria-describedby`, `aria-expanded`, `aria-controls`,\n * `aria-haspopup` — reaches the chip's interactive element. */\n [key: `aria-${string}`]: string | boolean | number | undefined;\n /** A test id, a `data-tour` anchor, or any other data attribute. */\n [key: `data-${string}`]: unknown;\n id?: string;\n /** A native tooltip. For anything a user must read, prefer the kit's `Tooltip`. */\n title?: string;\n}\n\n/**\n * Note on `onRemove` with `href`/`onClick`: a button cannot be nested inside a button or\n * a link, so when both are present the chip renders a wrapper holding TWO siblings — the\n * interactive body and the dismiss control. That is why the outer element is not always\n * the interactive one, and why the focus ring is drawn on the body rather than the\n * wrapper.\n */\nexport const Chip = forwardRef<HTMLElement, ChipProps>(function Chip(\n {\n children,\n tone = \"neutral\",\n size = \"md\",\n icon: Icon,\n selected = false,\n href,\n onClick,\n onRemove,\n removeLabel,\n disabled = false,\n className,\n tabIndex,\n role,\n onKeyDown,\n onFocus,\n ...rest\n },\n ref,\n) {\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS, { remove: removeLabel });\n const s = SIZE[size];\n const palette = TONE[tone];\n const interactive = !!href || !!onClick;\n const look = cn(\n CHIP_BASE,\n s.body,\n selected ? palette.selected : palette.idle,\n interactive && !disabled && \"cursor-pointer hover:brightness-[0.97] dark:hover:brightness-110\",\n disabled && \"cursor-default opacity-50\",\n className,\n );\n\n const body = (\n <>\n {Icon && <Icon className={cn(s.icon, \"shrink-0\")} aria-hidden />}\n <span className=\"min-w-0 truncate\">{children}</span>\n </>\n );\n\n const remove = onRemove ? (\n <button\n type=\"button\"\n // The name carries WHAT is being removed, not just \"Remove\" — a screen-reader user\n // tabbing a row of eight dismiss buttons otherwise hears the same word eight times\n // with no way to tell which one they are on.\n // Composed through `common.fieldValue` because the punctuation between the two\n // halves is the language's, not ours. A chip whose content is not plain text\n // has no value to name, and gets the bare verb rather than a dangling colon.\n aria-label={\n typeof children === \"string\" && children\n ? common.fieldValue(common.remove, children)\n : common.remove\n }\n onClick={(e) => {\n // The chip may itself be a link; removing it must not also follow it.\n e.preventDefault();\n e.stopPropagation();\n onRemove();\n }}\n disabled={disabled}\n className={cn(\n \"-mr-0.5 ml-0.5 shrink-0 rounded-full p-0.5 transition-colors\",\n \"hover:bg-[var(--bg-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)]\",\n disabled && \"pointer-events-none\",\n )}\n >\n <X className={s.remove} aria-hidden />\n </button>\n ) : null;\n\n // ── The three shapes.\n if (href && !disabled) {\n const link = (\n <a\n ref={ref as React.Ref<HTMLAnchorElement>}\n href={href}\n aria-current={selected ? \"true\" : undefined}\n className={cn(look, remove && \"pr-1.5\")}\n {...rest}\n >\n {body}\n {!remove && null}\n </a>\n );\n return remove ? (\n <span className=\"inline-flex items-center\">\n {link}\n {remove}\n </span>\n ) : (\n link\n );\n }\n\n if (onClick) {\n const button = (\n <button\n ref={ref as React.Ref<HTMLButtonElement>}\n type=\"button\"\n onClick={onClick}\n disabled={disabled}\n aria-pressed={selected}\n className={cn(look, remove && \"pr-1.5\")}\n {...rest}\n >\n {body}\n </button>\n );\n return remove ? (\n <span className=\"inline-flex items-center\">\n {button}\n {remove}\n </span>\n ) : (\n button\n );\n }\n\n return (\n <span\n ref={ref as React.Ref<HTMLSpanElement>}\n className={look}\n tabIndex={tabIndex}\n role={role}\n onKeyDown={onKeyDown}\n onFocus={onFocus}\n {...rest}\n >\n {body}\n {remove}\n </span>\n );\n});\n\n/* ── ChipInput ────────────────────────────────────────────────────────────── */\n\nexport interface ChipInputLabels {\n /** Announced after a value is added. Receives the value. */\n added: (value: string) => string;\n /** Announced after a value is removed. Receives the value. */\n removed: (value: string) => string;\n /** Accessible name for each chip's dismiss button. */\n remove: string;\n /** Shown when `max` is reached. Receives the limit. */\n atLimit: (max: number) => string;\n /** Shown when a duplicate is rejected. Receives the value. */\n duplicate: (value: string) => string;\n}\n\nexport const DEFAULT_CHIP_INPUT_LABELS: ChipInputLabels = {\n added: (v) => `${v} added`,\n removed: (v) => `${v} removed`,\n remove: \"Remove\",\n atLimit: (max) => `Limit of ${max} reached`,\n duplicate: (v) => `${v} is already in the list`,\n};\n\nexport function resolveChipInputLabels(labels?: Partial<ChipInputLabels>): ChipInputLabels {\n return labels ? { ...DEFAULT_CHIP_INPUT_LABELS, ...labels } : DEFAULT_CHIP_INPUT_LABELS;\n}\n\n/**\n * `onChange` is the field's own — the whole LIST, not a DOM event — so the wrapper\n * div's `onChange` is omitted rather than shadowed. `placeholder` is likewise this\n * component's, forwarded to the inner `<input>`; the div has none of its own.\n */\nexport interface ChipInputProps\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\" | \"placeholder\" | \"children\"> {\n value: string[];\n onChange: (next: string[]) => void;\n placeholder?: string;\n /** Visible label, rendered above the field. Without one, name the field with\n * `aria-label`. */\n label?: string;\n /**\n * @deprecated Pass `aria-label` instead — the DOM spelling the rest of this kit\n * now uses. Still honoured, and still second to `aria-label` when both are given.\n */\n ariaLabel?: string;\n /** Reject or rewrite a value on commit. Return a string to reject WITH that message. */\n validate?: (raw: string) => string | null;\n /** Characters that commit the current text, besides Enter. Default: comma. */\n separators?: string[];\n allowDuplicates?: boolean;\n max?: number;\n tone?: ChipTone;\n size?: ChipSize;\n disabled?: boolean;\n invalid?: boolean;\n /** Error text. Wires `aria-describedby` and implies `invalid`. */\n error?: ReactNode;\n labels?: Partial<ChipInputLabels>;\n className?: string;\n}\n\n/**\n * A field whose value is a LIST, entered as chips.\n *\n * The keyboard model is the whole component; the pills are the easy part. Per the WAI\n * pattern for a \"tag\" input:\n *\n * Enter, or any separator commit the typed text\n * Backspace on empty text move focus to the last chip (does NOT delete it)\n * ← → while on a chip move between chips\n * Backspace / Delete remove the focused chip, focus its neighbour\n * Escape clear what is typed but keep the committed chips\n * paste splits on the separators, so a pasted CSV becomes chips\n *\n * The Backspace-on-empty behaviour is the one worth arguing about. Deleting immediately\n * is more common and is a trap: it is a destructive action with no feedback on a key\n * people hit by reflex, and the value it destroys may have taken a while to type. Moving\n * focus first makes the second Backspace a deliberate one, and it is what lets a\n * keyboard user reach a chip at all.\n */\nexport function ChipInput({\n value,\n onChange,\n placeholder,\n label,\n ariaLabel,\n validate,\n separators = [\",\"],\n allowDuplicates = false,\n max,\n tone = \"neutral\",\n size = \"md\",\n disabled = false,\n invalid = false,\n error,\n labels,\n className,\n \"aria-label\": ariaLabelAttr,\n ...rest\n}: ChipInputProps) {\n // `labels` over the provider's `chipInput` over English — the same order\n // `resolveChipInputLabels` gives outside a provider.\n const text = useKitLabels(\"chipInput\", DEFAULT_CHIP_INPUT_LABELS, labels);\n // A batch of pasted values is announced as one list, joined the way the language\n // joins a list in a sentence (\"a, b and c added\") — hence the long conjunction,\n // where a trigger's summary would use the narrow one.\n const locale = useKitLocale();\n const [draft, setDraft] = useState(\"\");\n const [message, setMessage] = useState(\"\");\n const [focusedChip, setFocusedChip] = useState<number | null>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const chipRefs = useRef<Array<HTMLElement | null>>([]);\n const id = useId();\n const listId = `${id}-list`;\n const errorId = `${id}-error`;\n const isInvalid = invalid || !!error;\n\n const focusChip = (index: number | null) => {\n setFocusedChip(index);\n if (index === null) inputRef.current?.focus();\n else chipRefs.current[index]?.focus();\n };\n\n /**\n * Try to add every candidate, as ONE change.\n *\n * Batched rather than looped for a reason that bites immediately: `commit` closes over\n * `value`, so calling it once per pasted item makes every call compute its result from\n * the list as it was BEFORE the paste, and each `onChange` overwrites the last. A\n * pasted \"one,two,three\" left only \"three\". Accumulating locally and emitting once is\n * also the correct behaviour for an undo stack — a paste is one action.\n */\n const commitMany = (raws: string[]): { added: string[]; rejection: string | null } => {\n const next = [...value];\n const added: string[] = [];\n let rejection: string | null = null;\n\n for (const raw of raws) {\n const candidate = raw.trim();\n if (!candidate) continue;\n if (max !== undefined && next.length >= max) {\n rejection ??= text.atLimit(max);\n break;\n }\n if (!allowDuplicates && next.includes(candidate)) {\n rejection ??= text.duplicate(candidate);\n continue;\n }\n const invalidReason = validate?.(candidate);\n if (invalidReason) {\n rejection ??= invalidReason;\n continue;\n }\n next.push(candidate);\n added.push(candidate);\n }\n\n if (added.length) onChange(next);\n // A rejection is the more useful thing to say: \"three added\" is obvious from the\n // chips appearing, whereas \"already in the list\" is the only sign of what did not.\n const addedList = new Intl.ListFormat(locale, { type: \"conjunction\", style: \"long\" });\n setMessage(rejection ?? (added.length ? text.added(addedList.format(added)) : \"\"));\n return { added, rejection };\n };\n\n const commit = (raw: string): boolean => commitMany([raw]).added.length > 0;\n\n const removeAt = (index: number) => {\n const removed = value[index];\n onChange(value.filter((_, i) => i !== index));\n setMessage(text.removed(removed));\n // Focus the neighbour that takes its place, or the input when the list empties —\n // dropping focus to <body> here is how a keyboard user loses the field entirely.\n const next = index >= value.length - 1 ? null : index;\n requestAnimationFrame(() => focusChip(value.length - 1 === 0 ? null : next));\n };\n\n const onInputKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === \"Enter\") {\n // Only when there is something to commit: an empty Enter belongs to the form.\n if (draft.trim()) {\n e.preventDefault();\n if (commit(draft)) setDraft(\"\");\n }\n return;\n }\n if (separators.includes(e.key)) {\n e.preventDefault();\n if (commit(draft)) setDraft(\"\");\n return;\n }\n if (e.key === \"Escape\" && draft) {\n e.preventDefault();\n setDraft(\"\");\n return;\n }\n if (e.key === \"Backspace\" && !draft && value.length) {\n e.preventDefault();\n focusChip(value.length - 1);\n }\n };\n\n const onChipKeyDown = (e: KeyboardEvent<HTMLElement>, index: number) => {\n if (e.key === \"Backspace\" || e.key === \"Delete\") {\n e.preventDefault();\n removeAt(index);\n return;\n }\n if (e.key === \"ArrowLeft\" && index > 0) {\n e.preventDefault();\n focusChip(index - 1);\n return;\n }\n if (e.key === \"ArrowRight\") {\n e.preventDefault();\n focusChip(index === value.length - 1 ? null : index + 1);\n return;\n }\n if (e.key === \"Escape\") {\n e.preventDefault();\n focusChip(null);\n }\n };\n\n return (\n // The rest lands on the OUTER box — the thing a `data-tour` step or a test id\n // wants to point at — while the accessible name below goes on the `<input>`,\n // because that is what a screen-reader user actually lands in. Spreading the two\n // to the same element would have named a decorative wrapper and left the field\n // anonymous.\n <div {...rest} className={cn(\"space-y-1\", className)}>\n {label && (\n <label htmlFor={`${id}-input`} className=\"block text-sm text-[var(--text-secondary)]\">\n {label}\n </label>\n )}\n <div\n // `relative` so the live region below can be `sr-only` without escaping to the\n // initial containing block and inflating the document height.\n className={cn(\n \"relative flex flex-wrap items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--bg-surface)] px-2 py-1.5 shadow-sm\",\n \"focus-within:border-[var(--brand)] focus-within:ring-1 focus-within:ring-[var(--brand)]\",\n disabled && \"cursor-default bg-[var(--bg-surface-2)]\",\n isInvalid && FIELD_INVALID,\n )}\n onClick={() => !disabled && inputRef.current?.focus()}\n >\n {/* `display: contents` on the wrappers so the chips participate in the field's\n own flex wrap rather than forming a nested row. The list semantics are\n restored with explicit roles, because `contents` removes the ul/li boxes from\n the accessibility tree in several engines. */}\n {/* eslint-disable-next-line jsx-a11y/no-redundant-roles -- NOT redundant here: the\n `contents` display below removes the ul and li boxes from the box tree, and\n several engines drop the list semantics with them. The explicit role is what\n puts \"list, 3 items\" back. */}\n <ul id={listId} role=\"list\" className=\"contents\">\n {value.map((v, i) => (\n <li key={`${v}-${i}`} role=\"presentation\" className=\"contents\">\n <Chip\n ref={(el: HTMLElement | null) => {\n chipRefs.current[i] = el;\n }}\n tone={tone}\n size={size}\n disabled={disabled}\n removeLabel={text.remove}\n onRemove={disabled ? undefined : () => removeAt(i)}\n // A ROVING tabIndex: only the focused chip is tabbable, so Tab leaves\n // the field instead of walking through every value in it — the reason a\n // list of twenty tags is otherwise a twenty-stop detour for a keyboard.\n tabIndex={focusedChip === i ? 0 : -1}\n role=\"listitem\"\n aria-label={v}\n onKeyDown={(e) => onChipKeyDown(e, i)}\n onFocus={() => setFocusedChip(i)}\n data-chip-index={i}\n >\n {v}\n </Chip>\n </li>\n ))}\n </ul>\n <input\n id={`${id}-input`}\n ref={inputRef}\n value={draft}\n onChange={(e) => {\n setDraft(e.target.value);\n setMessage(\"\");\n }}\n onKeyDown={onInputKeyDown}\n onBlur={() => {\n // Commit on blur: a value typed and then clicked away from is a value the\n // user meant to add, and losing it silently is the commonest complaint\n // about this pattern.\n if (draft.trim() && commit(draft)) setDraft(\"\");\n }}\n onPaste={(e) => {\n const pasted = e.clipboardData.getData(\"text\");\n const pattern = new RegExp(`[${separators.map((s) => `\\\\${s}`).join(\"\")}\\n\\r]`);\n if (!pattern.test(pasted)) return;\n e.preventDefault();\n if (commitMany(pasted.split(pattern)).added.length) setDraft(\"\");\n }}\n placeholder={value.length ? undefined : placeholder}\n disabled={disabled}\n // A visible `label` is already wired through `htmlFor`, so adding a name\n // here would give the field two. Failing that, the DOM spelling wins and\n // the deprecated `ariaLabel` is the fallback.\n aria-label={label ? undefined : (ariaLabelAttr ?? ariaLabel)}\n aria-describedby={error ? errorId : undefined}\n aria-invalid={isInvalid || undefined}\n className=\"min-w-[6rem] flex-1 bg-transparent py-0.5 text-sm text-[var(--text-primary)] outline-none placeholder:text-[var(--text-placeholder)] disabled:cursor-default\"\n />\n {/* Additions, removals and rejections move no focus, so nothing would announce\n them. `sr-only-fixed` rather than `sr-only`: this sits inside a consumer's\n markup and must not extend the document height. */}\n <span role=\"status\" aria-live=\"polite\" aria-atomic className=\"sr-only-fixed\">\n {message}\n </span>\n </div>\n {error && (\n <p id={errorId} className=\"text-xs text-[var(--danger)]\">\n {error}\n </p>\n )}\n </div>\n );\n}\n"],"mappings":";AAgLI,mBACW,KADX;AAhLJ,SAAS,YAAY,OAAO,QAAQ,gBAAgB;AAEpD,SAAS,SAAS;AAElB,SAAS,UAAU;AACnB,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB,cAAc,oBAAoB;AA6BlE,MAAM,OAA6D;AAAA,EACjE,SAAS;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA,OAAO;AAAA,IACL,MAA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EAAG;AAC3B,oBAAE,eAAe;AACjB,sBAAI,WAAW,OAAO,MAAM,OAAO,CAAC,EAAE,MAAM,OAAQ,UAAS,EAAE;AAAA,gBACjE;AAAA,gBACA,aAAa,MAAM,SAAS,SAAY;AAAA,gBACxC;AAAA,gBAIA,cAAY,QAAQ,SAAa,iBAAiB;AAAA,gBAClD,oBAAkB,QAAQ,UAAU;AAAA,gBACpC,gBAAc,aAAa;AAAA,gBAC3B,WAAU;AAAA;AAAA,YACZ;AAAA,YAIA,oBAAC,UAAK,MAAK,UAAS,aAAU,UAAS,eAAW,MAAC,WAAU,iBAC1D,mBACH;AAAA;AAAA;AAAA,MACF;AAAA,MACC,SACC,oBAAC,OAAE,IAAI,SAAS,WAAU,gCACvB,iBACH;AAAA,OAEJ;AAAA;AAEJ;","names":["Chip"]}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { InputHTMLAttributes, ReactNode, ComponentType } from 'react';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A checkbox or a radio, presented as a bordered card: a title, a line of description,
|
|
6
|
+
* an optional icon — and the whole card is the hit area.
|
|
7
|
+
*
|
|
8
|
+
* Kastlan built this twice by hand: the "manage roles" dialog wraps a `Checkbox` in a
|
|
9
|
+
* bordered `<label>` per role, and the lease wizard's "set up recurring rent" option is
|
|
10
|
+
* a `Checkbox` with `className="rounded-md border p-3"`. Neither had a focus ring on
|
|
11
|
+
* the card or a checked look beyond the 16px box, and the role picker's border stayed
|
|
12
|
+
* grey whether the role was on or off.
|
|
13
|
+
*
|
|
14
|
+
* Still a native `<input>` underneath, for the reasons {@link Checkbox} gives: it
|
|
15
|
+
* submits with its form, answers to `required`, and a radio set sharing a `name` gets
|
|
16
|
+
* the browser's own arrow-key behaviour — which already flips in a right-to-left page.
|
|
17
|
+
* The card is a `<label>` wrapped round it, so a click anywhere on the card lands on
|
|
18
|
+
* the input; the input is NAMED by the title alone and DESCRIBED by the description,
|
|
19
|
+
* so a screen reader does not read the whole card as its name.
|
|
20
|
+
*
|
|
21
|
+
* Checked is said three ways, none of them colour alone: the box's tick (or the
|
|
22
|
+
* radio's dot), a heavier border, and the brand-tinted surface.
|
|
23
|
+
*/
|
|
24
|
+
type ChoiceCardType = "checkbox" | "radio";
|
|
25
|
+
interface ChoiceCardProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "title"> {
|
|
26
|
+
/** "checkbox" (default) for an on/off option or one of several; "radio" for one of
|
|
27
|
+
* a set — give every card of the set the same `name`, or use {@link ChoiceCardGroup}. */
|
|
28
|
+
type?: ChoiceCardType;
|
|
29
|
+
/** The option's name — the input's accessible name. */
|
|
30
|
+
title: ReactNode;
|
|
31
|
+
/** A line or two under the title. Attached with `aria-describedby`. */
|
|
32
|
+
description?: ReactNode;
|
|
33
|
+
/** A Lucide icon (or any component taking a `className`), shown at the card's start. */
|
|
34
|
+
icon?: ComponentType<{
|
|
35
|
+
className?: string;
|
|
36
|
+
"aria-hidden"?: boolean;
|
|
37
|
+
}>;
|
|
38
|
+
/** Checkbox only: "some but not all". See {@link CheckboxProps.indeterminate}. */
|
|
39
|
+
indeterminate?: boolean;
|
|
40
|
+
/** Paints the card and sets `aria-invalid` together. */
|
|
41
|
+
invalid?: boolean;
|
|
42
|
+
/** What is wrong, in the caller's words. Rendered in the card and attached with
|
|
43
|
+
* `aria-describedby`; implies `invalid`. */
|
|
44
|
+
error?: ReactNode;
|
|
45
|
+
/** The checked state as a boolean. Fires alongside `onChange`, never instead of it. */
|
|
46
|
+
onCheckedChange?: (checked: boolean) => void;
|
|
47
|
+
/** Classes for the `<input>`. `className` styles the card. */
|
|
48
|
+
inputClassName?: string;
|
|
49
|
+
}
|
|
50
|
+
declare const ChoiceCard: react.ForwardRefExoticComponent<ChoiceCardProps & react.RefAttributes<HTMLInputElement>>;
|
|
51
|
+
interface ChoiceCardOption<T extends string> {
|
|
52
|
+
value: T;
|
|
53
|
+
title: ReactNode;
|
|
54
|
+
description?: ReactNode;
|
|
55
|
+
icon?: ChoiceCardProps["icon"];
|
|
56
|
+
disabled?: boolean;
|
|
57
|
+
}
|
|
58
|
+
interface ChoiceCardGroupBaseProps<T extends string> {
|
|
59
|
+
options: ChoiceCardOption<T>[];
|
|
60
|
+
/** The question the cards answer. Rendered as the fieldset's `<legend>`, which is
|
|
61
|
+
* what names the group. Without one, pass `aria-label`. */
|
|
62
|
+
legend?: ReactNode;
|
|
63
|
+
"aria-label"?: string;
|
|
64
|
+
/** Shared by every input — what a plain form submits under. Generated if omitted. */
|
|
65
|
+
name?: string;
|
|
66
|
+
/** Classes for the card grid. Default: one column, two from `sm` up. */
|
|
67
|
+
className?: string;
|
|
68
|
+
/** Classes for every card. */
|
|
69
|
+
cardClassName?: string;
|
|
70
|
+
disabled?: boolean;
|
|
71
|
+
/** What is wrong with the answer as a whole. Rendered under the cards and attached
|
|
72
|
+
* to the fieldset. */
|
|
73
|
+
error?: ReactNode;
|
|
74
|
+
/** Radio mode only: marks the first input `required`, which is how a radio set is. */
|
|
75
|
+
required?: boolean;
|
|
76
|
+
}
|
|
77
|
+
/** One of the set: radios. `value` is `null` while nothing is chosen. */
|
|
78
|
+
interface ChoiceCardSingleProps<T extends string> extends ChoiceCardGroupBaseProps<T> {
|
|
79
|
+
multiple?: false;
|
|
80
|
+
value: T | null;
|
|
81
|
+
onChange: (value: T) => void;
|
|
82
|
+
}
|
|
83
|
+
/** Any of the set: checkboxes. */
|
|
84
|
+
interface ChoiceCardMultipleProps<T extends string> extends ChoiceCardGroupBaseProps<T> {
|
|
85
|
+
multiple: true;
|
|
86
|
+
value: T[];
|
|
87
|
+
onChange: (value: T[]) => void;
|
|
88
|
+
}
|
|
89
|
+
type ChoiceCardGroupProps<T extends string> = ChoiceCardSingleProps<T> | ChoiceCardMultipleProps<T>;
|
|
90
|
+
/**
|
|
91
|
+
* A set of {@link ChoiceCard}s answering one question, in a `<fieldset>`.
|
|
92
|
+
*
|
|
93
|
+
* `multiple` picks the input: radios (one of the set, the browser's arrow keys
|
|
94
|
+
* between them) or checkboxes (any of the set, Tab between them). The value is kept
|
|
95
|
+
* in the order of `options`, not the order the boxes were ticked, so a list saved
|
|
96
|
+
* from it does not depend on the order someone clicked in.
|
|
97
|
+
*/
|
|
98
|
+
declare function ChoiceCardGroup<T extends string>(props: ChoiceCardGroupProps<T>): react.JSX.Element;
|
|
99
|
+
|
|
100
|
+
export { ChoiceCard, ChoiceCardGroup, type ChoiceCardGroupProps, type ChoiceCardMultipleProps, type ChoiceCardOption, type ChoiceCardProps, type ChoiceCardSingleProps, type ChoiceCardType };
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { forwardRef, useCallback, useEffect, useId, useRef } from "react";
|
|
4
|
+
import { Check, Minus } from "lucide-react";
|
|
5
|
+
import { cn } from "../lib/cn.js";
|
|
6
|
+
import { assignRef, hasMessage, mergeDescribedBy } from "./choice-parts.js";
|
|
7
|
+
const CARD = "flex cursor-pointer items-start gap-3 rounded-lg border border-[var(--border)] bg-[var(--bg-surface)] p-3 shadow-sm transition-colors hover:border-[var(--border-strong)] hover:bg-[var(--bg-hover)] has-[:checked]:border-[var(--brand)] has-[:checked]:bg-[var(--brand-bg)] has-[:checked]:ring-1 has-[:checked]:ring-[var(--brand)] has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-[var(--brand)] has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-60";
|
|
8
|
+
const CARD_DISABLED = "hover:border-[var(--border)] hover:bg-[var(--bg-surface)]";
|
|
9
|
+
const CARD_INVALID = "border-[var(--danger-border)] ring-1 ring-[var(--danger-border)] has-[:checked]:border-[var(--danger-border)] has-[:checked]:ring-[var(--danger-border)]";
|
|
10
|
+
const BOX = "peer size-4 shrink-0 appearance-none border border-[var(--border-strong)] bg-[var(--bg-surface)] transition-colors checked:border-[var(--brand)] focus:outline-none disabled:cursor-not-allowed";
|
|
11
|
+
const CHECKBOX = "rounded-[4px] checked:bg-[var(--brand)]";
|
|
12
|
+
const RADIO = "rounded-full checked:border-[5px]";
|
|
13
|
+
const ChoiceCard = forwardRef(function ChoiceCard2({
|
|
14
|
+
type = "checkbox",
|
|
15
|
+
title,
|
|
16
|
+
description,
|
|
17
|
+
icon: Icon,
|
|
18
|
+
indeterminate = false,
|
|
19
|
+
invalid,
|
|
20
|
+
error,
|
|
21
|
+
onCheckedChange,
|
|
22
|
+
onChange,
|
|
23
|
+
className,
|
|
24
|
+
inputClassName,
|
|
25
|
+
id,
|
|
26
|
+
disabled,
|
|
27
|
+
...rest
|
|
28
|
+
}, ref) {
|
|
29
|
+
const generated = useId();
|
|
30
|
+
const inputId = id ?? generated;
|
|
31
|
+
const titleId = `${inputId}-title`;
|
|
32
|
+
const descriptionId = `${inputId}-description`;
|
|
33
|
+
const errorId = `${inputId}-error`;
|
|
34
|
+
const showDescription = hasMessage(description);
|
|
35
|
+
const showError = hasMessage(error);
|
|
36
|
+
const isInvalid = Boolean(invalid) || showError;
|
|
37
|
+
const mixed = type === "checkbox" && indeterminate;
|
|
38
|
+
const local = useRef(null);
|
|
39
|
+
const setRef = useCallback(
|
|
40
|
+
(node) => {
|
|
41
|
+
local.current = node;
|
|
42
|
+
assignRef(ref, node);
|
|
43
|
+
},
|
|
44
|
+
[ref]
|
|
45
|
+
);
|
|
46
|
+
useEffect(() => {
|
|
47
|
+
if (local.current) local.current.indeterminate = mixed;
|
|
48
|
+
});
|
|
49
|
+
return /* @__PURE__ */ jsxs(
|
|
50
|
+
"label",
|
|
51
|
+
{
|
|
52
|
+
htmlFor: inputId,
|
|
53
|
+
className: cn(CARD, disabled && CARD_DISABLED, isInvalid && CARD_INVALID, className),
|
|
54
|
+
children: [
|
|
55
|
+
/* @__PURE__ */ jsxs("span", { className: "relative flex h-5 shrink-0 items-center", children: [
|
|
56
|
+
/* @__PURE__ */ jsx(
|
|
57
|
+
"input",
|
|
58
|
+
{
|
|
59
|
+
ref: setRef,
|
|
60
|
+
id: inputId,
|
|
61
|
+
disabled,
|
|
62
|
+
...rest,
|
|
63
|
+
type,
|
|
64
|
+
"aria-labelledby": rest["aria-labelledby"] ?? titleId,
|
|
65
|
+
"aria-invalid": isInvalid || rest["aria-invalid"] || void 0,
|
|
66
|
+
"aria-describedby": mergeDescribedBy(
|
|
67
|
+
rest["aria-describedby"],
|
|
68
|
+
showDescription && descriptionId,
|
|
69
|
+
showError && errorId
|
|
70
|
+
),
|
|
71
|
+
onChange: (e) => {
|
|
72
|
+
onChange?.(e);
|
|
73
|
+
onCheckedChange?.(e.target.checked);
|
|
74
|
+
},
|
|
75
|
+
className: cn(
|
|
76
|
+
BOX,
|
|
77
|
+
type === "radio" ? RADIO : CHECKBOX,
|
|
78
|
+
mixed && "border-[var(--brand)] bg-[var(--brand)]",
|
|
79
|
+
inputClassName
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
),
|
|
83
|
+
type === "checkbox" && (mixed ? /* @__PURE__ */ jsx(
|
|
84
|
+
Minus,
|
|
85
|
+
{
|
|
86
|
+
"aria-hidden": true,
|
|
87
|
+
strokeWidth: 3,
|
|
88
|
+
className: "pointer-events-none absolute inset-0 m-auto size-3 text-[var(--brand-contrast)]"
|
|
89
|
+
}
|
|
90
|
+
) : /* @__PURE__ */ jsx(
|
|
91
|
+
Check,
|
|
92
|
+
{
|
|
93
|
+
"aria-hidden": true,
|
|
94
|
+
strokeWidth: 3,
|
|
95
|
+
className: "pointer-events-none invisible absolute inset-0 m-auto size-3 text-[var(--brand-contrast)] peer-checked:visible"
|
|
96
|
+
}
|
|
97
|
+
))
|
|
98
|
+
] }),
|
|
99
|
+
Icon && /* @__PURE__ */ jsx(Icon, { "aria-hidden": true, className: "mt-0.5 size-4 shrink-0 text-[var(--text-secondary)]" }),
|
|
100
|
+
/* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
|
|
101
|
+
/* @__PURE__ */ jsx(
|
|
102
|
+
"span",
|
|
103
|
+
{
|
|
104
|
+
id: titleId,
|
|
105
|
+
className: "block select-none text-sm font-medium leading-5 text-[var(--text-primary)]",
|
|
106
|
+
children: title
|
|
107
|
+
}
|
|
108
|
+
),
|
|
109
|
+
showDescription && /* @__PURE__ */ jsx("span", { id: descriptionId, className: "mt-0.5 block text-xs text-[var(--text-muted)]", children: description }),
|
|
110
|
+
showError && /* @__PURE__ */ jsx("span", { id: errorId, className: "mt-1 block text-[11px] leading-tight text-[var(--danger)]", children: error })
|
|
111
|
+
] })
|
|
112
|
+
]
|
|
113
|
+
}
|
|
114
|
+
);
|
|
115
|
+
});
|
|
116
|
+
ChoiceCard.displayName = "ChoiceCard";
|
|
117
|
+
function ChoiceCardGroup(props) {
|
|
118
|
+
const { options, legend, name, className, cardClassName, disabled, error, required } = props;
|
|
119
|
+
const generated = useId();
|
|
120
|
+
const groupName = name ?? generated;
|
|
121
|
+
const errorId = `${generated}-error`;
|
|
122
|
+
const showError = hasMessage(error);
|
|
123
|
+
const isChecked = (v) => props.multiple ? props.value.includes(v) : props.value === v;
|
|
124
|
+
const toggle = (v, on) => {
|
|
125
|
+
if (props.multiple) {
|
|
126
|
+
const next = new Set(props.value);
|
|
127
|
+
if (on) next.add(v);
|
|
128
|
+
else next.delete(v);
|
|
129
|
+
props.onChange(options.map((o) => o.value).filter((x) => next.has(x)));
|
|
130
|
+
} else if (on) {
|
|
131
|
+
props.onChange(v);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
return /* @__PURE__ */ jsxs(
|
|
135
|
+
"fieldset",
|
|
136
|
+
{
|
|
137
|
+
"aria-label": props["aria-label"],
|
|
138
|
+
"aria-describedby": showError ? errorId : void 0,
|
|
139
|
+
disabled,
|
|
140
|
+
className: "min-w-0",
|
|
141
|
+
children: [
|
|
142
|
+
legend !== void 0 && /* @__PURE__ */ jsx("legend", { className: "mb-2 text-sm font-medium text-[var(--text-primary)]", children: legend }),
|
|
143
|
+
/* @__PURE__ */ jsx("div", { className: cn("grid gap-2 sm:grid-cols-2", className), children: options.map((o, i) => /* @__PURE__ */ jsx(
|
|
144
|
+
ChoiceCard,
|
|
145
|
+
{
|
|
146
|
+
type: props.multiple ? "checkbox" : "radio",
|
|
147
|
+
name: groupName,
|
|
148
|
+
value: o.value,
|
|
149
|
+
title: o.title,
|
|
150
|
+
description: o.description,
|
|
151
|
+
icon: o.icon,
|
|
152
|
+
disabled: o.disabled,
|
|
153
|
+
invalid: showError,
|
|
154
|
+
required: !props.multiple && required && i === 0 ? true : void 0,
|
|
155
|
+
checked: isChecked(o.value),
|
|
156
|
+
onCheckedChange: (on) => toggle(o.value, on),
|
|
157
|
+
className: cardClassName
|
|
158
|
+
},
|
|
159
|
+
o.value
|
|
160
|
+
)) }),
|
|
161
|
+
showError && /* @__PURE__ */ jsx("p", { id: errorId, className: "mt-1 text-[11px] leading-tight text-[var(--danger)]", children: error })
|
|
162
|
+
]
|
|
163
|
+
}
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
export {
|
|
167
|
+
ChoiceCard,
|
|
168
|
+
ChoiceCardGroup
|
|
169
|
+
};
|
|
170
|
+
//# sourceMappingURL=choice-card.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/components/choice-card.tsx"],"sourcesContent":["import { forwardRef, useCallback, useEffect, useId, useRef } from \"react\";\nimport type { ChangeEvent, ComponentType, InputHTMLAttributes, ReactNode } from \"react\";\nimport { Check, Minus } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { assignRef, hasMessage, mergeDescribedBy } from \"./choice-parts\";\n\n/**\n * A checkbox or a radio, presented as a bordered card: a title, a line of description,\n * an optional icon — and the whole card is the hit area.\n *\n * Kastlan built this twice by hand: the \"manage roles\" dialog wraps a `Checkbox` in a\n * bordered `<label>` per role, and the lease wizard's \"set up recurring rent\" option is\n * a `Checkbox` with `className=\"rounded-md border p-3\"`. Neither had a focus ring on\n * the card or a checked look beyond the 16px box, and the role picker's border stayed\n * grey whether the role was on or off.\n *\n * Still a native `<input>` underneath, for the reasons {@link Checkbox} gives: it\n * submits with its form, answers to `required`, and a radio set sharing a `name` gets\n * the browser's own arrow-key behaviour — which already flips in a right-to-left page.\n * The card is a `<label>` wrapped round it, so a click anywhere on the card lands on\n * the input; the input is NAMED by the title alone and DESCRIBED by the description,\n * so a screen reader does not read the whole card as its name.\n *\n * Checked is said three ways, none of them colour alone: the box's tick (or the\n * radio's dot), a heavier border, and the brand-tinted surface.\n */\n\nexport type ChoiceCardType = \"checkbox\" | \"radio\";\n\nexport interface ChoiceCardProps extends Omit<InputHTMLAttributes<HTMLInputElement>, \"type\" | \"title\"> {\n /** \"checkbox\" (default) for an on/off option or one of several; \"radio\" for one of\n * a set — give every card of the set the same `name`, or use {@link ChoiceCardGroup}. */\n type?: ChoiceCardType;\n /** The option's name — the input's accessible name. */\n title: ReactNode;\n /** A line or two under the title. Attached with `aria-describedby`. */\n description?: ReactNode;\n /** A Lucide icon (or any component taking a `className`), shown at the card's start. */\n icon?: ComponentType<{ className?: string; \"aria-hidden\"?: boolean }>;\n /** Checkbox only: \"some but not all\". See {@link CheckboxProps.indeterminate}. */\n indeterminate?: boolean;\n /** Paints the card and sets `aria-invalid` together. */\n invalid?: boolean;\n /** What is wrong, in the caller's words. Rendered in the card and attached with\n * `aria-describedby`; implies `invalid`. */\n error?: ReactNode;\n /** The checked state as a boolean. Fires alongside `onChange`, never instead of it. */\n onCheckedChange?: (checked: boolean) => void;\n /** Classes for the `<input>`. `className` styles the card. */\n inputClassName?: string;\n}\n\n// The card. `has-[:checked]` and `has-[:focus-visible]` read the INPUT's state, so an\n// uncontrolled card (`defaultChecked`, a plain form) looks right with no React state.\nconst CARD =\n \"flex cursor-pointer items-start gap-3 rounded-lg border border-[var(--border)] bg-[var(--bg-surface)] p-3 shadow-sm transition-colors \" +\n \"hover:border-[var(--border-strong)] hover:bg-[var(--bg-hover)] \" +\n \"has-[:checked]:border-[var(--brand)] has-[:checked]:bg-[var(--brand-bg)] has-[:checked]:ring-1 has-[:checked]:ring-[var(--brand)] \" +\n // The focus mark is the CARD's, not the 16px box's: the card is what was clicked and\n // what the eye is on. An OUTLINE rather than a ring, because the checked state already\n // spends the ring — two `ring-*` widths on one element are decided by stylesheet\n // order, and the loser would be the focus mark. Offset, so the two never merge.\n \"has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-[var(--brand)] \" +\n // Read from the input too, so a card disabled by its `<fieldset>` fades as well.\n \"has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-60\";\n\n// No hover offer on a card that cannot be changed.\nconst CARD_DISABLED = \"hover:border-[var(--border)] hover:bg-[var(--bg-surface)]\";\n\nconst CARD_INVALID =\n \"border-[var(--danger-border)] ring-1 ring-[var(--danger-border)] has-[:checked]:border-[var(--danger-border)] has-[:checked]:ring-[var(--danger-border)]\";\n\nconst BOX =\n \"peer size-4 shrink-0 appearance-none border border-[var(--border-strong)] bg-[var(--bg-surface)] transition-colors \" +\n \"checked:border-[var(--brand)] focus:outline-none disabled:cursor-not-allowed\";\nconst CHECKBOX = \"rounded-[4px] checked:bg-[var(--brand)]\";\n// A radio's dot is its BORDER: a 5px brand border round a surface-coloured 4px\n// centre. No glyph to lay over it, and it scales with the box.\nconst RADIO = \"rounded-full checked:border-[5px]\";\n\nexport const ChoiceCard = forwardRef<HTMLInputElement, ChoiceCardProps>(function ChoiceCard(\n {\n type = \"checkbox\",\n title,\n description,\n icon: Icon,\n indeterminate = false,\n invalid,\n error,\n onCheckedChange,\n onChange,\n className,\n inputClassName,\n id,\n disabled,\n ...rest\n },\n ref,\n) {\n const generated = useId();\n const inputId = id ?? generated;\n const titleId = `${inputId}-title`;\n const descriptionId = `${inputId}-description`;\n const errorId = `${inputId}-error`;\n const showDescription = hasMessage(description);\n const showError = hasMessage(error);\n const isInvalid = Boolean(invalid) || showError;\n const mixed = type === \"checkbox\" && indeterminate;\n\n const local = useRef<HTMLInputElement | null>(null);\n const setRef = useCallback(\n (node: HTMLInputElement | null) => {\n local.current = node;\n assignRef(ref, node);\n },\n [ref],\n );\n // After every render, as Checkbox does: a click clears the DOM property.\n useEffect(() => {\n if (local.current) local.current.indeterminate = mixed;\n });\n\n return (\n <label\n htmlFor={inputId}\n className={cn(CARD, disabled && CARD_DISABLED, isInvalid && CARD_INVALID, className)}\n >\n {/* A 20px cell, so the box centres on the title's first line (text-sm). */}\n <span className=\"relative flex h-5 shrink-0 items-center\">\n <input\n ref={setRef}\n id={inputId}\n disabled={disabled}\n {...rest}\n type={type}\n aria-labelledby={rest[\"aria-labelledby\"] ?? titleId}\n aria-invalid={isInvalid || rest[\"aria-invalid\"] || undefined}\n aria-describedby={mergeDescribedBy(\n rest[\"aria-describedby\"],\n showDescription && descriptionId,\n showError && errorId,\n )}\n onChange={(e: ChangeEvent<HTMLInputElement>) => {\n onChange?.(e);\n onCheckedChange?.(e.target.checked);\n }}\n className={cn(\n BOX,\n type === \"radio\" ? RADIO : CHECKBOX,\n mixed && \"border-[var(--brand)] bg-[var(--brand)]\",\n inputClassName,\n )}\n />\n {type === \"checkbox\" &&\n (mixed ? (\n <Minus\n aria-hidden\n strokeWidth={3}\n className=\"pointer-events-none absolute inset-0 m-auto size-3 text-[var(--brand-contrast)]\"\n />\n ) : (\n <Check\n aria-hidden\n strokeWidth={3}\n className=\"pointer-events-none invisible absolute inset-0 m-auto size-3 text-[var(--brand-contrast)] peer-checked:visible\"\n />\n ))}\n </span>\n {Icon && <Icon aria-hidden className=\"mt-0.5 size-4 shrink-0 text-[var(--text-secondary)]\" />}\n <span className=\"min-w-0 flex-1\">\n <span\n id={titleId}\n // `select-none`: a double-click to toggle twice would otherwise select the words.\n className=\"block select-none text-sm font-medium leading-5 text-[var(--text-primary)]\"\n >\n {title}\n </span>\n {showDescription && (\n <span id={descriptionId} className=\"mt-0.5 block text-xs text-[var(--text-muted)]\">\n {description}\n </span>\n )}\n {showError && (\n <span id={errorId} className=\"mt-1 block text-[11px] leading-tight text-[var(--danger)]\">\n {error}\n </span>\n )}\n </span>\n </label>\n );\n});\nChoiceCard.displayName = \"ChoiceCard\";\n\n/* ── ChoiceCardGroup ─────────────────────────────────────────────────────── */\n\nexport interface ChoiceCardOption<T extends string> {\n value: T;\n title: ReactNode;\n description?: ReactNode;\n icon?: ChoiceCardProps[\"icon\"];\n disabled?: boolean;\n}\n\ninterface ChoiceCardGroupBaseProps<T extends string> {\n options: ChoiceCardOption<T>[];\n /** The question the cards answer. Rendered as the fieldset's `<legend>`, which is\n * what names the group. Without one, pass `aria-label`. */\n legend?: ReactNode;\n \"aria-label\"?: string;\n /** Shared by every input — what a plain form submits under. Generated if omitted. */\n name?: string;\n /** Classes for the card grid. Default: one column, two from `sm` up. */\n className?: string;\n /** Classes for every card. */\n cardClassName?: string;\n disabled?: boolean;\n /** What is wrong with the answer as a whole. Rendered under the cards and attached\n * to the fieldset. */\n error?: ReactNode;\n /** Radio mode only: marks the first input `required`, which is how a radio set is. */\n required?: boolean;\n}\n\n/** One of the set: radios. `value` is `null` while nothing is chosen. */\nexport interface ChoiceCardSingleProps<T extends string> extends ChoiceCardGroupBaseProps<T> {\n multiple?: false;\n value: T | null;\n onChange: (value: T) => void;\n}\n\n/** Any of the set: checkboxes. */\nexport interface ChoiceCardMultipleProps<T extends string> extends ChoiceCardGroupBaseProps<T> {\n multiple: true;\n value: T[];\n onChange: (value: T[]) => void;\n}\n\nexport type ChoiceCardGroupProps<T extends string> =\n | ChoiceCardSingleProps<T>\n | ChoiceCardMultipleProps<T>;\n\n/**\n * A set of {@link ChoiceCard}s answering one question, in a `<fieldset>`.\n *\n * `multiple` picks the input: radios (one of the set, the browser's arrow keys\n * between them) or checkboxes (any of the set, Tab between them). The value is kept\n * in the order of `options`, not the order the boxes were ticked, so a list saved\n * from it does not depend on the order someone clicked in.\n */\nexport function ChoiceCardGroup<T extends string>(props: ChoiceCardGroupProps<T>) {\n const { options, legend, name, className, cardClassName, disabled, error, required } = props;\n const generated = useId();\n const groupName = name ?? generated;\n const errorId = `${generated}-error`;\n const showError = hasMessage(error);\n\n const isChecked = (v: T) => (props.multiple ? props.value.includes(v) : props.value === v);\n const toggle = (v: T, on: boolean) => {\n if (props.multiple) {\n const next = new Set(props.value);\n if (on) next.add(v);\n else next.delete(v);\n props.onChange(options.map((o) => o.value).filter((x) => next.has(x)));\n } else if (on) {\n props.onChange(v);\n }\n };\n\n return (\n <fieldset\n aria-label={props[\"aria-label\"]}\n aria-describedby={showError ? errorId : undefined}\n disabled={disabled}\n className=\"min-w-0\"\n >\n {legend !== undefined && (\n <legend className=\"mb-2 text-sm font-medium text-[var(--text-primary)]\">{legend}</legend>\n )}\n <div className={cn(\"grid gap-2 sm:grid-cols-2\", className)}>\n {options.map((o, i) => (\n <ChoiceCard\n key={o.value}\n type={props.multiple ? \"checkbox\" : \"radio\"}\n name={groupName}\n value={o.value}\n title={o.title}\n description={o.description}\n icon={o.icon}\n disabled={o.disabled}\n invalid={showError}\n required={!props.multiple && required && i === 0 ? true : undefined}\n checked={isChecked(o.value)}\n onCheckedChange={(on) => toggle(o.value, on)}\n className={cardClassName}\n />\n ))}\n </div>\n {showError && (\n <p id={errorId} className=\"mt-1 text-[11px] leading-tight text-[var(--danger)]\">\n {error}\n </p>\n )}\n </fieldset>\n );\n}\n"],"mappings":";AAgIM,SACE,KADF;AAhIN,SAAS,YAAY,aAAa,WAAW,OAAO,cAAc;AAElE,SAAS,OAAO,aAAa;AAC7B,SAAS,UAAU;AACnB,SAAS,WAAW,YAAY,wBAAwB;AAkDxD,MAAM,OACJ;AAYF,MAAM,gBAAgB;AAEtB,MAAM,eACJ;AAEF,MAAM,MACJ;AAEF,MAAM,WAAW;AAGjB,MAAM,QAAQ;AAEP,MAAM,aAAa,WAA8C,SAASA,YAC/E;AAAA,EACE,OAAO;AAAA,EACP;AAAA,EACA;AAAA,EACA,MAAM;AAAA,EACN,gBAAgB;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AA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AAA,IAClB;AAAA,EACF;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACC,cAAY,MAAM,YAAY;AAAA,MAC9B,oBAAkB,YAAY,UAAU;AAAA,MACxC;AAAA,MACA,WAAU;AAAA,MAET;AAAA,mBAAW,UACV,oBAAC,YAAO,WAAU,uDAAuD,kBAAO;AAAA,QAElF,oBAAC,SAAI,WAAW,GAAG,6BAA6B,SAAS,GACtD,kBAAQ,IAAI,CAAC,GAAG,MACf;AAAA,UAAC;AAAA;AAAA,YAEC,MAAM,MAAM,WAAW,aAAa;AAAA,YACpC,MAAM;AAAA,YACN,OAAO,EAAE;AAAA,YACT,OAAO,EAAE;AAAA,YACT,aAAa,EAAE;AAAA,YACf,MAAM,EAAE;AAAA,YACR,UAAU,EAAE;AAAA,YACZ,SAAS;AAAA,YACT,UAAU,CAAC,MAAM,YAAY,YAAY,MAAM,IAAI,OAAO;AAAA,YAC1D,SAAS,UAAU,EAAE,KAAK;AAAA,YAC1B,iBAAiB,CAAC,OAAO,OAAO,EAAE,OAAO,EAAE;AAAA,YAC3C,WAAW;AAAA;AAAA,UAZN,EAAE;AAAA,QAaT,CACD,GACH;AAAA,QACC,aACC,oBAAC,OAAE,IAAI,SAAS,WAAU,uDACvB,iBACH;AAAA;AAAA;AAAA,EAEJ;AAEJ;","names":["ChoiceCard"]}
|
|
@@ -17,14 +17,63 @@ interface ComboOption<V extends string | number> {
|
|
|
17
17
|
*/
|
|
18
18
|
group?: string;
|
|
19
19
|
}
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Where a combobox's rows come from, and how a query narrows them. Shared by the
|
|
22
|
+
* trigger pickers ({@link useComboboxCore}) and the inline {@link Autocomplete}, so
|
|
23
|
+
* the two cannot drift in what a failed lookup or a too-short query does.
|
|
24
|
+
*/
|
|
25
|
+
interface OptionSourceOptions<V extends string | number> {
|
|
26
|
+
/** Already-loaded options (client-side filtered unless `filter` is false), also
|
|
27
|
+
* used to resolve labels. */
|
|
22
28
|
options?: ComboOption<V>[];
|
|
23
|
-
/** Async option source, debounced and race-safe; stale responses are ignored
|
|
29
|
+
/** Async option source, debounced and race-safe; stale responses are ignored,
|
|
30
|
+
* and a rejection is caught and reported as `failed`. */
|
|
24
31
|
loadOptions?: (query: string) => Promise<ComboOption<V>[]>;
|
|
25
32
|
/** External loading flag, OR-ed with the internal async state. */
|
|
26
33
|
loading?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Narrow `options` by the query (label/sublabel substring). Default `true`.
|
|
36
|
+
*
|
|
37
|
+
* `false` shows `options` exactly as given, in the given order — for a list the
|
|
38
|
+
* caller has already searched and ranked on a server (Keksdose's geocoder), which a
|
|
39
|
+
* second, client-side substring filter could only get wrong: a provider that
|
|
40
|
+
* matches "Bahnhofstr." to "Bahnhofstrasse" is right, and a label filter would
|
|
41
|
+
* throw that row away.
|
|
42
|
+
*/
|
|
43
|
+
filter?: boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Below this many (trimmed) characters nothing is offered and `loadOptions` is not
|
|
46
|
+
* called. Default `0` — the pickers list everything on open. Set it for a source
|
|
47
|
+
* that is costly or rate-limited: one letter against a geocoder matches half a
|
|
48
|
+
* continent, and a request per opened panel is a request nobody asked for.
|
|
49
|
+
*/
|
|
50
|
+
minChars?: number;
|
|
51
|
+
/** Quiet time after the last keystroke before `loadOptions` runs. Default 150 ms. */
|
|
52
|
+
debounceMs?: number;
|
|
27
53
|
}
|
|
54
|
+
interface OptionSource<V extends string | number> {
|
|
55
|
+
results: ComboOption<V>[];
|
|
56
|
+
busy: boolean;
|
|
57
|
+
/** The last lookup for this query REJECTED. The rows are emptied with it: results
|
|
58
|
+
* from an earlier query under a failed one would read as the answer to it. */
|
|
59
|
+
failed: boolean;
|
|
60
|
+
/** The query is shorter than `minChars`, so nothing was asked. */
|
|
61
|
+
tooShort: boolean;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The rows half of a combobox: client-side filtering, or a debounced, race-safe
|
|
65
|
+
* `loadOptions` with its loading and failure states.
|
|
66
|
+
*
|
|
67
|
+
* `active` gates the async side — a closed list asks nothing. Loading is DERIVED
|
|
68
|
+
* ("the settled answer is for a different query") rather than flagged on in the
|
|
69
|
+
* effect, so there is no render between a keystroke and the debounce in which an
|
|
70
|
+
* empty list could claim "No results" for a question still being asked.
|
|
71
|
+
*/
|
|
72
|
+
declare function useOptionSource<V extends string | number>({ options, loadOptions, loading, filter, minChars, debounceMs, query, active, }: OptionSourceOptions<V> & {
|
|
73
|
+
query: string;
|
|
74
|
+
active: boolean;
|
|
75
|
+
}): OptionSource<V>;
|
|
76
|
+
type ComboboxCoreOptions<V extends string | number> = OptionSourceOptions<V>;
|
|
28
77
|
interface ComboboxCore<V extends string | number> {
|
|
29
78
|
triggerRef: RefObject<HTMLButtonElement | null>;
|
|
30
79
|
panelRef: RefObject<HTMLDivElement | null>;
|
|
@@ -37,6 +86,10 @@ interface ComboboxCore<V extends string | number> {
|
|
|
37
86
|
setActive: Dispatch<SetStateAction<number>>;
|
|
38
87
|
results: ComboOption<V>[];
|
|
39
88
|
busy: boolean;
|
|
89
|
+
/** See {@link OptionSource}. */
|
|
90
|
+
failed: boolean;
|
|
91
|
+
tooShort: boolean;
|
|
92
|
+
minChars: number;
|
|
40
93
|
rect: AnchorRect | null;
|
|
41
94
|
/** Where the dropdown goes, clamped to the visible viewport (feedback #135). */
|
|
42
95
|
placement: AnchoredPanel;
|
|
@@ -54,7 +107,22 @@ interface ComboboxCore<V extends string | number> {
|
|
|
54
107
|
* and multi-value comboboxes render their triggers on top of this and share
|
|
55
108
|
* {@link ComboboxPanel} for the dropdown.
|
|
56
109
|
*/
|
|
57
|
-
declare function useComboboxCore<V extends string | number>({ options,
|
|
110
|
+
declare function useComboboxCore<V extends string | number>({ options, minChars, ...source }: ComboboxCoreOptions<V>): ComboboxCore<V>;
|
|
111
|
+
/**
|
|
112
|
+
* {@link Input}'s `error` for the combobox family: the message under the field, its
|
|
113
|
+
* id on the control's `aria-describedby` (merged, never replacing — the hint the
|
|
114
|
+
* caller pointed at stays first), and `invalid` implied. ui.tsx's `useFieldError` is
|
|
115
|
+
* module-private, so this restates it on the same rules `choice-parts.ts` does.
|
|
116
|
+
*/
|
|
117
|
+
declare function useComboboxFieldError(error: ReactNode, invalid: boolean | undefined, describedBy?: string): {
|
|
118
|
+
isInvalid: boolean;
|
|
119
|
+
describedBy: string | undefined;
|
|
120
|
+
errorEl: react.JSX.Element | null;
|
|
121
|
+
};
|
|
122
|
+
/** The anchored suggestion list's box and rows — one look for {@link Combobox},
|
|
123
|
+
* {@link InlineEntityCombobox} and {@link Autocomplete}. */
|
|
124
|
+
declare const SUGGESTION_LIST_CLASS = "max-h-64 overflow-y-auto rounded-md border border-[var(--border)] bg-[var(--bg-surface)] py-1 shadow-lg";
|
|
125
|
+
declare const suggestionRowClass: (isActive: boolean) => string;
|
|
58
126
|
/**
|
|
59
127
|
* Keep the option the keyboard is on inside the visible part of the list.
|
|
60
128
|
*
|
|
@@ -88,6 +156,8 @@ interface ComboboxPanelProps<V extends string | number> extends ComponentPropsWi
|
|
|
88
156
|
* desktop, where the panel sits under the field that already says it. */
|
|
89
157
|
sheetTitle?: ReactNode;
|
|
90
158
|
closeLabel?: string;
|
|
159
|
+
/** Default: `combobox.loadError` from the {@link UiKitProvider}, else English. */
|
|
160
|
+
loadErrorLabel?: string;
|
|
91
161
|
}
|
|
92
162
|
/**
|
|
93
163
|
* The portalled dropdown (search header + result rows + optional create row)
|
|
@@ -115,6 +185,6 @@ interface ComboboxPanelProps<V extends string | number> extends ComponentPropsWi
|
|
|
115
185
|
* `tabIndex={-1}` because focus never leaves the search box — that is what
|
|
116
186
|
* `aria-activedescendant` is FOR.
|
|
117
187
|
*/
|
|
118
|
-
declare function ComboboxPanel<V extends string | number>({ core, listboxId, searchPlaceholder, emptyLabel, multi, isSelected, onChoose, showCreate, onCreate, createContent, sheetTitle, closeLabel, className, style, ...rest }: ComboboxPanelProps<V>): react.JSX.Element | null;
|
|
188
|
+
declare function ComboboxPanel<V extends string | number>({ core, listboxId, searchPlaceholder, emptyLabel, multi, isSelected, onChoose, showCreate, onCreate, createContent, sheetTitle, closeLabel, loadErrorLabel, className, style, ...rest }: ComboboxPanelProps<V>): react.JSX.Element | null;
|
|
119
189
|
|
|
120
|
-
export { type ComboOption, type ComboboxCore, type ComboboxCoreOptions, ComboboxPanel, type ComboboxPanelProps, useActiveOptionScroll, useComboboxCore };
|
|
190
|
+
export { type ComboOption, type ComboboxCore, type ComboboxCoreOptions, ComboboxPanel, type ComboboxPanelProps, type OptionSource, type OptionSourceOptions, SUGGESTION_LIST_CLASS, suggestionRowClass, useActiveOptionScroll, useComboboxCore, useComboboxFieldError, useOptionSource };
|