@betterinternship/components 3.4.2 → 3.5.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.
Files changed (87) hide show
  1. package/dist/components/autocomplete.d.ts +1 -2
  2. package/dist/components/autocomplete.js +75 -64
  3. package/dist/components/autocomplete.js.map +1 -1
  4. package/dist/components/checkbox-field.d.ts +18 -0
  5. package/dist/components/checkbox-field.js +25 -0
  6. package/dist/components/checkbox-field.js.map +1 -0
  7. package/dist/components/checkbox-group.d.ts +33 -0
  8. package/dist/components/checkbox-group.js +43 -0
  9. package/dist/components/checkbox-group.js.map +1 -0
  10. package/dist/components/checkbox.d.ts +1 -1
  11. package/dist/components/checkbox.js +6 -2
  12. package/dist/components/checkbox.js.map +1 -1
  13. package/dist/components/chip-select.d.ts +11 -2
  14. package/dist/components/chip-select.js +9 -4
  15. package/dist/components/chip-select.js.map +1 -1
  16. package/dist/components/{form-date-picker.d.ts → date-picker.d.ts} +11 -8
  17. package/dist/components/date-picker.js +57 -0
  18. package/dist/components/date-picker.js.map +1 -0
  19. package/dist/components/dropdown.js +7 -2
  20. package/dist/components/dropdown.js.map +1 -1
  21. package/dist/components/form-field.d.ts +60 -5
  22. package/dist/components/form-field.js +55 -5
  23. package/dist/components/form-field.js.map +1 -1
  24. package/dist/components/input.js +3 -1
  25. package/dist/components/input.js.map +1 -1
  26. package/dist/components/label.js +1 -1
  27. package/dist/components/label.js.map +1 -1
  28. package/dist/components/{form-month-picker.d.ts → month-picker.d.ts} +6 -6
  29. package/dist/components/month-picker.js +57 -0
  30. package/dist/components/month-picker.js.map +1 -0
  31. package/dist/components/radio-group.d.ts +11 -1
  32. package/dist/components/radio-group.js +17 -4
  33. package/dist/components/radio-group.js.map +1 -1
  34. package/dist/components/select.js +38 -2
  35. package/dist/components/select.js.map +1 -1
  36. package/dist/components/sheet.d.ts +1 -1
  37. package/dist/components/switch.d.ts +1 -1
  38. package/dist/components/switch.js +4 -1
  39. package/dist/components/switch.js.map +1 -1
  40. package/dist/components/table.js +5 -5
  41. package/dist/components/table.js.map +1 -1
  42. package/dist/components/textarea.d.ts +1 -1
  43. package/dist/components/textarea.js +3 -1
  44. package/dist/components/textarea.js.map +1 -1
  45. package/dist/components/time-input.d.ts +9 -0
  46. package/dist/components/time-input.js +65 -0
  47. package/dist/components/time-input.js.map +1 -0
  48. package/dist/design-tokens.d.ts +1 -1
  49. package/dist/hooks/use-field-focus.d.ts +1 -1
  50. package/dist/hooks/use-field-focus.js +1 -1
  51. package/dist/hooks/use-field-focus.js.map +1 -1
  52. package/dist/index.d.ts +5 -9
  53. package/dist/index.js +7 -11
  54. package/dist/index.js.map +1 -1
  55. package/dist/node_modules/tailwind-merge/dist/bundle-mjs.js +54 -2
  56. package/dist/node_modules/tailwind-merge/dist/bundle-mjs.js.map +1 -1
  57. package/dist/utils.js +11 -1
  58. package/dist/utils.js.map +1 -1
  59. package/package.json +28 -40
  60. package/theme.css +3 -1
  61. package/dist/components/form-checkbox-group.d.ts +0 -31
  62. package/dist/components/form-checkbox-group.js +0 -30
  63. package/dist/components/form-checkbox-group.js.map +0 -1
  64. package/dist/components/form-checkbox.d.ts +0 -15
  65. package/dist/components/form-checkbox.js +0 -15
  66. package/dist/components/form-checkbox.js.map +0 -1
  67. package/dist/components/form-date-picker.js +0 -56
  68. package/dist/components/form-date-picker.js.map +0 -1
  69. package/dist/components/form-input.d.ts +0 -11
  70. package/dist/components/form-input.js +0 -13
  71. package/dist/components/form-input.js.map +0 -1
  72. package/dist/components/form-month-picker.js +0 -56
  73. package/dist/components/form-month-picker.js.map +0 -1
  74. package/dist/components/form-radio.d.ts +0 -15
  75. package/dist/components/form-radio.js +0 -20
  76. package/dist/components/form-radio.js.map +0 -1
  77. package/dist/components/form-textarea.d.ts +0 -11
  78. package/dist/components/form-textarea.js +0 -12
  79. package/dist/components/form-textarea.js.map +0 -1
  80. package/dist/components/form.d.ts +0 -24
  81. package/dist/components/form.js +0 -71
  82. package/dist/components/form.js.map +0 -1
  83. package/dist/components/time-input-native.d.ts +0 -14
  84. package/dist/components/time-input-native.js +0 -62
  85. package/dist/components/time-input-native.js.map +0 -1
  86. package/dist/node_modules/react-hook-form/dist/index.esm.js +0 -706
  87. package/dist/node_modules/react-hook-form/dist/index.esm.js.map +0 -1
@@ -7,12 +7,11 @@ export interface IAutocompleteOption<ID extends number | string> {
7
7
  }
8
8
  type MobileDropdownMode = "sheet" | "inline";
9
9
  type InputIcons = boolean | "search" | "dropdown";
10
+ /** Unlabelled: put it in a `FormField` for a label. */
10
11
  type AutocompleteCommonProps<ID extends number | string> = {
11
- required?: boolean;
12
12
  options: IAutocompleteOption<ID>[];
13
13
  placeholder?: string;
14
14
  className?: string;
15
- label?: React.ReactNode;
16
15
  props?: any[];
17
16
  /** Allow a user to add their own text. Custom values are strings. */
18
17
  allowCustomValue?: boolean;
@@ -5,7 +5,7 @@ import { Input } from './input.js';
5
5
  import { useDetectClickOutside } from '../hooks/use-detect-click-outside.js';
6
6
  import { cn } from '../utils.js';
7
7
  import { X, ChevronDown, PlusCircleIcon, Search } from 'lucide-react';
8
- import { Label } from './label.js';
8
+ import { useFormFieldControl, FormFieldReset, useFormField } from './form-field.js';
9
9
  import { Button } from './button.js';
10
10
  import { CheckboxVisual } from './checkbox.js';
11
11
  import { Sheet, SheetContent, SheetTitle } from './sheet.js';
@@ -16,7 +16,7 @@ import { useFieldFocus, fieldFocusOutlineClassName, fieldInteractionClassName, F
16
16
  /* -------------------------------------------------------
17
17
  * Base component (array-based). Single uses length 0..1.
18
18
  * -----------------------------------------------------*/
19
- function AutocompleteBase({ required, options, value = [], setter, placeholder, className, multiple = true, label, labelAddon, allowCustomValue = false, preserveOptionOrder = false, emptyText = "No matching options", mobileDropdownMode = "sheet", inputIcons = false, ...props }) {
19
+ function AutocompleteBase({ options, value = [], setter, placeholder, className, multiple = true, allowCustomValue = false, preserveOptionOrder = false, emptyText = "No matching options", mobileDropdownMode = "sheet", inputIcons = false, ...props }) {
20
20
  const [query, setQuery] = useState("");
21
21
  const [isOpen, setIsOpen] = useState(false);
22
22
  const [dropdownMaxHeight, setDropdownMaxHeight] = useState();
@@ -37,7 +37,12 @@ function AutocompleteBase({ required, options, value = [], setter, placeholder,
37
37
  const lastSelectionRef = useRef(0);
38
38
  // Show the Button focus outline only for keyboard focus, not clicks.
39
39
  const { keyboardFocus, focusProps: fieldFocusProps } = useFieldFocus();
40
- const inputId = useId();
40
+ // Inside a FormField the input takes the field's id and links; its label names the sheet.
41
+ const field = useFormFieldControl({});
42
+ const { id: fieldId, ...fieldAria } = field;
43
+ const generatedId = useId();
44
+ const inputId = fieldId ?? generatedId;
45
+ const fieldLabel = useFormFieldLabel();
41
46
  const flatOptions = useMemo(() => options.flatMap((option) => option.children?.length ? option.children : [option]), [options]);
42
47
  const findExactOption = (value) => {
43
48
  const normalizedValue = value.trim().toLowerCase();
@@ -213,9 +218,11 @@ function AutocompleteBase({ required, options, value = [], setter, placeholder,
213
218
  return (jsxs("div", { className: cn("relative w-full overflow-visible", className), ref: (node) => {
214
219
  rootRef.current = node;
215
220
  clickOutsideRef.current = node;
216
- }, children: [label ? (jsx(Label, { label: label, required: required, labelAddon: labelAddon })) : null, multiple ? (
221
+ }, children: [multiple ? (
217
222
  // ---------- MULTI: chips inline inside the box ----------
218
- jsxs("div", { className: cn("relative flex min-h-form-control w-full flex-wrap items-center gap-1 rounded-control-lg border border-input bg-background px-[0.75em] pr-10 hover:border-input-hover", fieldClassName), ...fieldFocusProps, onClick: () => {
223
+ jsxs("div", { className: cn(
224
+ // text-base keeps the 0.75em padding at 12px, like the single input.
225
+ "relative flex min-h-form-control w-full flex-wrap items-center gap-1 rounded-control-lg border border-input bg-background px-[0.75em] pr-10 text-base text-foreground hover:border-input-hover", "has-[input[aria-invalid=true]]:border-destructive has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50", fieldClassName), ...fieldFocusProps, onClick: () => {
219
226
  setIsOpen(true);
220
227
  if (!suppressMobileKeyboard) {
221
228
  inputRef.current?.focus();
@@ -223,7 +230,7 @@ function AutocompleteBase({ required, options, value = [], setter, placeholder,
223
230
  }, children: [(value ?? []).map((id) => {
224
231
  const label = flatOptions.find((o) => o.id === id)?.name ?? String(id);
225
232
  return (jsxs("span", { className: "my-0.5 flex items-center gap-1 rounded-control-sm border border-input bg-muted px-2 text-xs", children: [label, jsx(Button, { type: "button", variant: "ghost", size: "xs", className: "ml-1 h-5 min-h-0 w-5 p-0 hover:bg-muted", onClick: (event) => { event.stopPropagation(); removeAt(id); }, "aria-label": `Remove ${label}`, children: jsx(X, { className: "h-3.5 w-3.5" }) })] }, String(id)));
226
- }), jsx("input", { id: inputId, ref: inputRef, value: query, onChange: (e) => {
233
+ }), jsx("input", { id: inputId, ...fieldAria, ref: inputRef, value: query, onChange: (e) => {
227
234
  setQuery(e.target.value);
228
235
  setIsOpen(true);
229
236
  }, onBlur: () => {
@@ -243,9 +250,9 @@ function AutocompleteBase({ required, options, value = [], setter, placeholder,
243
250
  }
244
251
  }, 150);
245
252
  }, onKeyDown: onMultiKeyDown, onFocus: () => { if (!useMobileSheet)
246
- setIsOpen(true); }, readOnly: suppressMobileKeyboard, placeholder: (value?.length ?? 0) === 0 ? placeholder : "", className: cn("h-[calc(var(--spacing-form-control)-2px)] min-w-[8ch] flex-1 border-none bg-transparent p-0 text-base outline-none focus:ring-0", "placeholder:text-muted-foreground/40"), ...props }), jsx(ChevronDown, { className: cn("pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none", isOpen && "rotate-180"), "aria-hidden": "true" })] })) : (
253
+ setIsOpen(true); }, readOnly: suppressMobileKeyboard, placeholder: (value?.length ?? 0) === 0 ? placeholder : "", className: cn("h-[calc(var(--spacing-form-control)-2px)] min-w-[8ch] flex-1 border-none bg-transparent p-0 text-base outline-none focus:ring-0 disabled:cursor-not-allowed", "placeholder:text-muted-foreground/40"), ...props }), jsx(ChevronDown, { className: cn("pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none", isOpen && "rotate-180"), "aria-hidden": "true" })] })) : (
247
254
  // ---------- SINGLE: regular input ----------
248
- decorateSingleInput(jsx(Input, { id: inputId, value: singleDisplay || query, className: cn("border-input", inputIcons === "search" || inputIcons === "dropdown" ? "pr-10" : inputIcons && "px-10"), placeholder: placeholder, readOnly: suppressMobileKeyboard, onChange: (e) => {
255
+ decorateSingleInput(jsx(Input, { id: inputId, ...fieldAria, value: singleDisplay || query, className: cn("border-input", inputIcons === "search" || inputIcons === "dropdown" ? "pr-10" : inputIcons && "px-10"), placeholder: placeholder, readOnly: suppressMobileKeyboard, onChange: (e) => {
249
256
  const nextQuery = e.target.value;
250
257
  if ((value?.length ?? 0) > 0) {
251
258
  setter([]);
@@ -288,7 +295,7 @@ function AutocompleteBase({ required, options, value = [], setter, placeholder,
288
295
  } }))), isOpen && (jsx(Sheet, { open: useMobileSheet && isOpen, onOpenChange: next => { if (!next) {
289
296
  setQuery('');
290
297
  setIsOpen(false);
291
- } }, children: jsxs(OptionsSurface, { ...sheetProps, ref: useMobileSheet ? sheetRef : undefined, role: useMobileSheet ? "dialog" : undefined, "aria-modal": useMobileSheet ? true : undefined, "aria-label": useMobileSheet ? (typeof label === "string" ? label : "Choose options") : undefined, className: cn("bg-background text-sm shadow-card border border-border", useMobileSheet
298
+ } }, children: jsx(OptionsSurface, { ...sheetProps, ref: useMobileSheet ? sheetRef : undefined, role: useMobileSheet ? "dialog" : undefined, "aria-modal": useMobileSheet ? true : undefined, "aria-label": useMobileSheet ? (fieldLabel ?? "Choose options") : undefined, className: cn("bg-background text-sm shadow-card border border-border", useMobileSheet
292
299
  ? "fixed left-0 right-0 z-(--z-popover) flex flex-col gap-0 overflow-hidden rounded-t-control-lg border-b-0 p-0"
293
300
  : "absolute left-0 right-0 z-50 mt-1 max-h-[400px] overflow-y-auto overscroll-contain rounded-control-lg"), style: useMobileSheet
294
301
  ? {
@@ -305,72 +312,76 @@ function AutocompleteBase({ required, options, value = [], setter, placeholder,
305
312
  marginBottom: 4,
306
313
  }),
307
314
  }
308
- : undefined, children: [useMobileSheet && (jsxs("div", { className: "shrink-0 px-4 pb-3 pt-4", children: [jsxs("div", { className: "mb-3 flex items-center justify-between gap-4", children: [jsx(SheetTitle, { className: "text-base font-semibold text-foreground", children: label || "Choose options" }), jsx("button", { ref: sheetCloseRef, type: "button", "aria-label": "Close options", className: "-mr-3 flex h-11 w-11 shrink-0 items-center justify-center rounded-control-lg text-muted-foreground hover:bg-muted", onClick: () => { setQuery(""); setIsOpen(false); }, children: jsx(X, { className: "h-5 w-5", "aria-hidden": "true" }) })] }), jsx(Input, { ref: sheetInputRef, "aria-label": typeof label === "string" ? `Search ${label}` : "Search options", value: query, placeholder: placeholder ?? "Search", className: "h-10 min-h-10 max-h-none text-base", onChange: (e) => {
309
- setQuery(e.target.value);
310
- setIsOpen(true);
311
- if ((value?.length ?? 0) > 0 && !multiple) {
312
- setter([]);
313
- }
314
- }, onKeyDown: (e) => {
315
- if (multiple) {
316
- onMultiKeyDown(e);
317
- return;
318
- }
319
- if (e.key === "Enter" && resolveQuerySelection(query)) {
320
- setIsOpen(false);
321
- e.preventDefault();
322
- }
323
- if (e.key === "Escape") {
324
- setIsOpen(false);
325
- }
326
- } })] })), jsxs("ul", { className: cn("flex flex-col gap-option-gap p-option-inset", useMobileSheet && "min-h-0 flex-1 overflow-y-auto overscroll-contain"), children: [allowCustomValue && (jsx("li", { className: "pointer-events-none px-option-x pb-1 pt-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground", children: "Suggestions" })), filtered.length ? (filtered.map((option, index) => {
327
- const active = selectedSet.has(option.id);
328
- const group = options.find((item) => item.children?.some((child) => child.id === option.id));
329
- const firstInGroup = group && !filtered.slice(0, index).some((item) => group.children?.some((child) => child.id === item.id));
330
- return (jsxs(Fragment, { children: [firstInGroup && group && (jsx("li", { children: multiple ? (jsxs("button", { type: "button", "aria-pressed": group.children.every((child) => selectedSet.has(child.id)), className: "flex min-h-option-row w-full cursor-pointer items-center gap-3 rounded-control-sm px-option-x py-2 text-left text-sm font-medium text-foreground transition-colors hover:bg-muted max-md:min-h-11", onClick: () => {
331
- const ids = group.children.map((child) => child.id);
332
- const next = new Set(value ?? []);
333
- const allSelected = ids.every((id) => next.has(id));
334
- ids.forEach((id) => allSelected ? next.delete(id) : next.add(id));
335
- setter(Array.from(next));
336
- }, children: [jsx(CheckboxVisual, { checked: group.children.every((child) => selectedSet.has(child.id)) ? true : group.children.some((child) => selectedSet.has(child.id)) ? 'indeterminate' : false }), group.name] })) : jsx("div", { className: "px-option-x py-2 text-sm font-medium text-foreground", children: group.name }) })), jsx("li", { children: jsxs("button", { type: "button", "aria-pressed": multiple ? active : undefined, onClick: () => {
337
- toggle(option.id);
338
- if (multiple) {
339
- // keep open for rapid multi-pick
340
- setQuery("");
341
- if (!useMobileSheet) {
342
- inputRef.current?.focus();
343
- }
344
- }
345
- else {
346
- setQuery("");
347
- setIsOpen(false);
348
- }
349
- }, className: cn("flex min-h-option-row w-full cursor-pointer items-center gap-3 rounded-control-sm px-option-x py-2 text-left text-sm text-muted-foreground transition-colors hover:bg-muted", useMobileSheet && "min-h-12", group && "pl-8", active && "bg-primary-tint"), children: [multiple ? (jsx(CheckboxVisual, { checked: active })) : null, option.name] }) })] }, String(option.id)));
350
- })) : (!allowCustomValue || !query.trim() ? (jsx("li", { className: "px-option-x py-2 text-sm text-muted-foreground", children: emptyText })) : null), allowCustomValue && query.trim() && !findExactOption(query) && (jsx("li", { children: jsxs("button", { type: "button", className: "flex min-h-11 w-full cursor-pointer items-center gap-2 rounded-control-sm px-option-x py-2 text-left text-sm text-primary transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-primary", onMouseDown: (event) => event.preventDefault(), onClick: () => {
351
- const text = query.trim();
315
+ : undefined, children: jsxs(FormFieldReset, { children: [useMobileSheet && (jsxs("div", { className: "shrink-0 px-4 pb-3 pt-4", children: [jsxs("div", { className: "mb-3 flex items-center justify-between gap-4", children: [jsx(SheetTitle, { className: "text-base font-semibold text-foreground", children: fieldLabel ?? "Choose options" }), jsx("button", { ref: sheetCloseRef, type: "button", "aria-label": "Close options", className: "-mr-3 flex h-11 w-11 shrink-0 items-center justify-center rounded-control-lg text-muted-foreground hover:bg-muted", onClick: () => { setQuery(""); setIsOpen(false); }, children: jsx(X, { className: "h-5 w-5", "aria-hidden": "true" }) })] }), jsx(Input, { ref: sheetInputRef, "aria-label": fieldLabel ? `Search ${fieldLabel}` : "Search options", value: query, placeholder: placeholder ?? "Search", className: "h-10 min-h-10 max-h-none text-base", onChange: (e) => {
316
+ setQuery(e.target.value);
317
+ setIsOpen(true);
318
+ if ((value?.length ?? 0) > 0 && !multiple) {
319
+ setter([]);
320
+ }
321
+ }, onKeyDown: (e) => {
352
322
  if (multiple) {
353
- setter(Array.from(new Set([...(value ?? []), text])));
354
- setQuery("");
323
+ onMultiKeyDown(e);
324
+ return;
355
325
  }
356
- else {
357
- resolveQuerySelection(text);
326
+ if (e.key === "Enter" && resolveQuerySelection(query)) {
358
327
  setIsOpen(false);
328
+ e.preventDefault();
359
329
  }
360
- }, children: [jsx(PlusCircleIcon, { className: "h-4 w-4", "aria-hidden": "true" }), "Add \u201C", query.trim(), "\u201D"] }) }))] }), useMobileSheet && multiple && (jsx("div", { className: "shrink-0 border-t border-border bg-background px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]", children: jsx(Button, { type: "button", variant: "outline", className: "min-h-11 w-full", onClick: () => {
361
- setQuery("");
362
- setIsOpen(false);
363
- }, children: "Done" }) }))] }) }))] }));
330
+ if (e.key === "Escape") {
331
+ setIsOpen(false);
332
+ }
333
+ } })] })), jsxs("ul", { className: cn("flex flex-col gap-option-gap p-option-inset", useMobileSheet && "min-h-0 flex-1 overflow-y-auto overscroll-contain"), children: [allowCustomValue && (jsx("li", { className: "pointer-events-none px-option-x pb-1 pt-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground", children: "Suggestions" })), filtered.length ? (filtered.map((option, index) => {
334
+ const active = selectedSet.has(option.id);
335
+ const group = options.find((item) => item.children?.some((child) => child.id === option.id));
336
+ const firstInGroup = group && !filtered.slice(0, index).some((item) => group.children?.some((child) => child.id === item.id));
337
+ return (jsxs(Fragment, { children: [firstInGroup && group && (jsx("li", { children: multiple ? (jsxs("button", { type: "button", "aria-pressed": group.children.every((child) => selectedSet.has(child.id)), className: "flex min-h-option-row w-full cursor-pointer items-center gap-3 rounded-control-sm px-option-x py-2 text-left text-sm font-medium text-foreground transition-colors hover:bg-muted max-md:min-h-11", onClick: () => {
338
+ const ids = group.children.map((child) => child.id);
339
+ const next = new Set(value ?? []);
340
+ const allSelected = ids.every((id) => next.has(id));
341
+ ids.forEach((id) => allSelected ? next.delete(id) : next.add(id));
342
+ setter(Array.from(next));
343
+ }, children: [jsx(CheckboxVisual, { checked: group.children.every((child) => selectedSet.has(child.id)) ? true : group.children.some((child) => selectedSet.has(child.id)) ? 'indeterminate' : false }), group.name] })) : jsx("div", { className: "px-option-x py-2 text-sm font-medium text-foreground", children: group.name }) })), jsx("li", { children: jsxs("button", { type: "button", "aria-pressed": multiple ? active : undefined, onClick: () => {
344
+ toggle(option.id);
345
+ if (multiple) {
346
+ // keep open for rapid multi-pick
347
+ setQuery("");
348
+ if (!useMobileSheet) {
349
+ inputRef.current?.focus();
350
+ }
351
+ }
352
+ else {
353
+ setQuery("");
354
+ setIsOpen(false);
355
+ }
356
+ }, className: cn("flex min-h-option-row w-full cursor-pointer items-center gap-3 rounded-control-sm px-option-x py-2 text-left text-sm text-muted-foreground transition-colors hover:bg-muted", useMobileSheet && "min-h-12", group && "pl-8", active && "bg-primary-tint"), children: [multiple ? (jsx(CheckboxVisual, { checked: active })) : null, option.name] }) })] }, String(option.id)));
357
+ })) : (!allowCustomValue || !query.trim() ? (jsx("li", { className: "px-option-x py-2 text-sm text-muted-foreground", children: emptyText })) : null), allowCustomValue && query.trim() && !findExactOption(query) && (jsx("li", { children: jsxs("button", { type: "button", className: "flex min-h-11 w-full cursor-pointer items-center gap-2 rounded-control-sm px-option-x py-2 text-left text-sm text-primary transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-primary", onMouseDown: (event) => event.preventDefault(), onClick: () => {
358
+ const text = query.trim();
359
+ if (multiple) {
360
+ setter(Array.from(new Set([...(value ?? []), text])));
361
+ setQuery("");
362
+ }
363
+ else {
364
+ resolveQuerySelection(text);
365
+ setIsOpen(false);
366
+ }
367
+ }, children: [jsx(PlusCircleIcon, { className: "h-4 w-4", "aria-hidden": "true" }), "Add \u201C", query.trim(), "\u201D"] }) }))] }), useMobileSheet && multiple && (jsx("div", { className: "shrink-0 border-t border-border bg-background px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]", children: jsx(Button, { type: "button", variant: "outline", className: "min-h-11 w-full", onClick: () => {
368
+ setQuery("");
369
+ setIsOpen(false);
370
+ }, children: "Done" }) }))] }) }) }))] }));
364
371
  }
365
372
  const Autocomplete = (config) => {
366
- const { required, options, placeholder, className, label, props, allowCustomValue = false, preserveOptionOrder = false, emptyText, mobileDropdownMode, inputIcons } = config;
367
- return (jsx(AutocompleteBase, { required: required, options: options, multiple: config.multiple === true, value: config.multiple === true ? config.value ?? [] : config.value != null ? [config.value] : [], setter: (arr) => {
373
+ const { options, placeholder, className, props, allowCustomValue = false, preserveOptionOrder = false, emptyText, mobileDropdownMode, inputIcons } = config;
374
+ return (jsx(AutocompleteBase, { options: options, multiple: config.multiple === true, value: config.multiple === true ? config.value ?? [] : config.value != null ? [config.value] : [], setter: (arr) => {
368
375
  if (config.multiple === true)
369
376
  config.setter(arr);
370
377
  else
371
378
  config.setter(arr[0] ?? null);
372
- }, placeholder: placeholder, className: className, label: label, allowCustomValue: allowCustomValue, preserveOptionOrder: preserveOptionOrder, emptyText: emptyText, mobileDropdownMode: mobileDropdownMode, inputIcons: inputIcons, ...props }));
379
+ }, placeholder: placeholder, className: className, allowCustomValue: allowCustomValue, preserveOptionOrder: preserveOptionOrder, emptyText: emptyText, mobileDropdownMode: mobileDropdownMode, inputIcons: inputIcons, ...props }));
373
380
  };
381
+ /** The surrounding FormField's label, when it is plain text. */
382
+ function useFormFieldLabel() {
383
+ return useFormField()?.labelText;
384
+ }
374
385
 
375
386
  export { Autocomplete };
376
387
  //# sourceMappingURL=autocomplete.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"autocomplete.js","sources":["../../src/components/autocomplete.tsx"],"sourcesContent":["\"use client\";\r\n\r\nimport { Fragment, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from \"react\";\r\nimport { Input } from \"./input\";\r\nimport { useDetectClickOutside } from '@/hooks/use-detect-click-outside';\r\nimport { cn } from \"@/utils\";\r\nimport { ChevronDown, PlusCircleIcon, Search, X } from \"lucide-react\";\r\nimport { Label } from \"./label\";\r\nimport { Button } from \"./button\";\r\nimport { CheckboxVisual } from \"./checkbox\";\r\nimport { Sheet, SheetContent, SheetTitle } from \"./sheet\";\r\nimport { useMobile } from \"@/hooks/use-mobile\";\r\nimport { useMobileSheetViewport } from \"@/hooks/use-mobile-sheet-viewport\";\r\nimport {\r\n FieldChromeContext,\r\n fieldFocusOutlineClassName,\r\n fieldInteractionClassName,\r\n useFieldFocus,\r\n} from \"@/hooks/use-field-focus\";\r\n\r\nexport interface IAutocompleteOption<ID extends number | string> {\r\n id: ID;\r\n name: string;\r\n keywords?: string[];\r\n /** Child options; in multiple mode the group can select all its children. */\r\n children?: IAutocompleteOption<ID>[];\r\n}\r\n\r\ntype MobileDropdownMode = \"sheet\" | \"inline\";\r\ntype InputIcons = boolean | \"search\" | \"dropdown\";\r\n\r\n/* -------------------------------------------------------\r\n * Base component (array-based). Single uses length 0..1.\r\n * -----------------------------------------------------*/\r\nfunction AutocompleteBase<ID extends number | string>({\r\n required,\r\n options,\r\n value = [],\r\n setter,\r\n placeholder,\r\n className,\r\n multiple = true,\r\n label,\r\n labelAddon,\r\n allowCustomValue = false,\r\n preserveOptionOrder = false,\r\n emptyText = \"No matching options\",\r\n mobileDropdownMode = \"sheet\",\r\n inputIcons = false,\r\n ...props\r\n}: {\r\n required?: boolean;\r\n options: IAutocompleteOption<ID>[];\r\n value?: ID[]; // single => 0..1 items, multi => any length\r\n setter: (next: ID[]) => void; // set the whole selection\r\n placeholder?: string;\r\n className?: string;\r\n multiple?: boolean;\r\n label?: React.ReactNode;\r\n labelAddon?: React.ReactNode;\r\n allowCustomValue?: boolean;\r\n preserveOptionOrder?: boolean;\r\n emptyText?: string;\r\n mobileDropdownMode?: MobileDropdownMode;\r\n inputIcons?: InputIcons;\r\n}) {\r\n const [query, setQuery] = useState(\"\");\r\n const [isOpen, setIsOpen] = useState(false);\r\n const [dropdownMaxHeight, setDropdownMaxHeight] = useState<number>();\r\n const isMobile = useMobile();\r\n const clickOutsideRef = useDetectClickOutside({\r\n onTriggered: () => {\r\n // Radix owns outside dismissal for the portalled modal sheet.\r\n if (isMobile && mobileDropdownMode === 'sheet') return;\r\n setIsOpen(false);\r\n },\r\n });\r\n const rootRef = useRef<HTMLDivElement | null>(null);\r\n const inputRef = useRef<HTMLInputElement | null>(null);\r\n const sheetInputRef = useRef<HTMLInputElement | null>(null);\r\n const sheetRef = useRef<HTMLDivElement | null>(null);\r\n const sheetCloseRef = useRef<HTMLButtonElement | null>(null);\r\n const lastSelectionRef = useRef(0);\r\n // Show the Button focus outline only for keyboard focus, not clicks.\r\n const { keyboardFocus, focusProps: fieldFocusProps } = useFieldFocus();\r\n\r\n const inputId = useId();\r\n const flatOptions = useMemo(\r\n () => options.flatMap((option) => option.children?.length ? option.children : [option]),\r\n [options],\r\n );\r\n\r\n const findExactOption = (value: string) => {\r\n const normalizedValue = value.trim().toLowerCase();\r\n return flatOptions.find(\r\n (o) =>\r\n o.name?.trim().toLowerCase() === normalizedValue ||\r\n o.keywords?.some((k) => k === normalizedValue),\r\n );\r\n };\r\n\r\n const resolveQuerySelection = (nextQuery: string, matchKeywords = true) => {\r\n const text = nextQuery.trim();\r\n if (!text) return false;\r\n\r\n const exact = matchKeywords\r\n ? findExactOption(text)\r\n : flatOptions.find(\r\n (o) => o.name?.trim().toLowerCase() === text.toLowerCase(),\r\n );\r\n if (exact) {\r\n setter([exact.id]);\r\n setQuery(\"\");\r\n return true;\r\n }\r\n\r\n if (allowCustomValue) {\r\n setter([text as unknown as ID]);\r\n setQuery(\"\");\r\n return true;\r\n }\r\n\r\n return false;\r\n };\r\n\r\n const selectedSet = useMemo(() => new Set(value ?? []), [value]);\r\n\r\n const filtered = useMemo(() => {\r\n const q = query.trim().toLowerCase();\r\n const base = q\r\n ? flatOptions.filter(\r\n (o) =>\r\n o.name?.toLowerCase().includes(q) ||\r\n options.some((group) => group.children?.some((child) => child.id === o.id) && group.name.toLowerCase().includes(q)) ||\r\n o.keywords?.some((k) => k.includes(q)),\r\n )\r\n : flatOptions;\r\n return preserveOptionOrder || options.some((option) => option.children?.length)\r\n ? base\r\n : base.slice().sort((a, b) => a.name.localeCompare(b.name));\r\n }, [query, flatOptions, options, preserveOptionOrder]);\r\n\r\n const toggle = (id: ID) => {\r\n lastSelectionRef.current = Date.now();\r\n if (!multiple) {\r\n setter([id]); // single-select\r\n setIsOpen(false);\r\n setQuery(\"\");\r\n return;\r\n }\r\n const set = new Set(value ?? []);\r\n if (set.has(id)) set.delete(id);\r\n else set.add(id);\r\n setter(Array.from(set));\r\n };\r\n\r\n const removeAt = (id: ID) => {\r\n const set = new Set(value ?? []);\r\n set.delete(id);\r\n setter(Array.from(set));\r\n };\r\n\r\n const selectedLabels = useMemo(\r\n () =>\r\n (value ?? [])\r\n .map((id) => {\r\n const label = flatOptions.find((o) => o.id === id)?.name;\r\n return label ?? (allowCustomValue ? String(id) : undefined);\r\n })\r\n .filter(Boolean) as string[],\r\n [value, flatOptions, allowCustomValue],\r\n );\r\n\r\n const singleDisplay = !multiple && (selectedLabels[0] ?? \"\");\r\n const useMobileSheet = isMobile && mobileDropdownMode === \"sheet\";\r\n const sheetViewport = useMobileSheetViewport(isOpen && useMobileSheet);\r\n // Desktop list: sized to the screen so it never runs off it. It opens\r\n // below the field, as tall as fits above the screen's bottom edge (16px\r\n // margin, at most 400px). With little room below (under 200px) and more\r\n // above, it opens upwards instead, sized to the space above. Re-measured\r\n // on scroll and resize while open.\r\n const [listFit, setListFit] = useState<{ maxHeight: number; above: boolean } | null>(null);\r\n useLayoutEffect(() => {\r\n if (!isOpen || useMobileSheet) return;\r\n const measure = () => {\r\n // The wrapper (label + field): inputRef is only attached in multiple\r\n // mode. The list hangs off its bottom, or sits above it when flipped.\r\n const field = rootRef.current?.getBoundingClientRect();\r\n if (!field) return;\r\n const below = window.innerHeight - field.bottom - 16;\r\n const above = field.top - 16;\r\n const openAbove = below < 200 && above > below;\r\n setListFit({\r\n above: openAbove,\r\n maxHeight: Math.max(120, Math.min(400, openAbove ? above : below)),\r\n });\r\n };\r\n measure();\r\n window.addEventListener(\"resize\", measure);\r\n window.addEventListener(\"scroll\", measure, true);\r\n return () => {\r\n window.removeEventListener(\"resize\", measure);\r\n window.removeEventListener(\"scroll\", measure, true);\r\n };\r\n }, [isOpen, useMobileSheet]);\r\n const useInlineMobileDropdown = isMobile && mobileDropdownMode === \"inline\";\r\n\r\n\r\n useEffect(() => {\r\n if (!isOpen || !useInlineMobileDropdown) {\r\n setDropdownMaxHeight(undefined);\r\n return;\r\n }\r\n\r\n const updateDropdownMaxHeight = () => {\r\n const rootRect = rootRef.current?.getBoundingClientRect();\r\n if (!rootRect) return;\r\n\r\n const viewportHeight =\r\n window.visualViewport?.height ?? window.innerHeight;\r\n const gap = 8;\r\n const availableHeight = viewportHeight - rootRect.bottom - gap;\r\n setDropdownMaxHeight(Math.max(0, Math.min(400, availableHeight)));\r\n };\r\n\r\n updateDropdownMaxHeight();\r\n window.addEventListener(\"resize\", updateDropdownMaxHeight);\r\n window.visualViewport?.addEventListener(\"resize\", updateDropdownMaxHeight);\r\n window.visualViewport?.addEventListener(\"scroll\", updateDropdownMaxHeight);\r\n\r\n return () => {\r\n window.removeEventListener(\"resize\", updateDropdownMaxHeight);\r\n window.visualViewport?.removeEventListener(\r\n \"resize\",\r\n updateDropdownMaxHeight,\r\n );\r\n window.visualViewport?.removeEventListener(\r\n \"scroll\",\r\n updateDropdownMaxHeight,\r\n );\r\n };\r\n }, [isOpen, useInlineMobileDropdown]);\r\n\r\n const suppressMobileKeyboard =\r\n isMobile && (useMobileSheet || (mobileDropdownMode === \"inline\" && !allowCustomValue));\r\n\r\n // --- keyboard helpers for multi\r\n const onMultiKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\r\n if (!multiple) return;\r\n if (allowCustomValue && e.key === \"Enter\" && query.trim().length > 0 && !findExactOption(query)) {\r\n const text = query.trim();\r\n const exact = findExactOption(text);\r\n const nextId = exact ? exact.id : (text as unknown as ID);\r\n const set = new Set(value ?? []);\r\n set.add(nextId);\r\n setter(Array.from(set));\r\n setQuery(\"\");\r\n setIsOpen(true);\r\n e.preventDefault();\r\n return;\r\n }\r\n if (\r\n e.key === \"Backspace\" &&\r\n query.length === 0 &&\r\n (value?.length ?? 0) > 0\r\n ) {\r\n const last = value[value.length - 1];\r\n removeAt(last);\r\n e.preventDefault();\r\n }\r\n if (e.key === \"Enter\") {\r\n const first = filtered[0];\r\n if (first) {\r\n toggle(first.id);\r\n setQuery(\"\");\r\n setIsOpen(true);\r\n e.preventDefault();\r\n }\r\n }\r\n if (e.key === \"ArrowDown\") setIsOpen(true);\r\n if (e.key === \"Escape\") setIsOpen(false);\r\n };\r\n\r\n // Same hover lift and press feedback as the Dropdown trigger.\r\n const fieldClassName = cn(\r\n fieldInteractionClassName,\r\n keyboardFocus && fieldFocusOutlineClassName,\r\n );\r\n\r\n const decorateSingleInput = (input: React.ReactNode) =>\r\n inputIcons ? (\r\n <div className={cn(\"relative min-w-0 flex-1\", fieldClassName)} {...fieldFocusProps}>\r\n {inputIcons !== \"search\" && inputIcons !== \"dropdown\" && (\r\n <Search\r\n className=\"pointer-events-none absolute left-3 top-1/2 z-20 h-4 w-4 -translate-y-1/2 text-muted-foreground\"\r\n aria-hidden=\"true\"\r\n />\r\n )}\r\n <FieldChromeContext value={true}>{input}</FieldChromeContext>\r\n {inputIcons === \"search\" ? (\r\n <Search\r\n className=\"pointer-events-none absolute right-3 top-1/2 z-20 h-4 w-4 -translate-y-1/2 text-muted-foreground\"\r\n aria-hidden=\"true\"\r\n />\r\n ) : (\r\n <ChevronDown\r\n className={cn(\r\n \"pointer-events-none absolute right-3 top-1/2 z-20 h-4 w-4 -translate-y-1/2 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none\",\r\n isOpen && \"rotate-180\",\r\n )}\r\n aria-hidden=\"true\"\r\n />\r\n )}\r\n </div>\r\n ) : (\r\n <div className={cn(\"relative min-w-0 flex-1\", fieldClassName)} {...fieldFocusProps}>\r\n <FieldChromeContext value={true}>{input}</FieldChromeContext>\r\n </div>\r\n );\r\n\r\n const OptionsSurface = useMobileSheet ? SheetContent : 'div';\r\n const sheetProps = useMobileSheet ? {\r\n side: 'bottom' as const,\r\n showCloseButton: false,\r\n overlayClassName: 'z-(--z-popover-overlay) bg-black/25 backdrop-blur-[1px]',\r\n 'aria-describedby': undefined,\r\n onOpenAutoFocus: (event: Event) => { event.preventDefault(); sheetCloseRef.current?.focus(); },\r\n onCloseAutoFocus: (event: Event) => { event.preventDefault(); inputRef.current?.focus(); },\r\n } : {};\r\n return (\r\n <div\r\n className={cn(\"relative w-full overflow-visible\", className)}\r\n ref={(node) => {\r\n rootRef.current = node;\r\n (\r\n clickOutsideRef as React.MutableRefObject<HTMLDivElement | null>\r\n ).current = node;\r\n }}\r\n >\r\n {label ? (\r\n <Label\r\n label={label}\r\n required={required}\r\n labelAddon={labelAddon}\r\n />\r\n ) : null}\r\n\r\n {multiple ? (\r\n // ---------- MULTI: chips inline inside the box ----------\r\n <div\r\n className={cn(\r\n \"relative flex min-h-form-control w-full flex-wrap items-center gap-1 rounded-control-lg border border-input bg-background px-[0.75em] pr-10 hover:border-input-hover\",\r\n fieldClassName,\r\n )}\r\n {...fieldFocusProps}\r\n onClick={() => {\r\n setIsOpen(true);\r\n if (!suppressMobileKeyboard) {\r\n inputRef.current?.focus();\r\n }\r\n }}\r\n >\r\n {(value ?? []).map((id) => {\r\n const label = flatOptions.find((o) => o.id === id)?.name ?? String(id);\r\n return (\r\n <span\r\n key={String(id)}\r\n className=\"my-0.5 flex items-center gap-1 rounded-control-sm border border-input bg-muted px-2 text-xs\"\r\n >\r\n {label}\r\n <Button\r\n type=\"button\"\r\n variant=\"ghost\"\r\n size=\"xs\"\r\n className=\"ml-1 h-5 min-h-0 w-5 p-0 hover:bg-muted\"\r\n onClick={(event) => { event.stopPropagation(); removeAt(id); }}\r\n aria-label={`Remove ${label}`}\r\n >\r\n <X className=\"h-3.5 w-3.5\" />\r\n </Button>\r\n </span>\r\n );\r\n })}\r\n <input\r\n id={inputId}\r\n ref={inputRef}\r\n value={query}\r\n onChange={(e) => {\r\n setQuery(e.target.value);\r\n setIsOpen(true);\r\n }}\r\n onBlur={() => {\r\n if (useMobileSheet) return;\r\n // Delay slightly to let dropdown option clicks register first\r\n setTimeout(() => {\r\n if (Date.now() - lastSelectionRef.current < 250) {\r\n return;\r\n }\r\n if (allowCustomValue && query.trim().length > 0) {\r\n const text = query.trim();\r\n const exact = findExactOption(text);\r\n const nextId = exact ? exact.id : (text as unknown as ID);\r\n setter(Array.from(new Set([...(value ?? []), nextId])));\r\n setQuery(\"\");\r\n }\r\n }, 150);\r\n }}\r\n onKeyDown={onMultiKeyDown}\r\n onFocus={() => { if (!useMobileSheet) setIsOpen(true); }}\r\n readOnly={suppressMobileKeyboard}\r\n placeholder={(value?.length ?? 0) === 0 ? placeholder : \"\"}\r\n className={cn(\r\n \"h-[calc(var(--spacing-form-control)-2px)] min-w-[8ch] flex-1 border-none bg-transparent p-0 text-base outline-none focus:ring-0\",\r\n \"placeholder:text-muted-foreground/40\",\r\n )}\r\n {...props}\r\n />\r\n <ChevronDown\r\n className={cn(\r\n \"pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none\",\r\n isOpen && \"rotate-180\",\r\n )}\r\n aria-hidden=\"true\"\r\n />\r\n </div>\r\n ) : (\r\n // ---------- SINGLE: regular input ----------\r\n decorateSingleInput(\r\n <Input\r\n id={inputId}\r\n value={singleDisplay || query}\r\n className={cn(\r\n \"border-input\",\r\n inputIcons === \"search\" || inputIcons === \"dropdown\" ? \"pr-10\" : inputIcons && \"px-10\",\r\n )}\r\n placeholder={placeholder}\r\n readOnly={suppressMobileKeyboard}\r\n onChange={(e) => {\r\n const nextQuery = e.target.value;\r\n\r\n if ((value?.length ?? 0) > 0) {\r\n setter([]);\r\n }\r\n\r\n const exact = findExactOption(nextQuery);\r\n // Only auto-fill on an exact NAME match; keyword/acronym matches\r\n // (e.g. \"dlsu\") require an explicit Enter, blur, or click.\r\n if (\r\n exact &&\r\n exact.name.trim().toLowerCase() ===\r\n nextQuery.trim().toLowerCase()\r\n ) {\r\n setter([exact.id]);\r\n setQuery(\"\");\r\n } else {\r\n setQuery(nextQuery);\r\n }\r\n\r\n setIsOpen(true);\r\n }}\r\n onFocus={() => { if (!useMobileSheet) setIsOpen(true); }}\r\n onClick={(e) => {\r\n setIsOpen(true);\r\n if (suppressMobileKeyboard) {\r\n e.currentTarget.blur();\r\n }\r\n }}\r\n onKeyDown={(e) => {\r\n if (e.key === \"Enter\" && resolveQuerySelection(query, true)) {\r\n setIsOpen(false);\r\n e.preventDefault();\r\n }\r\n }}\r\n onBlur={() => {\r\n if (useMobileSheet) return;\r\n // slight delay to let dropdown option clicks register first\r\n setTimeout(() => {\r\n if (Date.now() - lastSelectionRef.current < 250) {\r\n return;\r\n }\r\n if (!resolveQuerySelection(query, false)) setQuery(\"\");\r\n }, 150);\r\n }}\r\n />,\r\n )\r\n )}\r\n\r\n {isOpen && (\r\n <Sheet open={useMobileSheet && isOpen} onOpenChange={next => { if (!next) { setQuery(''); setIsOpen(false); } }}>\r\n <OptionsSurface\r\n {...sheetProps}\r\n ref={useMobileSheet ? sheetRef : undefined}\r\n role={useMobileSheet ? \"dialog\" : undefined}\r\n aria-modal={useMobileSheet ? true : undefined}\r\n aria-label={useMobileSheet ? (typeof label === \"string\" ? label : \"Choose options\") : undefined}\r\n className={cn(\r\n \"bg-background text-sm shadow-card border border-border\",\r\n useMobileSheet\r\n ? \"fixed left-0 right-0 z-(--z-popover) flex flex-col gap-0 overflow-hidden rounded-t-control-lg border-b-0 p-0\"\r\n : \"absolute left-0 right-0 z-50 mt-1 max-h-[400px] overflow-y-auto overscroll-contain rounded-control-lg\",\r\n )}\r\n style={\r\n useMobileSheet\r\n ? {\r\n bottom: sheetViewport?.bottom ?? 0,\r\n maxHeight: sheetViewport ? Math.min(sheetViewport.height, 640) : \"80dvh\",\r\n }\r\n : listFit\r\n ? {\r\n maxHeight: listFit.maxHeight,\r\n ...(listFit.above && {\r\n top: \"auto\",\r\n bottom: \"100%\",\r\n marginTop: 0,\r\n marginBottom: 4,\r\n }),\r\n }\r\n : undefined\r\n }\r\n >\r\n {useMobileSheet && (\r\n <div className=\"shrink-0 px-4 pb-3 pt-4\">\r\n <div className=\"mb-3 flex items-center justify-between gap-4\">\r\n <SheetTitle className=\"text-base font-semibold text-foreground\">{label || \"Choose options\"}</SheetTitle>\r\n <button ref={sheetCloseRef} type=\"button\" aria-label=\"Close options\" className=\"-mr-3 flex h-11 w-11 shrink-0 items-center justify-center rounded-control-lg text-muted-foreground hover:bg-muted\" onClick={() => { setQuery(\"\"); setIsOpen(false); }}>\r\n <X className=\"h-5 w-5\" aria-hidden=\"true\" />\r\n </button>\r\n </div>\r\n <Input\r\n ref={sheetInputRef}\r\n aria-label={typeof label === \"string\" ? `Search ${label}` : \"Search options\"}\r\n value={query}\r\n placeholder={placeholder ?? \"Search\"}\r\n className=\"h-10 min-h-10 max-h-none text-base\"\r\n onChange={(e) => {\r\n setQuery(e.target.value);\r\n setIsOpen(true);\r\n if ((value?.length ?? 0) > 0 && !multiple) {\r\n setter([]);\r\n }\r\n }}\r\n onKeyDown={(e) => {\r\n if (multiple) {\r\n onMultiKeyDown(e);\r\n return;\r\n }\r\n\r\n if (e.key === \"Enter\" && resolveQuerySelection(query)) {\r\n setIsOpen(false);\r\n e.preventDefault();\r\n }\r\n\r\n if (e.key === \"Escape\") {\r\n setIsOpen(false);\r\n }\r\n }}\r\n />\r\n </div>\r\n )}\r\n <ul className={cn(\"flex flex-col gap-option-gap p-option-inset\", useMobileSheet && \"min-h-0 flex-1 overflow-y-auto overscroll-contain\")}>\r\n {allowCustomValue && (\r\n <li className=\"pointer-events-none px-option-x pb-1 pt-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground\">\r\n Suggestions\r\n </li>\r\n )}\r\n {filtered.length ? (\r\n filtered.map((option, index) => {\r\n const active = selectedSet.has(option.id);\r\n const group = options.find((item) => item.children?.some((child) => child.id === option.id));\r\n const firstInGroup = group && !filtered.slice(0, index).some((item) => group.children?.some((child) => child.id === item.id));\r\n return (\r\n <Fragment key={String(option.id)}>\r\n {firstInGroup && group && (\r\n <li>\r\n {multiple ? (\r\n <button type=\"button\" aria-pressed={group.children!.every((child) => selectedSet.has(child.id))} className=\"flex min-h-option-row w-full cursor-pointer items-center gap-3 rounded-control-sm px-option-x py-2 text-left text-sm font-medium text-foreground transition-colors hover:bg-muted max-md:min-h-11\" onClick={() => {\r\n const ids = group.children!.map((child) => child.id);\r\n const next = new Set(value ?? []);\r\n const allSelected = ids.every((id) => next.has(id));\r\n ids.forEach((id) => allSelected ? next.delete(id) : next.add(id));\r\n setter(Array.from(next));\r\n }}>\r\n <CheckboxVisual checked={group.children!.every((child) => selectedSet.has(child.id)) ? true : group.children!.some((child) => selectedSet.has(child.id)) ? 'indeterminate' : false} />\r\n {group.name}\r\n </button>\r\n ) : <div className=\"px-option-x py-2 text-sm font-medium text-foreground\">{group.name}</div>}\r\n </li>\r\n )}\r\n <li>\r\n <button\r\n type=\"button\"\r\n aria-pressed={multiple ? active : undefined}\r\n onClick={() => {\r\n toggle(option.id);\r\n if (multiple) {\r\n // keep open for rapid multi-pick\r\n setQuery(\"\");\r\n if (!useMobileSheet) {\r\n inputRef.current?.focus();\r\n }\r\n } else {\r\n setQuery(\"\");\r\n setIsOpen(false);\r\n }\r\n }}\r\n className={cn(\r\n \"flex min-h-option-row w-full cursor-pointer items-center gap-3 rounded-control-sm px-option-x py-2 text-left text-sm text-muted-foreground transition-colors hover:bg-muted\",\r\n useMobileSheet && \"min-h-12\",\r\n group && \"pl-8\",\r\n active && \"bg-primary-tint\",\r\n )}\r\n >\r\n {multiple ? (\r\n <CheckboxVisual checked={active} />\r\n ) : null}\r\n {option.name}\r\n </button>\r\n </li>\r\n </Fragment>\r\n );\r\n })\r\n ) : (\r\n !allowCustomValue || !query.trim() ? (\r\n <li className=\"px-option-x py-2 text-sm text-muted-foreground\">\r\n {emptyText}\r\n </li>\r\n ) : null\r\n )}\r\n {allowCustomValue && query.trim() && !findExactOption(query) && (\r\n <li>\r\n <button\r\n type=\"button\"\r\n className=\"flex min-h-11 w-full cursor-pointer items-center gap-2 rounded-control-sm px-option-x py-2 text-left text-sm text-primary transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-primary\"\r\n onMouseDown={(event) => event.preventDefault()}\r\n onClick={() => {\r\n const text = query.trim();\r\n if (multiple) {\r\n setter(Array.from(new Set([...(value ?? []), text as unknown as ID])));\r\n setQuery(\"\");\r\n } else {\r\n resolveQuerySelection(text);\r\n setIsOpen(false);\r\n }\r\n }}\r\n >\r\n <PlusCircleIcon className=\"h-4 w-4\" aria-hidden=\"true\" />\r\n Add “{query.trim()}”\r\n </button>\r\n </li>\r\n )}\r\n </ul>\r\n {useMobileSheet && multiple && (\r\n <div className=\"shrink-0 border-t border-border bg-background px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]\">\r\n <Button\r\n type=\"button\"\r\n variant=\"outline\"\r\n className=\"min-h-11 w-full\"\r\n onClick={() => {\r\n setQuery(\"\");\r\n setIsOpen(false);\r\n }}\r\n >\r\n Done\r\n </Button>\r\n </div>\r\n )}\r\n </OptionsSurface>\r\n </Sheet>\r\n )}\r\n </div>\r\n );\r\n}\r\n\r\ntype AutocompleteCommonProps<ID extends number | string> = {\r\n required?: boolean;\r\n options: IAutocompleteOption<ID>[];\r\n placeholder?: string;\r\n className?: string;\r\n label?: React.ReactNode;\r\n props?: any[];\r\n /** Allow a user to add their own text. Custom values are strings. */\r\n allowCustomValue?: boolean;\r\n preserveOptionOrder?: boolean;\r\n emptyText?: string;\r\n mobileDropdownMode?: MobileDropdownMode;\r\n inputIcons?: InputIcons;\r\n};\r\n\r\nexport type AutocompleteProps<ID extends number | string> = AutocompleteCommonProps<ID> & (\r\n | { multiple?: false; value?: ID | null; setter: (value?: ID | null) => void }\r\n | { multiple: true; value?: ID[]; setter: (value: ID[]) => void }\r\n);\r\n\r\nexport const Autocomplete = <ID extends number | string>(config: AutocompleteProps<ID>) => {\r\n const { required, options, placeholder, className, label, props, allowCustomValue = false,\r\n preserveOptionOrder = false, emptyText, mobileDropdownMode, inputIcons } = config;\r\n return (\r\n <AutocompleteBase<ID>\r\n required={required}\r\n options={options}\r\n multiple={config.multiple === true}\r\n value={config.multiple === true ? config.value ?? [] : config.value != null ? [config.value] : []}\r\n setter={(arr) => {\r\n if (config.multiple === true) config.setter(arr);\r\n else config.setter(arr[0] ?? null);\r\n }}\r\n placeholder={placeholder}\r\n className={className}\r\n label={label}\r\n allowCustomValue={allowCustomValue}\r\n preserveOptionOrder={preserveOptionOrder}\r\n emptyText={emptyText}\r\n mobileDropdownMode={mobileDropdownMode}\r\n inputIcons={inputIcons}\r\n {...props}\r\n />\r\n );\r\n};\r\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AA+BA;;AAE0D;AAC1D;;;;AAmCE;;;;AAII;;;;AAGH;AACD;AACA;AACA;AACA;AACA;AACA;;;AAIA;AACA;AAKA;;AAEE;AAGI;AAEN;;AAGE;AACA;AAAW;;AAGT;;;AAKA;;AAEA;;;AAIA;;AAEA;;AAGF;AACF;AAEA;AAEA;;;;AAMY;AACA;;AAGV;AACE;;;AAIJ;AACE;;AAEE;;;;;;AAMF;AAAiB;;AACZ;;AAEP;AAEA;;AAEE;;AAEF;;AAKO;AACC;AACA;AACF;AACC;AAIP;AACA;;;;;;;;;;;;;;;AAcI;;;AAEA;;AAEA;AACE;;AAED;AACH;AACA;AACA;;AAEA;AACE;;AAEF;AACF;AACA;;AAIE;;;;;;AAOE;;;;;AAMA;AACF;AAEA;AACA;;;AAIA;AACE;;;AASF;AACF;AAEA;;AAIA;AACE;;;AAEE;AACA;AACA;;AAEA;;;;;;;AAOF;;;;;;;AASA;AACE;;AAEE;;;;;;AAMJ;;AACA;;AACF;;;;;AAwCA;AACE;AACA;AACA;AACA;;;;AAIF;AAIM;AAEE;AAEJ;;AAYE;;;AASM;;AAEJ;;AAIE;;AAwBE;;AAEF;AAEE;;;;;;;;AAOI;AACA;AACA;;;;;AAKN;AAEsC;;;AA8BpC;;;;AAMA;;;AAGA;AAEE;AACE;AAEF;;;;;;;;AAQkC;;;AAIlC;;AAEJ;AAEE;;;;AAIF;AAEE;;;;;;;AAME;;;;;;AAQoG;AAUnG;AACA;AAID;AACI;AACA;AACD;AACH;AACE;;AAEI;AACE;AACA;AACA;AACA;;AAEH;;AAmBD;;AAEA;;;AAGF;;;;;;;;;AAYE;;;AAGF;;AAaF;AACA;;AAOU;;AAEA;AACA;;;AAcJ;;;;;AAKI;;;;;;;;AAsBZ;AAeM;;;;;;;;;;;;;AAoCpB;AAsBO;AACL;AAEA;AAOM;AAA8B;;;AAEhC;AAYN;;"}
1
+ {"version":3,"file":"autocomplete.js","sources":["../../src/components/autocomplete.tsx"],"sourcesContent":["\"use client\";\r\n\r\nimport { Fragment, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from \"react\";\r\nimport { Input } from \"./input\";\r\nimport { useDetectClickOutside } from '@/hooks/use-detect-click-outside';\r\nimport { cn } from \"@/utils\";\r\nimport { ChevronDown, PlusCircleIcon, Search, X } from \"lucide-react\";\r\nimport { FormFieldReset, useFormField, useFormFieldControl } from \"./form-field\";\r\nimport { Button } from \"./button\";\r\nimport { CheckboxVisual } from \"./checkbox\";\r\nimport { Sheet, SheetContent, SheetTitle } from \"./sheet\";\r\nimport { useMobile } from \"@/hooks/use-mobile\";\r\nimport { useMobileSheetViewport } from \"@/hooks/use-mobile-sheet-viewport\";\r\nimport {\r\n FieldChromeContext,\r\n fieldFocusOutlineClassName,\r\n fieldInteractionClassName,\r\n useFieldFocus,\r\n} from \"@/hooks/use-field-focus\";\r\n\r\nexport interface IAutocompleteOption<ID extends number | string> {\r\n id: ID;\r\n name: string;\r\n keywords?: string[];\r\n /** Child options; in multiple mode the group can select all its children. */\r\n children?: IAutocompleteOption<ID>[];\r\n}\r\n\r\ntype MobileDropdownMode = \"sheet\" | \"inline\";\r\ntype InputIcons = boolean | \"search\" | \"dropdown\";\r\n\r\n/* -------------------------------------------------------\r\n * Base component (array-based). Single uses length 0..1.\r\n * -----------------------------------------------------*/\r\nfunction AutocompleteBase<ID extends number | string>({\r\n options,\r\n value = [],\r\n setter,\r\n placeholder,\r\n className,\r\n multiple = true,\r\n allowCustomValue = false,\r\n preserveOptionOrder = false,\r\n emptyText = \"No matching options\",\r\n mobileDropdownMode = \"sheet\",\r\n inputIcons = false,\r\n ...props\r\n}: {\r\n options: IAutocompleteOption<ID>[];\r\n value?: ID[]; // single => 0..1 items, multi => any length\r\n setter: (next: ID[]) => void; // set the whole selection\r\n placeholder?: string;\r\n className?: string;\r\n multiple?: boolean;\r\n allowCustomValue?: boolean;\r\n preserveOptionOrder?: boolean;\r\n emptyText?: string;\r\n mobileDropdownMode?: MobileDropdownMode;\r\n inputIcons?: InputIcons;\r\n}) {\r\n const [query, setQuery] = useState(\"\");\r\n const [isOpen, setIsOpen] = useState(false);\r\n const [dropdownMaxHeight, setDropdownMaxHeight] = useState<number>();\r\n const isMobile = useMobile();\r\n const clickOutsideRef = useDetectClickOutside({\r\n onTriggered: () => {\r\n // Radix owns outside dismissal for the portalled modal sheet.\r\n if (isMobile && mobileDropdownMode === 'sheet') return;\r\n setIsOpen(false);\r\n },\r\n });\r\n const rootRef = useRef<HTMLDivElement | null>(null);\r\n const inputRef = useRef<HTMLInputElement | null>(null);\r\n const sheetInputRef = useRef<HTMLInputElement | null>(null);\r\n const sheetRef = useRef<HTMLDivElement | null>(null);\r\n const sheetCloseRef = useRef<HTMLButtonElement | null>(null);\r\n const lastSelectionRef = useRef(0);\r\n // Show the Button focus outline only for keyboard focus, not clicks.\r\n const { keyboardFocus, focusProps: fieldFocusProps } = useFieldFocus();\r\n\r\n // Inside a FormField the input takes the field's id and links; its label names the sheet.\r\n const field = useFormFieldControl<{\r\n id?: string;\r\n \"aria-describedby\"?: string;\r\n \"aria-invalid\"?: React.AriaAttributes[\"aria-invalid\"];\r\n \"aria-required\"?: React.AriaAttributes[\"aria-required\"];\r\n }>({});\r\n const { id: fieldId, ...fieldAria } = field;\r\n const generatedId = useId();\r\n const inputId = fieldId ?? generatedId;\r\n const fieldLabel = useFormFieldLabel();\r\n const flatOptions = useMemo(\r\n () => options.flatMap((option) => option.children?.length ? option.children : [option]),\r\n [options],\r\n );\r\n\r\n const findExactOption = (value: string) => {\r\n const normalizedValue = value.trim().toLowerCase();\r\n return flatOptions.find(\r\n (o) =>\r\n o.name?.trim().toLowerCase() === normalizedValue ||\r\n o.keywords?.some((k) => k === normalizedValue),\r\n );\r\n };\r\n\r\n const resolveQuerySelection = (nextQuery: string, matchKeywords = true) => {\r\n const text = nextQuery.trim();\r\n if (!text) return false;\r\n\r\n const exact = matchKeywords\r\n ? findExactOption(text)\r\n : flatOptions.find(\r\n (o) => o.name?.trim().toLowerCase() === text.toLowerCase(),\r\n );\r\n if (exact) {\r\n setter([exact.id]);\r\n setQuery(\"\");\r\n return true;\r\n }\r\n\r\n if (allowCustomValue) {\r\n setter([text as unknown as ID]);\r\n setQuery(\"\");\r\n return true;\r\n }\r\n\r\n return false;\r\n };\r\n\r\n const selectedSet = useMemo(() => new Set(value ?? []), [value]);\r\n\r\n const filtered = useMemo(() => {\r\n const q = query.trim().toLowerCase();\r\n const base = q\r\n ? flatOptions.filter(\r\n (o) =>\r\n o.name?.toLowerCase().includes(q) ||\r\n options.some((group) => group.children?.some((child) => child.id === o.id) && group.name.toLowerCase().includes(q)) ||\r\n o.keywords?.some((k) => k.includes(q)),\r\n )\r\n : flatOptions;\r\n return preserveOptionOrder || options.some((option) => option.children?.length)\r\n ? base\r\n : base.slice().sort((a, b) => a.name.localeCompare(b.name));\r\n }, [query, flatOptions, options, preserveOptionOrder]);\r\n\r\n const toggle = (id: ID) => {\r\n lastSelectionRef.current = Date.now();\r\n if (!multiple) {\r\n setter([id]); // single-select\r\n setIsOpen(false);\r\n setQuery(\"\");\r\n return;\r\n }\r\n const set = new Set(value ?? []);\r\n if (set.has(id)) set.delete(id);\r\n else set.add(id);\r\n setter(Array.from(set));\r\n };\r\n\r\n const removeAt = (id: ID) => {\r\n const set = new Set(value ?? []);\r\n set.delete(id);\r\n setter(Array.from(set));\r\n };\r\n\r\n const selectedLabels = useMemo(\r\n () =>\r\n (value ?? [])\r\n .map((id) => {\r\n const label = flatOptions.find((o) => o.id === id)?.name;\r\n return label ?? (allowCustomValue ? String(id) : undefined);\r\n })\r\n .filter(Boolean) as string[],\r\n [value, flatOptions, allowCustomValue],\r\n );\r\n\r\n const singleDisplay = !multiple && (selectedLabels[0] ?? \"\");\r\n const useMobileSheet = isMobile && mobileDropdownMode === \"sheet\";\r\n const sheetViewport = useMobileSheetViewport(isOpen && useMobileSheet);\r\n // Desktop list: sized to the screen so it never runs off it. It opens\r\n // below the field, as tall as fits above the screen's bottom edge (16px\r\n // margin, at most 400px). With little room below (under 200px) and more\r\n // above, it opens upwards instead, sized to the space above. Re-measured\r\n // on scroll and resize while open.\r\n const [listFit, setListFit] = useState<{ maxHeight: number; above: boolean } | null>(null);\r\n useLayoutEffect(() => {\r\n if (!isOpen || useMobileSheet) return;\r\n const measure = () => {\r\n // The wrapper (label + field): inputRef is only attached in multiple\r\n // mode. The list hangs off its bottom, or sits above it when flipped.\r\n const field = rootRef.current?.getBoundingClientRect();\r\n if (!field) return;\r\n const below = window.innerHeight - field.bottom - 16;\r\n const above = field.top - 16;\r\n const openAbove = below < 200 && above > below;\r\n setListFit({\r\n above: openAbove,\r\n maxHeight: Math.max(120, Math.min(400, openAbove ? above : below)),\r\n });\r\n };\r\n measure();\r\n window.addEventListener(\"resize\", measure);\r\n window.addEventListener(\"scroll\", measure, true);\r\n return () => {\r\n window.removeEventListener(\"resize\", measure);\r\n window.removeEventListener(\"scroll\", measure, true);\r\n };\r\n }, [isOpen, useMobileSheet]);\r\n const useInlineMobileDropdown = isMobile && mobileDropdownMode === \"inline\";\r\n\r\n\r\n useEffect(() => {\r\n if (!isOpen || !useInlineMobileDropdown) {\r\n setDropdownMaxHeight(undefined);\r\n return;\r\n }\r\n\r\n const updateDropdownMaxHeight = () => {\r\n const rootRect = rootRef.current?.getBoundingClientRect();\r\n if (!rootRect) return;\r\n\r\n const viewportHeight =\r\n window.visualViewport?.height ?? window.innerHeight;\r\n const gap = 8;\r\n const availableHeight = viewportHeight - rootRect.bottom - gap;\r\n setDropdownMaxHeight(Math.max(0, Math.min(400, availableHeight)));\r\n };\r\n\r\n updateDropdownMaxHeight();\r\n window.addEventListener(\"resize\", updateDropdownMaxHeight);\r\n window.visualViewport?.addEventListener(\"resize\", updateDropdownMaxHeight);\r\n window.visualViewport?.addEventListener(\"scroll\", updateDropdownMaxHeight);\r\n\r\n return () => {\r\n window.removeEventListener(\"resize\", updateDropdownMaxHeight);\r\n window.visualViewport?.removeEventListener(\r\n \"resize\",\r\n updateDropdownMaxHeight,\r\n );\r\n window.visualViewport?.removeEventListener(\r\n \"scroll\",\r\n updateDropdownMaxHeight,\r\n );\r\n };\r\n }, [isOpen, useInlineMobileDropdown]);\r\n\r\n const suppressMobileKeyboard =\r\n isMobile && (useMobileSheet || (mobileDropdownMode === \"inline\" && !allowCustomValue));\r\n\r\n // --- keyboard helpers for multi\r\n const onMultiKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\r\n if (!multiple) return;\r\n if (allowCustomValue && e.key === \"Enter\" && query.trim().length > 0 && !findExactOption(query)) {\r\n const text = query.trim();\r\n const exact = findExactOption(text);\r\n const nextId = exact ? exact.id : (text as unknown as ID);\r\n const set = new Set(value ?? []);\r\n set.add(nextId);\r\n setter(Array.from(set));\r\n setQuery(\"\");\r\n setIsOpen(true);\r\n e.preventDefault();\r\n return;\r\n }\r\n if (\r\n e.key === \"Backspace\" &&\r\n query.length === 0 &&\r\n (value?.length ?? 0) > 0\r\n ) {\r\n const last = value[value.length - 1];\r\n removeAt(last);\r\n e.preventDefault();\r\n }\r\n if (e.key === \"Enter\") {\r\n const first = filtered[0];\r\n if (first) {\r\n toggle(first.id);\r\n setQuery(\"\");\r\n setIsOpen(true);\r\n e.preventDefault();\r\n }\r\n }\r\n if (e.key === \"ArrowDown\") setIsOpen(true);\r\n if (e.key === \"Escape\") setIsOpen(false);\r\n };\r\n\r\n // Same hover lift and press feedback as the Dropdown trigger.\r\n const fieldClassName = cn(\r\n fieldInteractionClassName,\r\n keyboardFocus && fieldFocusOutlineClassName,\r\n );\r\n\r\n const decorateSingleInput = (input: React.ReactNode) =>\r\n inputIcons ? (\r\n <div className={cn(\"relative min-w-0 flex-1\", fieldClassName)} {...fieldFocusProps}>\r\n {inputIcons !== \"search\" && inputIcons !== \"dropdown\" && (\r\n <Search\r\n className=\"pointer-events-none absolute left-3 top-1/2 z-20 h-4 w-4 -translate-y-1/2 text-muted-foreground\"\r\n aria-hidden=\"true\"\r\n />\r\n )}\r\n <FieldChromeContext value={true}>{input}</FieldChromeContext>\r\n {inputIcons === \"search\" ? (\r\n <Search\r\n className=\"pointer-events-none absolute right-3 top-1/2 z-20 h-4 w-4 -translate-y-1/2 text-muted-foreground\"\r\n aria-hidden=\"true\"\r\n />\r\n ) : (\r\n <ChevronDown\r\n className={cn(\r\n \"pointer-events-none absolute right-3 top-1/2 z-20 h-4 w-4 -translate-y-1/2 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none\",\r\n isOpen && \"rotate-180\",\r\n )}\r\n aria-hidden=\"true\"\r\n />\r\n )}\r\n </div>\r\n ) : (\r\n <div className={cn(\"relative min-w-0 flex-1\", fieldClassName)} {...fieldFocusProps}>\r\n <FieldChromeContext value={true}>{input}</FieldChromeContext>\r\n </div>\r\n );\r\n\r\n const OptionsSurface = useMobileSheet ? SheetContent : 'div';\r\n const sheetProps = useMobileSheet ? {\r\n side: 'bottom' as const,\r\n showCloseButton: false,\r\n overlayClassName: 'z-(--z-popover-overlay) bg-black/25 backdrop-blur-[1px]',\r\n 'aria-describedby': undefined,\r\n onOpenAutoFocus: (event: Event) => { event.preventDefault(); sheetCloseRef.current?.focus(); },\r\n onCloseAutoFocus: (event: Event) => { event.preventDefault(); inputRef.current?.focus(); },\r\n } : {};\r\n return (\r\n <div\r\n className={cn(\"relative w-full overflow-visible\", className)}\r\n ref={(node) => {\r\n rootRef.current = node;\r\n (\r\n clickOutsideRef as React.MutableRefObject<HTMLDivElement | null>\r\n ).current = node;\r\n }}\r\n >\r\n {multiple ? (\r\n // ---------- MULTI: chips inline inside the box ----------\r\n <div\r\n className={cn(\r\n // text-base keeps the 0.75em padding at 12px, like the single input.\r\n \"relative flex min-h-form-control w-full flex-wrap items-center gap-1 rounded-control-lg border border-input bg-background px-[0.75em] pr-10 text-base text-foreground hover:border-input-hover\",\r\n \"has-[input[aria-invalid=true]]:border-destructive has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50\",\r\n fieldClassName,\r\n )}\r\n {...fieldFocusProps}\r\n onClick={() => {\r\n setIsOpen(true);\r\n if (!suppressMobileKeyboard) {\r\n inputRef.current?.focus();\r\n }\r\n }}\r\n >\r\n {(value ?? []).map((id) => {\r\n const label = flatOptions.find((o) => o.id === id)?.name ?? String(id);\r\n return (\r\n <span\r\n key={String(id)}\r\n className=\"my-0.5 flex items-center gap-1 rounded-control-sm border border-input bg-muted px-2 text-xs\"\r\n >\r\n {label}\r\n <Button\r\n type=\"button\"\r\n variant=\"ghost\"\r\n size=\"xs\"\r\n className=\"ml-1 h-5 min-h-0 w-5 p-0 hover:bg-muted\"\r\n onClick={(event) => { event.stopPropagation(); removeAt(id); }}\r\n aria-label={`Remove ${label}`}\r\n >\r\n <X className=\"h-3.5 w-3.5\" />\r\n </Button>\r\n </span>\r\n );\r\n })}\r\n <input\r\n id={inputId}\r\n {...fieldAria}\r\n ref={inputRef}\r\n value={query}\r\n onChange={(e) => {\r\n setQuery(e.target.value);\r\n setIsOpen(true);\r\n }}\r\n onBlur={() => {\r\n if (useMobileSheet) return;\r\n // Delay slightly to let dropdown option clicks register first\r\n setTimeout(() => {\r\n if (Date.now() - lastSelectionRef.current < 250) {\r\n return;\r\n }\r\n if (allowCustomValue && query.trim().length > 0) {\r\n const text = query.trim();\r\n const exact = findExactOption(text);\r\n const nextId = exact ? exact.id : (text as unknown as ID);\r\n setter(Array.from(new Set([...(value ?? []), nextId])));\r\n setQuery(\"\");\r\n }\r\n }, 150);\r\n }}\r\n onKeyDown={onMultiKeyDown}\r\n onFocus={() => { if (!useMobileSheet) setIsOpen(true); }}\r\n readOnly={suppressMobileKeyboard}\r\n placeholder={(value?.length ?? 0) === 0 ? placeholder : \"\"}\r\n className={cn(\r\n \"h-[calc(var(--spacing-form-control)-2px)] min-w-[8ch] flex-1 border-none bg-transparent p-0 text-base outline-none focus:ring-0 disabled:cursor-not-allowed\",\r\n \"placeholder:text-muted-foreground/40\",\r\n )}\r\n {...props}\r\n />\r\n <ChevronDown\r\n className={cn(\r\n \"pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none\",\r\n isOpen && \"rotate-180\",\r\n )}\r\n aria-hidden=\"true\"\r\n />\r\n </div>\r\n ) : (\r\n // ---------- SINGLE: regular input ----------\r\n decorateSingleInput(\r\n <Input\r\n id={inputId}\r\n {...fieldAria}\r\n value={singleDisplay || query}\r\n className={cn(\r\n \"border-input\",\r\n inputIcons === \"search\" || inputIcons === \"dropdown\" ? \"pr-10\" : inputIcons && \"px-10\",\r\n )}\r\n placeholder={placeholder}\r\n readOnly={suppressMobileKeyboard}\r\n onChange={(e) => {\r\n const nextQuery = e.target.value;\r\n\r\n if ((value?.length ?? 0) > 0) {\r\n setter([]);\r\n }\r\n\r\n const exact = findExactOption(nextQuery);\r\n // Only auto-fill on an exact NAME match; keyword/acronym matches\r\n // (e.g. \"dlsu\") require an explicit Enter, blur, or click.\r\n if (\r\n exact &&\r\n exact.name.trim().toLowerCase() ===\r\n nextQuery.trim().toLowerCase()\r\n ) {\r\n setter([exact.id]);\r\n setQuery(\"\");\r\n } else {\r\n setQuery(nextQuery);\r\n }\r\n\r\n setIsOpen(true);\r\n }}\r\n onFocus={() => { if (!useMobileSheet) setIsOpen(true); }}\r\n onClick={(e) => {\r\n setIsOpen(true);\r\n if (suppressMobileKeyboard) {\r\n e.currentTarget.blur();\r\n }\r\n }}\r\n onKeyDown={(e) => {\r\n if (e.key === \"Enter\" && resolveQuerySelection(query, true)) {\r\n setIsOpen(false);\r\n e.preventDefault();\r\n }\r\n }}\r\n onBlur={() => {\r\n if (useMobileSheet) return;\r\n // slight delay to let dropdown option clicks register first\r\n setTimeout(() => {\r\n if (Date.now() - lastSelectionRef.current < 250) {\r\n return;\r\n }\r\n if (!resolveQuerySelection(query, false)) setQuery(\"\");\r\n }, 150);\r\n }}\r\n />,\r\n )\r\n )}\r\n\r\n {isOpen && (\r\n <Sheet open={useMobileSheet && isOpen} onOpenChange={next => { if (!next) { setQuery(''); setIsOpen(false); } }}>\r\n <OptionsSurface\r\n {...sheetProps}\r\n ref={useMobileSheet ? sheetRef : undefined}\r\n role={useMobileSheet ? \"dialog\" : undefined}\r\n aria-modal={useMobileSheet ? true : undefined}\r\n aria-label={useMobileSheet ? (fieldLabel ?? \"Choose options\") : undefined}\r\n className={cn(\r\n \"bg-background text-sm shadow-card border border-border\",\r\n useMobileSheet\r\n ? \"fixed left-0 right-0 z-(--z-popover) flex flex-col gap-0 overflow-hidden rounded-t-control-lg border-b-0 p-0\"\r\n : \"absolute left-0 right-0 z-50 mt-1 max-h-[400px] overflow-y-auto overscroll-contain rounded-control-lg\",\r\n )}\r\n style={\r\n useMobileSheet\r\n ? {\r\n bottom: sheetViewport?.bottom ?? 0,\r\n maxHeight: sheetViewport ? Math.min(sheetViewport.height, 640) : \"80dvh\",\r\n }\r\n : listFit\r\n ? {\r\n maxHeight: listFit.maxHeight,\r\n ...(listFit.above && {\r\n top: \"auto\",\r\n bottom: \"100%\",\r\n marginTop: 0,\r\n marginBottom: 4,\r\n }),\r\n }\r\n : undefined\r\n }\r\n >\r\n {/* The sheet's own search box must not take the field's id. */}\r\n <FormFieldReset>\r\n {useMobileSheet && (\r\n <div className=\"shrink-0 px-4 pb-3 pt-4\">\r\n <div className=\"mb-3 flex items-center justify-between gap-4\">\r\n <SheetTitle className=\"text-base font-semibold text-foreground\">{fieldLabel ?? \"Choose options\"}</SheetTitle>\r\n <button ref={sheetCloseRef} type=\"button\" aria-label=\"Close options\" className=\"-mr-3 flex h-11 w-11 shrink-0 items-center justify-center rounded-control-lg text-muted-foreground hover:bg-muted\" onClick={() => { setQuery(\"\"); setIsOpen(false); }}>\r\n <X className=\"h-5 w-5\" aria-hidden=\"true\" />\r\n </button>\r\n </div>\r\n <Input\r\n ref={sheetInputRef}\r\n aria-label={fieldLabel ? `Search ${fieldLabel}` : \"Search options\"}\r\n value={query}\r\n placeholder={placeholder ?? \"Search\"}\r\n className=\"h-10 min-h-10 max-h-none text-base\"\r\n onChange={(e) => {\r\n setQuery(e.target.value);\r\n setIsOpen(true);\r\n if ((value?.length ?? 0) > 0 && !multiple) {\r\n setter([]);\r\n }\r\n }}\r\n onKeyDown={(e) => {\r\n if (multiple) {\r\n onMultiKeyDown(e);\r\n return;\r\n }\r\n\r\n if (e.key === \"Enter\" && resolveQuerySelection(query)) {\r\n setIsOpen(false);\r\n e.preventDefault();\r\n }\r\n\r\n if (e.key === \"Escape\") {\r\n setIsOpen(false);\r\n }\r\n }}\r\n />\r\n </div>\r\n )}\r\n <ul className={cn(\"flex flex-col gap-option-gap p-option-inset\", useMobileSheet && \"min-h-0 flex-1 overflow-y-auto overscroll-contain\")}>\r\n {allowCustomValue && (\r\n <li className=\"pointer-events-none px-option-x pb-1 pt-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground\">\r\n Suggestions\r\n </li>\r\n )}\r\n {filtered.length ? (\r\n filtered.map((option, index) => {\r\n const active = selectedSet.has(option.id);\r\n const group = options.find((item) => item.children?.some((child) => child.id === option.id));\r\n const firstInGroup = group && !filtered.slice(0, index).some((item) => group.children?.some((child) => child.id === item.id));\r\n return (\r\n <Fragment key={String(option.id)}>\r\n {firstInGroup && group && (\r\n <li>\r\n {multiple ? (\r\n <button type=\"button\" aria-pressed={group.children!.every((child) => selectedSet.has(child.id))} className=\"flex min-h-option-row w-full cursor-pointer items-center gap-3 rounded-control-sm px-option-x py-2 text-left text-sm font-medium text-foreground transition-colors hover:bg-muted max-md:min-h-11\" onClick={() => {\r\n const ids = group.children!.map((child) => child.id);\r\n const next = new Set(value ?? []);\r\n const allSelected = ids.every((id) => next.has(id));\r\n ids.forEach((id) => allSelected ? next.delete(id) : next.add(id));\r\n setter(Array.from(next));\r\n }}>\r\n <CheckboxVisual checked={group.children!.every((child) => selectedSet.has(child.id)) ? true : group.children!.some((child) => selectedSet.has(child.id)) ? 'indeterminate' : false} />\r\n {group.name}\r\n </button>\r\n ) : <div className=\"px-option-x py-2 text-sm font-medium text-foreground\">{group.name}</div>}\r\n </li>\r\n )}\r\n <li>\r\n <button\r\n type=\"button\"\r\n aria-pressed={multiple ? active : undefined}\r\n onClick={() => {\r\n toggle(option.id);\r\n if (multiple) {\r\n // keep open for rapid multi-pick\r\n setQuery(\"\");\r\n if (!useMobileSheet) {\r\n inputRef.current?.focus();\r\n }\r\n } else {\r\n setQuery(\"\");\r\n setIsOpen(false);\r\n }\r\n }}\r\n className={cn(\r\n \"flex min-h-option-row w-full cursor-pointer items-center gap-3 rounded-control-sm px-option-x py-2 text-left text-sm text-muted-foreground transition-colors hover:bg-muted\",\r\n useMobileSheet && \"min-h-12\",\r\n group && \"pl-8\",\r\n active && \"bg-primary-tint\",\r\n )}\r\n >\r\n {multiple ? (\r\n <CheckboxVisual checked={active} />\r\n ) : null}\r\n {option.name}\r\n </button>\r\n </li>\r\n </Fragment>\r\n );\r\n })\r\n ) : (\r\n !allowCustomValue || !query.trim() ? (\r\n <li className=\"px-option-x py-2 text-sm text-muted-foreground\">\r\n {emptyText}\r\n </li>\r\n ) : null\r\n )}\r\n {allowCustomValue && query.trim() && !findExactOption(query) && (\r\n <li>\r\n <button\r\n type=\"button\"\r\n className=\"flex min-h-11 w-full cursor-pointer items-center gap-2 rounded-control-sm px-option-x py-2 text-left text-sm text-primary transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-primary\"\r\n onMouseDown={(event) => event.preventDefault()}\r\n onClick={() => {\r\n const text = query.trim();\r\n if (multiple) {\r\n setter(Array.from(new Set([...(value ?? []), text as unknown as ID])));\r\n setQuery(\"\");\r\n } else {\r\n resolveQuerySelection(text);\r\n setIsOpen(false);\r\n }\r\n }}\r\n >\r\n <PlusCircleIcon className=\"h-4 w-4\" aria-hidden=\"true\" />\r\n Add “{query.trim()}”\r\n </button>\r\n </li>\r\n )}\r\n </ul>\r\n {useMobileSheet && multiple && (\r\n <div className=\"shrink-0 border-t border-border bg-background px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]\">\r\n <Button\r\n type=\"button\"\r\n variant=\"outline\"\r\n className=\"min-h-11 w-full\"\r\n onClick={() => {\r\n setQuery(\"\");\r\n setIsOpen(false);\r\n }}\r\n >\r\n Done\r\n </Button>\r\n </div>\r\n )}\r\n </FormFieldReset>\r\n </OptionsSurface>\r\n </Sheet>\r\n )}\r\n </div>\r\n );\r\n}\r\n\r\n/** Unlabelled: put it in a `FormField` for a label. */\r\ntype AutocompleteCommonProps<ID extends number | string> = {\r\n options: IAutocompleteOption<ID>[];\r\n placeholder?: string;\r\n className?: string;\r\n props?: any[];\r\n /** Allow a user to add their own text. Custom values are strings. */\r\n allowCustomValue?: boolean;\r\n preserveOptionOrder?: boolean;\r\n emptyText?: string;\r\n mobileDropdownMode?: MobileDropdownMode;\r\n inputIcons?: InputIcons;\r\n};\r\n\r\nexport type AutocompleteProps<ID extends number | string> = AutocompleteCommonProps<ID> & (\r\n | { multiple?: false; value?: ID | null; setter: (value?: ID | null) => void }\r\n | { multiple: true; value?: ID[]; setter: (value: ID[]) => void }\r\n);\r\n\r\nexport const Autocomplete = <ID extends number | string>(config: AutocompleteProps<ID>) => {\r\n const { options, placeholder, className, props, allowCustomValue = false,\r\n preserveOptionOrder = false, emptyText, mobileDropdownMode, inputIcons } = config;\r\n return (\r\n <AutocompleteBase<ID>\r\n options={options}\r\n multiple={config.multiple === true}\r\n value={config.multiple === true ? config.value ?? [] : config.value != null ? [config.value] : []}\r\n setter={(arr) => {\r\n if (config.multiple === true) config.setter(arr);\r\n else config.setter(arr[0] ?? null);\r\n }}\r\n placeholder={placeholder}\r\n className={className}\r\n allowCustomValue={allowCustomValue}\r\n preserveOptionOrder={preserveOptionOrder}\r\n emptyText={emptyText}\r\n mobileDropdownMode={mobileDropdownMode}\r\n inputIcons={inputIcons}\r\n {...props}\r\n />\r\n );\r\n};\r\n\r\n/** The surrounding FormField's label, when it is plain text. */\r\nfunction useFormFieldLabel() {\r\n return useFormField()?.labelText;\r\n}\r\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AA+BA;;AAE0D;AAC1D;;;;AA6BE;;;;AAII;;;;AAGH;AACD;AACA;AACA;AACA;AACA;AACA;;;;AAKA;;AAOA;AACA;AACA;AACA;AAKA;;AAEE;AAGI;AAEN;;AAGE;AACA;AAAW;;AAGT;;;AAKA;;AAEA;;;AAIA;;AAEA;;AAGF;AACF;AAEA;AAEA;;;;AAMY;AACA;;AAGV;AACE;;;AAIJ;AACE;;AAEE;;;;;;AAMF;AAAiB;;AACZ;;AAEP;AAEA;;AAEE;;AAEF;;AAKO;AACC;AACA;AACF;AACC;AAIP;AACA;;;;;;;;;;;;;;;AAcI;;;AAEA;;AAEA;AACE;;AAED;AACH;AACA;AACA;;AAEA;AACE;;AAEF;AACF;AACA;;AAIE;;;;;;AAOE;;;;;AAMA;AACF;AAEA;AACA;;;AAIA;AACE;;;AASF;AACF;AAEA;;AAIA;AACE;;;AAEE;AACA;AACA;;AAEA;;;;;;;AAOF;;;;;;;AASA;AACE;;AAEE;;;;;;AAMJ;;AACA;;AACF;;;;;AAwCA;AACE;AACA;AACA;AACA;;;;AAIF;AAIM;AAEE;AAEJ;;;;;;;AAeQ;;AAEJ;;AAIE;;AAyBE;;AAEF;AAEE;;;;;;;;AAOI;AACA;AACA;;;;;AAKN;AAEsC;;;AA+BpC;;;;AAMA;;;AAGA;AAEE;AACE;AAEF;;;;;;;;AAQkC;;;AAIlC;;AAEJ;AAEE;;;;AAIF;AAEE;;;;;;;AAME;;;;;;AAQoG;AAUnG;AACA;AAID;AACI;AACA;AACD;AACH;AACE;;AAEI;AACE;AACA;AACA;AACA;;AAEH;;AAqBD;;AAEA;;;AAGF;;;;;;;;;AAYE;;;AAGF;;AAaF;AACA;;AAOU;;AAEA;AACA;;;AAcJ;;;;;AAKI;;;;;;;;AAsBZ;AAeM;;;;;;;;;;;;;AAqCpB;AAqBO;;;AASC;AAA8B;;;AAEhC;AAWN;AAEA;AACA;AACE;AACF;;"}
@@ -0,0 +1,18 @@
1
+ import * as React from 'react';
2
+ import { Checkbox } from '../components/checkbox';
3
+ export interface CheckboxFieldProps extends Omit<React.ComponentProps<typeof Checkbox>, 'children' | 'className'> {
4
+ /** The sentence beside the box. Clicking it toggles the box. */
5
+ children: React.ReactNode;
6
+ /** Shows the required mark after the sentence and tells assistive tech. Defaults to false. */
7
+ required?: boolean;
8
+ /** Help text under the sentence. */
9
+ description?: React.ReactNode;
10
+ /** Error under the sentence; also marks the box invalid. Inside a FormField, use the field's `error` instead. */
11
+ error?: React.ReactNode;
12
+ className?: string;
13
+ }
14
+ /**
15
+ * A checkbox with a clickable sentence beside it ("I agree to the terms…").
16
+ * Works on its own; inside a FormField the field's label also points at the box.
17
+ */
18
+ export declare function CheckboxField({ children, required, description, error, className, id: ownId, ...checkboxProps }: CheckboxFieldProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,25 @@
1
+ "use client";
2
+ import { jsxs, jsx } from 'react/jsx-runtime';
3
+ import * as React from 'react';
4
+ import { cn } from '../utils.js';
5
+ import { Checkbox } from './checkbox.js';
6
+ import { useFormFieldControl } from './form-field.js';
7
+
8
+ /**
9
+ * A checkbox with a clickable sentence beside it ("I agree to the terms…").
10
+ * Works on its own; inside a FormField the field's label also points at the box.
11
+ */
12
+ function CheckboxField({ children, required = false, description, error, className, id: ownId, ...checkboxProps }) {
13
+ const generated = React.useId();
14
+ // Inside a FormField this is the field's id; otherwise our own.
15
+ const { id = generated, ...field } = useFormFieldControl({ id: ownId });
16
+ const descriptionId = description ? `${id}-description` : undefined;
17
+ const errorId = error ? `${id}-error` : undefined;
18
+ const describedBy = [field['aria-describedby'], descriptionId, errorId].filter(Boolean).join(' ') || undefined;
19
+ return (jsxs("div", { className: cn('min-w-0', className), children: [jsxs("div", { className: "flex items-start gap-2", children: [jsx(Checkbox, { ...checkboxProps, id: id, "aria-describedby": describedBy, "aria-invalid": error ? true : field['aria-invalid'], "aria-required": required || field['aria-required'] || undefined,
20
+ // A 16px box on the sentence's 20px first line: drop it 2px so their centres meet.
21
+ className: "mt-0.5" }), jsxs("label", { htmlFor: id, className: "cursor-pointer text-sm leading-5 text-muted-foreground select-none", children: [children, required ? jsx("span", { className: "text-destructive", children: " *" }) : null] })] }), description ? (jsx("p", { id: descriptionId, className: "mt-1.5 text-sm text-muted-foreground", children: description })) : null, error ? (jsx("p", { id: errorId, className: "mt-1.5 whitespace-pre-line text-sm text-destructive", children: error })) : null] }));
22
+ }
23
+
24
+ export { CheckboxField };
25
+ //# sourceMappingURL=checkbox-field.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkbox-field.js","sources":["../../src/components/checkbox-field.tsx"],"sourcesContent":["'use client';\n\nimport * as React from 'react';\n\nimport { cn } from '@/utils';\nimport { Checkbox } from '@/components/checkbox';\nimport { useFormFieldControl } from './form-field';\n\nexport interface CheckboxFieldProps\n extends Omit<React.ComponentProps<typeof Checkbox>, 'children' | 'className'> {\n /** The sentence beside the box. Clicking it toggles the box. */\n children: React.ReactNode;\n /** Shows the required mark after the sentence and tells assistive tech. Defaults to false. */\n required?: boolean;\n /** Help text under the sentence. */\n description?: React.ReactNode;\n /** Error under the sentence; also marks the box invalid. Inside a FormField, use the field's `error` instead. */\n error?: React.ReactNode;\n className?: string;\n}\n\n/**\n * A checkbox with a clickable sentence beside it (\"I agree to the terms…\").\n * Works on its own; inside a FormField the field's label also points at the box.\n */\nexport function CheckboxField({\n children,\n required = false,\n description,\n error,\n className,\n id: ownId,\n ...checkboxProps\n}: CheckboxFieldProps) {\n const generated = React.useId();\n // Inside a FormField this is the field's id; otherwise our own.\n const { id = generated, ...field } = useFormFieldControl<{\n id?: string;\n 'aria-describedby'?: string;\n 'aria-invalid'?: React.AriaAttributes['aria-invalid'];\n 'aria-required'?: React.AriaAttributes['aria-required'];\n }>({ id: ownId });\n const descriptionId = description ? `${id}-description` : undefined;\n const errorId = error ? `${id}-error` : undefined;\n const describedBy =\n [field['aria-describedby'], descriptionId, errorId].filter(Boolean).join(' ') || undefined;\n\n return (\n <div className={cn('min-w-0', className)}>\n {/* The box sits on the sentence's first line (20px), so wrapped sentences still line up. */}\n <div className=\"flex items-start gap-2\">\n <Checkbox\n {...checkboxProps}\n id={id}\n aria-describedby={describedBy}\n aria-invalid={error ? true : field['aria-invalid']}\n aria-required={required || field['aria-required'] || undefined}\n // A 16px box on the sentence's 20px first line: drop it 2px so their centres meet.\n className=\"mt-0.5\"\n />\n <label htmlFor={id} className=\"cursor-pointer text-sm leading-5 text-muted-foreground select-none\">\n {children}\n {required ? <span className=\"text-destructive\"> *</span> : null}\n </label>\n </div>\n {description ? (\n <p id={descriptionId} className=\"mt-1.5 text-sm text-muted-foreground\">\n {description}\n </p>\n ) : null}\n {error ? (\n <p id={errorId} className=\"mt-1.5 whitespace-pre-line text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n </div>\n );\n}\n"],"names":[],"mappings":";;;;;;;AAqBA;;;AAGG;AACG;AASJ;;AAEA;AAMA;AACA;;;;AAeQ;AAmBV;;"}
@@ -0,0 +1,33 @@
1
+ import * as React from 'react';
2
+ export interface CheckboxGroupProps {
3
+ options: {
4
+ value: string | number;
5
+ label: string;
6
+ description?: string;
7
+ }[];
8
+ values: (string | number)[];
9
+ setter: (values: (string | number)[]) => void;
10
+ className?: string;
11
+ /** Multi-select hint shown above the options. */
12
+ hint?: React.ReactNode;
13
+ /** Columns on md+ screens. Defaults to 3. */
14
+ columns?: 1 | 2 | 3;
15
+ /** Fired when a single option is toggled, before the setter runs. */
16
+ onToggle?: (value: string | number, checked: boolean) => void;
17
+ id?: string;
18
+ /** Names the group when it has no visible label. Inside a FormField the field label names it. */
19
+ 'aria-label'?: string;
20
+ /** Id of the element naming the group. A surrounding FormField with `group` sets it. */
21
+ 'aria-labelledby'?: string;
22
+ /** Ids of help or error text. A surrounding FormField sets it from `description` and `error`. */
23
+ 'aria-describedby'?: string;
24
+ /** Marks the group invalid. A surrounding FormField sets it when it shows an error. */
25
+ 'aria-invalid'?: React.AriaAttributes['aria-invalid'];
26
+ /** Marks the group required. A surrounding FormField sets it from `required`. */
27
+ 'aria-required'?: React.AriaAttributes['aria-required'];
28
+ }
29
+ /**
30
+ * Multi-select option cards. Unlabelled: put it in a `FormField` with `group`
31
+ * for a label that names the whole group.
32
+ */
33
+ export declare const CheckboxGroup: ({ options, values, setter, className, hint, columns, onToggle, ...ownAria }: CheckboxGroupProps) => import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,43 @@
1
+ "use client";
2
+ import { jsxs, jsx } from 'react/jsx-runtime';
3
+ import { cn } from '../utils.js';
4
+ import { Checkbox } from './checkbox.js';
5
+ import { useFormFieldControl, FormFieldReset } from './form-field.js';
6
+
7
+ const GRID_COLS = {
8
+ 1: '',
9
+ 2: 'md:grid-cols-2',
10
+ 3: 'md:grid-cols-3',
11
+ };
12
+ /**
13
+ * Multi-select option cards. Unlabelled: put it in a `FormField` with `group`
14
+ * for a label that names the whole group.
15
+ */
16
+ const CheckboxGroup = ({ options, values, setter, className, hint = null, columns = 3, onToggle, ...ownAria }) => {
17
+ const aria = useFormFieldControl(ownAria, 'group');
18
+ const handleValueChange = (optionValue) => {
19
+ const willBeChecked = !values.includes(optionValue);
20
+ onToggle?.(optionValue, willBeChecked);
21
+ setter(willBeChecked
22
+ ? [...values, optionValue]
23
+ : values.filter((v) => v !== optionValue));
24
+ };
25
+ return (jsxs("div", { role: "group", ...aria, className: className, children: [hint && jsx("p", { className: "text-xs text-muted-foreground", children: hint }), jsx("div", { className: cn('grid grid-cols-1 gap-4', GRID_COLS[columns]), children: options.map((option) => {
26
+ const isChecked = values.includes(option.value);
27
+ return (
28
+ // The card is the control: focusable, toggled by click, Space or Enter.
29
+ jsxs("div", { role: "checkbox", "aria-checked": isChecked, tabIndex: 0, onClick: () => handleValueChange(option.value), onKeyDown: (event) => {
30
+ if (event.key !== ' ' && event.key !== 'Enter')
31
+ return;
32
+ event.preventDefault();
33
+ handleValueChange(option.value);
34
+ }, className: cn('group flex h-fit cursor-pointer items-start gap-3 rounded-control-lg border p-3 transition-colors duration-state ease-out-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none', isChecked
35
+ ? 'border-primary bg-primary-selected'
36
+ : 'border-border hover:border-input hover:bg-muted'), children: [jsx(FormFieldReset, { children: jsx(Checkbox, { checked: isChecked, tabIndex: -1, "aria-hidden": "true",
37
+ // A 16px box centred on the title's first line (2px padding + 20px line).
38
+ className: "pointer-events-none mt-1" }) }), jsxs("div", { className: "min-w-0 flex-1 space-y-1 pt-0.5", children: [jsx("span", { className: "block text-field-label font-field-label text-foreground", children: option.label }), option.description && (jsx("p", { className: "text-sm text-muted-foreground", children: option.description }))] })] }, option.value));
39
+ }) })] }));
40
+ };
41
+
42
+ export { CheckboxGroup };
43
+ //# sourceMappingURL=checkbox-group.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkbox-group.js","sources":["../../src/components/checkbox-group.tsx"],"sourcesContent":["'use client';\n\nimport * as React from 'react';\n\nimport { cn } from '@/utils';\nimport { Checkbox } from '@/components/checkbox';\nimport { FormFieldReset, useFormFieldControl } from './form-field';\n\nexport interface CheckboxGroupProps {\n options: { value: string | number; label: string; description?: string }[];\n values: (string | number)[];\n setter: (values: (string | number)[]) => void;\n className?: string;\n /** Multi-select hint shown above the options. */\n hint?: React.ReactNode;\n /** Columns on md+ screens. Defaults to 3. */\n columns?: 1 | 2 | 3;\n /** Fired when a single option is toggled, before the setter runs. */\n onToggle?: (value: string | number, checked: boolean) => void;\n id?: string;\n /** Names the group when it has no visible label. Inside a FormField the field label names it. */\n 'aria-label'?: string;\n /** Id of the element naming the group. A surrounding FormField with `group` sets it. */\n 'aria-labelledby'?: string;\n /** Ids of help or error text. A surrounding FormField sets it from `description` and `error`. */\n 'aria-describedby'?: string;\n /** Marks the group invalid. A surrounding FormField sets it when it shows an error. */\n 'aria-invalid'?: React.AriaAttributes['aria-invalid'];\n /** Marks the group required. A surrounding FormField sets it from `required`. */\n 'aria-required'?: React.AriaAttributes['aria-required'];\n}\n\nconst GRID_COLS: Record<1 | 2 | 3, string> = {\n 1: '',\n 2: 'md:grid-cols-2',\n 3: 'md:grid-cols-3',\n};\n\n/**\n * Multi-select option cards. Unlabelled: put it in a `FormField` with `group`\n * for a label that names the whole group.\n */\nexport const CheckboxGroup = ({\n options,\n values,\n setter,\n className,\n hint = null,\n columns = 3,\n onToggle,\n ...ownAria\n}: CheckboxGroupProps) => {\n const aria = useFormFieldControl(ownAria, 'group');\n const handleValueChange = (optionValue: string | number) => {\n const willBeChecked = !values.includes(optionValue);\n onToggle?.(optionValue, willBeChecked);\n setter(\n willBeChecked\n ? [...values, optionValue]\n : values.filter((v) => v !== optionValue),\n );\n };\n\n return (\n <div role=\"group\" {...aria} className={className}>\n {hint && <p className=\"text-xs text-muted-foreground\">{hint}</p>}\n\n <div className={cn('grid grid-cols-1 gap-4', GRID_COLS[columns])}>\n {options.map((option) => {\n const isChecked = values.includes(option.value);\n\n return (\n // The card is the control: focusable, toggled by click, Space or Enter.\n <div\n key={option.value}\n role=\"checkbox\"\n aria-checked={isChecked}\n tabIndex={0}\n onClick={() => handleValueChange(option.value)}\n onKeyDown={(event) => {\n if (event.key !== ' ' && event.key !== 'Enter') return;\n event.preventDefault();\n handleValueChange(option.value);\n }}\n className={cn(\n 'group flex h-fit cursor-pointer items-start gap-3 rounded-control-lg border p-3 transition-colors duration-state ease-out-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none',\n isChecked\n ? 'border-primary bg-primary-selected'\n : 'border-border hover:border-input hover:bg-muted',\n )}\n >\n <FormFieldReset>\n <Checkbox\n checked={isChecked}\n tabIndex={-1}\n aria-hidden=\"true\"\n // A 16px box centred on the title's first line (2px padding + 20px line).\n className=\"pointer-events-none mt-1\"\n />\n </FormFieldReset>\n <div className=\"min-w-0 flex-1 space-y-1 pt-0.5\">\n {/* Same size as a field label, but the main text colour: it's the option, not a caption. */}\n <span className=\"block text-field-label font-field-label text-foreground\">\n {option.label}\n </span>\n {option.description && (\n <p className=\"text-sm text-muted-foreground\">{option.description}</p>\n )}\n </div>\n </div>\n );\n })}\n </div>\n </div>\n );\n};\n"],"names":[],"mappings":";;;;;;AAgCA;AACE;AACA;AACA;;AAGF;;;AAGG;AACI;;AAWL;;AAEE;AACA;AAEI;AACA;AAEN;AAEA;;;;;;;;AAmBc;AACF;AAII;AACA;;AASA;AAcV;AAIR;;"}
@@ -4,5 +4,5 @@ import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
4
4
  declare function CheckboxVisual({ checked }: {
5
5
  checked: boolean | 'indeterminate';
6
6
  }): import("react/jsx-runtime").JSX.Element;
7
- declare function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>): import("react/jsx-runtime").JSX.Element;
7
+ declare function Checkbox({ className, ...ownProps }: React.ComponentProps<typeof CheckboxPrimitive.Root>): import("react/jsx-runtime").JSX.Element;
8
8
  export { Checkbox, CheckboxVisual };
@@ -3,6 +3,7 @@ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
3
  import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
4
4
  import { CheckIcon, MinusIcon } from 'lucide-react';
5
5
  import { cn } from '../utils.js';
6
+ import { useFormFieldControl } from './form-field.js';
6
7
 
7
8
  const checkboxClassName = 'peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground data-[state=indeterminate]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 cursor-pointer rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50';
8
9
  function CheckboxIndicatorIcons() {
@@ -13,8 +14,11 @@ function CheckboxVisual({ checked }) {
13
14
  const state = checked === 'indeterminate' ? 'indeterminate' : checked ? 'checked' : 'unchecked';
14
15
  return (jsx("span", { "aria-hidden": "true", "data-state": state, className: cn(checkboxClassName, 'pointer-events-none'), children: checked && jsx("span", { "data-state": state, className: "group/indicator flex items-center justify-center text-current transition-none", children: jsx(CheckboxIndicatorIcons, {}) }) }));
15
16
  }
16
- function Checkbox({ className, ...props }) {
17
- return (jsx(CheckboxPrimitive.Root, { "data-slot": "checkbox", onClick: (e) => e.stopPropagation(), className: cn(checkboxClassName, className), ...props, children: jsx(CheckboxPrimitive.Indicator, { "data-slot": "checkbox-indicator", className: "group/indicator flex items-center justify-center text-current transition-none", children: jsx(CheckboxIndicatorIcons, {}) }) }));
17
+ function Checkbox({ className, ...ownProps }) {
18
+ const props = useFormFieldControl(ownProps);
19
+ return (jsx(CheckboxPrimitive.Root, { "data-slot": "checkbox", onClick: (e) => e.stopPropagation(), className: cn(checkboxClassName,
20
+ // Always 16px, like the radio; a larger invisible area makes it easy to tap.
21
+ "relative after:absolute after:-inset-3 after:content-['']", className), ...props, children: jsx(CheckboxPrimitive.Indicator, { "data-slot": "checkbox-indicator", className: "group/indicator flex items-center justify-center text-current transition-none", children: jsx(CheckboxIndicatorIcons, {}) }) }));
18
22
  }
19
23
 
20
24
  export { Checkbox, CheckboxVisual };