@betterinternship/components 3.4.2 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/autocomplete.d.ts +1 -2
- package/dist/components/autocomplete.js +75 -64
- package/dist/components/autocomplete.js.map +1 -1
- package/dist/components/checkbox-field.d.ts +18 -0
- package/dist/components/checkbox-field.js +25 -0
- package/dist/components/checkbox-field.js.map +1 -0
- package/dist/components/checkbox-group.d.ts +33 -0
- package/dist/components/checkbox-group.js +43 -0
- package/dist/components/checkbox-group.js.map +1 -0
- package/dist/components/checkbox.d.ts +1 -1
- package/dist/components/checkbox.js +6 -2
- package/dist/components/checkbox.js.map +1 -1
- package/dist/components/chip-select.d.ts +11 -2
- package/dist/components/chip-select.js +9 -4
- package/dist/components/chip-select.js.map +1 -1
- package/dist/components/{form-date-picker.d.ts → date-picker.d.ts} +11 -8
- package/dist/components/date-picker.js +57 -0
- package/dist/components/date-picker.js.map +1 -0
- package/dist/components/dropdown.js +7 -2
- package/dist/components/dropdown.js.map +1 -1
- package/dist/components/form-field.d.ts +60 -5
- package/dist/components/form-field.js +55 -5
- package/dist/components/form-field.js.map +1 -1
- package/dist/components/input.js +3 -1
- package/dist/components/input.js.map +1 -1
- package/dist/components/{form-month-picker.d.ts → month-picker.d.ts} +6 -6
- package/dist/components/month-picker.js +57 -0
- package/dist/components/month-picker.js.map +1 -0
- package/dist/components/radio-group.d.ts +11 -1
- package/dist/components/radio-group.js +17 -4
- package/dist/components/radio-group.js.map +1 -1
- package/dist/components/select.js +38 -2
- package/dist/components/select.js.map +1 -1
- package/dist/components/sheet.d.ts +1 -1
- package/dist/components/switch.d.ts +1 -1
- package/dist/components/switch.js +4 -1
- package/dist/components/switch.js.map +1 -1
- package/dist/components/table.js +5 -5
- package/dist/components/table.js.map +1 -1
- package/dist/components/textarea.d.ts +1 -1
- package/dist/components/textarea.js +3 -1
- package/dist/components/textarea.js.map +1 -1
- package/dist/components/time-input.d.ts +9 -0
- package/dist/components/time-input.js +65 -0
- package/dist/components/time-input.js.map +1 -0
- package/dist/hooks/use-field-focus.d.ts +1 -1
- package/dist/hooks/use-field-focus.js +1 -1
- package/dist/hooks/use-field-focus.js.map +1 -1
- package/dist/index.d.ts +5 -9
- package/dist/index.js +7 -11
- package/dist/index.js.map +1 -1
- package/dist/node_modules/tailwind-merge/dist/bundle-mjs.js +54 -2
- package/dist/node_modules/tailwind-merge/dist/bundle-mjs.js.map +1 -1
- package/dist/utils.js +11 -1
- package/dist/utils.js.map +1 -1
- package/package.json +27 -40
- package/dist/components/form-checkbox-group.d.ts +0 -31
- package/dist/components/form-checkbox-group.js +0 -30
- package/dist/components/form-checkbox-group.js.map +0 -1
- package/dist/components/form-checkbox.d.ts +0 -15
- package/dist/components/form-checkbox.js +0 -15
- package/dist/components/form-checkbox.js.map +0 -1
- package/dist/components/form-date-picker.js +0 -56
- package/dist/components/form-date-picker.js.map +0 -1
- package/dist/components/form-input.d.ts +0 -11
- package/dist/components/form-input.js +0 -13
- package/dist/components/form-input.js.map +0 -1
- package/dist/components/form-month-picker.js +0 -56
- package/dist/components/form-month-picker.js.map +0 -1
- package/dist/components/form-radio.d.ts +0 -15
- package/dist/components/form-radio.js +0 -20
- package/dist/components/form-radio.js.map +0 -1
- package/dist/components/form-textarea.d.ts +0 -11
- package/dist/components/form-textarea.js +0 -12
- package/dist/components/form-textarea.js.map +0 -1
- package/dist/components/form.d.ts +0 -24
- package/dist/components/form.js +0 -71
- package/dist/components/form.js.map +0 -1
- package/dist/components/time-input-native.d.ts +0 -14
- package/dist/components/time-input-native.js +0 -62
- package/dist/components/time-input-native.js.map +0 -1
- package/dist/node_modules/react-hook-form/dist/index.esm.js +0 -706
- package/dist/node_modules/react-hook-form/dist/index.esm.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkbox.js","sources":["../../src/components/checkbox.tsx"],"sourcesContent":["'use client';\r\n\r\nimport * as React from 'react';\r\nimport * as CheckboxPrimitive from '@radix-ui/react-checkbox';\r\nimport { CheckIcon, MinusIcon } from 'lucide-react';\r\n\r\nimport { cn } from '@/utils';\r\n\r\nconst 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';\r\n\r\nfunction CheckboxIndicatorIcons() {\r\n return <>\r\n <CheckIcon className=\"animate-in zoom-in-50 fade-in-0 size-3.5 stroke-3 duration-150 group-data-[state=indeterminate]/indicator:hidden motion-reduce:animate-none\" />\r\n <MinusIcon className=\"animate-in zoom-in-50 fade-in-0 hidden size-3.5 stroke-3 duration-150 group-data-[state=indeterminate]/indicator:block motion-reduce:animate-none\" />\r\n </>;\r\n}\r\n\r\n/** Non-interactive checkbox appearance for a control that owns its selection state. */\r\nfunction CheckboxVisual({ checked }: { checked: boolean | 'indeterminate' }) {\r\n const state = checked === 'indeterminate' ? 'indeterminate' : checked ? 'checked' : 'unchecked';\r\n return (\r\n <span aria-hidden=\"true\" data-state={state} className={cn(checkboxClassName, 'pointer-events-none')}>\r\n {checked && <span data-state={state} className=\"group/indicator flex items-center justify-center text-current transition-none\"><CheckboxIndicatorIcons /></span>}\r\n </span>\r\n );\r\n}\r\n\r\nfunction Checkbox({\r\n className,\r\n ...
|
|
1
|
+
{"version":3,"file":"checkbox.js","sources":["../../src/components/checkbox.tsx"],"sourcesContent":["'use client';\r\n\r\nimport * as React from 'react';\r\nimport * as CheckboxPrimitive from '@radix-ui/react-checkbox';\r\nimport { CheckIcon, MinusIcon } from 'lucide-react';\r\n\r\nimport { cn } from '@/utils';\r\nimport { useFormFieldControl } from './form-field';\r\n\r\nconst 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';\r\n\r\nfunction CheckboxIndicatorIcons() {\r\n return <>\r\n <CheckIcon className=\"animate-in zoom-in-50 fade-in-0 size-3.5 stroke-3 duration-150 group-data-[state=indeterminate]/indicator:hidden motion-reduce:animate-none\" />\r\n <MinusIcon className=\"animate-in zoom-in-50 fade-in-0 hidden size-3.5 stroke-3 duration-150 group-data-[state=indeterminate]/indicator:block motion-reduce:animate-none\" />\r\n </>;\r\n}\r\n\r\n/** Non-interactive checkbox appearance for a control that owns its selection state. */\r\nfunction CheckboxVisual({ checked }: { checked: boolean | 'indeterminate' }) {\r\n const state = checked === 'indeterminate' ? 'indeterminate' : checked ? 'checked' : 'unchecked';\r\n return (\r\n <span aria-hidden=\"true\" data-state={state} className={cn(checkboxClassName, 'pointer-events-none')}>\r\n {checked && <span data-state={state} className=\"group/indicator flex items-center justify-center text-current transition-none\"><CheckboxIndicatorIcons /></span>}\r\n </span>\r\n );\r\n}\r\n\r\nfunction Checkbox({\r\n className,\r\n ...ownProps\r\n}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {\r\n const props = useFormFieldControl(ownProps);\r\n return (\r\n <CheckboxPrimitive.Root\r\n data-slot=\"checkbox\"\r\n onClick={(e) => e.stopPropagation()}\r\n className={cn(\r\n checkboxClassName,\r\n // Always 16px, like the radio; a larger invisible area makes it easy to tap.\r\n \"relative after:absolute after:-inset-3 after:content-['']\",\r\n className,\r\n )}\r\n {...props}\r\n >\r\n <CheckboxPrimitive.Indicator\r\n data-slot=\"checkbox-indicator\"\r\n className=\"group/indicator flex items-center justify-center text-current transition-none\"\r\n >\r\n <CheckboxIndicatorIcons />\r\n </CheckboxPrimitive.Indicator>\r\n </CheckboxPrimitive.Root>\r\n );\r\n}\r\n\r\nexport { Checkbox, CheckboxVisual };\r\n"],"names":[],"mappings":";;;;;;;AASA;AAEA;AACE;AAIF;AAEA;AACA;;AAEE;AAKF;AAEA;AAIE;;;;AAqBF;;"}
|
|
@@ -5,6 +5,12 @@ export type Option = {
|
|
|
5
5
|
export type ChipSelectProps = {
|
|
6
6
|
options: Option[];
|
|
7
7
|
className?: string;
|
|
8
|
+
/** Names the group when it has no visible label. Inside a FormField with `group`, the field label names it. */
|
|
9
|
+
'aria-label'?: string;
|
|
10
|
+
/** Id of the element naming the group. A surrounding FormField with `group` sets it. */
|
|
11
|
+
'aria-labelledby'?: string;
|
|
12
|
+
/** Ids of help or error text. A surrounding FormField sets it from `description` and `error`. */
|
|
13
|
+
'aria-describedby'?: string;
|
|
8
14
|
} & ({
|
|
9
15
|
multiple: true;
|
|
10
16
|
value: string[];
|
|
@@ -14,5 +20,8 @@ export type ChipSelectProps = {
|
|
|
14
20
|
value: string | null;
|
|
15
21
|
onChange: (value: string | null) => void;
|
|
16
22
|
});
|
|
17
|
-
/**
|
|
18
|
-
|
|
23
|
+
/**
|
|
24
|
+
* A compact form choice group supporting single or multiple selection.
|
|
25
|
+
* Put it in a FormField with `group` for a label that names the whole group.
|
|
26
|
+
*/
|
|
27
|
+
export declare function ChipSelect({ value, onChange, options, className, multiple, ...ownAria }: ChipSelectProps): import("react/jsx-runtime").JSX.Element;
|
|
@@ -2,17 +2,22 @@
|
|
|
2
2
|
import { jsx, jsxs } from 'react/jsx-runtime';
|
|
3
3
|
import * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group';
|
|
4
4
|
import { CheckboxVisual } from './checkbox.js';
|
|
5
|
+
import { RadioVisual } from './radio-group.js';
|
|
5
6
|
import { cn } from '../utils.js';
|
|
7
|
+
import { useFormFieldControl } from './form-field.js';
|
|
6
8
|
|
|
7
9
|
const chipClassName = (selected) => cn('inline-flex min-h-11 w-max max-w-full items-center gap-2 rounded-full border border-landing-control bg-background px-3 py-2 text-sm font-medium text-landing-nav transition-colors duration-state enabled:hover:border-landing-control-hover enabled:hover:bg-[rgb(55_65_81_/_6%)] enabled:hover:text-landing-nav-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none', selected && 'border-primary bg-primary-tint text-primary enabled:hover:border-primary enabled:hover:bg-primary-tint enabled:hover:text-primary');
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
/**
|
|
11
|
+
* A compact form choice group supporting single or multiple selection.
|
|
12
|
+
* Put it in a FormField with `group` for a label that names the whole group.
|
|
13
|
+
*/
|
|
14
|
+
function ChipSelect({ value, onChange, options, className, multiple = false, ...ownAria }) {
|
|
15
|
+
const { id: _id, ...aria } = useFormFieldControl(ownAria, 'group');
|
|
11
16
|
const groupValue = (multiple ? value : value ?? '');
|
|
12
17
|
const SelectGroup = ToggleGroupPrimitive.Root;
|
|
13
18
|
return (jsx(SelectGroup, { type: multiple ? 'multiple' : 'single', value: groupValue, onValueChange: (next) => multiple
|
|
14
19
|
? onChange(next)
|
|
15
|
-
: onChange(next || null), className: cn('flex flex-wrap justify-start gap-2', className), children: options.map((option) => {
|
|
20
|
+
: onChange(next || null), className: cn('flex flex-wrap justify-start gap-2', className), ...aria, children: options.map((option) => {
|
|
16
21
|
const selected = multiple ? value.includes(option.value) : value === option.value;
|
|
17
22
|
return jsxs(ToggleGroupPrimitive.Item, { value: option.value, className: chipClassName(selected), children: [multiple ? jsx(CheckboxVisual, { checked: selected }) : jsx(RadioVisual, { checked: selected }), option.label] }, option.value);
|
|
18
23
|
}) }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chip-select.js","sources":["../../src/components/chip-select.tsx"],"sourcesContent":["\"use client\";\r\n\r\nimport * as React from 'react';\r\nimport * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group';\r\nimport { CheckboxVisual } from './checkbox';\r\nimport { cn } from '@/utils';\r\n\r\nexport type Option = { value: string; label: string };\r\n\r\nconst chipClassName = (selected: boolean) => cn(\r\n 'inline-flex min-h-11 w-max max-w-full items-center gap-2 rounded-full border border-landing-control bg-background px-3 py-2 text-sm font-medium text-landing-nav transition-colors duration-state enabled:hover:border-landing-control-hover enabled:hover:bg-[rgb(55_65_81_/_6%)] enabled:hover:text-landing-nav-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none',\r\n selected && 'border-primary bg-primary-tint text-primary enabled:hover:border-primary enabled:hover:bg-primary-tint enabled:hover:text-primary',\r\n);\r\n\r\
|
|
1
|
+
{"version":3,"file":"chip-select.js","sources":["../../src/components/chip-select.tsx"],"sourcesContent":["\"use client\";\r\n\r\nimport * as React from 'react';\r\nimport * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group';\r\nimport { CheckboxVisual } from './checkbox';\r\nimport { RadioVisual } from './radio-group';\r\nimport { cn } from '@/utils';\r\nimport { useFormFieldControl } from './form-field';\r\n\r\nexport type Option = { value: string; label: string };\r\n\r\nconst chipClassName = (selected: boolean) => cn(\r\n 'inline-flex min-h-11 w-max max-w-full items-center gap-2 rounded-full border border-landing-control bg-background px-3 py-2 text-sm font-medium text-landing-nav transition-colors duration-state enabled:hover:border-landing-control-hover enabled:hover:bg-[rgb(55_65_81_/_6%)] enabled:hover:text-landing-nav-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none',\r\n selected && 'border-primary bg-primary-tint text-primary enabled:hover:border-primary enabled:hover:bg-primary-tint enabled:hover:text-primary',\r\n);\r\n\r\nexport type ChipSelectProps = {\r\n options: Option[];\r\n className?: string;\r\n /** Names the group when it has no visible label. Inside a FormField with `group`, the field label names it. */\r\n 'aria-label'?: string;\r\n /** Id of the element naming the group. A surrounding FormField with `group` sets it. */\r\n 'aria-labelledby'?: string;\r\n /** Ids of help or error text. A surrounding FormField sets it from `description` and `error`. */\r\n 'aria-describedby'?: string;\r\n} & ({\r\n multiple: true;\r\n value: string[];\r\n onChange: (value: string[]) => void;\r\n} | {\r\n multiple?: false;\r\n value: string | null;\r\n onChange: (value: string | null) => void;\r\n});\r\n\r\n/**\r\n * A compact form choice group supporting single or multiple selection.\r\n * Put it in a FormField with `group` for a label that names the whole group.\r\n */\r\nexport function ChipSelect({ value, onChange, options, className, multiple = false, ...ownAria }: ChipSelectProps) {\r\n const { id: _id, ...aria } = useFormFieldControl<{\r\n id?: string;\r\n 'aria-label'?: string;\r\n 'aria-labelledby'?: string;\r\n 'aria-describedby'?: string;\r\n 'aria-invalid'?: React.AriaAttributes['aria-invalid'];\r\n 'aria-required'?: React.AriaAttributes['aria-required'];\r\n }>(ownAria, 'group');\r\n const groupValue = (multiple ? value : value ?? '') as string | string[];\r\n const SelectGroup = ToggleGroupPrimitive.Root as React.ComponentType<any>;\r\n return (\r\n <SelectGroup\r\n type={multiple ? 'multiple' : 'single'}\r\n value={groupValue}\r\n onValueChange={(next: string | string[]) => multiple\r\n ? (onChange as (value: string[]) => void)(next as string[])\r\n : (onChange as (value: string | null) => void)((next as string) || null)}\r\n className={cn('flex flex-wrap justify-start gap-2', className)}\r\n {...aria}\r\n >\r\n {options.map((option) => {\r\n const selected = multiple ? (value as string[]).includes(option.value) : value === option.value;\r\n return <ToggleGroupPrimitive.Item key={option.value} value={option.value} className={chipClassName(selected)}>\r\n {multiple ? <CheckboxVisual checked={selected} /> : <RadioVisual checked={selected} />}\r\n {option.label}\r\n </ToggleGroupPrimitive.Item>;\r\n })}\r\n </SelectGroup>\r\n );\r\n}\r\n"],"names":[],"mappings":";;;;;;;;AAWA;AAwBA;;;AAGG;;AAED;AAQA;AACA;;AAMM;;;;;AAcR;;"}
|
|
@@ -1,20 +1,26 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
|
+
/** Props the trigger takes from the caller or the surrounding FormField. */
|
|
3
|
+
type TriggerProps = Pick<React.ButtonHTMLAttributes<HTMLButtonElement>, 'id' | 'aria-label' | 'aria-labelledby' | 'aria-describedby' | 'aria-invalid' | 'aria-required' | 'disabled'>;
|
|
2
4
|
/**
|
|
3
|
-
* Accepts/returns a number timestamp (ms) via `date` / `setter`.
|
|
5
|
+
* A date picker. Accepts/returns a number timestamp (ms) via `date` / `setter`.
|
|
6
|
+
* Unlabelled: put it in a `FormField` for a label.
|
|
4
7
|
*/
|
|
5
|
-
export interface
|
|
8
|
+
export interface DatePickerProps extends TriggerProps {
|
|
6
9
|
mode?: 'single' | 'multiple' | 'range';
|
|
10
|
+
/** Selected dates in `multiple` mode, as timestamps (ms). */
|
|
7
11
|
dates?: number[];
|
|
12
|
+
/** Called with every selected date (sorted timestamps) in `multiple` mode. */
|
|
8
13
|
onDatesChange?: (dates: number[]) => void;
|
|
14
|
+
/** Selected range in `range` mode, as timestamps (ms). */
|
|
9
15
|
range?: {
|
|
10
16
|
from?: number;
|
|
11
17
|
to?: number;
|
|
12
18
|
};
|
|
19
|
+
/** Called with the new range, or undefined when cleared, in `range` mode. */
|
|
13
20
|
onRangeChange?: (range: {
|
|
14
21
|
from?: number;
|
|
15
22
|
to?: number;
|
|
16
23
|
} | undefined) => void;
|
|
17
|
-
label?: string;
|
|
18
24
|
date?: number;
|
|
19
25
|
setter?: (value?: number) => void;
|
|
20
26
|
className?: string;
|
|
@@ -24,10 +30,6 @@ export interface FormDatePickerProps extends React.InputHTMLAttributes<HTMLInput
|
|
|
24
30
|
contentClassName?: string;
|
|
25
31
|
/** 'buttons' is the old name for DayPicker's 'label' layout. */
|
|
26
32
|
captionLayout?: 'buttons' | 'label' | 'dropdown';
|
|
27
|
-
required?: boolean;
|
|
28
|
-
tooltip?: string;
|
|
29
|
-
tooltipId?: string;
|
|
30
|
-
labelAddon?: React.ReactNode;
|
|
31
33
|
/** Optional: disable dates (react-day-picker style) */
|
|
32
34
|
disabledDays?: Date | {
|
|
33
35
|
before?: Date;
|
|
@@ -44,4 +46,5 @@ export interface FormDatePickerProps extends React.InputHTMLAttributes<HTMLInput
|
|
|
44
46
|
/** Format the button text */
|
|
45
47
|
format?: (d: Date) => string;
|
|
46
48
|
}
|
|
47
|
-
export declare const
|
|
49
|
+
export declare const DatePicker: ({ mode, dates, onDatesChange, range, onRangeChange, date, setter, className, side, align, sideOffset, contentClassName, captionLayout, disabledDays, allowedDates, autoClose, placeholder, format, ...ownTriggerProps }: DatePickerProps) => import("react/jsx-runtime").JSX.Element;
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx, jsxs } from 'react/jsx-runtime';
|
|
3
|
+
import * as React from 'react';
|
|
4
|
+
import { CalendarDays, X } from 'lucide-react';
|
|
5
|
+
import { cn } from '../utils.js';
|
|
6
|
+
import { fieldTriggerClassName } from '../hooks/use-field-focus.js';
|
|
7
|
+
import { Button } from './button.js';
|
|
8
|
+
import { Calendar } from './calendar.js';
|
|
9
|
+
import { Popover, PopoverTrigger, PopoverContent } from './popover.js';
|
|
10
|
+
import { useFormFieldControl, FormFieldReset } from './form-field.js';
|
|
11
|
+
|
|
12
|
+
const DatePicker = ({ mode = 'single', dates, onDatesChange, range, onRangeChange, date, setter, className, side = 'bottom', align = 'start', sideOffset = 6, contentClassName, captionLayout = 'dropdown', disabledDays, allowedDates, autoClose = true, placeholder = 'Select date', format = (d) => d.toLocaleDateString(), ...ownTriggerProps }) => {
|
|
13
|
+
const triggerProps = useFormFieldControl(ownTriggerProps);
|
|
14
|
+
const [open, setOpen] = React.useState(false);
|
|
15
|
+
const selected = date != null && date > 86400000 ? new Date(date) : undefined;
|
|
16
|
+
const selectedRange = range ? { from: range.from != null ? new Date(range.from) : undefined, to: range.to != null ? new Date(range.to) : undefined } : undefined;
|
|
17
|
+
if (mode === 'multiple')
|
|
18
|
+
return jsx(DateMultiPicker, { dates: dates, setter: onDatesChange, className: className, contentClassName: contentClassName, allowedDates: allowedDates, disabledDays: disabledDays, triggerProps: triggerProps });
|
|
19
|
+
return (jsx("div", { className: cn('flex flex-col', className), children: jsxs(Popover, { open: open, onOpenChange: setOpen, children: [jsx(PopoverTrigger, { asChild: true, children: jsxs(Button, { variant: "outline", ...triggerProps, className: cn("w-full justify-between px-field-padding-x py-0", fieldTriggerClassName), children: [mode === 'range' && selectedRange?.from ? `${format(selectedRange.from)}${selectedRange.to ? ` – ${format(selectedRange.to)}` : ' – …'}` : selected ? format(selected) : jsx("span", { className: "text-muted-foreground/40", children: placeholder }), jsx(CalendarDays, { className: "h-4 w-4 text-muted-foreground" })] }) }), jsx(PopoverContent, { align: align, side: side, sideOffset: sideOffset, className: cn('w-auto overflow-hidden p-0', contentClassName), children: jsx(FormFieldReset, { children: mode === 'range' ? jsx(Calendar, { mode: "range", selected: selectedRange, captionLayout: captionLayout === 'buttons' ? 'label' : captionLayout, disabled: disabledDays, allowedDates: allowedDates, excludeDisabled: true, onSelect: (next) => {
|
|
20
|
+
onRangeChange?.(next ? { from: next.from?.getTime(), to: next.to?.getTime() } : undefined);
|
|
21
|
+
// Range selection stays open so the user can adjust both ends,
|
|
22
|
+
// matching multiple-date selection behavior.
|
|
23
|
+
} }) : jsx(Calendar, { mode: "single", selected: selected, captionLayout: captionLayout === 'buttons' ? 'label' : captionLayout, disabled: disabledDays, allowedDates: allowedDates, onSelect: (d) => {
|
|
24
|
+
setter?.(d ? d.getTime() : undefined);
|
|
25
|
+
if (autoClose)
|
|
26
|
+
setOpen(false);
|
|
27
|
+
} }) }) })] }) }));
|
|
28
|
+
};
|
|
29
|
+
const DateMultiPicker = ({ dates = [], setter, className, contentClassName, allowedDates, disabledDays, triggerProps, }) => {
|
|
30
|
+
const [open, setOpen] = React.useState(false);
|
|
31
|
+
const selected = dates
|
|
32
|
+
.filter((value) => Number.isFinite(value))
|
|
33
|
+
.map((value) => {
|
|
34
|
+
const parts = new Intl.DateTimeFormat('en-US', {
|
|
35
|
+
timeZone: 'Asia/Manila',
|
|
36
|
+
year: 'numeric',
|
|
37
|
+
month: 'numeric',
|
|
38
|
+
day: 'numeric',
|
|
39
|
+
}).formatToParts(new Date(value));
|
|
40
|
+
const get = (type) => Number(parts.find((part) => part.type === type)?.value);
|
|
41
|
+
return new Date(get('year'), get('month') - 1, get('day'));
|
|
42
|
+
});
|
|
43
|
+
const toManilaTimestamp = (date) => Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) -
|
|
44
|
+
8 * 60 * 60 * 1000;
|
|
45
|
+
return (jsxs("div", { className: cn('flex flex-col', className), children: [jsxs(Popover, { open: open, onOpenChange: setOpen, children: [jsx(PopoverTrigger, { asChild: true, children: jsxs(Button, { variant: "outline", ...triggerProps, className: cn("w-full justify-between px-field-padding-x py-0", fieldTriggerClassName), children: [selected.length
|
|
46
|
+
? `${selected.length} date${selected.length === 1 ? '' : 's'} selected`
|
|
47
|
+
: jsx("span", { className: "text-muted-foreground/40", children: "Select dates" }), jsx(CalendarDays, { className: "h-4 w-4 text-muted-foreground" })] }) }), jsx(PopoverContent, { align: "start", sideOffset: 6, className: cn('w-auto overflow-hidden p-0', contentClassName), children: jsx(FormFieldReset, { children: jsx(Calendar, { mode: "multiple", captionLayout: "label", allowedDates: allowedDates, disabled: disabledDays, selected: selected, onSelect: (next) => setter?.((next ?? []).map(toManilaTimestamp).sort((a, b) => a - b)) }) }) })] }), !!selected.length && (jsx("div", { className: "flex flex-wrap gap-1.5", children: selected.map((date) => (jsxs(Button, { type: "button", variant: "outline", size: "sm", className: "h-7 gap-1 px-2 text-xs", onClick: () => setter?.(selected
|
|
48
|
+
.filter((selectedDate) => selectedDate.getTime() !== date.getTime())
|
|
49
|
+
.map(toManilaTimestamp)), children: [date.toLocaleDateString(undefined, {
|
|
50
|
+
month: 'short',
|
|
51
|
+
day: 'numeric',
|
|
52
|
+
year: 'numeric',
|
|
53
|
+
}), jsx(X, { className: "h-3 w-3" }), jsxs("span", { className: "sr-only", children: ["Remove ", date.toLocaleDateString()] })] }, date.getTime()))) }))] }));
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export { DatePicker };
|
|
57
|
+
//# sourceMappingURL=date-picker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"date-picker.js","sources":["../../src/components/date-picker.tsx"],"sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport type { Matcher } from '@daypicker/react';\nimport { CalendarDays, X } from 'lucide-react';\n\nimport { cn } from '@/utils';\nimport { fieldTriggerClassName } from '@/hooks/use-field-focus';\nimport { Button } from '@/components/button';\nimport { Calendar } from '@/components/calendar';\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from '@/components/popover';\nimport { FormFieldReset, useFormFieldControl } from './form-field';\n\n/** Props the trigger takes from the caller or the surrounding FormField. */\ntype TriggerProps = Pick<\n React.ButtonHTMLAttributes<HTMLButtonElement>,\n 'id' | 'aria-label' | 'aria-labelledby' | 'aria-describedby' | 'aria-invalid' | 'aria-required' | 'disabled'\n>;\n\n/**\n * A date picker. Accepts/returns a number timestamp (ms) via `date` / `setter`.\n * Unlabelled: put it in a `FormField` for a label.\n */\nexport interface DatePickerProps extends TriggerProps {\n mode?: 'single' | 'multiple' | 'range';\n /** Selected dates in `multiple` mode, as timestamps (ms). */\n dates?: number[];\n /** Called with every selected date (sorted timestamps) in `multiple` mode. */\n onDatesChange?: (dates: number[]) => void;\n /** Selected range in `range` mode, as timestamps (ms). */\n range?: { from?: number; to?: number };\n /** Called with the new range, or undefined when cleared, in `range` mode. */\n onRangeChange?: (range: { from?: number; to?: number } | undefined) => void;\n date?: number;\n setter?: (value?: number) => void;\n className?: string;\n side?: 'top' | 'right' | 'bottom' | 'left';\n align?: 'start' | 'center' | 'end';\n sideOffset?: number;\n contentClassName?: string;\n /** 'buttons' is the old name for DayPicker's 'label' layout. */\n captionLayout?: 'buttons' | 'label' | 'dropdown';\n\n /** Optional: disable dates (react-day-picker style) */\n disabledDays?:\n | Date\n | { before?: Date; after?: Date; from?: Date; to?: Date }\n | Date[];\n /** Only these local calendar dates can be selected. */\n allowedDates?: Date[];\n\n /** Close popover automatically on select (default true) */\n autoClose?: boolean;\n\n /** Placeholder text when no date selected */\n placeholder?: string;\n\n /** Format the button text */\n format?: (d: Date) => string;\n}\n\nexport const DatePicker = ({\n mode = 'single',\n dates,\n onDatesChange,\n range,\n onRangeChange,\n date,\n setter,\n className,\n side = 'bottom',\n align = 'start',\n sideOffset = 6,\n contentClassName,\n captionLayout = 'dropdown',\n disabledDays,\n allowedDates,\n autoClose = true,\n placeholder = 'Select date',\n format = (d) => d.toLocaleDateString(),\n ...ownTriggerProps\n}: DatePickerProps) => {\n const triggerProps = useFormFieldControl(ownTriggerProps);\n const [open, setOpen] = React.useState(false);\n const selected = date != null && date > 86400000 ? new Date(date) : undefined;\n const selectedRange = range ? { from: range.from != null ? new Date(range.from) : undefined, to: range.to != null ? new Date(range.to) : undefined } : undefined;\n\n if (mode === 'multiple') return <DateMultiPicker dates={dates} setter={onDatesChange} className={className} contentClassName={contentClassName} allowedDates={allowedDates} disabledDays={disabledDays as Matcher | Matcher[]} triggerProps={triggerProps} />;\n\n return (\n <div className={cn('flex flex-col', className)}>\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <Button\n variant=\"outline\"\n {...triggerProps}\n className={cn(\"w-full justify-between px-field-padding-x py-0\", fieldTriggerClassName)}\n >\n {mode === 'range' && selectedRange?.from ? `${format(selectedRange.from)}${selectedRange.to ? ` – ${format(selectedRange.to)}` : ' – …'}` : selected ? format(selected) : <span className=\"text-muted-foreground/40\">{placeholder}</span>}\n <CalendarDays className=\"h-4 w-4 text-muted-foreground\" />\n </Button>\n </PopoverTrigger>\n\n <PopoverContent\n align={align}\n side={side}\n sideOffset={sideOffset}\n className={cn(\n 'w-auto overflow-hidden p-0',\n contentClassName,\n )}\n >\n <FormFieldReset>\n {mode === 'range' ? <Calendar\n mode=\"range\"\n selected={selectedRange}\n captionLayout={captionLayout === 'buttons' ? 'label' : captionLayout}\n disabled={disabledDays as Matcher[]}\n allowedDates={allowedDates}\n excludeDisabled\n onSelect={(next) => {\n onRangeChange?.(next ? { from: next.from?.getTime(), to: next.to?.getTime() } : undefined);\n // Range selection stays open so the user can adjust both ends,\n // matching multiple-date selection behavior.\n }}\n /> : <Calendar\n mode=\"single\"\n selected={selected}\n captionLayout={\n captionLayout === 'buttons' ? 'label' : captionLayout\n }\n disabled={disabledDays as Matcher[]}\n allowedDates={allowedDates}\n onSelect={(d) => {\n setter?.(d ? d.getTime() : undefined);\n if (autoClose) setOpen(false);\n }}\n />}\n </FormFieldReset>\n </PopoverContent>\n </Popover>\n </div>\n );\n};\n\ninterface DateMultiPickerProps {\n dates?: number[];\n setter?: (value: number[]) => void;\n className?: string;\n contentClassName?: string;\n /** Only these local calendar dates can be selected. */\n allowedDates?: Date[];\n disabledDays?: Matcher | Matcher[];\n triggerProps: TriggerProps;\n}\n\nconst DateMultiPicker = ({\n dates = [],\n setter,\n className,\n contentClassName,\n allowedDates,\n disabledDays,\n triggerProps,\n}: DateMultiPickerProps) => {\n const [open, setOpen] = React.useState(false);\n const selected = dates\n .filter((value) => Number.isFinite(value))\n .map((value) => {\n const parts = new Intl.DateTimeFormat('en-US', {\n timeZone: 'Asia/Manila',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n }).formatToParts(new Date(value));\n const get = (type: string) =>\n Number(parts.find((part) => part.type === type)?.value);\n return new Date(get('year'), get('month') - 1, get('day'));\n });\n const toManilaTimestamp = (date: Date) =>\n Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) -\n 8 * 60 * 60 * 1000;\n\n return (\n <div className={cn('flex flex-col', className)}>\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <Button\n variant=\"outline\"\n {...triggerProps}\n className={cn(\"w-full justify-between px-field-padding-x py-0\", fieldTriggerClassName)}\n >\n {selected.length\n ? `${selected.length} date${selected.length === 1 ? '' : 's'} selected`\n : <span className=\"text-muted-foreground/40\">Select dates</span>}\n <CalendarDays className=\"h-4 w-4 text-muted-foreground\" />\n </Button>\n </PopoverTrigger>\n <PopoverContent\n align=\"start\"\n sideOffset={6}\n className={cn(\n 'w-auto overflow-hidden p-0',\n contentClassName,\n )}\n >\n <FormFieldReset>\n <Calendar\n mode=\"multiple\"\n captionLayout=\"label\"\n allowedDates={allowedDates}\n disabled={disabledDays}\n selected={selected}\n onSelect={(next) =>\n setter?.(\n (next ?? []).map(toManilaTimestamp).sort((a, b) => a - b),\n )\n }\n />\n </FormFieldReset>\n </PopoverContent>\n </Popover>\n {!!selected.length && (\n <div className=\"flex flex-wrap gap-1.5\">\n {selected.map((date) => (\n <Button\n key={date.getTime()}\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"h-7 gap-1 px-2 text-xs\"\n onClick={() =>\n setter?.(\n selected\n .filter(\n (selectedDate) =>\n selectedDate.getTime() !== date.getTime(),\n )\n .map(toManilaTimestamp),\n )\n }\n >\n {date.toLocaleDateString(undefined, {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n })}\n <X className=\"h-3 w-3\" />\n <span className=\"sr-only\">\n Remove {date.toLocaleDateString()}\n </span>\n </Button>\n ))}\n </div>\n )}\n </div>\n );\n};\n"],"names":[],"mappings":";;;;;;;;;;;AAiEO;AAqBL;AACA;;;;AAIyB;AAEzB;AAgCc;;;AAGF;AAUE;AACA;;AACF;AAOd;AAaA;AASE;;AAEG;AACA;;AAEG;AACA;AACA;AACA;;;;AAKJ;;AAGA;;AAYU;AACA;AAwCO;;AASL;AACA;AACA;AACD;AAWf;;"}
|
|
@@ -6,6 +6,7 @@ import { useMobileSheetViewport } from '../hooks/use-mobile-sheet-viewport.js';
|
|
|
6
6
|
import { MobileSheetPortal } from './mobile-sheet-portal.js';
|
|
7
7
|
import { cn } from '../utils.js';
|
|
8
8
|
import { fieldTriggerClassName } from '../hooks/use-field-focus.js';
|
|
9
|
+
import { useFormField, useFormFieldControl } from './form-field.js';
|
|
9
10
|
import { ChevronDown, X } from 'lucide-react';
|
|
10
11
|
import { useRouter } from 'next/navigation';
|
|
11
12
|
import { createContext, useState, useContext, useRef, useCallback, useEffect, Children } from 'react';
|
|
@@ -93,6 +94,10 @@ const GroupableRadioDropdown = ({ name, options, onChange, disabled, defaultValu
|
|
|
93
94
|
const sheetRef = useRef(null);
|
|
94
95
|
const sheetCloseRef = useRef(null);
|
|
95
96
|
const useSheet = isOpen && isMobile;
|
|
97
|
+
// The phone sheet's title: the field's label when inside a FormField.
|
|
98
|
+
const sheetTitle = useFormField()?.labelText ?? fallback;
|
|
99
|
+
// Inside a FormField the trigger takes the field's id, so the label opens it.
|
|
100
|
+
const fieldProps = useFormFieldControl({});
|
|
96
101
|
const closeSheet = useCallback(() => {
|
|
97
102
|
setIsOpen(false);
|
|
98
103
|
triggerRef.current?.focus();
|
|
@@ -135,7 +140,7 @@ const GroupableRadioDropdown = ({ name, options, onChange, disabled, defaultValu
|
|
|
135
140
|
setIsOpen(false);
|
|
136
141
|
}, [activeDropdown, name]);
|
|
137
142
|
const selected = value || value === 0 ? options.find((o) => o.id === value) : undefined;
|
|
138
|
-
return (jsxs("div", { className: cn("relative w-full max-w-svw min-w-0", className), ref: ref, children: [jsxs(Button, { ref: triggerRef, type: "button", variant: "outline", disabled: disabled, size: size, onClick: handleClick, onTouchEnd: (e) => e.stopPropagation(), "aria-haspopup": "listbox", "aria-expanded": isOpen, className: cn("w-full max-w-full min-w-0", "h-auto py-1", fieldTriggerClassName, "flex items-center justify-between gap-2"), children: [jsx("span", { className: "flex-1 min-w-0 text-left pr-2 leading-relaxed", children: selected ? (jsx("span", { className: "block whitespace-normal wrap-break-word", children: selected.name })) : (jsx("span", { className: "text-muted-foreground/40 font-normal", children: fallback })) }), jsx(ChevronDown, { className: cn("shrink-0 w-4 h-4 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none", isOpen ? "rotate-180" : "") })] }), isOpen && (jsxs(MobileSheetPortal, { enabled: isMobile, children: [isMobile && (jsx("button", { type: "button", "aria-label": "Close options", tabIndex: -1, className: "fixed inset-0 z-(--z-popover-overlay) bg-black/25 backdrop-blur-[1px]", onClick: closeSheet })), jsxs("div", { ref: isMobile ? sheetRef : undefined, role: isMobile ? "dialog" : undefined, "aria-modal": isMobile ? true : undefined, "aria-label": isMobile ?
|
|
143
|
+
return (jsxs("div", { className: cn("relative w-full max-w-svw min-w-0", className), ref: ref, children: [jsxs(Button, { ...fieldProps, ref: triggerRef, type: "button", variant: "outline", disabled: disabled, size: size, onClick: handleClick, onTouchEnd: (e) => e.stopPropagation(), "aria-haspopup": "listbox", "aria-expanded": isOpen, className: cn("w-full max-w-full min-w-0", "h-auto py-1", fieldTriggerClassName, "flex items-center justify-between gap-2"), children: [jsx("span", { className: "flex-1 min-w-0 text-left pr-2 leading-relaxed", children: selected ? (jsx("span", { className: "block whitespace-normal wrap-break-word", children: selected.name })) : (jsx("span", { className: "text-muted-foreground/40 font-normal", children: fallback })) }), jsx(ChevronDown, { className: cn("shrink-0 w-4 h-4 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none", isOpen ? "rotate-180" : "") })] }), isOpen && (jsxs(MobileSheetPortal, { enabled: isMobile, children: [isMobile && (jsx("button", { type: "button", "aria-label": "Close options", tabIndex: -1, className: "fixed inset-0 z-(--z-popover-overlay) bg-black/25 backdrop-blur-[1px]", onClick: closeSheet })), jsxs("div", { ref: isMobile ? sheetRef : undefined, role: isMobile ? "dialog" : undefined, "aria-modal": isMobile ? true : undefined, "aria-label": isMobile ? sheetTitle : undefined, onKeyDown: isMobile
|
|
139
144
|
? (event) => {
|
|
140
145
|
if (event.key === "Escape") {
|
|
141
146
|
event.preventDefault();
|
|
@@ -167,7 +172,7 @@ const GroupableRadioDropdown = ({ name, options, onChange, disabled, defaultValu
|
|
|
167
172
|
? Math.min(sheetViewport.height, 640)
|
|
168
173
|
: "80dvh",
|
|
169
174
|
}
|
|
170
|
-
: undefined, children: [isMobile && (jsxs("div", { className: "flex shrink-0 items-center justify-between gap-4 px-4 pb-2 pt-4", children: [jsx("h2", { className: "text-base font-semibold text-foreground", children:
|
|
175
|
+
: undefined, children: [isMobile && (jsxs("div", { className: "flex shrink-0 items-center justify-between gap-4 px-4 pb-2 pt-4", children: [jsx("h2", { className: "text-base font-semibold text-foreground", children: sheetTitle }), jsx("button", { ref: sheetCloseRef, type: "button", "aria-label": "Close options", className: "-mr-3 flex h-11 w-11 shrink-0 cursor-pointer items-center justify-center rounded-control-lg text-muted-foreground hover:bg-muted", onClick: closeSheet, children: jsx(X, { className: "h-5 w-5", "aria-hidden": "true" }) })] })), jsx("div", { role: "listbox", className: cn("relative flex flex-col gap-option-gap overflow-y-auto overscroll-contain p-option-inset touch-pan-y [-webkit-overflow-scrolling:touch] [scrollbar-width:thin] [scrollbar-color:var(--color-border-hover)_var(--muted)]", isMobile ? "min-h-0 flex-1" : "max-h-[400px]"), children: options.map((option, index) => (jsx(DropdownOptionButton, { set_is_open: setIsOpen, size: size, children: jsx(DropdownOption, { highlighted: value === option.id, on_click: () => handleChange(option.id), children: jsx("span", { className: "block whitespace-normal wrap-break-word pr-2", children: option.name }) }) }, index))) })] })] }))] }));
|
|
171
176
|
};
|
|
172
177
|
/**
|
|
173
178
|
* This creates a dropdown menu for navigating with improved mobile support.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dropdown.js","sources":["../../src/components/dropdown.tsx"],"sourcesContent":["'use client';\r\n\r\n/**\r\n * @ Author: BetterInternship\r\n * @ Create Time: 2025-06-14 23:30:09\r\n * @ Modified time: 2025-10-31 18:13:16\r\n * @ Description:\r\n *\r\n * Stateful dropdown group component.\r\n */\r\n\r\nimport { Button } from \"./button\";\r\nimport { useMobile } from \"@/hooks/use-mobile\";\r\nimport { useMobileSheetViewport } from \"@/hooks/use-mobile-sheet-viewport\";\r\nimport { MobileSheetPortal } from \"./mobile-sheet-portal\";\r\nimport { cn } from \"@/utils\";\r\nimport { fieldTriggerClassName } from \"@/hooks/use-field-focus\";\r\nimport { ChevronDown, X } from \"lucide-react\";\r\nimport { useRouter } from \"next/navigation\";\r\nimport React, {\r\n Children,\r\n createContext,\r\n useCallback,\r\n useContext,\r\n useEffect,\r\n useRef,\r\n useState,\r\n} from \"react\";\r\nimport { useDetectClickOutside } from '@/hooks/use-detect-click-outside';\r\n\r\n/**\r\n * The group context interface.\r\n * What's available in the group context to other components.\r\n */\r\ninterface IDropdownGroupContext {\r\n activeDropdown: string;\r\n setActiveDropdown: (dropdown: string) => void;\r\n}\r\nconst DropdownGroupContext = createContext<IDropdownGroupContext>(\r\n {} as IDropdownGroupContext,\r\n);\r\n\r\n/**\r\n * A wrapper around the contents of a dropdown option.\r\n *\r\n * @component\r\n */\r\ntype IDropdownOptionProps = {\r\n children?: React.ReactNode;\r\n highlighted?: boolean;\r\n disabled?: boolean;\r\n href?: string;\r\n on_click?: () => void;\r\n};\r\nexport const DropdownOption = ({ children }: IDropdownOptionProps) => {\r\n return <>{children}</>;\r\n};\r\n\r\n/**\r\n * Creates a standard button dropdowns must use with mobile optimization.\r\n * Not meant to be used elsewhere.\r\n *\r\n * @component\r\n */\r\nconst DropdownOptionButton = ({\r\n children,\r\n set_is_open,\r\n size = \"xs\",\r\n}: {\r\n children: React.ReactElement<IDropdownOptionProps>;\r\n set_is_open: (is_open: boolean) => void;\r\n size?: \"xs\" | \"sm\" | \"md\" | \"lg\";\r\n}) => {\r\n const router = useRouter();\r\n const is_mobile = useMobile();\r\n const [scrolling, setScrolling] = useState(false);\r\n const dropdown_button_ref = useRef<HTMLInputElement>({} as HTMLInputElement);\r\n\r\n const handleClick = useCallback(\r\n (e: React.MouseEvent) => {\r\n e.stopPropagation();\r\n set_is_open(false);\r\n children.props.on_click && children.props.on_click();\r\n children.props.href && router.push(children.props.href);\r\n },\r\n [children.props, router, set_is_open],\r\n );\r\n\r\n const onTouchStart = (e: any) => {\r\n e.stopPropagation();\r\n setScrolling(true);\r\n };\r\n\r\n const onTouchEnd = (e: any) => {\r\n e.stopPropagation();\r\n setScrolling(false);\r\n };\r\n\r\n useEffect(() => {\r\n const dropdown_button = dropdown_button_ref.current;\r\n if (!dropdown_button) return;\r\n\r\n // Attach passive touchstart handler\r\n dropdown_button.addEventListener(\"touchstart\", onTouchStart, {\r\n passive: true,\r\n });\r\n\r\n dropdown_button.addEventListener(\"touchend\", onTouchEnd, {\r\n passive: true,\r\n });\r\n\r\n // Cleanup on unmount\r\n return () => {\r\n dropdown_button.removeEventListener(\"touchstart\", onTouchStart);\r\n dropdown_button.removeEventListener(\"touchend\", onTouchEnd);\r\n };\r\n }, [onTouchStart]);\r\n\r\n return (\r\n <button\r\n // @ts-ignore\r\n ref={dropdown_button_ref}\r\n className={cn(\r\n \"flex min-h-option-row w-full cursor-pointer items-center gap-2 rounded-control-sm px-option-x py-2 text-left text-muted-foreground transition-colors hover:bg-muted\",\r\n is_mobile ? \"min-h-12 py-3 active:bg-muted touch-manipulation\" : \"\",\r\n `text-${size}`,\r\n children.props.highlighted ? \"bg-primary-tint\" : \"\",\r\n )}\r\n onClick={(e) => !scrolling && handleClick(e)}\r\n >\r\n <div className=\"w-full\">{children}</div>\r\n </button>\r\n );\r\n};\r\n\r\n/**\r\n * This component creates a context provider for dropdowns inside it to use.\r\n * The dropdowns inside can modify the active dropdown when they're clicked.\r\n * This way, only one dropdown in the group is active at a time.\r\n *\r\n * @component\r\n */\r\nexport const DropdownGroup = ({ children }: { children: React.ReactNode }) => {\r\n const [activeDropdown, setActiveDropdown] = useState(\"\");\r\n const group_dropdown_context: IDropdownGroupContext = {\r\n activeDropdown,\r\n setActiveDropdown,\r\n };\r\n\r\n return (\r\n <DropdownGroupContext value={group_dropdown_context}>\r\n {children}\r\n </DropdownGroupContext>\r\n );\r\n};\r\n\r\ninterface IRadioDropdownOption<ID> {\r\n id: ID;\r\n name: string;\r\n}\r\n\r\n/**\r\n * This represents a single dropdown inside the group with mobile optimization.\r\n * Inherits the provided context (if there is none, that's fine).\r\n *\r\n * @component\r\n */\r\nexport const GroupableRadioDropdown = <ID extends number | string>({\r\n name,\r\n options,\r\n onChange,\r\n disabled,\r\n defaultValue = null,\r\n size = \"sm\",\r\n className = \"\",\r\n fallback = \"Select option\",\r\n}: {\r\n name: string;\r\n options: IRadioDropdownOption<ID>[];\r\n onChange: (option: ID) => void;\r\n defaultValue?: ID | ID[] | null;\r\n disabled?: boolean | undefined;\r\n size?: \"xs\" | \"sm\" | \"md\" | \"lg\";\r\n className?: string;\r\n fallback?: string;\r\n}) => {\r\n const isMobile = useMobile();\r\n const { activeDropdown, setActiveDropdown } =\r\n useContext(DropdownGroupContext);\r\n const [isOpen, setIsOpen] = useState(false);\r\n const sheetViewport = useMobileSheetViewport(isOpen && isMobile);\r\n const [value, setValue] = useState(defaultValue);\r\n const ref = useDetectClickOutside({ onTriggered: () => setIsOpen(false) });\r\n const triggerRef = useRef<HTMLButtonElement>(null);\r\n const sheetRef = useRef<HTMLDivElement>(null);\r\n const sheetCloseRef = useRef<HTMLButtonElement>(null);\r\n const useSheet = isOpen && isMobile;\r\n\r\n const closeSheet = useCallback(() => {\r\n setIsOpen(false);\r\n triggerRef.current?.focus();\r\n }, []);\r\n\r\n // While the mobile sheet is open: lock page scroll and move focus into it.\r\n useEffect(() => {\r\n if (!useSheet) return;\r\n const overflow = document.body.style.overflow;\r\n document.body.style.overflow = \"hidden\";\r\n const frame = window.requestAnimationFrame(() =>\r\n sheetCloseRef.current?.focus(),\r\n );\r\n return () => {\r\n window.cancelAnimationFrame(frame);\r\n document.body.style.overflow = overflow;\r\n };\r\n }, [useSheet]);\r\n\r\n // Just so it's not stuck at the first default when the default changes\r\n useEffect(() => {\r\n setValue(defaultValue);\r\n }, [defaultValue]);\r\n\r\n /**\r\n * Activates dropdown\r\n */\r\n const handleClick = useCallback(\r\n (e: React.MouseEvent) => {\r\n e.stopPropagation();\r\n setIsOpen(!isOpen);\r\n setActiveDropdown(name);\r\n },\r\n [isOpen, name, setActiveDropdown],\r\n );\r\n\r\n /**\r\n * Changes dropdown value\r\n */\r\n const handleChange = useCallback(\r\n (option: ID) => {\r\n setValue(option);\r\n onChange(option);\r\n setIsOpen(false);\r\n },\r\n [onChange],\r\n );\r\n\r\n // Check if it's still the active dropdown\r\n useEffect(() => {\r\n if (activeDropdown !== name) setIsOpen(false);\r\n }, [activeDropdown, name]);\r\n\r\n const selected =\r\n value || value === 0 ? options.find((o) => o.id === value) : undefined;\r\n\r\n return (\r\n <div\r\n className={cn(\"relative w-full max-w-svw min-w-0\", className)}\r\n ref={ref}\r\n >\r\n <Button\r\n ref={triggerRef}\r\n type=\"button\"\r\n variant=\"outline\"\r\n disabled={disabled}\r\n size={size}\r\n onClick={handleClick}\r\n onTouchEnd={(e) => e.stopPropagation()}\r\n aria-haspopup=\"listbox\"\r\n aria-expanded={isOpen}\r\n className={cn(\r\n \"w-full max-w-full min-w-0\",\r\n \"h-auto py-1\",\r\n fieldTriggerClassName,\r\n \"flex items-center justify-between gap-2\",\r\n )}\r\n >\r\n {/* shrinkable text container */}\r\n <span className=\"flex-1 min-w-0 text-left pr-2 leading-relaxed\">\r\n {selected ? (\r\n <span className=\"block whitespace-normal wrap-break-word\">\r\n {selected.name}\r\n </span>\r\n ) : (\r\n <span className=\"text-muted-foreground/40 font-normal\">\r\n {fallback}\r\n </span>\r\n )}\r\n </span>\r\n\r\n <ChevronDown\r\n className={cn(\r\n \"shrink-0 w-4 h-4 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none\",\r\n isOpen ? \"rotate-180\" : \"\",\r\n )}\r\n />\r\n </Button>\r\n\r\n {isOpen && (\r\n <MobileSheetPortal enabled={isMobile}>\r\n {isMobile && (\r\n <button\r\n type=\"button\"\r\n aria-label=\"Close options\"\r\n tabIndex={-1}\r\n className=\"fixed inset-0 z-(--z-popover-overlay) bg-black/25 backdrop-blur-[1px]\"\r\n onClick={closeSheet}\r\n />\r\n )}\r\n <div\r\n ref={isMobile ? sheetRef : undefined}\r\n role={isMobile ? \"dialog\" : undefined}\r\n aria-modal={isMobile ? true : undefined}\r\n aria-label={isMobile ? fallback : undefined}\r\n onKeyDown={\r\n isMobile\r\n ? (event) => {\r\n if (event.key === \"Escape\") {\r\n event.preventDefault();\r\n closeSheet();\r\n }\r\n if (event.key !== \"Tab\") return;\r\n const focusable =\r\n sheetRef.current?.querySelectorAll<HTMLElement>(\r\n \"button:not([disabled]):not([tabindex='-1'])\",\r\n );\r\n if (!focusable?.length) return;\r\n const first = focusable[0];\r\n const last = focusable[focusable.length - 1];\r\n if (event.shiftKey && document.activeElement === first) {\r\n event.preventDefault();\r\n last.focus();\r\n } else if (\r\n !event.shiftKey &&\r\n document.activeElement === last\r\n ) {\r\n event.preventDefault();\r\n first.focus();\r\n }\r\n }\r\n : undefined\r\n }\r\n className={cn(\r\n \"border border-border bg-background shadow-card\",\r\n isMobile\r\n ? \"fixed left-0 right-0 z-(--z-popover) flex flex-col overflow-hidden rounded-t-control-lg border-b-0 pb-[max(0.75rem,env(safe-area-inset-bottom))]\"\r\n : \"absolute left-0 right-0 top-full z-[9999] mt-1 max-w-full overflow-hidden rounded-control-lg\",\r\n )}\r\n style={\r\n isMobile\r\n ? {\r\n bottom: sheetViewport?.bottom ?? 0,\r\n maxHeight: sheetViewport\r\n ? Math.min(sheetViewport.height, 640)\r\n : \"80dvh\",\r\n }\r\n : undefined\r\n }\r\n >\r\n {isMobile && (\r\n <div className=\"flex shrink-0 items-center justify-between gap-4 px-4 pb-2 pt-4\">\r\n <h2 className=\"text-base font-semibold text-foreground\">\r\n {fallback}\r\n </h2>\r\n <button\r\n ref={sheetCloseRef}\r\n type=\"button\"\r\n aria-label=\"Close options\"\r\n className=\"-mr-3 flex h-11 w-11 shrink-0 cursor-pointer items-center justify-center rounded-control-lg text-muted-foreground hover:bg-muted\"\r\n onClick={closeSheet}\r\n >\r\n <X className=\"h-5 w-5\" aria-hidden=\"true\" />\r\n </button>\r\n </div>\r\n )}\r\n <div\r\n role=\"listbox\"\r\n className={cn(\r\n \"relative flex flex-col gap-option-gap overflow-y-auto overscroll-contain p-option-inset touch-pan-y [-webkit-overflow-scrolling:touch] [scrollbar-width:thin] [scrollbar-color:var(--color-border-hover)_var(--muted)]\",\r\n isMobile ? \"min-h-0 flex-1\" : \"max-h-[400px]\",\r\n )}\r\n >\r\n {options.map((option, index) => (\r\n <DropdownOptionButton\r\n key={index}\r\n set_is_open={setIsOpen}\r\n size={size}\r\n >\r\n <DropdownOption\r\n highlighted={value === option.id}\r\n on_click={() => handleChange(option.id)}\r\n >\r\n <span className=\"block whitespace-normal wrap-break-word pr-2\">\r\n {option.name}\r\n </span>\r\n </DropdownOption>\r\n </DropdownOptionButton>\r\n ))}\r\n </div>\r\n </div>\r\n </MobileSheetPortal>\r\n )}\r\n </div>\r\n );\r\n};\r\n\r\n/**\r\n * This creates a dropdown menu for navigating with improved mobile support.\r\n *\r\n * @component\r\n */\r\nexport const GroupableNavDropdown = ({\r\n display,\r\n content,\r\n children,\r\n className = \"\",\r\n showArrow = true,\r\n}: {\r\n display?: React.ReactNode;\r\n content?: React.ReactNode;\r\n children?:\r\n | React.ReactElement<IDropdownOptionProps>\r\n | React.ReactElement<IDropdownOptionProps>[];\r\n className?: string;\r\n showArrow?: boolean;\r\n}) => {\r\n const is_mobile = useMobile();\r\n const [is_open, set_is_open] = useState(false);\r\n const dropdownRef = useRef<HTMLDivElement>(null);\r\n const buttonRef = useRef<HTMLButtonElement>(null);\r\n const touchStartRef = useRef<{\r\n x: number;\r\n y: number;\r\n target: EventTarget | null;\r\n } | null>(null);\r\n\r\n // Close dropdown handler\r\n const closeDropdown = useCallback(() => {\r\n set_is_open(false);\r\n }, []);\r\n\r\n // Handle clicks outside dropdown\r\n useEffect(() => {\r\n const handleClickOutside = (event: MouseEvent) => {\r\n if (\r\n !is_mobile &&\r\n dropdownRef.current &&\r\n !dropdownRef.current.contains(event.target as Node) &&\r\n buttonRef.current &&\r\n !buttonRef.current.contains(event.target as Node)\r\n ) {\r\n closeDropdown();\r\n }\r\n };\r\n\r\n if (is_open && !is_mobile) {\r\n document.addEventListener(\"mousedown\", handleClickOutside);\r\n return () =>\r\n document.removeEventListener(\"mousedown\", handleClickOutside);\r\n }\r\n }, [is_open, is_mobile, closeDropdown]);\r\n\r\n // Mobile touch handlers\r\n const handleTouchStart = useCallback(\r\n (e: TouchEvent) => {\r\n if (!is_mobile || !is_open) return;\r\n\r\n const touch = e.touches[0];\r\n touchStartRef.current = {\r\n x: touch.clientX,\r\n y: touch.clientY,\r\n target: e.target,\r\n };\r\n },\r\n [is_mobile, is_open],\r\n );\r\n\r\n const handleTouchEnd = useCallback(\r\n (e: TouchEvent) => {\r\n if (!is_mobile || !is_open || !touchStartRef.current) return;\r\n\r\n const touch = e.changedTouches[0];\r\n const startTouch = touchStartRef.current;\r\n\r\n // Calculate touch movement\r\n const deltaX = Math.abs(touch.clientX - startTouch.x);\r\n const deltaY = Math.abs(touch.clientY - startTouch.y);\r\n const isSwipe = deltaX > 10 || deltaY > 10;\r\n\r\n // Check if touch is outside dropdown area\r\n const target = e.target as Element;\r\n const isOutsideDropdown =\r\n dropdownRef.current &&\r\n !dropdownRef.current.contains(target) &&\r\n buttonRef.current &&\r\n !buttonRef.current.contains(target);\r\n\r\n // Close if touch ended outside and wasn't a swipe\r\n if (!isSwipe && isOutsideDropdown) {\r\n closeDropdown();\r\n }\r\n\r\n touchStartRef.current = null;\r\n },\r\n [is_mobile, is_open, closeDropdown],\r\n );\r\n\r\n // Set up mobile touch listeners\r\n useEffect(() => {\r\n if (is_mobile && is_open) {\r\n document.addEventListener(\"touchstart\", handleTouchStart);\r\n document.addEventListener(\"touchend\", handleTouchEnd);\r\n\r\n return () => {\r\n document.removeEventListener(\"touchstart\", handleTouchStart);\r\n document.removeEventListener(\"touchend\", handleTouchEnd);\r\n };\r\n }\r\n }, [is_mobile, is_open, handleTouchStart, handleTouchEnd]);\r\n\r\n // Prevent event propagation for dropdown content\r\n const handleDropdownInteraction = useCallback(\r\n (e: React.MouseEvent | React.TouchEvent) => {\r\n e.stopPropagation();\r\n },\r\n [],\r\n );\r\n\r\n // Toggle dropdown\r\n const handleButtonClick = useCallback(\r\n (e: React.MouseEvent) => {\r\n e.stopPropagation();\r\n set_is_open(!is_open);\r\n },\r\n [is_open],\r\n );\r\n\r\n return (\r\n <div className={cn(\"relative z-[100]\", className)} ref={dropdownRef}>\r\n <Button\r\n ref={buttonRef}\r\n type=\"button\"\r\n variant=\"ghost\"\r\n className=\"relative flex items-center gap-2 h-12 px-3 z-[1000]\"\r\n onClick={handleButtonClick}\r\n onTouchEnd={(e) => e.stopPropagation()}\r\n >\r\n {display}\r\n {showArrow && (\r\n <ChevronDown\r\n className={cn(\r\n \"w-4 h-4 text-muted-foreground transition-transform\",\r\n is_open ? \"rotate-180\" : \"\",\r\n )}\r\n />\r\n )}\r\n </Button>\r\n\r\n {is_open && (\r\n <div\r\n className={cn(\r\n \"absolute right-0 mt-2 bg-background border border-border rounded-control-lg overflow-hidden shadow-card z-[1000]\",\r\n is_mobile ? \"w-56\" : \"w-48\", // Slightly wider on mobile for better touch targets\r\n className,\r\n )}\r\n onClick={handleDropdownInteraction}\r\n onTouchStart={handleDropdownInteraction}\r\n onTouchEnd={handleDropdownInteraction}\r\n >\r\n <div\r\n className={cn(\r\n \"relative z-[1000] flex max-h-64 flex-col gap-option-gap overflow-y-auto overscroll-contain p-option-inset [scrollbar-width:thin] [scrollbar-color:var(--color-border-hover)_var(--muted)]\",\r\n is_mobile ? \"max-h-80\" : \"max-h-64\",\r\n )}\r\n >\r\n {content}\r\n\r\n {Children.map(children, (child, index) => {\r\n return (\r\n <DropdownOptionButton key={index} set_is_open={set_is_open}>\r\n {child ? child : <></>}\r\n </DropdownOptionButton>\r\n );\r\n })}\r\n </div>\r\n </div>\r\n )}\r\n </div>\r\n );\r\n};\r\n"],"names":[],"mappings":";;;;;;;;;;;;;AAsCA;;;AAkBA;AAEA;;;;;AAKG;AACH;AASE;AACA;;AAEA;AAEA;;;;AAKI;;AAKJ;;;AAGA;AAEA;;;AAGA;;AAGE;AACA;;;AAGA;AACE;AACD;AAED;AACE;AACD;;AAGD;AACE;AACA;AACF;AACF;AAEA;;AAGI;AAYN;AAEA;;;;;;AAMG;;;AAGD;;;;;AAUF;AAOA;;;;;AAKG;AACI;AAmBL;;;;;AAMA;AACA;AACA;AACA;AACA;AAEA;;AAEE;;;;AAKA;;;;AAGA;AAGA;AACE;;AAEF;AACF;;;;AAKA;AAEA;;AAEG;AACH;;AAGI;;;AAMJ;;AAEG;AACH;;;;AAKE;;;;;AAOF;AAEA;;AAgEc;AACI;;AAEE;;AAEF;;;;;AAMA;;;;;;;AAOE;;;;;;AAWN;AACA;AAIA;AACI;AACA;;AAEE;AACH;AACH;AAgDhB;AAEA;;;;AAIG;;AAgBD;;AAEA;AACA;AACA;;AAOA;;;;;AAME;AACE;AAEE;;AAEA;;AAGA;;AAEJ;AAEA;AACE;;;;;AAOJ;AAEI;;;;;;;;AAQF;AAIF;;;;AAKI;;AAGA;AACA;;;AAIA;AACA;AAEE;AACA;;;AAIF;AACE;;AAGF;;;;AAOF;AACE;AACA;AAEA;AACE;AACA;AACF;;;;AAKJ;;;;AAQA;;AAGI;AACF;;;;AAkDQ;AAMZ;;"}
|
|
1
|
+
{"version":3,"file":"dropdown.js","sources":["../../src/components/dropdown.tsx"],"sourcesContent":["'use client';\r\n\r\n/**\r\n * @ Author: BetterInternship\r\n * @ Create Time: 2025-06-14 23:30:09\r\n * @ Modified time: 2025-10-31 18:13:16\r\n * @ Description:\r\n *\r\n * Stateful dropdown group component.\r\n */\r\n\r\nimport { Button } from \"./button\";\r\nimport { useMobile } from \"@/hooks/use-mobile\";\r\nimport { useMobileSheetViewport } from \"@/hooks/use-mobile-sheet-viewport\";\r\nimport { MobileSheetPortal } from \"./mobile-sheet-portal\";\r\nimport { cn } from \"@/utils\";\r\nimport { fieldTriggerClassName } from \"@/hooks/use-field-focus\";\r\nimport { useFormField, useFormFieldControl } from \"./form-field\";\r\nimport { ChevronDown, X } from \"lucide-react\";\r\nimport { useRouter } from \"next/navigation\";\r\nimport React, {\r\n Children,\r\n createContext,\r\n useCallback,\r\n useContext,\r\n useEffect,\r\n useRef,\r\n useState,\r\n} from \"react\";\r\nimport { useDetectClickOutside } from '@/hooks/use-detect-click-outside';\r\n\r\n/**\r\n * The group context interface.\r\n * What's available in the group context to other components.\r\n */\r\ninterface IDropdownGroupContext {\r\n activeDropdown: string;\r\n setActiveDropdown: (dropdown: string) => void;\r\n}\r\nconst DropdownGroupContext = createContext<IDropdownGroupContext>(\r\n {} as IDropdownGroupContext,\r\n);\r\n\r\n/**\r\n * A wrapper around the contents of a dropdown option.\r\n *\r\n * @component\r\n */\r\ntype IDropdownOptionProps = {\r\n children?: React.ReactNode;\r\n highlighted?: boolean;\r\n disabled?: boolean;\r\n href?: string;\r\n on_click?: () => void;\r\n};\r\nexport const DropdownOption = ({ children }: IDropdownOptionProps) => {\r\n return <>{children}</>;\r\n};\r\n\r\n/**\r\n * Creates a standard button dropdowns must use with mobile optimization.\r\n * Not meant to be used elsewhere.\r\n *\r\n * @component\r\n */\r\nconst DropdownOptionButton = ({\r\n children,\r\n set_is_open,\r\n size = \"xs\",\r\n}: {\r\n children: React.ReactElement<IDropdownOptionProps>;\r\n set_is_open: (is_open: boolean) => void;\r\n size?: \"xs\" | \"sm\" | \"md\" | \"lg\";\r\n}) => {\r\n const router = useRouter();\r\n const is_mobile = useMobile();\r\n const [scrolling, setScrolling] = useState(false);\r\n const dropdown_button_ref = useRef<HTMLInputElement>({} as HTMLInputElement);\r\n\r\n const handleClick = useCallback(\r\n (e: React.MouseEvent) => {\r\n e.stopPropagation();\r\n set_is_open(false);\r\n children.props.on_click && children.props.on_click();\r\n children.props.href && router.push(children.props.href);\r\n },\r\n [children.props, router, set_is_open],\r\n );\r\n\r\n const onTouchStart = (e: any) => {\r\n e.stopPropagation();\r\n setScrolling(true);\r\n };\r\n\r\n const onTouchEnd = (e: any) => {\r\n e.stopPropagation();\r\n setScrolling(false);\r\n };\r\n\r\n useEffect(() => {\r\n const dropdown_button = dropdown_button_ref.current;\r\n if (!dropdown_button) return;\r\n\r\n // Attach passive touchstart handler\r\n dropdown_button.addEventListener(\"touchstart\", onTouchStart, {\r\n passive: true,\r\n });\r\n\r\n dropdown_button.addEventListener(\"touchend\", onTouchEnd, {\r\n passive: true,\r\n });\r\n\r\n // Cleanup on unmount\r\n return () => {\r\n dropdown_button.removeEventListener(\"touchstart\", onTouchStart);\r\n dropdown_button.removeEventListener(\"touchend\", onTouchEnd);\r\n };\r\n }, [onTouchStart]);\r\n\r\n return (\r\n <button\r\n // @ts-ignore\r\n ref={dropdown_button_ref}\r\n className={cn(\r\n \"flex min-h-option-row w-full cursor-pointer items-center gap-2 rounded-control-sm px-option-x py-2 text-left text-muted-foreground transition-colors hover:bg-muted\",\r\n is_mobile ? \"min-h-12 py-3 active:bg-muted touch-manipulation\" : \"\",\r\n `text-${size}`,\r\n children.props.highlighted ? \"bg-primary-tint\" : \"\",\r\n )}\r\n onClick={(e) => !scrolling && handleClick(e)}\r\n >\r\n <div className=\"w-full\">{children}</div>\r\n </button>\r\n );\r\n};\r\n\r\n/**\r\n * This component creates a context provider for dropdowns inside it to use.\r\n * The dropdowns inside can modify the active dropdown when they're clicked.\r\n * This way, only one dropdown in the group is active at a time.\r\n *\r\n * @component\r\n */\r\nexport const DropdownGroup = ({ children }: { children: React.ReactNode }) => {\r\n const [activeDropdown, setActiveDropdown] = useState(\"\");\r\n const group_dropdown_context: IDropdownGroupContext = {\r\n activeDropdown,\r\n setActiveDropdown,\r\n };\r\n\r\n return (\r\n <DropdownGroupContext value={group_dropdown_context}>\r\n {children}\r\n </DropdownGroupContext>\r\n );\r\n};\r\n\r\ninterface IRadioDropdownOption<ID> {\r\n id: ID;\r\n name: string;\r\n}\r\n\r\n/**\r\n * This represents a single dropdown inside the group with mobile optimization.\r\n * Inherits the provided context (if there is none, that's fine).\r\n *\r\n * @component\r\n */\r\nexport const GroupableRadioDropdown = <ID extends number | string>({\r\n name,\r\n options,\r\n onChange,\r\n disabled,\r\n defaultValue = null,\r\n size = \"sm\",\r\n className = \"\",\r\n fallback = \"Select option\",\r\n}: {\r\n name: string;\r\n options: IRadioDropdownOption<ID>[];\r\n onChange: (option: ID) => void;\r\n defaultValue?: ID | ID[] | null;\r\n disabled?: boolean | undefined;\r\n size?: \"xs\" | \"sm\" | \"md\" | \"lg\";\r\n className?: string;\r\n fallback?: string;\r\n}) => {\r\n const isMobile = useMobile();\r\n const { activeDropdown, setActiveDropdown } =\r\n useContext(DropdownGroupContext);\r\n const [isOpen, setIsOpen] = useState(false);\r\n const sheetViewport = useMobileSheetViewport(isOpen && isMobile);\r\n const [value, setValue] = useState(defaultValue);\r\n const ref = useDetectClickOutside({ onTriggered: () => setIsOpen(false) });\r\n const triggerRef = useRef<HTMLButtonElement>(null);\r\n const sheetRef = useRef<HTMLDivElement>(null);\r\n const sheetCloseRef = useRef<HTMLButtonElement>(null);\r\n const useSheet = isOpen && isMobile;\r\n // The phone sheet's title: the field's label when inside a FormField.\r\n const sheetTitle = useFormField()?.labelText ?? fallback;\r\n // Inside a FormField the trigger takes the field's id, so the label opens it.\r\n const fieldProps = 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\r\n const closeSheet = useCallback(() => {\r\n setIsOpen(false);\r\n triggerRef.current?.focus();\r\n }, []);\r\n\r\n // While the mobile sheet is open: lock page scroll and move focus into it.\r\n useEffect(() => {\r\n if (!useSheet) return;\r\n const overflow = document.body.style.overflow;\r\n document.body.style.overflow = \"hidden\";\r\n const frame = window.requestAnimationFrame(() =>\r\n sheetCloseRef.current?.focus(),\r\n );\r\n return () => {\r\n window.cancelAnimationFrame(frame);\r\n document.body.style.overflow = overflow;\r\n };\r\n }, [useSheet]);\r\n\r\n // Just so it's not stuck at the first default when the default changes\r\n useEffect(() => {\r\n setValue(defaultValue);\r\n }, [defaultValue]);\r\n\r\n /**\r\n * Activates dropdown\r\n */\r\n const handleClick = useCallback(\r\n (e: React.MouseEvent) => {\r\n e.stopPropagation();\r\n setIsOpen(!isOpen);\r\n setActiveDropdown(name);\r\n },\r\n [isOpen, name, setActiveDropdown],\r\n );\r\n\r\n /**\r\n * Changes dropdown value\r\n */\r\n const handleChange = useCallback(\r\n (option: ID) => {\r\n setValue(option);\r\n onChange(option);\r\n setIsOpen(false);\r\n },\r\n [onChange],\r\n );\r\n\r\n // Check if it's still the active dropdown\r\n useEffect(() => {\r\n if (activeDropdown !== name) setIsOpen(false);\r\n }, [activeDropdown, name]);\r\n\r\n const selected =\r\n value || value === 0 ? options.find((o) => o.id === value) : undefined;\r\n\r\n return (\r\n <div\r\n className={cn(\"relative w-full max-w-svw min-w-0\", className)}\r\n ref={ref}\r\n >\r\n <Button\r\n {...fieldProps}\r\n ref={triggerRef}\r\n type=\"button\"\r\n variant=\"outline\"\r\n disabled={disabled}\r\n size={size}\r\n onClick={handleClick}\r\n onTouchEnd={(e) => e.stopPropagation()}\r\n aria-haspopup=\"listbox\"\r\n aria-expanded={isOpen}\r\n className={cn(\r\n \"w-full max-w-full min-w-0\",\r\n \"h-auto py-1\",\r\n fieldTriggerClassName,\r\n \"flex items-center justify-between gap-2\",\r\n )}\r\n >\r\n {/* shrinkable text container */}\r\n <span className=\"flex-1 min-w-0 text-left pr-2 leading-relaxed\">\r\n {selected ? (\r\n <span className=\"block whitespace-normal wrap-break-word\">\r\n {selected.name}\r\n </span>\r\n ) : (\r\n <span className=\"text-muted-foreground/40 font-normal\">\r\n {fallback}\r\n </span>\r\n )}\r\n </span>\r\n\r\n <ChevronDown\r\n className={cn(\r\n \"shrink-0 w-4 h-4 text-muted-foreground transition-transform duration-interactive ease-out-strong motion-reduce:transition-none\",\r\n isOpen ? \"rotate-180\" : \"\",\r\n )}\r\n />\r\n </Button>\r\n\r\n {isOpen && (\r\n <MobileSheetPortal enabled={isMobile}>\r\n {isMobile && (\r\n <button\r\n type=\"button\"\r\n aria-label=\"Close options\"\r\n tabIndex={-1}\r\n className=\"fixed inset-0 z-(--z-popover-overlay) bg-black/25 backdrop-blur-[1px]\"\r\n onClick={closeSheet}\r\n />\r\n )}\r\n <div\r\n ref={isMobile ? sheetRef : undefined}\r\n role={isMobile ? \"dialog\" : undefined}\r\n aria-modal={isMobile ? true : undefined}\r\n aria-label={isMobile ? sheetTitle : undefined}\r\n onKeyDown={\r\n isMobile\r\n ? (event) => {\r\n if (event.key === \"Escape\") {\r\n event.preventDefault();\r\n closeSheet();\r\n }\r\n if (event.key !== \"Tab\") return;\r\n const focusable =\r\n sheetRef.current?.querySelectorAll<HTMLElement>(\r\n \"button:not([disabled]):not([tabindex='-1'])\",\r\n );\r\n if (!focusable?.length) return;\r\n const first = focusable[0];\r\n const last = focusable[focusable.length - 1];\r\n if (event.shiftKey && document.activeElement === first) {\r\n event.preventDefault();\r\n last.focus();\r\n } else if (\r\n !event.shiftKey &&\r\n document.activeElement === last\r\n ) {\r\n event.preventDefault();\r\n first.focus();\r\n }\r\n }\r\n : undefined\r\n }\r\n className={cn(\r\n \"border border-border bg-background shadow-card\",\r\n isMobile\r\n ? \"fixed left-0 right-0 z-(--z-popover) flex flex-col overflow-hidden rounded-t-control-lg border-b-0 pb-[max(0.75rem,env(safe-area-inset-bottom))]\"\r\n : \"absolute left-0 right-0 top-full z-[9999] mt-1 max-w-full overflow-hidden rounded-control-lg\",\r\n )}\r\n style={\r\n isMobile\r\n ? {\r\n bottom: sheetViewport?.bottom ?? 0,\r\n maxHeight: sheetViewport\r\n ? Math.min(sheetViewport.height, 640)\r\n : \"80dvh\",\r\n }\r\n : undefined\r\n }\r\n >\r\n {isMobile && (\r\n <div className=\"flex shrink-0 items-center justify-between gap-4 px-4 pb-2 pt-4\">\r\n <h2 className=\"text-base font-semibold text-foreground\">\r\n {sheetTitle}\r\n </h2>\r\n <button\r\n ref={sheetCloseRef}\r\n type=\"button\"\r\n aria-label=\"Close options\"\r\n className=\"-mr-3 flex h-11 w-11 shrink-0 cursor-pointer items-center justify-center rounded-control-lg text-muted-foreground hover:bg-muted\"\r\n onClick={closeSheet}\r\n >\r\n <X className=\"h-5 w-5\" aria-hidden=\"true\" />\r\n </button>\r\n </div>\r\n )}\r\n <div\r\n role=\"listbox\"\r\n className={cn(\r\n \"relative flex flex-col gap-option-gap overflow-y-auto overscroll-contain p-option-inset touch-pan-y [-webkit-overflow-scrolling:touch] [scrollbar-width:thin] [scrollbar-color:var(--color-border-hover)_var(--muted)]\",\r\n isMobile ? \"min-h-0 flex-1\" : \"max-h-[400px]\",\r\n )}\r\n >\r\n {options.map((option, index) => (\r\n <DropdownOptionButton\r\n key={index}\r\n set_is_open={setIsOpen}\r\n size={size}\r\n >\r\n <DropdownOption\r\n highlighted={value === option.id}\r\n on_click={() => handleChange(option.id)}\r\n >\r\n <span className=\"block whitespace-normal wrap-break-word pr-2\">\r\n {option.name}\r\n </span>\r\n </DropdownOption>\r\n </DropdownOptionButton>\r\n ))}\r\n </div>\r\n </div>\r\n </MobileSheetPortal>\r\n )}\r\n </div>\r\n );\r\n};\r\n\r\n/**\r\n * This creates a dropdown menu for navigating with improved mobile support.\r\n *\r\n * @component\r\n */\r\nexport const GroupableNavDropdown = ({\r\n display,\r\n content,\r\n children,\r\n className = \"\",\r\n showArrow = true,\r\n}: {\r\n display?: React.ReactNode;\r\n content?: React.ReactNode;\r\n children?:\r\n | React.ReactElement<IDropdownOptionProps>\r\n | React.ReactElement<IDropdownOptionProps>[];\r\n className?: string;\r\n showArrow?: boolean;\r\n}) => {\r\n const is_mobile = useMobile();\r\n const [is_open, set_is_open] = useState(false);\r\n const dropdownRef = useRef<HTMLDivElement>(null);\r\n const buttonRef = useRef<HTMLButtonElement>(null);\r\n const touchStartRef = useRef<{\r\n x: number;\r\n y: number;\r\n target: EventTarget | null;\r\n } | null>(null);\r\n\r\n // Close dropdown handler\r\n const closeDropdown = useCallback(() => {\r\n set_is_open(false);\r\n }, []);\r\n\r\n // Handle clicks outside dropdown\r\n useEffect(() => {\r\n const handleClickOutside = (event: MouseEvent) => {\r\n if (\r\n !is_mobile &&\r\n dropdownRef.current &&\r\n !dropdownRef.current.contains(event.target as Node) &&\r\n buttonRef.current &&\r\n !buttonRef.current.contains(event.target as Node)\r\n ) {\r\n closeDropdown();\r\n }\r\n };\r\n\r\n if (is_open && !is_mobile) {\r\n document.addEventListener(\"mousedown\", handleClickOutside);\r\n return () =>\r\n document.removeEventListener(\"mousedown\", handleClickOutside);\r\n }\r\n }, [is_open, is_mobile, closeDropdown]);\r\n\r\n // Mobile touch handlers\r\n const handleTouchStart = useCallback(\r\n (e: TouchEvent) => {\r\n if (!is_mobile || !is_open) return;\r\n\r\n const touch = e.touches[0];\r\n touchStartRef.current = {\r\n x: touch.clientX,\r\n y: touch.clientY,\r\n target: e.target,\r\n };\r\n },\r\n [is_mobile, is_open],\r\n );\r\n\r\n const handleTouchEnd = useCallback(\r\n (e: TouchEvent) => {\r\n if (!is_mobile || !is_open || !touchStartRef.current) return;\r\n\r\n const touch = e.changedTouches[0];\r\n const startTouch = touchStartRef.current;\r\n\r\n // Calculate touch movement\r\n const deltaX = Math.abs(touch.clientX - startTouch.x);\r\n const deltaY = Math.abs(touch.clientY - startTouch.y);\r\n const isSwipe = deltaX > 10 || deltaY > 10;\r\n\r\n // Check if touch is outside dropdown area\r\n const target = e.target as Element;\r\n const isOutsideDropdown =\r\n dropdownRef.current &&\r\n !dropdownRef.current.contains(target) &&\r\n buttonRef.current &&\r\n !buttonRef.current.contains(target);\r\n\r\n // Close if touch ended outside and wasn't a swipe\r\n if (!isSwipe && isOutsideDropdown) {\r\n closeDropdown();\r\n }\r\n\r\n touchStartRef.current = null;\r\n },\r\n [is_mobile, is_open, closeDropdown],\r\n );\r\n\r\n // Set up mobile touch listeners\r\n useEffect(() => {\r\n if (is_mobile && is_open) {\r\n document.addEventListener(\"touchstart\", handleTouchStart);\r\n document.addEventListener(\"touchend\", handleTouchEnd);\r\n\r\n return () => {\r\n document.removeEventListener(\"touchstart\", handleTouchStart);\r\n document.removeEventListener(\"touchend\", handleTouchEnd);\r\n };\r\n }\r\n }, [is_mobile, is_open, handleTouchStart, handleTouchEnd]);\r\n\r\n // Prevent event propagation for dropdown content\r\n const handleDropdownInteraction = useCallback(\r\n (e: React.MouseEvent | React.TouchEvent) => {\r\n e.stopPropagation();\r\n },\r\n [],\r\n );\r\n\r\n // Toggle dropdown\r\n const handleButtonClick = useCallback(\r\n (e: React.MouseEvent) => {\r\n e.stopPropagation();\r\n set_is_open(!is_open);\r\n },\r\n [is_open],\r\n );\r\n\r\n return (\r\n <div className={cn(\"relative z-[100]\", className)} ref={dropdownRef}>\r\n <Button\r\n ref={buttonRef}\r\n type=\"button\"\r\n variant=\"ghost\"\r\n className=\"relative flex items-center gap-2 h-12 px-3 z-[1000]\"\r\n onClick={handleButtonClick}\r\n onTouchEnd={(e) => e.stopPropagation()}\r\n >\r\n {display}\r\n {showArrow && (\r\n <ChevronDown\r\n className={cn(\r\n \"w-4 h-4 text-muted-foreground transition-transform\",\r\n is_open ? \"rotate-180\" : \"\",\r\n )}\r\n />\r\n )}\r\n </Button>\r\n\r\n {is_open && (\r\n <div\r\n className={cn(\r\n \"absolute right-0 mt-2 bg-background border border-border rounded-control-lg overflow-hidden shadow-card z-[1000]\",\r\n is_mobile ? \"w-56\" : \"w-48\", // Slightly wider on mobile for better touch targets\r\n className,\r\n )}\r\n onClick={handleDropdownInteraction}\r\n onTouchStart={handleDropdownInteraction}\r\n onTouchEnd={handleDropdownInteraction}\r\n >\r\n <div\r\n className={cn(\r\n \"relative z-[1000] flex max-h-64 flex-col gap-option-gap overflow-y-auto overscroll-contain p-option-inset [scrollbar-width:thin] [scrollbar-color:var(--color-border-hover)_var(--muted)]\",\r\n is_mobile ? \"max-h-80\" : \"max-h-64\",\r\n )}\r\n >\r\n {content}\r\n\r\n {Children.map(children, (child, index) => {\r\n return (\r\n <DropdownOptionButton key={index} set_is_open={set_is_open}>\r\n {child ? child : <></>}\r\n </DropdownOptionButton>\r\n );\r\n })}\r\n </div>\r\n </div>\r\n )}\r\n </div>\r\n );\r\n};\r\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAuCA;;;AAkBA;AAEA;;;;;AAKG;AACH;AASE;AACA;;AAEA;AAEA;;;;AAKI;;AAKJ;;;AAGA;AAEA;;;AAGA;;AAGE;AACA;;;AAGA;AACE;AACD;AAED;AACE;AACD;;AAGD;AACE;AACA;AACF;AACF;AAEA;;AAGI;AAYN;AAEA;;;;;;AAMG;;;AAGD;;;;;AAUF;AAOA;;;;;AAKG;AACI;AAmBL;;;;;AAMA;AACA;AACA;AACA;AACA;;;;AAIA;AAOA;;AAEE;;;;AAKA;;;;AAGA;AAGA;AACE;;AAEF;AACF;;;;AAKA;AAEA;;AAEG;AACH;;AAGI;;;AAMJ;;AAEG;AACH;;;;AAKE;;;;;AAOF;AAEA;;AAiEc;AACI;;AAEE;;AAEF;;;;;AAMA;;;;;;;AAOE;;;;;;AAWN;AACA;AAIA;AACI;AACA;;AAEE;AACH;AACH;AAgDhB;AAEA;;;;AAIG;;AAgBD;;AAEA;AACA;AACA;;AAOA;;;;;AAME;AACE;AAEE;;AAEA;;AAGA;;AAEJ;AAEA;AACE;;;;;AAOJ;AAEI;;;;;;;;AAQF;AAIF;;;;AAKI;;AAGA;AACA;;;AAIA;AACA;AAEE;AACA;;;AAIF;AACE;;AAGF;;;;AAOF;AACE;AACA;AAEA;AACE;AACA;AACF;;;;AAKJ;;;;AAQA;;AAGI;AACF;;;;AAkDQ;AAMZ;;"}
|
|
@@ -1,14 +1,69 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
|
+
/** What a `FormField` tells the control inside it. */
|
|
3
|
+
export interface FormFieldContextValue {
|
|
4
|
+
/** Id for the control; the label points at it. */
|
|
5
|
+
id: string;
|
|
6
|
+
/** Id of the label element, for controls labelled as a group. */
|
|
7
|
+
labelId: string;
|
|
8
|
+
/** Ids of the help text and error message, space-separated, when shown. */
|
|
9
|
+
describedBy?: string;
|
|
10
|
+
invalid: boolean;
|
|
11
|
+
required: boolean;
|
|
12
|
+
/** The label when it is plain text, for controls that need an accessible name elsewhere (e.g. a phone sheet). */
|
|
13
|
+
labelText?: string;
|
|
14
|
+
}
|
|
15
|
+
/** The surrounding field, or null outside a `FormField`. */
|
|
16
|
+
export declare function useFormField(): FormFieldContextValue | null;
|
|
17
|
+
type ControlAria = {
|
|
18
|
+
id?: string;
|
|
19
|
+
'aria-describedby'?: string;
|
|
20
|
+
'aria-invalid'?: React.AriaAttributes['aria-invalid'];
|
|
21
|
+
'aria-required'?: React.AriaAttributes['aria-required'];
|
|
22
|
+
'aria-labelledby'?: string;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Fills in the id and accessibility links from the surrounding `FormField`.
|
|
26
|
+
* Anything the caller passes explicitly wins. A `group` control (radio group,
|
|
27
|
+
* checkbox group) is named by the label instead of taking the id.
|
|
28
|
+
*/
|
|
29
|
+
export declare function useFormFieldControl<P extends ControlAria>(props: P, kind?: 'control' | 'group'): P;
|
|
30
|
+
/**
|
|
31
|
+
* Hides the surrounding field from the controls inside it. For a component's
|
|
32
|
+
* own internal controls (a year picker inside a date popover, a search box in a
|
|
33
|
+
* phone sheet) so they don't take the field's id.
|
|
34
|
+
*/
|
|
35
|
+
export declare function FormFieldReset({ children }: {
|
|
36
|
+
children: React.ReactNode;
|
|
37
|
+
}): import("react/jsx-runtime").JSX.Element;
|
|
2
38
|
export interface FormFieldProps {
|
|
3
|
-
label?:
|
|
39
|
+
label?: React.ReactNode;
|
|
40
|
+
/** Shows the required mark and tells assistive tech. Defaults to false. */
|
|
4
41
|
required?: boolean;
|
|
42
|
+
/** Help shown from the question-mark icon beside the label. */
|
|
5
43
|
tooltip?: string;
|
|
6
|
-
/** Accepted for compatibility; not used by the Radix tooltip. */
|
|
7
|
-
tooltipId?: string;
|
|
8
44
|
/** Rendered to the right of the label, on the label's own row. */
|
|
9
45
|
labelAddon?: React.ReactNode;
|
|
46
|
+
/** Help text under the control. */
|
|
47
|
+
description?: React.ReactNode;
|
|
48
|
+
/** Error under the control; also marks the control invalid. */
|
|
49
|
+
error?: React.ReactNode;
|
|
50
|
+
/** Id for the control. Generated when omitted. */
|
|
51
|
+
id?: string;
|
|
52
|
+
/**
|
|
53
|
+
* The child is a group of controls (RadioGroup, CheckboxGroup): the label
|
|
54
|
+
* names the group instead of pointing at one control.
|
|
55
|
+
*/
|
|
56
|
+
group?: boolean;
|
|
10
57
|
className?: string;
|
|
11
58
|
children: React.ReactNode;
|
|
12
59
|
}
|
|
13
|
-
/**
|
|
14
|
-
|
|
60
|
+
/**
|
|
61
|
+
* The one labelled form field: label row (label, required mark, tooltip,
|
|
62
|
+
* addon), then the control, then help text and error. Put any plain control
|
|
63
|
+
* inside (Input, Textarea, SelectTrigger, Checkbox, Switch, Autocomplete,
|
|
64
|
+
* GroupableRadioDropdown, DatePicker, MonthPicker, TimeInput, or
|
|
65
|
+
* RadioGroup/CheckboxGroup/ChipSelect with `group`);
|
|
66
|
+
* it picks up the id and links automatically.
|
|
67
|
+
*/
|
|
68
|
+
export declare function FormField({ label, required, tooltip, labelAddon, description, error, id, group, className, children, }: FormFieldProps): import("react/jsx-runtime").JSX.Element;
|
|
69
|
+
export {};
|
|
@@ -1,10 +1,60 @@
|
|
|
1
|
-
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx, jsxs } from 'react/jsx-runtime';
|
|
3
|
+
import * as React from 'react';
|
|
4
|
+
import { cn } from '../utils.js';
|
|
2
5
|
import { Label } from './label.js';
|
|
3
6
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
+
const FormFieldContext = React.createContext(null);
|
|
8
|
+
/** The surrounding field, or null outside a `FormField`. */
|
|
9
|
+
function useFormField() {
|
|
10
|
+
return React.useContext(FormFieldContext);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Fills in the id and accessibility links from the surrounding `FormField`.
|
|
14
|
+
* Anything the caller passes explicitly wins. A `group` control (radio group,
|
|
15
|
+
* checkbox group) is named by the label instead of taking the id.
|
|
16
|
+
*/
|
|
17
|
+
function useFormFieldControl(props, kind = 'control') {
|
|
18
|
+
const field = useFormField();
|
|
19
|
+
if (!field)
|
|
20
|
+
return props;
|
|
21
|
+
return {
|
|
22
|
+
...props,
|
|
23
|
+
...(kind === 'control'
|
|
24
|
+
? { id: props.id ?? field.id }
|
|
25
|
+
: { 'aria-labelledby': props['aria-labelledby'] ?? field.labelId }),
|
|
26
|
+
'aria-describedby': props['aria-describedby'] ?? field.describedBy,
|
|
27
|
+
'aria-invalid': props['aria-invalid'] ?? (field.invalid || undefined),
|
|
28
|
+
'aria-required': props['aria-required'] ?? (field.required || undefined),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Hides the surrounding field from the controls inside it. For a component's
|
|
33
|
+
* own internal controls (a year picker inside a date popover, a search box in a
|
|
34
|
+
* phone sheet) so they don't take the field's id.
|
|
35
|
+
*/
|
|
36
|
+
function FormFieldReset({ children }) {
|
|
37
|
+
return jsx(FormFieldContext.Provider, { value: null, children: children });
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The one labelled form field: label row (label, required mark, tooltip,
|
|
41
|
+
* addon), then the control, then help text and error. Put any plain control
|
|
42
|
+
* inside (Input, Textarea, SelectTrigger, Checkbox, Switch, Autocomplete,
|
|
43
|
+
* GroupableRadioDropdown, DatePicker, MonthPicker, TimeInput, or
|
|
44
|
+
* RadioGroup/CheckboxGroup/ChipSelect with `group`);
|
|
45
|
+
* it picks up the id and links automatically.
|
|
46
|
+
*/
|
|
47
|
+
function FormField({ label, required = false, tooltip, labelAddon, description, error, id, group = false, className, children, }) {
|
|
48
|
+
const generated = React.useId();
|
|
49
|
+
const controlId = id ?? generated;
|
|
50
|
+
const labelId = `${controlId}-label`;
|
|
51
|
+
const descriptionId = description ? `${controlId}-description` : undefined;
|
|
52
|
+
const errorId = error ? `${controlId}-error` : undefined;
|
|
53
|
+
const describedBy = [descriptionId, errorId].filter(Boolean).join(' ') || undefined;
|
|
54
|
+
const labelText = typeof label === 'string' ? label : undefined;
|
|
55
|
+
const value = React.useMemo(() => ({ id: controlId, labelId, describedBy, invalid: !!error, required, labelText }), [controlId, labelId, describedBy, error, required, labelText]);
|
|
56
|
+
return (jsxs("div", { className: cn('min-w-0', className), children: [label ? (jsx(Label, { label: label, required: required, tooltip: tooltip, labelAddon: labelAddon, labelProps: group ? { id: labelId } : { id: labelId, htmlFor: controlId } })) : null, jsx(FormFieldContext.Provider, { value: value, children: children }), 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] }));
|
|
7
57
|
}
|
|
8
58
|
|
|
9
|
-
export { FormField };
|
|
59
|
+
export { FormField, FormFieldReset, useFormField, useFormFieldControl };
|
|
10
60
|
//# sourceMappingURL=form-field.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form-field.js","sources":["../../src/components/form-field.tsx"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"form-field.js","sources":["../../src/components/form-field.tsx"],"sourcesContent":["'use client';\n\nimport * as React from 'react';\n\nimport { cn } from '@/utils';\nimport { Label } from './label';\n\n/** What a `FormField` tells the control inside it. */\nexport interface FormFieldContextValue {\n /** Id for the control; the label points at it. */\n id: string;\n /** Id of the label element, for controls labelled as a group. */\n labelId: string;\n /** Ids of the help text and error message, space-separated, when shown. */\n describedBy?: string;\n invalid: boolean;\n required: boolean;\n /** The label when it is plain text, for controls that need an accessible name elsewhere (e.g. a phone sheet). */\n labelText?: string;\n}\n\nconst FormFieldContext = React.createContext<FormFieldContextValue | null>(null);\n\n/** The surrounding field, or null outside a `FormField`. */\nexport function useFormField() {\n return React.useContext(FormFieldContext);\n}\n\ntype ControlAria = {\n id?: string;\n 'aria-describedby'?: string;\n 'aria-invalid'?: React.AriaAttributes['aria-invalid'];\n 'aria-required'?: React.AriaAttributes['aria-required'];\n 'aria-labelledby'?: string;\n};\n\n/**\n * Fills in the id and accessibility links from the surrounding `FormField`.\n * Anything the caller passes explicitly wins. A `group` control (radio group,\n * checkbox group) is named by the label instead of taking the id.\n */\nexport function useFormFieldControl<P extends ControlAria>(props: P, kind: 'control' | 'group' = 'control'): P {\n const field = useFormField();\n if (!field) return props;\n return {\n ...props,\n ...(kind === 'control'\n ? { id: props.id ?? field.id }\n : { 'aria-labelledby': props['aria-labelledby'] ?? field.labelId }),\n 'aria-describedby': props['aria-describedby'] ?? field.describedBy,\n 'aria-invalid': props['aria-invalid'] ?? (field.invalid || undefined),\n 'aria-required': props['aria-required'] ?? (field.required || undefined),\n };\n}\n\n/**\n * Hides the surrounding field from the controls inside it. For a component's\n * own internal controls (a year picker inside a date popover, a search box in a\n * phone sheet) so they don't take the field's id.\n */\nexport function FormFieldReset({ children }: { children: React.ReactNode }) {\n return <FormFieldContext.Provider value={null}>{children}</FormFieldContext.Provider>;\n}\n\nexport interface FormFieldProps {\n label?: React.ReactNode;\n /** Shows the required mark and tells assistive tech. Defaults to false. */\n required?: boolean;\n /** Help shown from the question-mark icon beside the label. */\n tooltip?: string;\n /** Rendered to the right of the label, on the label's own row. */\n labelAddon?: React.ReactNode;\n /** Help text under the control. */\n description?: React.ReactNode;\n /** Error under the control; also marks the control invalid. */\n error?: React.ReactNode;\n /** Id for the control. Generated when omitted. */\n id?: string;\n /**\n * The child is a group of controls (RadioGroup, CheckboxGroup): the label\n * names the group instead of pointing at one control.\n */\n group?: boolean;\n className?: string;\n children: React.ReactNode;\n}\n\n/**\n * The one labelled form field: label row (label, required mark, tooltip,\n * addon), then the control, then help text and error. Put any plain control\n * inside (Input, Textarea, SelectTrigger, Checkbox, Switch, Autocomplete,\n * GroupableRadioDropdown, DatePicker, MonthPicker, TimeInput, or\n * RadioGroup/CheckboxGroup/ChipSelect with `group`);\n * it picks up the id and links automatically.\n */\nexport function FormField({\n label,\n required = false,\n tooltip,\n labelAddon,\n description,\n error,\n id,\n group = false,\n className,\n children,\n}: FormFieldProps) {\n const generated = React.useId();\n const controlId = id ?? generated;\n const labelId = `${controlId}-label`;\n const descriptionId = description ? `${controlId}-description` : undefined;\n const errorId = error ? `${controlId}-error` : undefined;\n const describedBy = [descriptionId, errorId].filter(Boolean).join(' ') || undefined;\n const labelText = typeof label === 'string' ? label : undefined;\n\n const value = React.useMemo<FormFieldContextValue>(\n () => ({ id: controlId, labelId, describedBy, invalid: !!error, required, labelText }),\n [controlId, labelId, describedBy, error, required, labelText],\n );\n\n return (\n <div className={cn('min-w-0', className)}>\n {label ? (\n <Label\n label={label}\n required={required}\n tooltip={tooltip}\n labelAddon={labelAddon}\n labelProps={group ? { id: labelId } : { id: labelId, htmlFor: controlId }}\n />\n ) : null}\n <FormFieldContext.Provider value={value}>{children}</FormFieldContext.Provider>\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;AAEA;;AAEE;AACF;AAUA;;;;AAIG;;AAED;AACA;AAAY;;AAEV;;;AAGE;;AAEF;AACA;;AAEJ;AAEA;;;;AAIG;AACG;;AAEN;AAyBA;;;;;;;AAOG;AACG;AAYJ;AACA;AACA;AACA;AACA;AACA;AACA;;;AA+BF;;"}
|
package/dist/components/input.js
CHANGED
|
@@ -4,10 +4,12 @@ import * as React from 'react';
|
|
|
4
4
|
import { EyeOff, Eye } from 'lucide-react';
|
|
5
5
|
import { cn } from '../utils.js';
|
|
6
6
|
import { useFieldChromeOwned, useFieldFocus, chain, fieldFocusOutlineClassName, fieldInteractionClassName } from '../hooks/use-field-focus.js';
|
|
7
|
+
import { useFormFieldControl } from './form-field.js';
|
|
7
8
|
|
|
8
9
|
const fieldClassName = 'bg-background pointer-events-auto relative z-10 box-border flex h-form-control min-h-form-control max-h-form-control w-full rounded-control-lg border border-input hover:border-input-hover px-[0.75em] py-0 text-base text-foreground ring-0';
|
|
9
10
|
const fieldDetailsClassName = 'file:text-foreground placeholder:text-muted-foreground/40 file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none aria-invalid:border-destructive disabled:cursor-not-allowed disabled:opacity-50';
|
|
10
|
-
const Input = React.forwardRef(({ className, type, disabled, onPointerDown, onFocus, onBlur, ...
|
|
11
|
+
const Input = React.forwardRef(({ className, type, disabled, onPointerDown, onFocus, onBlur, ...ownProps }, ref) => {
|
|
12
|
+
const props = useFormFieldControl(ownProps);
|
|
11
13
|
const [passwordVisible, setPasswordVisible] = React.useState(false);
|
|
12
14
|
const chromeOwned = useFieldChromeOwned();
|
|
13
15
|
const { keyboardFocus, focusProps } = useFieldFocus();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"input.js","sources":["../../src/components/input.tsx"],"sourcesContent":["'use client';\r\n\r\nimport * as React from 'react';\r\nimport { Eye, EyeOff } from 'lucide-react';\r\n\r\nimport { cn } from '@/utils';\r\nimport {\r\n chain,\r\n fieldFocusOutlineClassName,\r\n fieldInteractionClassName,\r\n useFieldChromeOwned,\r\n useFieldFocus,\r\n} from '@/hooks/use-field-focus';\r\n\r\nconst fieldClassName =\r\n 'bg-background pointer-events-auto relative z-10 box-border flex h-form-control min-h-form-control max-h-form-control w-full rounded-control-lg border border-input hover:border-input-hover px-[0.75em] py-0 text-base text-foreground ring-0';\r\nconst fieldDetailsClassName =\r\n 'file:text-foreground placeholder:text-muted-foreground/40 file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none aria-invalid:border-destructive disabled:cursor-not-allowed disabled:opacity-50';\r\n\r\nconst Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(\r\n ({ className, type, disabled, onPointerDown, onFocus, onBlur, ...
|
|
1
|
+
{"version":3,"file":"input.js","sources":["../../src/components/input.tsx"],"sourcesContent":["'use client';\r\n\r\nimport * as React from 'react';\r\nimport { Eye, EyeOff } from 'lucide-react';\r\n\r\nimport { cn } from '@/utils';\r\nimport {\r\n chain,\r\n fieldFocusOutlineClassName,\r\n fieldInteractionClassName,\r\n useFieldChromeOwned,\r\n useFieldFocus,\r\n} from '@/hooks/use-field-focus';\r\nimport { useFormFieldControl } from './form-field';\r\n\r\nconst fieldClassName =\r\n 'bg-background pointer-events-auto relative z-10 box-border flex h-form-control min-h-form-control max-h-form-control w-full rounded-control-lg border border-input hover:border-input-hover px-[0.75em] py-0 text-base text-foreground ring-0';\r\nconst fieldDetailsClassName =\r\n 'file:text-foreground placeholder:text-muted-foreground/40 file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none aria-invalid:border-destructive disabled:cursor-not-allowed disabled:opacity-50';\r\n\r\nconst Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(\r\n ({ className, type, disabled, onPointerDown, onFocus, onBlur, ...ownProps }, ref) => {\r\n const props = useFormFieldControl(ownProps);\r\n const [passwordVisible, setPasswordVisible] = React.useState(false);\r\n const chromeOwned = useFieldChromeOwned();\r\n const { keyboardFocus, focusProps } = useFieldFocus();\r\n const handlers = {\r\n onPointerDown: chain(onPointerDown, focusProps.onPointerDown),\r\n onFocus: chain(onFocus, focusProps.onFocus),\r\n onBlur: chain(onBlur, focusProps.onBlur),\r\n };\r\n const chrome = !chromeOwned && !disabled && cn(\r\n fieldInteractionClassName,\r\n keyboardFocus && fieldFocusOutlineClassName,\r\n );\r\n\r\n if (type === 'password') {\r\n const Icon = passwordVisible ? EyeOff : Eye;\r\n\r\n return (\r\n // The wrapper carries the lift and outline so the toggle moves with the field.\r\n <div className={cn('relative', chrome)}>\r\n <input\r\n type={passwordVisible ? 'text' : 'password'}\r\n className={cn(fieldClassName, 'pr-10', fieldDetailsClassName, className)}\r\n ref={ref}\r\n disabled={disabled}\r\n {...handlers}\r\n {...props}\r\n />\r\n <button\r\n type=\"button\"\r\n className=\"text-muted-foreground hover:text-foreground absolute inset-y-0 right-0 z-20 flex w-10 items-center justify-center disabled:cursor-not-allowed disabled:opacity-50\"\r\n onClick={() => setPasswordVisible((current) => !current)}\r\n disabled={disabled}\r\n aria-label={passwordVisible ? 'Hide password' : 'Show password'}\r\n aria-pressed={passwordVisible}\r\n >\r\n <Icon className=\"h-4 w-4\" aria-hidden=\"true\" />\r\n </button>\r\n </div>\r\n );\r\n }\r\n\r\n return (\r\n <input\r\n type={type}\r\n className={cn(fieldClassName, fieldDetailsClassName, chrome, className)}\r\n ref={ref}\r\n disabled={disabled}\r\n {...handlers}\r\n {...props}\r\n />\r\n );\r\n },\r\n);\r\nInput.displayName = 'Input';\r\n\r\nexport { Input };\r\n"],"names":[],"mappings":";;;;;;;;AAeA;AAEA;AAGA;AAEI;AACA;AACA;;AAEA;;;;;AAKA;AAKA;;;;;;AA4BA;AAUF;AAEF;;"}
|