@fuf-stack/uniform 1.27.0 → 1.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/Checkboxes/index.d.mts +11 -13
- package/dist/Checkboxes/index.d.mts.map +1 -1
- package/dist/Checkboxes/index.mjs +2 -4
- package/dist/Checkboxes/index.mjs.map +1 -1
- package/dist/DatePicker/index.d.mts +14 -16
- package/dist/DatePicker/index.d.mts.map +1 -1
- package/dist/DatePicker/index.mjs +3 -6
- package/dist/DatePicker/index.mjs.map +1 -1
- package/dist/FieldArray/index.d.mts +2 -8
- package/dist/FieldArray/index.d.mts.map +1 -1
- package/dist/FieldArray/index.mjs +12 -22
- package/dist/FieldArray/index.mjs.map +1 -1
- package/dist/FieldCard/index.d.mts +0 -2
- package/dist/FieldCard/index.d.mts.map +1 -1
- package/dist/FieldCard/index.mjs +5 -8
- package/dist/FieldCard/index.mjs.map +1 -1
- package/dist/{FieldCopyTestIdButton-CRJBix9D.mjs → FieldCopyTestIdButton-Y9SfvaM9.mjs} +4 -6
- package/dist/{FieldCopyTestIdButton-CRJBix9D.mjs.map → FieldCopyTestIdButton-Y9SfvaM9.mjs.map} +1 -1
- package/dist/{FieldValidationError-ByRoIxaM.mjs → FieldValidationError-BcUV0r1I.mjs} +3 -5
- package/dist/{FieldValidationError-ByRoIxaM.mjs.map → FieldValidationError-BcUV0r1I.mjs.map} +1 -1
- package/dist/Form/index.d.mts +1 -3
- package/dist/Form/index.d.mts.map +1 -1
- package/dist/Form/index.mjs +10 -12
- package/dist/Form/index.mjs.map +1 -1
- package/dist/FormContext-B8G_Xxd6.mjs +512 -0
- package/dist/FormContext-B8G_Xxd6.mjs.map +1 -0
- package/dist/FormContext-BnNJYZOo.d.mts +124 -0
- package/dist/FormContext-BnNJYZOo.d.mts.map +1 -0
- package/dist/Grid/index.d.mts +0 -2
- package/dist/Grid/index.d.mts.map +1 -1
- package/dist/Grid/index.mjs +1 -2
- package/dist/{Grid-CTs-Rb9G.mjs → Grid-Us2JFczS.mjs} +3 -5
- package/dist/{Grid-CTs-Rb9G.mjs.map → Grid-Us2JFczS.mjs.map} +1 -1
- package/dist/Input/index.d.mts +21 -19
- package/dist/Input/index.d.mts.map +1 -1
- package/dist/Input/index.mjs +106 -13
- package/dist/Input/index.mjs.map +1 -1
- package/dist/RadioBoxes/index.d.mts +2 -6
- package/dist/RadioBoxes/index.d.mts.map +1 -1
- package/dist/RadioBoxes/index.mjs +3 -6
- package/dist/RadioBoxes/index.mjs.map +1 -1
- package/dist/RadioTabs/index.d.mts +46 -48
- package/dist/RadioTabs/index.d.mts.map +1 -1
- package/dist/RadioTabs/index.mjs +2 -4
- package/dist/RadioTabs/index.mjs.map +1 -1
- package/dist/Radios/index.d.mts +14 -16
- package/dist/Radios/index.d.mts.map +1 -1
- package/dist/Radios/index.mjs +2 -4
- package/dist/Radios/index.mjs.map +1 -1
- package/dist/Select/index.d.mts +5 -7
- package/dist/Select/index.d.mts.map +1 -1
- package/dist/Select/index.mjs +4 -7
- package/dist/Select/index.mjs.map +1 -1
- package/dist/Slider/index.d.mts +31 -33
- package/dist/Slider/index.d.mts.map +1 -1
- package/dist/Slider/index.mjs +2 -4
- package/dist/Slider/index.mjs.map +1 -1
- package/dist/SubmitButton/index.d.mts +0 -2
- package/dist/SubmitButton/index.d.mts.map +1 -1
- package/dist/SubmitButton/index.mjs +2 -4
- package/dist/SubmitButton/index.mjs.map +1 -1
- package/dist/Switch/index.d.mts +16 -18
- package/dist/Switch/index.d.mts.map +1 -1
- package/dist/Switch/index.mjs +2 -4
- package/dist/Switch/index.mjs.map +1 -1
- package/dist/SwitchBox/index.d.mts +35 -37
- package/dist/SwitchBox/index.d.mts.map +1 -1
- package/dist/SwitchBox/index.mjs +2 -4
- package/dist/SwitchBox/index.mjs.map +1 -1
- package/dist/TextArea/index.d.mts +0 -2
- package/dist/TextArea/index.d.mts.map +1 -1
- package/dist/TextArea/index.mjs +2 -4
- package/dist/TextArea/index.mjs.map +1 -1
- package/dist/Time/index.d.mts +0 -2
- package/dist/Time/index.d.mts.map +1 -1
- package/dist/Time/index.mjs +3 -6
- package/dist/Time/index.mjs.map +1 -1
- package/dist/helpers/index.d.mts +0 -6
- package/dist/helpers/index.d.mts.map +1 -1
- package/dist/helpers/index.mjs +3 -6
- package/dist/helpers/index.mjs.map +1 -1
- package/dist/hooks/useClientValidation/index.d.mts +0 -2
- package/dist/hooks/useClientValidation/index.d.mts.map +1 -1
- package/dist/hooks/useClientValidation/index.mjs +3 -5
- package/dist/hooks/useController/index.d.mts +1 -2
- package/dist/hooks/useController/index.mjs +2 -4
- package/dist/hooks/useFormContext/index.d.mts +2 -3
- package/dist/hooks/useFormContext/index.mjs +2 -4
- package/dist/hooks/useInput/index.mjs +2 -4
- package/dist/hooks/useInputValueDebounce/index.d.mts +2 -4
- package/dist/hooks/useInputValueDebounce/index.d.mts.map +1 -1
- package/dist/hooks/useInputValueDebounce/index.mjs +3 -5
- package/dist/hooks/useInputValueDebounce/index.mjs.map +1 -1
- package/dist/hooks/useInputValueTransform/index.d.mts +1 -1
- package/dist/hooks/useInputValueTransform/index.mjs +2 -4
- package/dist/hooks/useUniformField/index.d.mts +2 -98
- package/dist/hooks/useUniformField/index.mjs +11 -11
- package/dist/hooks/useUniformField/index.mjs.map +1 -1
- package/dist/hooks/useUniformFieldArray/index.d.mts +23 -49
- package/dist/hooks/useUniformFieldArray/index.d.mts.map +1 -1
- package/dist/hooks/useUniformFieldArray/index.mjs +3 -5
- package/dist/hooks/useUniformFieldArray/index.mjs.map +1 -1
- package/dist/hooks/useWatchFormReset/index.d.mts +0 -2
- package/dist/hooks/useWatchFormReset/index.d.mts.map +1 -1
- package/dist/hooks/useWatchFormReset/index.mjs +3 -5
- package/dist/hooks/useWatchUserChange/index.d.mts +2 -4
- package/dist/hooks/useWatchUserChange/index.d.mts.map +1 -1
- package/dist/hooks/useWatchUserChange/index.mjs +3 -5
- package/dist/hooks/useWatchUserChange/index.mjs.map +1 -1
- package/dist/index-DaiTW5Bl.d.mts +99 -0
- package/dist/index-DaiTW5Bl.d.mts.map +1 -0
- package/dist/partials/FieldCopyTestIdButton/index.d.mts +0 -2
- package/dist/partials/FieldCopyTestIdButton/index.d.mts.map +1 -1
- package/dist/partials/FieldCopyTestIdButton/index.mjs +1 -2
- package/dist/partials/FieldValidationError/index.d.mts +0 -2
- package/dist/partials/FieldValidationError/index.d.mts.map +1 -1
- package/dist/partials/FieldValidationError/index.mjs +1 -2
- package/dist/{useController-CK39i6HI.mjs → useController-CJjMqXU5.mjs} +3 -4
- package/dist/{useController-CK39i6HI.mjs.map → useController-CJjMqXU5.mjs.map} +1 -1
- package/dist/{useController-DcK2YHbw.d.mts → useController-CdFEp-Wa.d.mts} +2 -4
- package/dist/useController-CdFEp-Wa.d.mts.map +1 -0
- package/dist/{useFormContext-fYWtlnpE.mjs → useFormContext-BEjPBdzb.mjs} +3 -4
- package/dist/useFormContext-BEjPBdzb.mjs.map +1 -0
- package/dist/useFormContext-BhPzFXwF.d.mts +45 -0
- package/dist/useFormContext-BhPzFXwF.d.mts.map +1 -0
- package/dist/useInput-NPbS4w_n.mjs +1 -0
- package/dist/{useInputValueTransform-DJ5zkqSy.mjs → useInputValueTransform-D44BLp1Z.mjs} +2 -3
- package/dist/{useInputValueTransform-DJ5zkqSy.mjs.map → useInputValueTransform-D44BLp1Z.mjs.map} +1 -1
- package/dist/{useInputValueTransform-LOaEim7k.d.mts → useInputValueTransform-cevZBrIN.d.mts} +3 -5
- package/dist/useInputValueTransform-cevZBrIN.d.mts.map +1 -0
- package/package.json +10 -10
- package/dist/FormContext-CsFiNvuJ.d.mts +0 -19
- package/dist/FormContext-CsFiNvuJ.d.mts.map +0 -1
- package/dist/FormContext-gHSwOlcy.mjs +0 -278
- package/dist/FormContext-gHSwOlcy.mjs.map +0 -1
- package/dist/hooks/useUniformField/index.d.mts.map +0 -1
- package/dist/index-CAdGtKE_.d.mts +0 -1
- package/dist/index-D5HVU2jP.d.mts +0 -1
- package/dist/useController-DcK2YHbw.d.mts.map +0 -1
- package/dist/useFormContext-B3QGVVaO.d.mts +0 -66
- package/dist/useFormContext-B3QGVVaO.d.mts.map +0 -1
- package/dist/useFormContext-fYWtlnpE.mjs.map +0 -1
- package/dist/useInput-C0aJaAGe.mjs +0 -2
- package/dist/useInputValueTransform-LOaEim7k.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["DatePicker","HeroDatePicker","DatePicker"],"sources":["../../src/DatePicker/dateHelpers.ts","../../src/DatePicker/DatePicker.tsx","../../src/DatePicker/index.ts"],"sourcesContent":["import type { DatePicker as HeroDatePicker } from '@heroui/date-picker';\nimport type { ComponentProps } from 'react';\n\nimport {\n getLocalTimeZone,\n now,\n parseAbsolute,\n parseAbsoluteToLocal,\n parseDate,\n parseDateTime,\n parseZonedDateTime,\n} from '@internationalized/date';\n\n/** Value type accepted by the HeroUI DatePicker */\nexport type DatePickerValue = ComponentProps<typeof HeroDatePicker>['value'];\n\n/** Cast unknown input to the DatePicker value union type. */\nconst asDatePickerValue = (value: unknown): DatePickerValue => {\n return value as DatePickerValue;\n};\n\n/** Check whether a value already looks like an @internationalized/date object. */\nconst isDateValueLike = (value: unknown): value is object => {\n return !!value && typeof value === 'object' && 'calendar' in value;\n};\n\n/** True for ISO datetime strings that do not yet include timezone information. */\nconst isNaiveDateTimeString = (value: string): boolean => {\n return /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !hasExplicitTimeZone(value);\n};\n\n/** True when an input already carries timezone/offset information. */\nconst hasExplicitTimeZone = (value: string): boolean => {\n if (value.includes('[') && value.includes(']')) {\n return true;\n }\n\n return /(?:[zZ]|[+-]\\d{2}:\\d{2})$/.test(value);\n};\n\n/** Safely run a parser and return `null` on parsing errors. */\nconst tryParse = (parser: () => unknown): DatePickerValue => {\n try {\n return asDatePickerValue(parser());\n } catch {\n return null;\n }\n};\n\n/**\n * Parse a form value into a HeroUI DatePicker compatible `DateValue`.\n *\n * Accepts existing `DateValue` objects, native `Date` instances, and ISO-like\n * strings (date, date-time, zoned, and absolute). Returns `null` when the value\n * is empty or cannot be parsed.\n */\nexport const parseDateValue = (\n value: unknown,\n timeZone?: string,\n): DatePickerValue => {\n if (value == null || value === '') {\n return null;\n }\n\n if (isDateValueLike(value)) {\n return asDatePickerValue(value);\n }\n\n if (value instanceof Date) {\n return asDatePickerValue(\n timeZone\n ? parseAbsolute(value.toISOString(), timeZone)\n : parseAbsoluteToLocal(value.toISOString()),\n );\n }\n\n if (typeof value !== 'string') {\n return null;\n }\n\n const normalizedValue = value.trim();\n if (normalizedValue === '') {\n return null;\n }\n\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(normalizedValue)) {\n return tryParse(() => {\n return parseDate(normalizedValue);\n });\n }\n\n const parsers: (() => unknown)[] = [\n ...(timeZone && isNaiveDateTimeString(normalizedValue)\n ? [\n () => {\n return parseZonedDateTime(`${normalizedValue}[${timeZone}]`);\n },\n ]\n : []),\n () => {\n return timeZone\n ? parseAbsolute(normalizedValue, timeZone)\n : parseAbsoluteToLocal(normalizedValue);\n },\n () => {\n return parseZonedDateTime(normalizedValue);\n },\n () => {\n return parseDateTime(normalizedValue);\n },\n () => {\n return parseDate(normalizedValue);\n },\n ];\n\n return (\n parsers\n .map((parser) => {\n return tryParse(parser);\n })\n .find((parsedValue) => {\n return parsedValue != null;\n }) ?? null\n );\n};\n\n/** Resolve the timezone used by the DatePicker when time fields are enabled. */\nexport const resolveDatePickerTimeZone = (\n withTime: boolean,\n timeZone?: string,\n): string | undefined => {\n if (!withTime) {\n return timeZone;\n }\n\n return timeZone ?? getLocalTimeZone();\n};\n\n/** Build the default placeholder value for time-enabled pickers. */\nexport const getDatePickerPlaceholderValue = (\n withTime: boolean,\n timeZone?: string,\n): DatePickerValue => {\n const resolvedTimeZone = resolveDatePickerTimeZone(withTime, timeZone);\n if (!resolvedTimeZone || !withTime) {\n return undefined;\n }\n\n return asDatePickerValue(now(resolvedTimeZone));\n};\n\n/**\n * Convert a date value into a UTC ISO string.\n *\n * `CalendarDate` and `CalendarDateTime` values are interpreted in the provided\n * timezone. `ZonedDateTime` values use their own timezone and offset.\n */\nexport const dateValueToUtcIsoString = (\n value: DatePickerValue,\n timeZone: string,\n): string | null => {\n if (value == null) {\n return null;\n }\n\n const maybeWithAbsoluteString = value as { toAbsoluteString?: () => string };\n if (typeof maybeWithAbsoluteString.toAbsoluteString === 'function') {\n return maybeWithAbsoluteString.toAbsoluteString();\n }\n\n const maybeWithToDate = value as { toDate?: (zone: string) => Date };\n if (typeof maybeWithToDate.toDate === 'function') {\n return maybeWithToDate.toDate(timeZone).toISOString();\n }\n\n return null;\n};\n","import type { TVClassName, TVProps } from '@fuf-stack/pixel-utils';\nimport type { DatePickerProps as HeroDatePickerProps } from '@heroui/date-picker';\nimport type { ReactNode } from 'react';\nimport type { DatePickerValue } from './dateHelpers';\n\nimport { DatePicker as HeroDatePicker } from '@heroui/date-picker';\n\nimport { tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\n\nimport { useUniformField } from '../hooks/useUniformField';\nimport {\n dateValueToUtcIsoString,\n getDatePickerPlaceholderValue,\n parseDateValue,\n resolveDatePickerTimeZone,\n} from './dateHelpers';\n\nexport const datePickerVariants = tv({\n slots: {\n /** wrapper around the whole date picker */\n base: '',\n /** helper wrapper for error/description */\n helperWrapper: [\n // set padding to 0 for error message exit animation\n 'p-0',\n ],\n /** the calendar element */\n calendar: '',\n /** the calendar's content element */\n calendarContent: '',\n /**\n * inner wrapper (HeroUI inputWrapper slot)\n *\n * NOTE: Unlike HeroUI Input, the DatePicker does not expose a\n * `data-focus` indicator on the group, so the focus border has to be\n * driven by the native `focus-within` state of the segment inputs.\n */\n inputWrapper: 'bg-content1 focus-within:border-focus',\n /** field label */\n label: 'cursor-default',\n /** the calendar popover element */\n popoverContent: '',\n /** selector button element */\n selectorButton: '',\n /** selector icon element */\n selectorIcon: '',\n /** the time-input component element */\n timeInput: '',\n /** the time-input component's label element */\n timeInputLabel: '',\n },\n});\n\ntype VariantProps = TVProps<typeof datePickerVariants>;\ntype ClassName = TVClassName<typeof datePickerVariants>;\n\nexport interface DatePickerProps extends VariantProps {\n /** Custom aria-label for accessibility. If not provided, falls back to field name when no visible label exists */\n ariaLabel?: string;\n /** CSS class name */\n className?: ClassName;\n /** date picker is disabled */\n disabled?: boolean;\n /**\n * Optional hour cycle override.\n *\n * When omitted, the picker uses the user's locale default (12-hour or 24-hour).\n */\n hourCycle?: 12 | 24;\n /** hide timezone abbreviation for zoned values */\n hideTimeZone?: boolean;\n /** form field label */\n label?: ReactNode;\n /** latest selectable value as ISO string */\n maxValue?: string;\n /** earliest selectable value as ISO string */\n minValue?: string;\n /** form field name */\n name: string;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n /**\n * Optional advanced override for the display/interpretation timezone.\n *\n * When omitted, the picker uses the current user's local timezone while\n * `withTime` is enabled.\n */\n timeZone?: string;\n /**\n * Enables date-time mode.\n *\n * - `false` (default): date-only input (`day` granularity)\n * - `true`: includes time segments (`minute` granularity)\n */\n withTime?: boolean;\n /** value format stored in form state (`string` stores UTC ISO values) */\n valueType?: 'dateValue' | 'string';\n}\n\n/**\n * DatePicker component based on [HeroUI DatePicker](https://v2.heroui.com/docs/components/date-picker)\n */\nconst DatePicker = ({\n className: _className = undefined,\n hourCycle = 24,\n hideTimeZone = false,\n maxValue = undefined,\n minValue = undefined,\n name,\n timeZone = undefined,\n valueType = 'string',\n withTime = false,\n ...uniformFieldProps\n}: DatePickerProps) => {\n const {\n ariaLabel,\n disabled,\n errorMessage,\n field: { onBlur, onChange, ref, value },\n invalid,\n label,\n required,\n testId,\n } = useUniformField({ name, ...uniformFieldProps });\n\n // classNames from slots\n const variants = datePickerVariants();\n const classNames = variantsToClassNames(variants, _className, 'base');\n const resolvedTimeZone = resolveDatePickerTimeZone(withTime, timeZone);\n\n // Normalize incoming form value into HeroUI's DateValue shape so the field can\n // render consistently from UTC strings, local strings, Date instances, or DateValue objects.\n const parsedValue = parseDateValue(\n value,\n withTime ? resolvedTimeZone : timeZone,\n );\n\n // Build the default placeholder value for time-enabled pickers.\n const placeholderValue = getDatePickerPlaceholderValue(withTime, timeZone);\n\n // Parse ISO boundary strings into HeroUI DateValue objects.\n const parsedMinValue = parseDateValue(\n minValue,\n withTime ? resolvedTimeZone : timeZone,\n ) as unknown as HeroDatePickerProps['minValue'];\n const parsedMaxValue = parseDateValue(\n maxValue,\n withTime ? resolvedTimeZone : timeZone,\n ) as unknown as HeroDatePickerProps['maxValue'];\n\n // Normalize DatePicker output into the configured storage format before writing to form state.\n const handleChange = (nextValue: DatePickerValue) => {\n if (nextValue == null) {\n onChange(null);\n return;\n }\n\n if (valueType === 'dateValue') {\n onChange(nextValue);\n return;\n }\n\n // String mode always stores UTC ISO values so form state is timezone-neutral\n // and comparable across users/locales.\n onChange(\n dateValueToUtcIsoString(nextValue, resolvedTimeZone ?? 'UTC') ??\n String(nextValue),\n );\n };\n\n return (\n <HeroDatePicker\n ref={ref}\n aria-label={label ? undefined : ariaLabel}\n classNames={{\n base: classNames.base,\n calendar: classNames.calendar,\n calendarContent: classNames.calendarContent,\n helperWrapper: classNames.helperWrapper,\n inputWrapper: classNames.inputWrapper,\n label: classNames.label,\n popoverContent: classNames.popoverContent,\n selectorButton: classNames.selectorButton,\n selectorIcon: classNames.selectorIcon,\n timeInput: classNames.timeInput,\n timeInputLabel: classNames.timeInputLabel,\n }}\n data-testid={testId}\n errorMessage={errorMessage}\n granularity={withTime ? 'minute' : 'day'}\n hideTimeZone={hideTimeZone}\n hourCycle={hourCycle}\n id={testId}\n isDisabled={disabled}\n isInvalid={invalid}\n isRequired={required}\n label={label}\n labelPlacement=\"outside\"\n maxValue={parsedMaxValue}\n minValue={parsedMinValue}\n name={name}\n onBlur={onBlur}\n onChange={handleChange}\n placeholderValue={placeholderValue}\n radius=\"sm\"\n value={parsedValue}\n variant=\"bordered\"\n />\n );\n};\n\nexport default DatePicker;\n","import DatePicker from './DatePicker';\n\nexport type { DatePickerProps } from './DatePicker';\n\nexport { datePickerVariants } from './DatePicker';\n\nexport default DatePicker;\n"],"mappings":";;;;;;;AAiBA,MAAM,qBAAqB,UAAoC;CAC7D,OAAO;AACT;;AAGA,MAAM,mBAAmB,UAAoC;CAC3D,OAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,cAAc;AAC/D;;AAGA,MAAM,yBAAyB,UAA2B;CACxD,OAAO,sBAAsB,KAAK,KAAK,KAAK,CAAC,oBAAoB,KAAK;AACxE;;AAGA,MAAM,uBAAuB,UAA2B;CACtD,IAAI,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,GAAG,GAC3C,OAAO;CAGT,OAAO,4BAA4B,KAAK,KAAK;AAC/C;;AAGA,MAAM,YAAY,WAA2C;CAC3D,IAAI;EACF,OAAO,kBAAkB,OAAO,CAAC;CACnC,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;AASA,MAAa,kBACX,OACA,aACoB;CACpB,IAAI,SAAS,QAAQ,UAAU,IAC7B,OAAO;CAGT,IAAI,gBAAgB,KAAK,GACvB,OAAO,kBAAkB,KAAK;CAGhC,IAAI,iBAAiB,MACnB,OAAO,kBACL,WACI,cAAc,MAAM,YAAY,GAAG,QAAQ,IAC3C,qBAAqB,MAAM,YAAY,CAAC,CAC9C;CAGF,IAAI,OAAO,UAAU,UACnB,OAAO;CAGT,MAAM,kBAAkB,MAAM,KAAK;CACnC,IAAI,oBAAoB,IACtB,OAAO;CAGT,IAAI,sBAAsB,KAAK,eAAe,GAC5C,OAAO,eAAe;EACpB,OAAO,UAAU,eAAe;CAClC,CAAC;CA2BH,OACE;EAxBA,GAAI,YAAY,sBAAsB,eAAe,IACjD,OACQ;GACJ,OAAO,mBAAmB,GAAG,gBAAgB,GAAG,SAAS,EAAE;EAC7D,CACF,IACA,CAAC;QACC;GACJ,OAAO,WACH,cAAc,iBAAiB,QAAQ,IACvC,qBAAqB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Q,UAAU,KAAK,SAChC,SACA,OACA,UACA,WACE,gBAAgB;EAAE;EAAM,GAAG;CAAkB,CAAC;CAGlD,MAAM,WAAW,mBAAmB;CACpC,MAAM,aAAa,qBAAqB,UAAU,YAAY,MAAM;CACpE,MAAM,mBAAmB,0BAA0B,UAAU,QAAQ;CAIrE,MAAM,cAAc,eAClB,OACA,WAAW,mBAAmB,QAChC;CAGA,MAAM,mBAAmB,8BAA8B,UAAU,QAAQ;CAGzE,MAAM,iBAAiB,eACrB,UACA,WAAW,mBAAmB,QAChC;CACA,MAAM,iBAAiB,eACrB,UACA,WAAW,mBAAmB,QAChC;CAGA,MAAM,gBAAgB,cAA+B;EACnD,IAAI,aAAa,MAAM;GACrB,SAAS,IAAI;GACb;EACF;EAEA,IAAI,cAAc,aAAa;GAC7B,SAAS,SAAS;GAClB;EACF;EAIA,SACE,wBAAwB,WAAW,oBAAoB,KAAK,KAC1D,OAAO,SAAS,CACpB;CACF;CAEA,OACE,oBAACC,YAAD;EACO;EACL,cAAY,QAAQ,KAAA,IAAY;EAChC,YAAY;GACV,MAAM,WAAW;GACjB,UAAU,WAAW;GACrB,iBAAiB,WAAW;GAC5B,eAAe,WAAW;GAC1B,cAAc,WAAW;GACzB,OAAO,WAAW;GAClB,gBAAgB,WAAW;GAC3B,gBAAgB,WAAW;GAC3B,cAAc,WAAW;GACzB,WAAW,WAAW;GACtB,gBAAgB,WAAW;EAC7B;EACA,eAAa;EACC;EACd,aAAa,WAAW,WAAW;EACrB;EACH;EACX,IAAI;EACJ,YAAY;EACZ,WAAW;EACX,YAAY;EACL;EACP,gBAAe;EACf,UAAU;EACV,UAAU;EACJ;EACE;EACR,UAAU;EACQ;EAClB,QAAO;EACP,OAAO;EACP,SAAQ;CACT,CAAA;AAEL;;;AC3MA,IAAA,qBAAeC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["DatePicker","HeroDatePicker","DatePicker"],"sources":["../../src/DatePicker/dateHelpers.ts","../../src/DatePicker/DatePicker.tsx","../../src/DatePicker/index.ts"],"sourcesContent":["import type { DatePicker as HeroDatePicker } from '@heroui/date-picker';\nimport type { ComponentProps } from 'react';\n\nimport {\n getLocalTimeZone,\n now,\n parseAbsolute,\n parseAbsoluteToLocal,\n parseDate,\n parseDateTime,\n parseZonedDateTime,\n} from '@internationalized/date';\n\n/** Value type accepted by the HeroUI DatePicker */\nexport type DatePickerValue = ComponentProps<typeof HeroDatePicker>['value'];\n\n/** Cast unknown input to the DatePicker value union type. */\nconst asDatePickerValue = (value: unknown): DatePickerValue => {\n return value as DatePickerValue;\n};\n\n/** Check whether a value already looks like an @internationalized/date object. */\nconst isDateValueLike = (value: unknown): value is object => {\n return !!value && typeof value === 'object' && 'calendar' in value;\n};\n\n/** True for ISO datetime strings that do not yet include timezone information. */\nconst isNaiveDateTimeString = (value: string): boolean => {\n return /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !hasExplicitTimeZone(value);\n};\n\n/** True when an input already carries timezone/offset information. */\nconst hasExplicitTimeZone = (value: string): boolean => {\n if (value.includes('[') && value.includes(']')) {\n return true;\n }\n\n return /(?:[zZ]|[+-]\\d{2}:\\d{2})$/.test(value);\n};\n\n/** Safely run a parser and return `null` on parsing errors. */\nconst tryParse = (parser: () => unknown): DatePickerValue => {\n try {\n return asDatePickerValue(parser());\n } catch {\n return null;\n }\n};\n\n/**\n * Parse a form value into a HeroUI DatePicker compatible `DateValue`.\n *\n * Accepts existing `DateValue` objects, native `Date` instances, and ISO-like\n * strings (date, date-time, zoned, and absolute). Returns `null` when the value\n * is empty or cannot be parsed.\n */\nexport const parseDateValue = (\n value: unknown,\n timeZone?: string,\n): DatePickerValue => {\n if (value == null || value === '') {\n return null;\n }\n\n if (isDateValueLike(value)) {\n return asDatePickerValue(value);\n }\n\n if (value instanceof Date) {\n return asDatePickerValue(\n timeZone\n ? parseAbsolute(value.toISOString(), timeZone)\n : parseAbsoluteToLocal(value.toISOString()),\n );\n }\n\n if (typeof value !== 'string') {\n return null;\n }\n\n const normalizedValue = value.trim();\n if (normalizedValue === '') {\n return null;\n }\n\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(normalizedValue)) {\n return tryParse(() => {\n return parseDate(normalizedValue);\n });\n }\n\n const parsers: (() => unknown)[] = [\n ...(timeZone && isNaiveDateTimeString(normalizedValue)\n ? [\n () => {\n return parseZonedDateTime(`${normalizedValue}[${timeZone}]`);\n },\n ]\n : []),\n () => {\n return timeZone\n ? parseAbsolute(normalizedValue, timeZone)\n : parseAbsoluteToLocal(normalizedValue);\n },\n () => {\n return parseZonedDateTime(normalizedValue);\n },\n () => {\n return parseDateTime(normalizedValue);\n },\n () => {\n return parseDate(normalizedValue);\n },\n ];\n\n return (\n parsers\n .map((parser) => {\n return tryParse(parser);\n })\n .find((parsedValue) => {\n return parsedValue != null;\n }) ?? null\n );\n};\n\n/** Resolve the timezone used by the DatePicker when time fields are enabled. */\nexport const resolveDatePickerTimeZone = (\n withTime: boolean,\n timeZone?: string,\n): string | undefined => {\n if (!withTime) {\n return timeZone;\n }\n\n return timeZone ?? getLocalTimeZone();\n};\n\n/** Build the default placeholder value for time-enabled pickers. */\nexport const getDatePickerPlaceholderValue = (\n withTime: boolean,\n timeZone?: string,\n): DatePickerValue => {\n const resolvedTimeZone = resolveDatePickerTimeZone(withTime, timeZone);\n if (!resolvedTimeZone || !withTime) {\n return undefined;\n }\n\n return asDatePickerValue(now(resolvedTimeZone));\n};\n\n/**\n * Convert a date value into a UTC ISO string.\n *\n * `CalendarDate` and `CalendarDateTime` values are interpreted in the provided\n * timezone. `ZonedDateTime` values use their own timezone and offset.\n */\nexport const dateValueToUtcIsoString = (\n value: DatePickerValue,\n timeZone: string,\n): string | null => {\n if (value == null) {\n return null;\n }\n\n const maybeWithAbsoluteString = value as { toAbsoluteString?: () => string };\n if (typeof maybeWithAbsoluteString.toAbsoluteString === 'function') {\n return maybeWithAbsoluteString.toAbsoluteString();\n }\n\n const maybeWithToDate = value as { toDate?: (zone: string) => Date };\n if (typeof maybeWithToDate.toDate === 'function') {\n return maybeWithToDate.toDate(timeZone).toISOString();\n }\n\n return null;\n};\n","import type { TVClassName, TVProps } from '@fuf-stack/pixel-utils';\nimport type { DatePickerProps as HeroDatePickerProps } from '@heroui/date-picker';\nimport type { ReactNode } from 'react';\nimport type { DatePickerValue } from './dateHelpers';\n\nimport { DatePicker as HeroDatePicker } from '@heroui/date-picker';\n\nimport { tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\n\nimport { useUniformField } from '../hooks/useUniformField';\nimport {\n dateValueToUtcIsoString,\n getDatePickerPlaceholderValue,\n parseDateValue,\n resolveDatePickerTimeZone,\n} from './dateHelpers';\n\nexport const datePickerVariants = tv({\n slots: {\n /** wrapper around the whole date picker */\n base: '',\n /** helper wrapper for error/description */\n helperWrapper: [\n // set padding to 0 for error message exit animation\n 'p-0',\n ],\n /** the calendar element */\n calendar: '',\n /** the calendar's content element */\n calendarContent: '',\n /**\n * inner wrapper (HeroUI inputWrapper slot)\n *\n * NOTE: Unlike HeroUI Input, the DatePicker does not expose a\n * `data-focus` indicator on the group, so the focus border has to be\n * driven by the native `focus-within` state of the segment inputs.\n */\n inputWrapper: 'bg-content1 focus-within:border-focus',\n /** field label */\n label: 'cursor-default',\n /** the calendar popover element */\n popoverContent: '',\n /** selector button element */\n selectorButton: '',\n /** selector icon element */\n selectorIcon: '',\n /** the time-input component element */\n timeInput: '',\n /** the time-input component's label element */\n timeInputLabel: '',\n },\n});\n\ntype VariantProps = TVProps<typeof datePickerVariants>;\ntype ClassName = TVClassName<typeof datePickerVariants>;\n\nexport interface DatePickerProps extends VariantProps {\n /** Custom aria-label for accessibility. If not provided, falls back to field name when no visible label exists */\n ariaLabel?: string;\n /** CSS class name */\n className?: ClassName;\n /** date picker is disabled */\n disabled?: boolean;\n /** hide timezone abbreviation for zoned values */\n hideTimeZone?: boolean;\n /**\n * Optional hour cycle override.\n *\n * When omitted, the picker uses the user's locale default (12-hour or 24-hour).\n */\n hourCycle?: 12 | 24;\n /** form field label */\n label?: ReactNode;\n /** latest selectable value as ISO string */\n maxValue?: string;\n /** earliest selectable value as ISO string */\n minValue?: string;\n /** form field name */\n name: string;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n /**\n * Optional advanced override for the display/interpretation timezone.\n *\n * When omitted, the picker uses the current user's local timezone while\n * `withTime` is enabled.\n */\n timeZone?: string;\n /** value format stored in form state (`string` stores UTC ISO values) */\n valueType?: 'dateValue' | 'string';\n /**\n * Enables date-time mode.\n *\n * - `false` (default): date-only input (`day` granularity)\n * - `true`: includes time segments (`minute` granularity)\n */\n withTime?: boolean;\n}\n\n/**\n * DatePicker component based on [HeroUI DatePicker](https://v2.heroui.com/docs/components/date-picker)\n */\nconst DatePicker = ({\n className: _className = undefined,\n hourCycle = 24,\n hideTimeZone = false,\n maxValue = undefined,\n minValue = undefined,\n name,\n timeZone = undefined,\n valueType = 'string',\n withTime = false,\n ...uniformFieldProps\n}: DatePickerProps) => {\n const {\n ariaLabel,\n disabled,\n errorMessage,\n field: { onBlur, onChange, ref, value },\n invalid,\n label,\n required,\n testId,\n } = useUniformField({ name, ...uniformFieldProps });\n\n // classNames from slots\n const variants = datePickerVariants();\n const classNames = variantsToClassNames(variants, _className, 'base');\n const resolvedTimeZone = resolveDatePickerTimeZone(withTime, timeZone);\n\n // Normalize incoming form value into HeroUI's DateValue shape so the field can\n // render consistently from UTC strings, local strings, Date instances, or DateValue objects.\n const parsedValue = parseDateValue(\n value,\n withTime ? resolvedTimeZone : timeZone,\n );\n\n // Build the default placeholder value for time-enabled pickers.\n const placeholderValue = getDatePickerPlaceholderValue(withTime, timeZone);\n\n // Parse ISO boundary strings into HeroUI DateValue objects.\n const parsedMinValue = parseDateValue(\n minValue,\n withTime ? resolvedTimeZone : timeZone,\n ) as unknown as HeroDatePickerProps['minValue'];\n const parsedMaxValue = parseDateValue(\n maxValue,\n withTime ? resolvedTimeZone : timeZone,\n ) as unknown as HeroDatePickerProps['maxValue'];\n\n // Normalize DatePicker output into the configured storage format before writing to form state.\n const handleChange = (nextValue: DatePickerValue) => {\n if (nextValue == null) {\n onChange(null);\n return;\n }\n\n if (valueType === 'dateValue') {\n onChange(nextValue);\n return;\n }\n\n // String mode always stores UTC ISO values so form state is timezone-neutral\n // and comparable across users/locales.\n onChange(\n dateValueToUtcIsoString(nextValue, resolvedTimeZone ?? 'UTC') ??\n String(nextValue),\n );\n };\n\n return (\n <HeroDatePicker\n ref={ref}\n aria-label={label ? undefined : ariaLabel}\n classNames={{\n base: classNames.base,\n calendar: classNames.calendar,\n calendarContent: classNames.calendarContent,\n helperWrapper: classNames.helperWrapper,\n inputWrapper: classNames.inputWrapper,\n label: classNames.label,\n popoverContent: classNames.popoverContent,\n selectorButton: classNames.selectorButton,\n selectorIcon: classNames.selectorIcon,\n timeInput: classNames.timeInput,\n timeInputLabel: classNames.timeInputLabel,\n }}\n data-testid={testId}\n errorMessage={errorMessage}\n granularity={withTime ? 'minute' : 'day'}\n hideTimeZone={hideTimeZone}\n hourCycle={hourCycle}\n id={testId}\n isDisabled={disabled}\n isInvalid={invalid}\n isRequired={required}\n label={label}\n labelPlacement=\"outside\"\n maxValue={parsedMaxValue}\n minValue={parsedMinValue}\n name={name}\n onBlur={onBlur}\n onChange={handleChange}\n placeholderValue={placeholderValue}\n radius=\"sm\"\n value={parsedValue}\n variant=\"bordered\"\n />\n );\n};\n\nexport default DatePicker;\n","import DatePicker from './DatePicker';\n\nexport type { DatePickerProps } from './DatePicker';\n\nexport { datePickerVariants } from './DatePicker';\n\nexport default DatePicker;\n"],"mappings":";;;;;;;AAiBA,MAAM,qBAAqB,UAAoC;CAC7D,OAAO;AACT;;AAGA,MAAM,mBAAmB,UAAoC;CAC3D,OAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,cAAc;AAC/D;;AAGA,MAAM,yBAAyB,UAA2B;CACxD,OAAO,sBAAsB,KAAK,KAAK,KAAK,CAAC,oBAAoB,KAAK;AACxE;;AAGA,MAAM,uBAAuB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,QAChC;CAGA,MAAM,gBAAgB,cAA+B;EACnD,IAAI,aAAa,MAAM;GACrB,SAAS,IAAI;GACb;EACF;EAEA,IAAI,cAAc,aAAa;GAC7B,SAAS,SAAS;GAClB;EACF;EAIA,SACE,wBAAwB,WAAW,oBAAoB,KAAK,KAC1D,OAAO,SAAS,CACpB;CACF;CAEA,OACE,oBAACC,YAAD;EACO;EACL,cAAY,QAAQ,KAAA,IAAY;EAChC,YAAY;GACV,MAAM,WAAW;GACjB,UAAU,WAAW;GACrB,iBAAiB,WAAW;GAC5B,eAAe,WAAW;GAC1B,cAAc,WAAW;GACzB,OAAO,WAAW;GAClB,gBAAgB,WAAW;GAC3B,gBAAgB,WAAW;GAC3B,cAAc,WAAW;GACzB,WAAW,WAAW;GACtB,gBAAgB,WAAW;EAC7B;EACA,eAAa;EACC;EACd,aAAa,WAAW,WAAW;EACrB;EACH;EACX,IAAI;EACJ,YAAY;EACZ,WAAW;EACX,YAAY;EACL;EACP,gBAAe;EACf,UAAU;EACV,UAAU;EACJ;EACE;EACR,UAAU;EACQ;EAClB,QAAO;EACP,OAAO;EACP,SAAQ;CACT,CAAA;AAEL;;AC3MA,IAAA,qBAAeC"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { TVClassName, TVProps } from "@fuf-stack/pixel-utils";
|
|
2
|
-
import { CSSProperties, JSX
|
|
3
|
-
//#region src/FieldArray/subcomponents/FieldArrayElement.d.ts
|
|
2
|
+
import { CSSProperties, JSX, ReactNode } from "react";
|
|
4
3
|
interface FieldArrayElementMethods {
|
|
5
4
|
/** Add new element at end */
|
|
6
5
|
append: () => void;
|
|
@@ -11,8 +10,6 @@ interface FieldArrayElementMethods {
|
|
|
11
10
|
/** Remove current element */
|
|
12
11
|
remove: () => void;
|
|
13
12
|
}
|
|
14
|
-
//#endregion
|
|
15
|
-
//#region src/FieldArray/types.d.ts
|
|
16
13
|
type VariantProps = TVProps<typeof fieldArrayVariants>;
|
|
17
14
|
type ClassName = TVClassName<typeof fieldArrayVariants>;
|
|
18
15
|
/** provided all data and methods to render a field array element */
|
|
@@ -27,7 +24,7 @@ type FieldArrayChildrenRenderFn = (args: {
|
|
|
27
24
|
name: string;
|
|
28
25
|
/** field name of the current element */
|
|
29
26
|
testId: string;
|
|
30
|
-
}) => JSX
|
|
27
|
+
}) => JSX.Element;
|
|
31
28
|
interface FieldArrayFeatures {
|
|
32
29
|
/** enables duplicating existing elements */
|
|
33
30
|
duplicate?: boolean;
|
|
@@ -56,8 +53,6 @@ interface FieldArrayProps extends FieldArrayFeatures, VariantProps {
|
|
|
56
53
|
/** HTML data-testid attribute used in e2e tests */
|
|
57
54
|
testId?: string;
|
|
58
55
|
}
|
|
59
|
-
//#endregion
|
|
60
|
-
//#region src/FieldArray/FieldArray.d.ts
|
|
61
56
|
export declare const fieldArrayVariants: ((props?: ({
|
|
62
57
|
hasLabel?: boolean | undefined;
|
|
63
58
|
} & ({
|
|
@@ -547,6 +542,5 @@ export declare const fieldArrayVariants: ((props?: ({
|
|
|
547
542
|
* FieldArray component based in [RHF useFieldArray](https://react-hook-form.com/docs/usefieldarray)
|
|
548
543
|
*/
|
|
549
544
|
declare const FieldArray: ({ appendButtonText, children, className: _className, duplicate, elementInitialValue: _elementInitialValue, elementMarginBottom, flat, insertAfter, lastElementNotRemovable, name, sortable, ...uniformFieldProps }: FieldArrayProps) => import("react").JSX.Element;
|
|
550
|
-
//#endregion
|
|
551
545
|
export { type FieldArrayChildrenRenderFn, type FieldArrayFeatures, type FieldArrayProps, FieldArray as default };
|
|
552
546
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/FieldArray/subcomponents/FieldArrayElement.tsx","../../src/FieldArray/types.ts","../../src/FieldArray/FieldArray.tsx"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/FieldArray/subcomponents/FieldArrayElement.tsx","../../src/FieldArray/types.ts","../../src/FieldArray/FieldArray.tsx"],"mappings":";;UAiBiB;;EAEf;;EAEA;;EAEA;;EAEA;;KCpBG,eAAe,eAAe;KAC9B,YAAY,mBAAmB;;KAGxB,8BAA8B;;EAExC;;EAEA;;EAEA,SAAS;;EAET;;EAEA;MACI,IAAI;UAEO;;EAEf;;EAEA;;EAEA;;UAGe,wBAAwB,oBAAoB;;EAE3D;;EAEA,UAAU;;EAEV,YAAY;EAEZ;EAKA,sBAAsB;;EAEtB;;EAEA,QAAQ;;EAER;;EAEA;;EAEA;;qBCzCW,sBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA+FzB,eAAc,kBAAA,UAAA,WAAA,YAAA,WAAA,qBAAA,sBAAA,qBAAA,MAAA,aAAA,yBAAA,MAAA,aAAA,qBAajB,oCAAe,IAAA"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { flatArrayKey } from "../helpers/index.mjs";
|
|
2
|
-
import { n as FieldValidationError } from "../FieldValidationError-
|
|
2
|
+
import { n as FieldValidationError } from "../FieldValidationError-BcUV0r1I.mjs";
|
|
3
3
|
import { useUniformField } from "../hooks/useUniformField/index.mjs";
|
|
4
4
|
import { useUniformFieldArray } from "../hooks/useUniformFieldArray/index.mjs";
|
|
5
|
-
import { t as Grid_default } from "../Grid-
|
|
5
|
+
import { t as Grid_default } from "../Grid-Us2JFczS.mjs";
|
|
6
6
|
import { cn, tv, variantsToClassNames } from "@fuf-stack/pixel-utils";
|
|
7
7
|
import { useState } from "react";
|
|
8
8
|
import { Button, Menu } from "@fuf-stack/pixels";
|
|
@@ -15,7 +15,7 @@ import { CSS } from "@dnd-kit/utilities";
|
|
|
15
15
|
import { VscInsert } from "react-icons/vsc";
|
|
16
16
|
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors } from "@dnd-kit/core";
|
|
17
17
|
import { restrictToVerticalAxis, restrictToWindowEdges } from "@dnd-kit/modifiers";
|
|
18
|
-
|
|
18
|
+
// src/FieldArray/subcomponents/ElementAppendButton.tsx
|
|
19
19
|
const ElementAppendButton = ({ appendButtonText = "Add Element", className = void 0, onClick, testId = void 0 }) => {
|
|
20
20
|
return /* @__PURE__ */ jsxs(Button, {
|
|
21
21
|
className: cn(className),
|
|
@@ -27,8 +27,7 @@ const ElementAppendButton = ({ appendButtonText = "Add Element", className = voi
|
|
|
27
27
|
children: [/* @__PURE__ */ jsx(FaPlus, {}), /* @__PURE__ */ jsx("span", { children: appendButtonText })]
|
|
28
28
|
});
|
|
29
29
|
};
|
|
30
|
-
|
|
31
|
-
//#region src/FieldArray/subcomponents/ElementActionsMenu.tsx
|
|
30
|
+
// src/FieldArray/subcomponents/ElementActionsMenu.tsx
|
|
32
31
|
/**
|
|
33
32
|
* Menu component for field array element actions (remove, duplicate, insert after)
|
|
34
33
|
*/
|
|
@@ -75,8 +74,7 @@ const ElementActionsMenu = ({ className = void 0, duplicate = false, insertAfter
|
|
|
75
74
|
}
|
|
76
75
|
});
|
|
77
76
|
};
|
|
78
|
-
|
|
79
|
-
//#region src/FieldArray/subcomponents/ElementRemoveButton.tsx
|
|
77
|
+
// src/FieldArray/subcomponents/ElementRemoveButton.tsx
|
|
80
78
|
const ElementRemoveButton = ({ className = void 0, disableAnimation = false, onClick, testId = void 0 }) => {
|
|
81
79
|
const button = /* @__PURE__ */ jsx(Button, {
|
|
82
80
|
ariaLabel: "remove element",
|
|
@@ -107,8 +105,7 @@ const ElementRemoveButton = ({ className = void 0, disableAnimation = false, onC
|
|
|
107
105
|
children: button
|
|
108
106
|
});
|
|
109
107
|
};
|
|
110
|
-
|
|
111
|
-
//#region src/FieldArray/subcomponents/SortDragHandle.tsx
|
|
108
|
+
// src/FieldArray/subcomponents/SortDragHandle.tsx
|
|
112
109
|
/**
|
|
113
110
|
* Drag handle component that integrates with dnd-kit sortable functionality.
|
|
114
111
|
* Renders a vertical grip icon that can be used to reorder items.
|
|
@@ -123,8 +120,7 @@ const SortDragHandle = ({ className = void 0, id, testId = void 0 }) => {
|
|
|
123
120
|
children: /* @__PURE__ */ jsx(FaGripVertical, {})
|
|
124
121
|
});
|
|
125
122
|
};
|
|
126
|
-
|
|
127
|
-
//#region src/FieldArray/subcomponents/FieldArrayElement.tsx
|
|
123
|
+
// src/FieldArray/subcomponents/FieldArrayElement.tsx
|
|
128
124
|
/**
|
|
129
125
|
* Form array element component using react-hook-form with drag-drop sorting
|
|
130
126
|
* and validation capabilities. Animations when elements are added or removed
|
|
@@ -227,8 +223,7 @@ const FieldArrayElement = ({ children, className, disableAnimation = false, dupl
|
|
|
227
223
|
}, id) : null
|
|
228
224
|
});
|
|
229
225
|
};
|
|
230
|
-
|
|
231
|
-
//#region src/FieldArray/subcomponents/FieldArrayLabel.tsx
|
|
226
|
+
// src/FieldArray/subcomponents/FieldArrayLabel.tsx
|
|
232
227
|
/**
|
|
233
228
|
* Renders the label for a FieldArray component.
|
|
234
229
|
*
|
|
@@ -250,8 +245,7 @@ const FieldArrayLabel = ({ className = void 0, label: _label, name }) => {
|
|
|
250
245
|
children: label
|
|
251
246
|
});
|
|
252
247
|
};
|
|
253
|
-
|
|
254
|
-
//#region src/FieldArray/subcomponents/FieldArrayValidationError.tsx
|
|
248
|
+
// src/FieldArray/subcomponents/FieldArrayValidationError.tsx
|
|
255
249
|
/**
|
|
256
250
|
* Renders array-level validation errors for FieldArray.
|
|
257
251
|
*
|
|
@@ -300,8 +294,7 @@ const FieldArrayValidationError = ({ name }) => {
|
|
|
300
294
|
}, "field-array-errors") : null
|
|
301
295
|
});
|
|
302
296
|
};
|
|
303
|
-
|
|
304
|
-
//#region src/FieldArray/subcomponents/SortContext.tsx
|
|
297
|
+
// src/FieldArray/subcomponents/SortContext.tsx
|
|
305
298
|
/**
|
|
306
299
|
* A wrapper component that provides drag-and-drop sorting functionality for field arrays
|
|
307
300
|
* using dnd-kit and react-hook-form.
|
|
@@ -343,8 +336,7 @@ const SortContext = ({ children, fields, move, name, sortable }) => {
|
|
|
343
336
|
})
|
|
344
337
|
});
|
|
345
338
|
};
|
|
346
|
-
|
|
347
|
-
//#region src/FieldArray/FieldArray.tsx
|
|
339
|
+
// src/FieldArray/FieldArray.tsx
|
|
348
340
|
const fieldArrayVariants = tv({
|
|
349
341
|
slots: {
|
|
350
342
|
/** base class for the field array wrapper */
|
|
@@ -483,10 +475,8 @@ const FieldArray = ({ appendButtonText = "Add Element", children, className: _cl
|
|
|
483
475
|
]
|
|
484
476
|
});
|
|
485
477
|
};
|
|
486
|
-
|
|
487
|
-
//#region src/FieldArray/index.ts
|
|
478
|
+
// src/FieldArray/index.ts
|
|
488
479
|
var FieldArray_default = FieldArray;
|
|
489
|
-
//#endregion
|
|
490
480
|
export { FieldArray_default as default, fieldArrayVariants };
|
|
491
481
|
|
|
492
482
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["Grid"],"sources":["../../src/FieldArray/subcomponents/ElementAppendButton.tsx","../../src/FieldArray/subcomponents/ElementActionsMenu.tsx","../../src/FieldArray/subcomponents/ElementRemoveButton.tsx","../../src/FieldArray/subcomponents/SortDragHandle.tsx","../../src/FieldArray/subcomponents/FieldArrayElement.tsx","../../src/FieldArray/subcomponents/FieldArrayLabel.tsx","../../src/FieldArray/subcomponents/FieldArrayValidationError.tsx","../../src/FieldArray/subcomponents/SortContext.tsx","../../src/FieldArray/FieldArray.tsx","../../src/FieldArray/index.ts"],"sourcesContent":["import type { ClassValue } from '@fuf-stack/pixel-utils';\n\nimport { FaPlus } from 'react-icons/fa';\n\nimport { cn } from '@fuf-stack/pixel-utils';\nimport { Button } from '@fuf-stack/pixels';\n\ninterface ElementAppendButtonProps {\n /** text of the append element button */\n appendButtonText?: string;\n /** CSS class name */\n className?: ClassValue;\n /** click handler */\n onClick: () => void;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\nconst ElementAppendButton = ({\n appendButtonText = 'Add Element',\n className = undefined,\n onClick,\n testId = undefined,\n}: ElementAppendButtonProps) => {\n return (\n <Button\n className={cn(className)}\n disableAnimation\n onClick={onClick}\n size=\"sm\"\n testId={testId}\n variant=\"light\"\n >\n <FaPlus />\n <span>{appendButtonText}</span>\n </Button>\n );\n};\n\nexport default ElementAppendButton;\n","import type { ClassValue } from '@fuf-stack/pixel-utils';\nimport type { MenuItem } from '@fuf-stack/pixels';\nimport type { Key } from 'react';\nimport type { FieldArrayElementMethods } from './FieldArrayElement';\n\nimport { FaCopy, FaTimes } from 'react-icons/fa';\nimport { VscInsert } from 'react-icons/vsc';\n\nimport { cn } from '@fuf-stack/pixel-utils';\nimport { Menu } from '@fuf-stack/pixels';\n\nexport interface ElementActionsMenuProps {\n /** CSS class name */\n className?: ClassValue;\n /** Whether duplicate action is available */\n duplicate?: boolean;\n /** Whether insert after action is available */\n insertAfter?: boolean;\n /** Whether to show remove button (false when last element is not deletable) */\n showRemove?: boolean;\n /** Field array operation methods */\n methods: FieldArrayElementMethods;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\n/**\n * Menu component for field array element actions (remove, duplicate, insert after)\n */\nconst ElementActionsMenu = ({\n className = undefined,\n duplicate = false,\n insertAfter = false,\n showRemove = true,\n methods,\n testId = undefined,\n}: ElementActionsMenuProps) => {\n const handleAction = (key: Key) => {\n switch (key) {\n case 'remove':\n methods.remove();\n break;\n case 'duplicate':\n methods.duplicate();\n break;\n case 'insertAfter':\n methods.insert();\n break;\n default:\n break;\n }\n };\n\n // Build menu items based on available actions\n const menuItems: MenuItem[] = [];\n\n if (duplicate) {\n menuItems.push({\n key: 'duplicate',\n label: 'Duplicate',\n icon: <FaCopy />,\n });\n }\n\n if (insertAfter) {\n menuItems.push({\n key: 'insertAfter',\n label: 'Insert After',\n icon: <VscInsert />,\n });\n }\n\n if (showRemove) {\n menuItems.push({\n key: 'remove',\n className: 'text-danger',\n label: 'Remove',\n icon: <FaTimes />,\n });\n }\n\n return (\n <Menu\n ariaLabel=\"Element actions\"\n items={menuItems}\n onAction={handleAction}\n placement=\"right\"\n testId={testId}\n triggerButtonProps={{\n className: cn(className),\n disableRipple: true,\n size: 'md',\n variant: 'light',\n }}\n />\n );\n};\n\nexport default ElementActionsMenu;\n","import type { ClassValue } from '@fuf-stack/pixel-utils';\n\nimport { FaTimes } from 'react-icons/fa';\n\nimport { motion } from '@fuf-stack/pixel-motion';\nimport { cn } from '@fuf-stack/pixel-utils';\nimport { Button } from '@fuf-stack/pixels';\n\ninterface ElementRemoveButtonProps {\n /** CSS class name */\n className?: ClassValue;\n /** Globally disable animations (used for first render or prefers-reduced-motion) */\n disableAnimation?: boolean;\n /** click handler */\n onClick: () => void;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\nconst ElementRemoveButton = ({\n className = undefined,\n disableAnimation = false,\n onClick,\n testId = undefined,\n}: ElementRemoveButtonProps) => {\n const button = (\n <Button\n ariaLabel=\"remove element\"\n className={cn(className)}\n color=\"danger\"\n icon={<FaTimes />}\n onClick={onClick}\n size=\"sm\"\n testId={testId}\n variant=\"light\"\n />\n );\n\n if (disableAnimation) {\n return button;\n }\n\n return (\n <motion.div\n animate={{ opacity: 1, width: 'auto' }}\n className=\"flex\"\n exit={{ opacity: 0, width: 0 }}\n initial={{ opacity: 0, width: 0 }}\n transition={{ duration: 0.2 }}\n >\n {button}\n </motion.div>\n );\n};\n\nexport default ElementRemoveButton;\n","import type { ClassValue } from '@fuf-stack/pixel-utils';\n\nimport { FaGripVertical } from 'react-icons/fa';\n\nimport { useSortable } from '@dnd-kit/sortable';\n\nimport { cn } from '@fuf-stack/pixel-utils';\n\ninterface SortDragHandleProps {\n /** Optional CSS class name */\n className?: ClassValue;\n /** Unique identifier for sortable item */\n id: string | number;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\n/**\n * Drag handle component that integrates with dnd-kit sortable functionality.\n * Renders a vertical grip icon that can be used to reorder items.\n */\nconst SortDragHandle = ({\n className = undefined,\n id,\n testId = undefined,\n}: SortDragHandleProps) => {\n // Get dnd-kit sortable attributes and listeners\n const { attributes, listeners } = useSortable({ id });\n\n return (\n <div\n className={cn(className)}\n data-testid={testId}\n {...attributes}\n {...listeners}\n >\n <FaGripVertical />\n </div>\n );\n};\n\nexport default SortDragHandle;\n","import type { Variants as MotionVariants } from '@fuf-stack/pixel-motion';\nimport type { ClassValue } from '@fuf-stack/pixel-utils';\nimport type { FieldArrayFeatures } from '../types';\n\nimport { useState } from 'react';\n\nimport { useSortable } from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\n\nimport { AnimatePresence, motion } from '@fuf-stack/pixel-motion';\nimport { cn } from '@fuf-stack/pixel-utils';\n\nimport Grid from '../../Grid';\nimport ElementActionsMenu from './ElementActionsMenu';\nimport ElementRemoveButton from './ElementRemoveButton';\nimport SortDragHandle from './SortDragHandle';\n\nexport interface FieldArrayElementMethods {\n /** Add new element at end */\n append: () => void;\n /** Clone current element */\n duplicate: () => void;\n /** Add new element after current */\n insert: () => void;\n /** Remove current element */\n remove: () => void;\n}\n\ninterface FieldArrayElementProps extends FieldArrayFeatures {\n /** Form elements to render inside array element */\n children: React.ReactNode;\n /** CSS class names for component parts */\n className: {\n /** Class of wrapper grid inside the li that wraps the rendered element fields directly */\n elementFieldsGrid?: ClassValue;\n /** Class for the li (performs motion animations) */\n listItem?: ClassValue;\n /** Class for the li inner div (wraps the rendered element fields) */\n listItemInner?: ClassValue;\n /** Class for the actions menu button */\n actionsMenuButton?: ClassValue;\n /** Class for the remove element button (when menu is not used) */\n removeButton?: ClassValue;\n /** Class for the drag handle when sorting enabled */\n sortDragHandle?: ClassValue;\n };\n /** Globally disable animations for this item (used for first render or prefers-reduced-motion) */\n disableAnimation?: boolean;\n /** Bottom margin for elements (for backwards compatibility) */\n elementMarginBottom?: React.CSSProperties['marginBottom'];\n /** All fields in the form array */\n fields: Record<'id', string>[];\n /** Unique identifier for drag/drop */\n id: string | number;\n /** Field index in array */\n index: number;\n /** Prevent deletion of last remaining element */\n lastNotDeletable?: boolean;\n /** Field array operation methods */\n methods: FieldArrayElementMethods;\n /** HTML data-testid of the element */\n testId?: string;\n}\n\n/**\n * Form array element component using react-hook-form with drag-drop sorting\n * and validation capabilities. Animations when elements are added or removed\n * improve the user experience and provide a better visual feedback.\n */\nconst FieldArrayElement = ({\n children,\n className,\n disableAnimation = false,\n duplicate = false,\n elementMarginBottom: _elementMarginBottom = undefined,\n fields,\n id,\n index: _index,\n insertAfter = false,\n lastNotDeletable = true,\n methods,\n sortable = false,\n testId = undefined,\n}: FieldArrayElementProps) => {\n // Apply transform styles when sortable is enabled for smooth drag animations\n // transform: handles the item's position during drag\n // transition: controls the animation timing when dropping\n const { setNodeRef, transform, transition, isDragging } = useSortable({ id });\n const sortingStyle = sortable\n ? {\n transform: CSS.Translate.toString(transform),\n transition,\n zIndex: isDragging ? 50 : undefined,\n }\n : undefined;\n\n // Local visibility to allow exit animation before removing from RHF state\n const [isVisible, setIsVisible] = useState(true);\n\n // Motion variants for the list item\n const listItemMotionVariants: MotionVariants = {\n hidden: { opacity: 0, height: 0, marginBottom: 0 },\n visible: {\n opacity: 1,\n height: 'auto',\n transition: { duration: 0.2, ease: 'circOut' },\n // push last visible item down to overlap with append button (hide double border)\n marginBottom: '-1px',\n },\n exit: {\n opacity: 0,\n height: 0,\n marginBottom: 0,\n transition: {\n // on exit first fade out, then shrink\n opacity: { duration: 0.1, ease: 'circOut' },\n height: { delay: 0.1, duration: 0.2, ease: 'circOut' },\n },\n },\n };\n\n // Height animation handled on <motion.li> using overflow hidden\n return (\n <AnimatePresence\n mode=\"wait\"\n // remove from RHF state after exit animation\n onExitComplete={() => {\n methods.remove();\n }}\n >\n {isVisible ? (\n <motion.li\n key={id}\n ref={setNodeRef}\n animate={disableAnimation ? undefined : 'visible'}\n className={cn(className.listItem)}\n data-dragging={isDragging}\n data-testid={`${testId}_element`}\n exit={disableAnimation ? undefined : 'exit'}\n initial={disableAnimation ? false : 'hidden'}\n style={sortingStyle}\n variants={disableAnimation ? undefined : listItemMotionVariants}\n >\n <div className={cn(className.listItemInner)}>\n {/** sorting drag handle */}\n {sortable ? (\n <SortDragHandle\n className={className.sortDragHandle}\n id={id}\n testId={`${testId}_sort_drag_handle`}\n />\n ) : null}\n\n {/** render element fields in Grid component */}\n <Grid\n className={cn(className.elementFieldsGrid)}\n testId={`${testId}_element_fields_grid`}\n >\n {/* render actual fields */}\n {children}\n </Grid>\n\n {/** actions menu when duplicate or insertAfter is enabled */}\n {duplicate || insertAfter ? (\n <ElementActionsMenu\n className={className.actionsMenuButton}\n duplicate={duplicate}\n insertAfter={insertAfter}\n methods={{\n ...methods,\n remove: () => {\n if (disableAnimation) {\n methods.remove();\n } else {\n setIsVisible(false);\n }\n },\n }}\n showRemove={!(lastNotDeletable && fields.length === 1)}\n testId={`${testId}_actions_menu`}\n />\n ) : (\n <>\n {/** remove element button (when menu is not used) */}\n <AnimatePresence initial={false}>\n {lastNotDeletable && fields.length === 1 ? null : (\n <ElementRemoveButton\n key=\"remove-button\"\n className={className.removeButton}\n disableAnimation={disableAnimation}\n onClick={() => {\n if (disableAnimation) {\n methods.remove();\n } else {\n setIsVisible(false);\n }\n }}\n testId={`${testId}_remove_button`}\n />\n )}\n </AnimatePresence>\n </>\n )}\n </div>\n </motion.li>\n ) : null}\n </AnimatePresence>\n );\n};\n\nexport default FieldArrayElement;\n","import type { ReactNode } from 'react';\n\nimport { cn } from '@fuf-stack/pixel-utils';\n\nimport { useUniformField } from '../../hooks/useUniformField';\n\nexport interface FieldArrayLabelProps {\n /** CSS class name */\n className?: string;\n /** Label content */\n label: ReactNode;\n /** Field name */\n name: string;\n}\n\n/**\n * Renders the label for a FieldArray component.\n *\n * This component handles displaying the array label with proper accessibility\n * attributes using the label props from useUniformField.\n */\nconst FieldArrayLabel = ({\n className = undefined,\n label: _label,\n name,\n}: FieldArrayLabelProps) => {\n const { error, getLabelProps, invalid, label } = useUniformField({\n name,\n label: _label,\n });\n\n // when no label is provided, don't render anything\n if (!_label) {\n return null;\n }\n\n // @ts-expect-error - error._errors exists but not typed\n const hasErrors = invalid && error?._errors;\n\n return (\n <div\n {...getLabelProps()}\n aria-level={3}\n className={cn(getLabelProps()?.className, className, {\n // when there are no array level errors, the label should have foreground color\n 'text-foreground!': !hasErrors,\n })}\n role=\"heading\"\n >\n {label}\n </div>\n );\n};\n\nexport default FieldArrayLabel;\n","import {\n AnimatePresence,\n motion,\n useReducedMotion,\n} from '@fuf-stack/pixel-motion';\nimport { cn } from '@fuf-stack/pixel-utils';\n\nimport { useUniformField } from '../../hooks/useUniformField';\nimport FieldValidationError from '../../partials/FieldValidationError/FieldValidationError';\n\nexport interface FieldArrayValidationErrorProps {\n /** Field name */\n name: string;\n}\n\n/**\n * Renders array-level validation errors for FieldArray.\n *\n * This component handles validation errors that apply to the entire array\n * (e.g., \"Array must contain at least 3 elements\", \"Array elements are not unique\"),\n * as opposed to field-level errors which apply to individual array elements.\n *\n * The component wraps errors in the proper accessibility markup and animates\n * them in/out using Framer Motion when they appear or are resolved.\n */\nconst FieldArrayValidationError = ({\n name,\n}: FieldArrayValidationErrorProps) => {\n const {\n error,\n getErrorMessageProps,\n getHelperWrapperProps,\n invalid,\n testId,\n } = useUniformField({\n name,\n });\n\n // disable all animation if user prefers reduced motion\n const disableAnimation = useReducedMotion();\n\n // @ts-expect-error - error._errors exists but not typed\n const hasErrors = invalid && error?._errors;\n\n return (\n <AnimatePresence initial={!disableAnimation}>\n {hasErrors ? (\n <motion.div\n key=\"field-array-errors\"\n animate={\n disableAnimation ? undefined : { opacity: 1, height: 'auto' }\n }\n exit={disableAnimation ? undefined : { opacity: 0, height: 0 }}\n initial={disableAnimation ? false : { height: 0, opacity: 0 }}\n style={{ overflow: 'hidden' }}\n transition={{ duration: 0.4, ease: 'circOut' }}\n >\n <div\n {...getHelperWrapperProps()}\n className={cn(\n getHelperWrapperProps()?.className,\n // force helper to be visible and add padding (pt-1 to compensate for inner content's top padding)\n 'block px-3 pb-2 pt-1',\n )}\n >\n <div {...getErrorMessageProps()}>\n <FieldValidationError\n // @ts-expect-error - error._errors exists but not typed\n error={error._errors}\n testId={testId}\n />\n </div>\n </div>\n </motion.div>\n ) : null}\n </AnimatePresence>\n );\n};\n\nexport default FieldArrayValidationError;\n","import type { DragEndEvent } from '@dnd-kit/core';\nimport type { ReactNode } from 'react';\nimport type { UseFieldArrayMove } from 'react-hook-form';\n\nimport { useFormContext } from 'react-hook-form';\n\nimport {\n closestCenter,\n DndContext,\n KeyboardSensor,\n PointerSensor,\n useSensor,\n useSensors,\n} from '@dnd-kit/core';\nimport {\n restrictToVerticalAxis,\n restrictToWindowEdges,\n} from '@dnd-kit/modifiers';\nimport {\n SortableContext,\n verticalListSortingStrategy,\n} from '@dnd-kit/sortable';\n\ninterface SortContextProps {\n /** child components */\n children: ReactNode;\n /** Array of objects containing unique IDs for sortable items */\n fields: Record<'id', string>[];\n /** name of the field array */\n name: string;\n /** react-hook-form's move function to update field array indices */\n move: UseFieldArrayMove;\n /** enable/disable sorting functionality */\n sortable: boolean;\n}\n\n/**\n * A wrapper component that provides drag-and-drop sorting functionality for field arrays\n * using dnd-kit and react-hook-form.\n *\n * This component integrates with react-hook-form's field arrays to enable vertical\n * drag-and-drop reordering of form fields. It supports both pointer (mouse/touch)\n * and keyboard interactions for accessibility.\n */\nconst SortContext = ({\n children,\n fields,\n move,\n name,\n sortable,\n}: SortContextProps): ReactNode => {\n const { trigger } = useFormContext();\n\n // Initialize sensors for both pointer (mouse/touch) and keyboard interactions\n const sensors = useSensors(\n useSensor(PointerSensor),\n useSensor(KeyboardSensor),\n );\n\n // Early return if sorting is disabled\n if (!sortable) {\n return children;\n }\n\n /**\n * Handles the end of a drag operation by updating field positions\n * @param event - The drag end event containing active and over elements\n */\n const handleDragEnd = (event: DragEndEvent) => {\n const { active, over } = event;\n\n // Only move if dropping over a different item\n if (active.id !== over?.id) {\n // Find the indices of the dragged item and drop target\n const oldIndex = fields.findIndex((field) => {\n return field.id === active.id;\n });\n const newIndex = fields.findIndex((field) => {\n return field.id === over?.id;\n });\n // Update the field array order using react-hook-form's move function\n move(oldIndex, newIndex);\n\n // Finally trigger validation for the array field,\n // so validation errors are updated for the new order\n trigger(name);\n }\n };\n\n return (\n <DndContext\n collisionDetection={closestCenter}\n modifiers={[restrictToVerticalAxis, restrictToWindowEdges]}\n onDragEnd={handleDragEnd}\n sensors={sensors}\n >\n <SortableContext\n items={fields.map((field) => {\n return field.id;\n })}\n strategy={verticalListSortingStrategy}\n >\n {children}\n </SortableContext>\n </DndContext>\n );\n};\n\nexport default SortContext;\n","import type { FieldArrayElementMethods } from './subcomponents/FieldArrayElement';\nimport type { FieldArrayProps } from './types';\n\nimport { cn, tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\n\nimport { flatArrayKey } from '../helpers';\nimport { useUniformFieldArray } from '../hooks/useUniformFieldArray';\nimport ElementAppendButton from './subcomponents/ElementAppendButton';\nimport FieldArrayElement from './subcomponents/FieldArrayElement';\nimport FieldArrayLabel from './subcomponents/FieldArrayLabel';\nimport FieldArrayValidationError from './subcomponents/FieldArrayValidationError';\nimport SortContext from './subcomponents/SortContext';\n\nexport const fieldArrayVariants = tv({\n slots: {\n /** base class for the field array wrapper */\n base: [\n // base styles\n 'overflow-hidden rounded-small border border-divider bg-content1',\n // divider between items\n 'divide-y divide-divider',\n ],\n /** class for the actions menu button */\n actionsMenuButton: [\n // base styles\n 'flex items-center justify-center text-default-600',\n // fixed height/no round corners/center align\n 'h-full rounded-none',\n // focus styles - inset ring\n 'outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus',\n ],\n /** class for the append button */\n appendButton: [\n // base styles\n 'w-full justify-start rounded-b-small rounded-t-none font-semibold',\n // match label height (p-3 = 12px vertical padding + text-base line height)\n '!h-[48px] !min-h-0',\n // focus styles - inset ring with rounded bottom corners to match container\n 'outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus',\n ],\n /** class for the element fields grid */\n elementFieldsGrid: ['w-full grow p-3'],\n /** class for the label */\n label: [\n // override HeroUI label positioning and display\n 'pointer-events-auto! static! z-auto! block! w-full!',\n // reset any transforms or translations\n 'translate-x-0! translate-y-0! transform-none!',\n // card header styling - use text-medium (16px) instead of text-base for correct 48px height\n 'rounded-t-small p-3 font-semibold text-medium',\n ],\n /** class for the list */\n list: ['overflow-hidden'],\n /** class for the list wrapper */\n listWrapper: ['overflow-hidden'],\n /** class for the list item (performs motion animations) */\n listItem: [\n // base styles\n 'group relative flex flex-row',\n // overlap borders by shifting first item up 1px (similar to how last item overlaps with append button)\n 'first:-mt-px',\n ],\n /** class for the list item inner */\n listItemInner: [\n // base styles\n 'flex w-full flex-row items-stretch divide-divider bg-content1',\n // x division and borders\n 'divide-x divide-solid border-b border-t border-divider',\n ],\n /** class for the remove button */\n removeButton: [\n // base styles\n 'flex items-center justify-center',\n // fixed height/no round corners\n '!h-full !min-h-0 !rounded-none px-3',\n // focus styles - inset ring\n 'outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus',\n ],\n /** class for the sort drag handle */\n sortDragHandle: [\n // base styles\n 'flex cursor-grab items-center justify-center px-2 text-default-600 transition-colors',\n // hover and dragging state\n 'hover:bg-default-100 active:cursor-grabbing group-data-[dragging=true]:bg-default-100',\n // focus styles - inset ring\n 'outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus',\n ],\n },\n variants: {\n hasLabel: {\n false: {\n // focus styles - when there is no label, the first item actions menu button should have rounded top right corners\n actionsMenuButton:\n 'group-[:first-child]:!rounded-tr-small group-[:first-child]:group-data-[dragging=true]:!rounded-tr-none',\n // focus styles - when there is no label, the first item remove button focus ring should have rounded top right corners\n removeButton:\n 'group-[:first-child]:!rounded-tr-small group-[:first-child]:group-data-[dragging=true]:!rounded-tr-none',\n // focus styles - when there is no label, the first item sort drag handle focus ring should have rounded top left corners\n sortDragHandle:\n 'group-[:first-child]:rounded-tl-small group-[:first-child]:group-data-[dragging=true]:rounded-tl-none',\n },\n },\n },\n});\n\n/**\n * FieldArray component based in [RHF useFieldArray](https://react-hook-form.com/docs/usefieldarray)\n */\nconst FieldArray = ({\n appendButtonText = 'Add Element',\n children,\n className: _className = undefined,\n duplicate = false,\n elementInitialValue: _elementInitialValue = null,\n elementMarginBottom = undefined,\n flat = false,\n insertAfter = false,\n lastElementNotRemovable = false,\n name,\n sortable = false,\n ...uniformFieldProps\n}: FieldArrayProps) => {\n const {\n fields,\n append,\n remove,\n insert,\n move,\n disableAnimation,\n elementInitialValue,\n getValues,\n testId,\n } = useUniformFieldArray({\n name,\n flat,\n elementInitialValue: _elementInitialValue,\n lastElementNotRemovable,\n ...uniformFieldProps,\n });\n\n // className from slots\n const variants = fieldArrayVariants({ hasLabel: !!uniformFieldProps.label });\n const className = variantsToClassNames(variants, _className, 'base');\n\n return (\n <div className={className.base}>\n {/* field array label */}\n <FieldArrayLabel\n className={className.label}\n label={uniformFieldProps.label}\n name={name}\n />\n\n {fields.length ? (\n /* list wrapper */\n <div className={cn(className.listWrapper)}>\n {/* sortable context */}\n <SortContext\n fields={fields}\n move={move}\n name={name}\n sortable={sortable}\n >\n {/* list container */}\n <ul className={className.list} data-testid={testId}>\n {/* fields / list elements */}\n {fields.map((field, index) => {\n const elementName = flat\n ? `${name}.${index}.${flatArrayKey}`\n : `${name}.${index}`;\n const elementTestId = `${testId}_${index}`;\n\n // create methods for element\n const elementMethods: FieldArrayElementMethods = {\n append: () => {\n append(elementInitialValue);\n },\n duplicate: () => {\n const values = getValues(name);\n const currentValue = (values as unknown[])[index];\n const nextValue = flat\n ? { [flatArrayKey]: currentValue }\n : currentValue;\n insert(index + 1, nextValue);\n },\n insert: () => {\n insert(index + 1, elementInitialValue);\n },\n remove: () => {\n remove(index);\n },\n };\n\n return (\n <FieldArrayElement\n key={field.id}\n className={className}\n disableAnimation={disableAnimation}\n duplicate={duplicate}\n elementMarginBottom={elementMarginBottom}\n fields={fields}\n id={field.id}\n index={index}\n insertAfter={insertAfter}\n lastNotDeletable={lastElementNotRemovable}\n methods={elementMethods}\n sortable={sortable}\n testId={elementTestId}\n >\n {children({\n index,\n length: fields.length,\n methods: elementMethods,\n name: elementName,\n testId: elementTestId,\n })}\n </FieldArrayElement>\n );\n })}\n </ul>\n </SortContext>\n </div>\n ) : null}\n\n {/* top level field array errors */}\n <FieldArrayValidationError name={name} />\n\n {/* append elements button */}\n <ElementAppendButton\n appendButtonText={appendButtonText}\n className={className.appendButton}\n onClick={() => {\n append(elementInitialValue);\n }}\n testId={`${testId}_append_button`}\n />\n </div>\n );\n};\n\nexport default FieldArray;\n","import FieldArray from './FieldArray';\n\nexport type * from './types';\n\nexport { fieldArrayVariants } from './FieldArray';\n\nexport default FieldArray;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAM,uBAAuB,EAC3B,mBAAmB,eACnB,YAAY,KAAA,GACZ,SACA,SAAS,KAAA,QACqB;CAC9B,OACE,qBAAC,QAAD;EACE,WAAW,GAAG,SAAS;EACvB,kBAAA;EACS;EACT,MAAK;EACG;EACR,SAAQ;EANV,UAAA,CAQE,oBAAC,QAAD,CAAS,CAAA,GACT,oBAAC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BAAmB;IAC5B;IACA,QAAQ,GAAG,OAAO;GACnB,CAAA;EACE;;AAET;;;ACxOA,IAAA,qBAAe"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["Grid"],"sources":["../../src/FieldArray/subcomponents/ElementAppendButton.tsx","../../src/FieldArray/subcomponents/ElementActionsMenu.tsx","../../src/FieldArray/subcomponents/ElementRemoveButton.tsx","../../src/FieldArray/subcomponents/SortDragHandle.tsx","../../src/FieldArray/subcomponents/FieldArrayElement.tsx","../../src/FieldArray/subcomponents/FieldArrayLabel.tsx","../../src/FieldArray/subcomponents/FieldArrayValidationError.tsx","../../src/FieldArray/subcomponents/SortContext.tsx","../../src/FieldArray/FieldArray.tsx","../../src/FieldArray/index.ts"],"sourcesContent":["import type { ClassValue } from '@fuf-stack/pixel-utils';\n\nimport { FaPlus } from 'react-icons/fa';\n\nimport { cn } from '@fuf-stack/pixel-utils';\nimport { Button } from '@fuf-stack/pixels';\n\ninterface ElementAppendButtonProps {\n /** text of the append element button */\n appendButtonText?: string;\n /** CSS class name */\n className?: ClassValue;\n /** click handler */\n onClick: () => void;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\nconst ElementAppendButton = ({\n appendButtonText = 'Add Element',\n className = undefined,\n onClick,\n testId = undefined,\n}: ElementAppendButtonProps) => {\n return (\n <Button\n className={cn(className)}\n disableAnimation\n onClick={onClick}\n size=\"sm\"\n testId={testId}\n variant=\"light\"\n >\n <FaPlus />\n <span>{appendButtonText}</span>\n </Button>\n );\n};\n\nexport default ElementAppendButton;\n","import type { ClassValue } from '@fuf-stack/pixel-utils';\nimport type { MenuItem } from '@fuf-stack/pixels';\nimport type { Key } from 'react';\nimport type { FieldArrayElementMethods } from './FieldArrayElement';\n\nimport { FaCopy, FaTimes } from 'react-icons/fa';\nimport { VscInsert } from 'react-icons/vsc';\n\nimport { cn } from '@fuf-stack/pixel-utils';\nimport { Menu } from '@fuf-stack/pixels';\n\nexport interface ElementActionsMenuProps {\n /** CSS class name */\n className?: ClassValue;\n /** Whether duplicate action is available */\n duplicate?: boolean;\n /** Whether insert after action is available */\n insertAfter?: boolean;\n /** Field array operation methods */\n methods: FieldArrayElementMethods;\n /** Whether to show remove button (false when last element is not deletable) */\n showRemove?: boolean;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\n/**\n * Menu component for field array element actions (remove, duplicate, insert after)\n */\nconst ElementActionsMenu = ({\n className = undefined,\n duplicate = false,\n insertAfter = false,\n showRemove = true,\n methods,\n testId = undefined,\n}: ElementActionsMenuProps) => {\n const handleAction = (key: Key) => {\n switch (key) {\n case 'remove':\n methods.remove();\n break;\n case 'duplicate':\n methods.duplicate();\n break;\n case 'insertAfter':\n methods.insert();\n break;\n default:\n break;\n }\n };\n\n // Build menu items based on available actions\n const menuItems: MenuItem[] = [];\n\n if (duplicate) {\n menuItems.push({\n key: 'duplicate',\n label: 'Duplicate',\n icon: <FaCopy />,\n });\n }\n\n if (insertAfter) {\n menuItems.push({\n key: 'insertAfter',\n label: 'Insert After',\n icon: <VscInsert />,\n });\n }\n\n if (showRemove) {\n menuItems.push({\n key: 'remove',\n className: 'text-danger',\n label: 'Remove',\n icon: <FaTimes />,\n });\n }\n\n return (\n <Menu\n ariaLabel=\"Element actions\"\n items={menuItems}\n onAction={handleAction}\n placement=\"right\"\n testId={testId}\n triggerButtonProps={{\n className: cn(className),\n disableRipple: true,\n size: 'md',\n variant: 'light',\n }}\n />\n );\n};\n\nexport default ElementActionsMenu;\n","import type { ClassValue } from '@fuf-stack/pixel-utils';\n\nimport { FaTimes } from 'react-icons/fa';\n\nimport { motion } from '@fuf-stack/pixel-motion';\nimport { cn } from '@fuf-stack/pixel-utils';\nimport { Button } from '@fuf-stack/pixels';\n\ninterface ElementRemoveButtonProps {\n /** CSS class name */\n className?: ClassValue;\n /** Globally disable animations (used for first render or prefers-reduced-motion) */\n disableAnimation?: boolean;\n /** click handler */\n onClick: () => void;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\nconst ElementRemoveButton = ({\n className = undefined,\n disableAnimation = false,\n onClick,\n testId = undefined,\n}: ElementRemoveButtonProps) => {\n const button = (\n <Button\n ariaLabel=\"remove element\"\n className={cn(className)}\n color=\"danger\"\n icon={<FaTimes />}\n onClick={onClick}\n size=\"sm\"\n testId={testId}\n variant=\"light\"\n />\n );\n\n if (disableAnimation) {\n return button;\n }\n\n return (\n <motion.div\n animate={{ opacity: 1, width: 'auto' }}\n className=\"flex\"\n exit={{ opacity: 0, width: 0 }}\n initial={{ opacity: 0, width: 0 }}\n transition={{ duration: 0.2 }}\n >\n {button}\n </motion.div>\n );\n};\n\nexport default ElementRemoveButton;\n","import type { ClassValue } from '@fuf-stack/pixel-utils';\n\nimport { FaGripVertical } from 'react-icons/fa';\n\nimport { useSortable } from '@dnd-kit/sortable';\n\nimport { cn } from '@fuf-stack/pixel-utils';\n\ninterface SortDragHandleProps {\n /** Optional CSS class name */\n className?: ClassValue;\n /** Unique identifier for sortable item */\n id: string | number;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\n/**\n * Drag handle component that integrates with dnd-kit sortable functionality.\n * Renders a vertical grip icon that can be used to reorder items.\n */\nconst SortDragHandle = ({\n className = undefined,\n id,\n testId = undefined,\n}: SortDragHandleProps) => {\n // Get dnd-kit sortable attributes and listeners\n const { attributes, listeners } = useSortable({ id });\n\n return (\n <div\n className={cn(className)}\n data-testid={testId}\n {...attributes}\n {...listeners}\n >\n <FaGripVertical />\n </div>\n );\n};\n\nexport default SortDragHandle;\n","import type { Variants as MotionVariants } from '@fuf-stack/pixel-motion';\nimport type { ClassValue } from '@fuf-stack/pixel-utils';\nimport type { FieldArrayFeatures } from '../types';\n\nimport { useState } from 'react';\n\nimport { useSortable } from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\n\nimport { AnimatePresence, motion } from '@fuf-stack/pixel-motion';\nimport { cn } from '@fuf-stack/pixel-utils';\n\nimport Grid from '../../Grid';\nimport ElementActionsMenu from './ElementActionsMenu';\nimport ElementRemoveButton from './ElementRemoveButton';\nimport SortDragHandle from './SortDragHandle';\n\nexport interface FieldArrayElementMethods {\n /** Add new element at end */\n append: () => void;\n /** Clone current element */\n duplicate: () => void;\n /** Add new element after current */\n insert: () => void;\n /** Remove current element */\n remove: () => void;\n}\n\ninterface FieldArrayElementProps extends FieldArrayFeatures {\n /** Form elements to render inside array element */\n children: React.ReactNode;\n /** CSS class names for component parts */\n className: {\n /** Class of wrapper grid inside the li that wraps the rendered element fields directly */\n elementFieldsGrid?: ClassValue;\n /** Class for the li (performs motion animations) */\n listItem?: ClassValue;\n /** Class for the li inner div (wraps the rendered element fields) */\n listItemInner?: ClassValue;\n /** Class for the actions menu button */\n actionsMenuButton?: ClassValue;\n /** Class for the remove element button (when menu is not used) */\n removeButton?: ClassValue;\n /** Class for the drag handle when sorting enabled */\n sortDragHandle?: ClassValue;\n };\n /** Globally disable animations for this item (used for first render or prefers-reduced-motion) */\n disableAnimation?: boolean;\n /** Bottom margin for elements (for backwards compatibility) */\n elementMarginBottom?: React.CSSProperties['marginBottom'];\n /** All fields in the form array */\n fields: Record<'id', string>[];\n /** Unique identifier for drag/drop */\n id: string | number;\n /** Field index in array */\n index: number;\n /** Prevent deletion of last remaining element */\n lastNotDeletable?: boolean;\n /** Field array operation methods */\n methods: FieldArrayElementMethods;\n /** HTML data-testid of the element */\n testId?: string;\n}\n\n/**\n * Form array element component using react-hook-form with drag-drop sorting\n * and validation capabilities. Animations when elements are added or removed\n * improve the user experience and provide a better visual feedback.\n */\nconst FieldArrayElement = ({\n children,\n className,\n disableAnimation = false,\n duplicate = false,\n elementMarginBottom: _elementMarginBottom = undefined,\n fields,\n id,\n index: _index,\n insertAfter = false,\n lastNotDeletable = true,\n methods,\n sortable = false,\n testId = undefined,\n}: FieldArrayElementProps) => {\n // Apply transform styles when sortable is enabled for smooth drag animations\n // transform: handles the item's position during drag\n // transition: controls the animation timing when dropping\n const { setNodeRef, transform, transition, isDragging } = useSortable({ id });\n const sortingStyle = sortable\n ? {\n transform: CSS.Translate.toString(transform),\n transition,\n zIndex: isDragging ? 50 : undefined,\n }\n : undefined;\n\n // Local visibility to allow exit animation before removing from RHF state\n const [isVisible, setIsVisible] = useState(true);\n\n // Motion variants for the list item\n const listItemMotionVariants: MotionVariants = {\n hidden: { opacity: 0, height: 0, marginBottom: 0 },\n visible: {\n opacity: 1,\n height: 'auto',\n transition: { duration: 0.2, ease: 'circOut' },\n // push last visible item down to overlap with append button (hide double border)\n marginBottom: '-1px',\n },\n exit: {\n opacity: 0,\n height: 0,\n marginBottom: 0,\n transition: {\n // on exit first fade out, then shrink\n opacity: { duration: 0.1, ease: 'circOut' },\n height: { delay: 0.1, duration: 0.2, ease: 'circOut' },\n },\n },\n };\n\n // Height animation handled on <motion.li> using overflow hidden\n return (\n <AnimatePresence\n mode=\"wait\"\n // remove from RHF state after exit animation\n onExitComplete={() => {\n methods.remove();\n }}\n >\n {isVisible ? (\n <motion.li\n key={id}\n ref={setNodeRef}\n animate={disableAnimation ? undefined : 'visible'}\n className={cn(className.listItem)}\n data-dragging={isDragging}\n data-testid={`${testId}_element`}\n exit={disableAnimation ? undefined : 'exit'}\n initial={disableAnimation ? false : 'hidden'}\n style={sortingStyle}\n variants={disableAnimation ? undefined : listItemMotionVariants}\n >\n <div className={cn(className.listItemInner)}>\n {/** sorting drag handle */}\n {sortable ? (\n <SortDragHandle\n className={className.sortDragHandle}\n id={id}\n testId={`${testId}_sort_drag_handle`}\n />\n ) : null}\n\n {/** render element fields in Grid component */}\n <Grid\n className={cn(className.elementFieldsGrid)}\n testId={`${testId}_element_fields_grid`}\n >\n {/* render actual fields */}\n {children}\n </Grid>\n\n {/** actions menu when duplicate or insertAfter is enabled */}\n {duplicate || insertAfter ? (\n <ElementActionsMenu\n className={className.actionsMenuButton}\n duplicate={duplicate}\n insertAfter={insertAfter}\n methods={{\n ...methods,\n remove: () => {\n if (disableAnimation) {\n methods.remove();\n } else {\n setIsVisible(false);\n }\n },\n }}\n showRemove={!(lastNotDeletable && fields.length === 1)}\n testId={`${testId}_actions_menu`}\n />\n ) : (\n <>\n {/** remove element button (when menu is not used) */}\n <AnimatePresence initial={false}>\n {lastNotDeletable && fields.length === 1 ? null : (\n <ElementRemoveButton\n key=\"remove-button\"\n className={className.removeButton}\n disableAnimation={disableAnimation}\n onClick={() => {\n if (disableAnimation) {\n methods.remove();\n } else {\n setIsVisible(false);\n }\n }}\n testId={`${testId}_remove_button`}\n />\n )}\n </AnimatePresence>\n </>\n )}\n </div>\n </motion.li>\n ) : null}\n </AnimatePresence>\n );\n};\n\nexport default FieldArrayElement;\n","import type { ReactNode } from 'react';\n\nimport { cn } from '@fuf-stack/pixel-utils';\n\nimport { useUniformField } from '../../hooks/useUniformField';\n\nexport interface FieldArrayLabelProps {\n /** CSS class name */\n className?: string;\n /** Label content */\n label: ReactNode;\n /** Field name */\n name: string;\n}\n\n/**\n * Renders the label for a FieldArray component.\n *\n * This component handles displaying the array label with proper accessibility\n * attributes using the label props from useUniformField.\n */\nconst FieldArrayLabel = ({\n className = undefined,\n label: _label,\n name,\n}: FieldArrayLabelProps) => {\n const { error, getLabelProps, invalid, label } = useUniformField({\n name,\n label: _label,\n });\n\n // when no label is provided, don't render anything\n if (!_label) {\n return null;\n }\n\n // @ts-expect-error - error._errors exists but not typed\n const hasErrors = invalid && error?._errors;\n\n return (\n <div\n {...getLabelProps()}\n aria-level={3}\n className={cn(getLabelProps()?.className, className, {\n // when there are no array level errors, the label should have foreground color\n 'text-foreground!': !hasErrors,\n })}\n role=\"heading\"\n >\n {label}\n </div>\n );\n};\n\nexport default FieldArrayLabel;\n","import {\n AnimatePresence,\n motion,\n useReducedMotion,\n} from '@fuf-stack/pixel-motion';\nimport { cn } from '@fuf-stack/pixel-utils';\n\nimport { useUniformField } from '../../hooks/useUniformField';\nimport FieldValidationError from '../../partials/FieldValidationError/FieldValidationError';\n\nexport interface FieldArrayValidationErrorProps {\n /** Field name */\n name: string;\n}\n\n/**\n * Renders array-level validation errors for FieldArray.\n *\n * This component handles validation errors that apply to the entire array\n * (e.g., \"Array must contain at least 3 elements\", \"Array elements are not unique\"),\n * as opposed to field-level errors which apply to individual array elements.\n *\n * The component wraps errors in the proper accessibility markup and animates\n * them in/out using Framer Motion when they appear or are resolved.\n */\nconst FieldArrayValidationError = ({\n name,\n}: FieldArrayValidationErrorProps) => {\n const {\n error,\n getErrorMessageProps,\n getHelperWrapperProps,\n invalid,\n testId,\n } = useUniformField({\n name,\n });\n\n // disable all animation if user prefers reduced motion\n const disableAnimation = useReducedMotion();\n\n // @ts-expect-error - error._errors exists but not typed\n const hasErrors = invalid && error?._errors;\n\n return (\n <AnimatePresence initial={!disableAnimation}>\n {hasErrors ? (\n <motion.div\n key=\"field-array-errors\"\n animate={\n disableAnimation ? undefined : { opacity: 1, height: 'auto' }\n }\n exit={disableAnimation ? undefined : { opacity: 0, height: 0 }}\n initial={disableAnimation ? false : { height: 0, opacity: 0 }}\n style={{ overflow: 'hidden' }}\n transition={{ duration: 0.4, ease: 'circOut' }}\n >\n <div\n {...getHelperWrapperProps()}\n className={cn(\n getHelperWrapperProps()?.className,\n // force helper to be visible and add padding (pt-1 to compensate for inner content's top padding)\n 'block px-3 pb-2 pt-1',\n )}\n >\n <div {...getErrorMessageProps()}>\n <FieldValidationError\n // @ts-expect-error - error._errors exists but not typed\n error={error._errors}\n testId={testId}\n />\n </div>\n </div>\n </motion.div>\n ) : null}\n </AnimatePresence>\n );\n};\n\nexport default FieldArrayValidationError;\n","import type { DragEndEvent } from '@dnd-kit/core';\nimport type { ReactNode } from 'react';\nimport type { UseFieldArrayMove } from 'react-hook-form';\n\nimport { useFormContext } from 'react-hook-form';\n\nimport {\n closestCenter,\n DndContext,\n KeyboardSensor,\n PointerSensor,\n useSensor,\n useSensors,\n} from '@dnd-kit/core';\nimport {\n restrictToVerticalAxis,\n restrictToWindowEdges,\n} from '@dnd-kit/modifiers';\nimport {\n SortableContext,\n verticalListSortingStrategy,\n} from '@dnd-kit/sortable';\n\ninterface SortContextProps {\n /** child components */\n children: ReactNode;\n /** Array of objects containing unique IDs for sortable items */\n fields: Record<'id', string>[];\n /** react-hook-form's move function to update field array indices */\n move: UseFieldArrayMove;\n /** name of the field array */\n name: string;\n /** enable/disable sorting functionality */\n sortable: boolean;\n}\n\n/**\n * A wrapper component that provides drag-and-drop sorting functionality for field arrays\n * using dnd-kit and react-hook-form.\n *\n * This component integrates with react-hook-form's field arrays to enable vertical\n * drag-and-drop reordering of form fields. It supports both pointer (mouse/touch)\n * and keyboard interactions for accessibility.\n */\nconst SortContext = ({\n children,\n fields,\n move,\n name,\n sortable,\n}: SortContextProps): ReactNode => {\n const { trigger } = useFormContext();\n\n // Initialize sensors for both pointer (mouse/touch) and keyboard interactions\n const sensors = useSensors(\n useSensor(PointerSensor),\n useSensor(KeyboardSensor),\n );\n\n // Early return if sorting is disabled\n if (!sortable) {\n return children;\n }\n\n /**\n * Handles the end of a drag operation by updating field positions\n * @param event - The drag end event containing active and over elements\n */\n const handleDragEnd = (event: DragEndEvent) => {\n const { active, over } = event;\n\n // Only move if dropping over a different item\n if (active.id !== over?.id) {\n // Find the indices of the dragged item and drop target\n const oldIndex = fields.findIndex((field) => {\n return field.id === active.id;\n });\n const newIndex = fields.findIndex((field) => {\n return field.id === over?.id;\n });\n // Update the field array order using react-hook-form's move function\n move(oldIndex, newIndex);\n\n // Finally trigger validation for the array field,\n // so validation errors are updated for the new order\n trigger(name);\n }\n };\n\n return (\n <DndContext\n collisionDetection={closestCenter}\n modifiers={[restrictToVerticalAxis, restrictToWindowEdges]}\n onDragEnd={handleDragEnd}\n sensors={sensors}\n >\n <SortableContext\n items={fields.map((field) => {\n return field.id;\n })}\n strategy={verticalListSortingStrategy}\n >\n {children}\n </SortableContext>\n </DndContext>\n );\n};\n\nexport default SortContext;\n","import type { FieldArrayElementMethods } from './subcomponents/FieldArrayElement';\nimport type { FieldArrayProps } from './types';\n\nimport { cn, tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\n\nimport { flatArrayKey } from '../helpers';\nimport { useUniformFieldArray } from '../hooks/useUniformFieldArray';\nimport ElementAppendButton from './subcomponents/ElementAppendButton';\nimport FieldArrayElement from './subcomponents/FieldArrayElement';\nimport FieldArrayLabel from './subcomponents/FieldArrayLabel';\nimport FieldArrayValidationError from './subcomponents/FieldArrayValidationError';\nimport SortContext from './subcomponents/SortContext';\n\nexport const fieldArrayVariants = tv({\n slots: {\n /** base class for the field array wrapper */\n base: [\n // base styles\n 'overflow-hidden rounded-small border border-divider bg-content1',\n // divider between items\n 'divide-y divide-divider',\n ],\n /** class for the actions menu button */\n actionsMenuButton: [\n // base styles\n 'flex items-center justify-center text-default-600',\n // fixed height/no round corners/center align\n 'h-full rounded-none',\n // focus styles - inset ring\n 'outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus',\n ],\n /** class for the append button */\n appendButton: [\n // base styles\n 'w-full justify-start rounded-b-small rounded-t-none font-semibold',\n // match label height (p-3 = 12px vertical padding + text-base line height)\n '!h-[48px] !min-h-0',\n // focus styles - inset ring with rounded bottom corners to match container\n 'outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus',\n ],\n /** class for the element fields grid */\n elementFieldsGrid: ['w-full grow p-3'],\n /** class for the label */\n label: [\n // override HeroUI label positioning and display\n 'pointer-events-auto! static! z-auto! block! w-full!',\n // reset any transforms or translations\n 'translate-x-0! translate-y-0! transform-none!',\n // card header styling - use text-medium (16px) instead of text-base for correct 48px height\n 'rounded-t-small p-3 font-semibold text-medium',\n ],\n /** class for the list */\n list: ['overflow-hidden'],\n /** class for the list wrapper */\n listWrapper: ['overflow-hidden'],\n /** class for the list item (performs motion animations) */\n listItem: [\n // base styles\n 'group relative flex flex-row',\n // overlap borders by shifting first item up 1px (similar to how last item overlaps with append button)\n 'first:-mt-px',\n ],\n /** class for the list item inner */\n listItemInner: [\n // base styles\n 'flex w-full flex-row items-stretch divide-divider bg-content1',\n // x division and borders\n 'divide-x divide-solid border-b border-t border-divider',\n ],\n /** class for the remove button */\n removeButton: [\n // base styles\n 'flex items-center justify-center',\n // fixed height/no round corners\n '!h-full !min-h-0 !rounded-none px-3',\n // focus styles - inset ring\n 'outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus',\n ],\n /** class for the sort drag handle */\n sortDragHandle: [\n // base styles\n 'flex cursor-grab items-center justify-center px-2 text-default-600 transition-colors',\n // hover and dragging state\n 'hover:bg-default-100 active:cursor-grabbing group-data-[dragging=true]:bg-default-100',\n // focus styles - inset ring\n 'outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus',\n ],\n },\n variants: {\n hasLabel: {\n false: {\n // focus styles - when there is no label, the first item actions menu button should have rounded top right corners\n actionsMenuButton:\n 'group-[:first-child]:!rounded-tr-small group-[:first-child]:group-data-[dragging=true]:!rounded-tr-none',\n // focus styles - when there is no label, the first item remove button focus ring should have rounded top right corners\n removeButton:\n 'group-[:first-child]:!rounded-tr-small group-[:first-child]:group-data-[dragging=true]:!rounded-tr-none',\n // focus styles - when there is no label, the first item sort drag handle focus ring should have rounded top left corners\n sortDragHandle:\n 'group-[:first-child]:rounded-tl-small group-[:first-child]:group-data-[dragging=true]:rounded-tl-none',\n },\n },\n },\n});\n\n/**\n * FieldArray component based in [RHF useFieldArray](https://react-hook-form.com/docs/usefieldarray)\n */\nconst FieldArray = ({\n appendButtonText = 'Add Element',\n children,\n className: _className = undefined,\n duplicate = false,\n elementInitialValue: _elementInitialValue = null,\n elementMarginBottom = undefined,\n flat = false,\n insertAfter = false,\n lastElementNotRemovable = false,\n name,\n sortable = false,\n ...uniformFieldProps\n}: FieldArrayProps) => {\n const {\n fields,\n append,\n remove,\n insert,\n move,\n disableAnimation,\n elementInitialValue,\n getValues,\n testId,\n } = useUniformFieldArray({\n name,\n flat,\n elementInitialValue: _elementInitialValue,\n lastElementNotRemovable,\n ...uniformFieldProps,\n });\n\n // className from slots\n const variants = fieldArrayVariants({ hasLabel: !!uniformFieldProps.label });\n const className = variantsToClassNames(variants, _className, 'base');\n\n return (\n <div className={className.base}>\n {/* field array label */}\n <FieldArrayLabel\n className={className.label}\n label={uniformFieldProps.label}\n name={name}\n />\n\n {fields.length ? (\n /* list wrapper */\n <div className={cn(className.listWrapper)}>\n {/* sortable context */}\n <SortContext\n fields={fields}\n move={move}\n name={name}\n sortable={sortable}\n >\n {/* list container */}\n <ul className={className.list} data-testid={testId}>\n {/* fields / list elements */}\n {fields.map((field, index) => {\n const elementName = flat\n ? `${name}.${index}.${flatArrayKey}`\n : `${name}.${index}`;\n const elementTestId = `${testId}_${index}`;\n\n // create methods for element\n const elementMethods: FieldArrayElementMethods = {\n append: () => {\n append(elementInitialValue);\n },\n duplicate: () => {\n const values = getValues(name);\n const currentValue = (values as unknown[])[index];\n const nextValue = flat\n ? { [flatArrayKey]: currentValue }\n : currentValue;\n insert(index + 1, nextValue);\n },\n insert: () => {\n insert(index + 1, elementInitialValue);\n },\n remove: () => {\n remove(index);\n },\n };\n\n return (\n <FieldArrayElement\n key={field.id}\n className={className}\n disableAnimation={disableAnimation}\n duplicate={duplicate}\n elementMarginBottom={elementMarginBottom}\n fields={fields}\n id={field.id}\n index={index}\n insertAfter={insertAfter}\n lastNotDeletable={lastElementNotRemovable}\n methods={elementMethods}\n sortable={sortable}\n testId={elementTestId}\n >\n {children({\n index,\n length: fields.length,\n methods: elementMethods,\n name: elementName,\n testId: elementTestId,\n })}\n </FieldArrayElement>\n );\n })}\n </ul>\n </SortContext>\n </div>\n ) : null}\n\n {/* top level field array errors */}\n <FieldArrayValidationError name={name} />\n\n {/* append elements button */}\n <ElementAppendButton\n appendButtonText={appendButtonText}\n className={className.appendButton}\n onClick={() => {\n append(elementInitialValue);\n }}\n testId={`${testId}_append_button`}\n />\n </div>\n );\n};\n\nexport default FieldArray;\n","import FieldArray from './FieldArray';\n\nexport type * from './types';\n\nexport { fieldArrayVariants } from './FieldArray';\n\nexport default FieldArray;\n"],"mappings":";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Q,OAAO;SACf,SAAS;SACT,MAAM;SACN,QAAQ;QACV,CAAC;OACgB,GArBZ,MAAM,EAqBM;MAEvB,CAAC;KACC,CAAA;IACO,CAAA;GACV,CAAA,IACH;GAGJ,oBAAC,2BAAD,EAAiC,KAAO,CAAA;GAGxC,oBAAC,qBAAD;IACoB;IAClB,WAAW,UAAU;IACrB,eAAe;KACb,OAAO,mBAAmB;IAC5B;IACA,QAAQ,GAAG,OAAO;GACnB,CAAA;EACE;;AAET;;ACxOA,IAAA,qBAAe"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { TVClassName } from "@fuf-stack/pixel-utils";
|
|
2
2
|
import { ReactNode } from "react";
|
|
3
|
-
//#region src/FieldCard/FieldCard.d.ts
|
|
4
3
|
export declare const fieldCardVariants: ((props?: ({
|
|
5
4
|
invalid?: boolean | undefined;
|
|
6
5
|
} & ({
|
|
@@ -313,6 +312,5 @@ interface FieldCardProps {
|
|
|
313
312
|
* - Danger outline when validation errors exist
|
|
314
313
|
*/
|
|
315
314
|
declare const FieldCard: ({ children, className: _className, name, ...uniformFieldProps }: FieldCardProps) => import("react").JSX.Element;
|
|
316
|
-
//#endregion
|
|
317
315
|
export { type FieldCardProps, FieldCard as default };
|
|
318
316
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/FieldCard/FieldCard.tsx"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/FieldCard/FieldCard.tsx"],"mappings":";;qBAsHa,qBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA2DzB,YAAY,mBAAmB;UAEnB;;EAEf,UAAU;;EAEV,YAAY;;EAEZ,OAAO;;EAEP;;EAEA;;;;;;;;;;;cAYI,cAAa,UAAA,WAAA,YAAA,SAAA,qBAKhB,mCAAc,IAAA"}
|
package/dist/FieldCard/index.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { n as FieldValidationError } from "../FieldValidationError-
|
|
2
|
-
import { n as useFormContext, t as checkFieldIsRequired } from "../useFormContext-
|
|
1
|
+
import { n as FieldValidationError } from "../FieldValidationError-BcUV0r1I.mjs";
|
|
2
|
+
import { n as useFormContext, t as checkFieldIsRequired } from "../useFormContext-BEjPBdzb.mjs";
|
|
3
3
|
import { useUniformField } from "../hooks/useUniformField/index.mjs";
|
|
4
4
|
import { cn, tv, variantsToClassNames } from "@fuf-stack/pixel-utils";
|
|
5
5
|
import { useDebounce } from "@fuf-stack/pixels";
|
|
6
6
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
7
7
|
import { AnimatePresence, motion, useReducedMotion } from "@fuf-stack/pixel-motion";
|
|
8
|
-
|
|
8
|
+
// src/FieldCard/subcomponents/FieldCardValidationError.tsx
|
|
9
9
|
/**
|
|
10
10
|
* Renders validation errors in the footer of a FieldCard component.
|
|
11
11
|
*
|
|
@@ -55,8 +55,7 @@ const FieldCardValidationError = ({ className = void 0, error = void 0, errorTex
|
|
|
55
55
|
}, "field-card-errors") : null
|
|
56
56
|
});
|
|
57
57
|
};
|
|
58
|
-
|
|
59
|
-
//#region src/FieldCard/FieldCard.tsx
|
|
58
|
+
// src/FieldCard/FieldCard.tsx
|
|
60
59
|
/**
|
|
61
60
|
* Recursively checks if any child field has an error (regardless of touched state).
|
|
62
61
|
* Returns true if at least one child has an error.
|
|
@@ -219,10 +218,8 @@ const FieldCard = ({ children, className: _className = void 0, name, ...uniformF
|
|
|
219
218
|
]
|
|
220
219
|
});
|
|
221
220
|
};
|
|
222
|
-
|
|
223
|
-
//#region src/FieldCard/index.ts
|
|
221
|
+
// src/FieldCard/index.ts
|
|
224
222
|
var FieldCard_default = FieldCard;
|
|
225
|
-
//#endregion
|
|
226
223
|
export { FieldCard_default as default, fieldCardVariants };
|
|
227
224
|
|
|
228
225
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/FieldCard/subcomponents/FieldCardValidationError.tsx","../../src/FieldCard/FieldCard.tsx","../../src/FieldCard/index.ts"],"sourcesContent":["import type { FieldError } from 'react-hook-form';\n\nimport {\n AnimatePresence,\n motion,\n useReducedMotion,\n} from '@fuf-stack/pixel-motion';\nimport { cn } from '@fuf-stack/pixel-utils';\n\nimport { useUniformField } from '../../hooks/useUniformField';\nimport FieldValidationError from '../../partials/FieldValidationError/FieldValidationError';\n\nexport interface FieldCardValidationErrorProps {\n /** CSS class name for the error footer wrapper */\n className?: string;\n /** Error object from parent FieldCard (passed directly to avoid duplicate hook calls) */\n error?: FieldError[] | undefined;\n /** CSS class name for the error text (controls color based on invalid state) */\n errorTextClassName?: string;\n /** Field name */\n name: string;\n}\n\n/**\n * Renders validation errors in the footer of a FieldCard component.\n *\n * This component handles displaying field-level validation errors with proper\n * accessibility attributes and animates them in/out using Framer Motion.\n *\n * Note: Object-level errors (_errors) are always shown when they exist,\n * but the danger styling is controlled by the parent FieldCard based on\n * whether child fields have been touched.\n */\nconst FieldCardValidationError = ({\n className = undefined,\n error = undefined,\n errorTextClassName = undefined,\n name,\n}: FieldCardValidationErrorProps) => {\n const { getErrorMessageProps, getHelperWrapperProps, testId } =\n useUniformField({\n name,\n });\n\n // disable all animation if user prefers reduced motion\n const disableAnimation = useReducedMotion();\n\n // Always show object-level errors (_errors) when they exist\n // @ts-expect-error - error._errors exists but not typed\n const hasErrors = !!error?._errors;\n\n return (\n <AnimatePresence initial={!disableAnimation}>\n {hasErrors ? (\n <motion.div\n key=\"field-card-errors\"\n animate={\n disableAnimation ? undefined : { opacity: 1, height: 'auto' }\n }\n exit={disableAnimation ? undefined : { opacity: 0, height: 0 }}\n initial={disableAnimation ? false : { height: 0, opacity: 0 }}\n style={{ overflow: 'hidden' }}\n transition={{ duration: 0.4, ease: 'circOut' }}\n >\n <div\n {...getHelperWrapperProps()}\n className={cn(getHelperWrapperProps()?.className, className)}\n >\n <div\n {...getErrorMessageProps()}\n className={cn(\n getErrorMessageProps()?.className,\n errorTextClassName,\n )}\n >\n <FieldValidationError\n // @ts-expect-error - error._errors exists but not typed\n error={error._errors}\n testId={testId}\n />\n </div>\n </div>\n </motion.div>\n ) : null}\n </AnimatePresence>\n );\n};\n\nexport default FieldCardValidationError;\n","import type { TVClassName } from '@fuf-stack/pixel-utils';\nimport type { ReactNode } from 'react';\n\nimport { tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\nimport { useDebounce } from '@fuf-stack/pixels';\n\nimport { checkFieldIsRequired, useFormContext } from '../hooks/useFormContext';\nimport { useUniformField } from '../hooks/useUniformField';\nimport FieldCardValidationError from './subcomponents/FieldCardValidationError';\n\n/**\n * Recursively checks if any child field has an error (regardless of touched state).\n * Returns true if at least one child has an error.\n */\nexport const hasAnyChildErrors = (\n errors: Record<string, unknown> | undefined,\n): boolean => {\n if (!errors) {\n return false;\n }\n\n return Object.keys(errors)\n .filter((key) => {\n return key !== '_errors';\n })\n .some((key) => {\n const errorValue = errors[key];\n if (errorValue === undefined) {\n return false;\n }\n // If errorValue is an array, it's a leaf field error\n if (Array.isArray(errorValue)) {\n return true;\n }\n // Recursively check nested objects\n if (typeof errorValue === 'object' && errorValue !== null) {\n return hasAnyChildErrors(errorValue as Record<string, unknown>);\n }\n return false;\n });\n};\n\n/**\n * Recursively checks if any child field is touched.\n * Returns true if at least one child is touched.\n */\nexport const hasAnyChildTouched = (\n touched: Record<string, unknown> | undefined,\n): boolean => {\n if (!touched) {\n return false;\n }\n\n return Object.keys(touched)\n .filter((key) => {\n return key !== '_errors';\n })\n .some((key) => {\n const touchedValue = touched[key];\n if (touchedValue === undefined) {\n return false;\n }\n // If touchedValue is truthy (boolean true), field is touched\n if (touchedValue === true) {\n return true;\n }\n // Recursively check nested objects\n if (typeof touchedValue === 'object' && touchedValue !== null) {\n return hasAnyChildTouched(touchedValue as Record<string, unknown>);\n }\n return false;\n });\n};\n\n/**\n * Recursively checks if any child field with an error is also touched.\n * Returns true if at least one touched child has an error.\n */\nexport const hasVisibleChildErrors = (\n errors: Record<string, unknown> | undefined,\n touched: Record<string, unknown> | undefined,\n): boolean => {\n if (!errors || !touched) {\n return false;\n }\n\n return Object.keys(errors)\n .filter((key) => {\n // Skip object-level errors (_errors) - those are handled separately\n return key !== '_errors';\n })\n .some((key) => {\n const errorValue = errors[key];\n const touchedValue = touched[key];\n\n // If this key doesn't exist in both errors and touched, skip\n if (errorValue === undefined || touchedValue === undefined) {\n return false;\n }\n\n // If errorValue is an array, it's a leaf field error\n if (Array.isArray(errorValue)) {\n // touchedValue being truthy means the field is touched\n return !!touchedValue;\n }\n\n // Recursively check nested objects\n if (typeof errorValue === 'object' && errorValue !== null) {\n return hasVisibleChildErrors(\n errorValue as Record<string, unknown>,\n touchedValue as Record<string, unknown>,\n );\n }\n\n return false;\n });\n};\n\nexport const fieldCardVariants = tv({\n slots: {\n /** base class for the field card wrapper */\n base: [\n // base styles\n 'overflow-hidden rounded-small border bg-content1',\n // animate border color change, respect reduced motion\n 'transition-colors duration-150 motion-reduce:transition-none',\n ],\n /** class for the label/header */\n label: [\n // override HeroUI label positioning and display\n 'pointer-events-auto! static! z-auto! block! w-full!',\n // reset any transforms or translations\n 'translate-x-0! translate-y-0! transform-none!',\n // card header styling - use text-medium (16px) for proper header size\n 'rounded-t-small border-b p-3 font-semibold text-medium',\n // animate border and text color change, respect reduced motion\n 'transition-colors duration-150 motion-reduce:transition-none',\n ],\n /** class for the content */\n content: [\n // same as p-3 of Card component\n 'p-3',\n // default grid for form components (see Grid component)\n 'grid gap-4',\n ],\n /** class for the error footer wrapper */\n errorFooter: [\n 'border-t',\n // force helper to be visible and add padding (pt-1 to compensate for inner content's top padding)\n 'block px-3 pb-2 pt-1',\n // animate border color change, respect reduced motion\n 'transition-colors duration-150 motion-reduce:transition-none',\n ],\n /** class for the error text (empty base, color controlled by variant) */\n errorText: [],\n },\n variants: {\n invalid: {\n true: {\n base: 'border-danger-200',\n label: 'border-danger-200 text-danger',\n errorFooter: 'border-danger-200',\n errorText: '!text-danger text-tiny',\n },\n false: {\n base: 'border-divider',\n label: 'border-divider text-foreground',\n errorFooter: 'border-divider',\n errorText: '!text-foreground-500 text-tiny',\n },\n },\n },\n defaultVariants: {\n invalid: false,\n },\n});\n\ntype ClassName = TVClassName<typeof fieldCardVariants>;\n\nexport interface FieldCardProps {\n /** Content to render inside the card */\n children: ReactNode;\n /** CSS class name */\n className?: ClassName;\n /** Label content for the card header */\n label: ReactNode;\n /** Field name for validation */\n name: string;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\n/**\n * FieldCard component - A card-styled container with label header and error footer\n *\n * Displays form field content in a card layout with:\n * - Label/title in the header\n * - Content in the body\n * - Validation errors in the footer\n * - Danger outline when validation errors exist\n */\nconst FieldCard = ({\n children,\n className: _className = undefined,\n name,\n ...uniformFieldProps\n}: FieldCardProps) => {\n const { error, getLabelProps, label } = useUniformField({\n name,\n ...uniformFieldProps,\n });\n\n const {\n control,\n formState: { touchedFields, submitCount },\n validation,\n } = useFormContext();\n\n // Check if any registered child field is required\n const validationInstance = validation?.baseInstance ?? validation?.instance;\n const registeredFields: string[] = Array.from(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (control as any)._names?.mount ?? [],\n );\n const childFieldPrefix = `${name}.`;\n const isRequired = validationInstance\n ? registeredFields\n .filter((f) => {\n return f.startsWith(childFieldPrefix);\n })\n .some((f) => {\n return checkFieldIsRequired(\n validationInstance,\n f.split('.').filter((k) => {\n return k !== '';\n }),\n );\n })\n : false;\n\n // Get touched state for this field's children by traversing the path\n const getNestedValue = (\n obj: Record<string, unknown> | undefined,\n path: string,\n ): Record<string, unknown> | undefined => {\n if (!obj) {\n return undefined;\n }\n const keys = path.split('.');\n let current: unknown = obj;\n keys.every((key) => {\n if (current && typeof current === 'object') {\n current = (current as Record<string, unknown>)[key];\n return true;\n }\n current = undefined;\n return false;\n });\n return current as Record<string, unknown> | undefined;\n };\n\n const fieldTouched = getNestedValue(touchedFields, name);\n\n // Check for object-level errors (_errors)\n // @ts-expect-error - error._errors exists but not typed\n const hasObjectErrors = !!error?._errors;\n\n const errorRecord = error as unknown as Record<string, unknown>;\n\n // Check if any child field has errors (regardless of touched state)\n const hasChildErrors = hasAnyChildErrors(errorRecord);\n // Check if any child field is touched\n const isAnyChildTouched = hasAnyChildTouched(fieldTouched);\n\n // Show invalid styling (danger border/header/error text) when:\n // 1. Any child field has an error AND (it's touched OR form was submitted), OR\n // 2. Object-level _errors exists AND no child errors AND (any child touched OR submitted)\n const rawShowInvalid =\n (hasChildErrors &&\n (hasVisibleChildErrors(errorRecord, fieldTouched) || submitCount > 0)) ||\n (hasObjectErrors &&\n !hasChildErrors &&\n (isAnyChildTouched || submitCount > 0));\n\n // Debounce to prevent flickering during rapid state changes\n const showInvalid = useDebounce(rawShowInvalid, 200);\n\n // className from slots\n const variants = fieldCardVariants({ invalid: showInvalid });\n const className = variantsToClassNames(variants, _className, 'base');\n\n return (\n <div className={className.base}>\n {/* card header with label */}\n {label ? (\n <div\n {...getLabelProps()}\n aria-level={3}\n // Override getLabelProps className to use our own invalid styling based on hasErrors,\n // not HeroUI's which is based on any child field being invalid\n className={className.label}\n role=\"heading\"\n >\n {label}\n {/* Manual asterisk: getLabelProps uses schema-required for the object itself,\n but FieldCard needs asterisk based on whether any CHILD field is required */}\n {isRequired ? (\n <span aria-hidden=\"true\" className=\"ml-0.5 text-danger\">\n *\n </span>\n ) : null}\n </div>\n ) : null}\n\n {/* card content */}\n <div className={className.content}>{children}</div>\n\n {/* card footer with validation errors - always show _errors, but danger styling controlled by showInvalid */}\n <FieldCardValidationError\n className={className.errorFooter}\n error={error}\n errorTextClassName={className.errorText}\n name={name}\n />\n </div>\n );\n};\n\nexport default FieldCard;\n","import FieldCard from './FieldCard';\n\nexport type { FieldCardProps } from './FieldCard';\n\nexport { fieldCardVariants } from './FieldCard';\n\nexport default FieldCard;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiCA,MAAM,4BAA4B,EAChC,YAAY,KAAA,GACZ,QAAQ,KAAA,GACR,qBAAqB,KAAA,GACrB,WACmC;CACnC,MAAM,EAAE,sBAAsB,uBAAuB,WACnD,gBAAgB,EACd,KACF,CAAC;CAGH,MAAM,mBAAmB,iBAAiB;CAI1C,MAAM,YAAY,CAAC,CAAC,OAAO;CAE3B,OACE,oBAAC,iBAAD;EAAiB,SAAS,CAAC;EACxB,UAAA,YACC,oBAAC,OAAO,KAAR;GAEE,SACE,mBAAmB,KAAA,IAAY;IAAE,SAAS;IAAG,QAAQ;GAAO;GAE9D,MAAM,mBAAmB,KAAA,IAAY;IAAE,SAAS;IAAG,QAAQ;GAAE;GAC7D,SAAS,mBAAmB,QAAQ;IAAE,QAAQ;IAAG,SAAS;GAAE;GAC5D,OAAO,EAAE,UAAU,SAAS;GAC5B,YAAY;IAAE,UAAU;IAAK,MAAM;GAAU;GAE7C,UAAA,oBAAC,OAAD;IACE,GAAI,sBAAsB;IAC1B,WAAW,GAAG,sBAAsB,CAAC,EAAE,WAAW,SAAS;IAE3D,UAAA,oBAAC,OAAD;KACE,GAAI,qBAAqB;KACzB,WAAW,GACT,qBAAqB,CAAC,EAAE,WACxB,kBACF;KAEA,UAAA,oBAAC,sBAAD;MAEE,OAAO,MAAM;MACL;KACT,CAAA;IACE,CAAA;GACF,CAAA;EACK,GA3BN,mBA2BM,IACV;CACW,CAAA;AAErB;;;;;;;ACxEA,MAAa,qBACX,WACY;CACZ,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CAGpB,MAAM,iBAAiB,kBAAkB,WAAW;CAEpD,MAAM,oBAAoB,mBAAmB,YAAY;CAKzD,MAAM,iBACH,mBACE,sBAAsB,aAAa,YAAY,KAAK,cAAc,MACpE,mBACC,CAAC,mBACA,qBAAqB,cAAc;CAGxC,MAAM,cAAc,YAAY,gBAAgB,GAAG;CAGnD,MAAM,WAAW,kBAAkB,EAAE,SAAS,YAAY,CAAC;CAC3D,MAAM,YAAY,qBAAqB,UAAU,YAAY,MAAM;CAEnE,OACE,qBAAC,OAAD;EAAK,WAAW,UAAU;EAA1B,UAAA;GAEG,QACC,qBAAC,OAAD;IACE,GAAI,cAAc;IAClB,cAAY;IAGZ,WAAW,UAAU;IACrB,MAAK;IANP,UAAA,CAQG,OAGA,aACC,oBAAC,QAAD;KAAM,eAAY;KAAO,WAAU;KAAqB,UAAA;IAElD,CAAA,IACJ,IACD;GACH,CAAA,IAAA;GAGJ,oBAAC,OAAD;IAAK,WAAW,UAAU;IAAU;GAAc,CAAA;GAGlD,oBAAC,0BAAD;IACE,WAAW,UAAU;IACd;IACP,oBAAoB,UAAU;IACxB;GACP,CAAA;EACE;;AAET;;;AChUA,IAAA,oBAAe"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/FieldCard/subcomponents/FieldCardValidationError.tsx","../../src/FieldCard/FieldCard.tsx","../../src/FieldCard/index.ts"],"sourcesContent":["import type { FieldError } from 'react-hook-form';\n\nimport {\n AnimatePresence,\n motion,\n useReducedMotion,\n} from '@fuf-stack/pixel-motion';\nimport { cn } from '@fuf-stack/pixel-utils';\n\nimport { useUniformField } from '../../hooks/useUniformField';\nimport FieldValidationError from '../../partials/FieldValidationError/FieldValidationError';\n\nexport interface FieldCardValidationErrorProps {\n /** CSS class name for the error footer wrapper */\n className?: string;\n /** Error object from parent FieldCard (passed directly to avoid duplicate hook calls) */\n error?: FieldError[] | undefined;\n /** CSS class name for the error text (controls color based on invalid state) */\n errorTextClassName?: string;\n /** Field name */\n name: string;\n}\n\n/**\n * Renders validation errors in the footer of a FieldCard component.\n *\n * This component handles displaying field-level validation errors with proper\n * accessibility attributes and animates them in/out using Framer Motion.\n *\n * Note: Object-level errors (_errors) are always shown when they exist,\n * but the danger styling is controlled by the parent FieldCard based on\n * whether child fields have been touched.\n */\nconst FieldCardValidationError = ({\n className = undefined,\n error = undefined,\n errorTextClassName = undefined,\n name,\n}: FieldCardValidationErrorProps) => {\n const { getErrorMessageProps, getHelperWrapperProps, testId } =\n useUniformField({\n name,\n });\n\n // disable all animation if user prefers reduced motion\n const disableAnimation = useReducedMotion();\n\n // Always show object-level errors (_errors) when they exist\n // @ts-expect-error - error._errors exists but not typed\n const hasErrors = !!error?._errors;\n\n return (\n <AnimatePresence initial={!disableAnimation}>\n {hasErrors ? (\n <motion.div\n key=\"field-card-errors\"\n animate={\n disableAnimation ? undefined : { opacity: 1, height: 'auto' }\n }\n exit={disableAnimation ? undefined : { opacity: 0, height: 0 }}\n initial={disableAnimation ? false : { height: 0, opacity: 0 }}\n style={{ overflow: 'hidden' }}\n transition={{ duration: 0.4, ease: 'circOut' }}\n >\n <div\n {...getHelperWrapperProps()}\n className={cn(getHelperWrapperProps()?.className, className)}\n >\n <div\n {...getErrorMessageProps()}\n className={cn(\n getErrorMessageProps()?.className,\n errorTextClassName,\n )}\n >\n <FieldValidationError\n // @ts-expect-error - error._errors exists but not typed\n error={error._errors}\n testId={testId}\n />\n </div>\n </div>\n </motion.div>\n ) : null}\n </AnimatePresence>\n );\n};\n\nexport default FieldCardValidationError;\n","import type { TVClassName } from '@fuf-stack/pixel-utils';\nimport type { ReactNode } from 'react';\n\nimport { tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\nimport { useDebounce } from '@fuf-stack/pixels';\n\nimport { checkFieldIsRequired, useFormContext } from '../hooks/useFormContext';\nimport { useUniformField } from '../hooks/useUniformField';\nimport FieldCardValidationError from './subcomponents/FieldCardValidationError';\n\n/**\n * Recursively checks if any child field has an error (regardless of touched state).\n * Returns true if at least one child has an error.\n */\nexport const hasAnyChildErrors = (\n errors: Record<string, unknown> | undefined,\n): boolean => {\n if (!errors) {\n return false;\n }\n\n return Object.keys(errors)\n .filter((key) => {\n return key !== '_errors';\n })\n .some((key) => {\n const errorValue = errors[key];\n if (errorValue === undefined) {\n return false;\n }\n // If errorValue is an array, it's a leaf field error\n if (Array.isArray(errorValue)) {\n return true;\n }\n // Recursively check nested objects\n if (typeof errorValue === 'object' && errorValue !== null) {\n return hasAnyChildErrors(errorValue as Record<string, unknown>);\n }\n return false;\n });\n};\n\n/**\n * Recursively checks if any child field is touched.\n * Returns true if at least one child is touched.\n */\nexport const hasAnyChildTouched = (\n touched: Record<string, unknown> | undefined,\n): boolean => {\n if (!touched) {\n return false;\n }\n\n return Object.keys(touched)\n .filter((key) => {\n return key !== '_errors';\n })\n .some((key) => {\n const touchedValue = touched[key];\n if (touchedValue === undefined) {\n return false;\n }\n // If touchedValue is truthy (boolean true), field is touched\n if (touchedValue === true) {\n return true;\n }\n // Recursively check nested objects\n if (typeof touchedValue === 'object' && touchedValue !== null) {\n return hasAnyChildTouched(touchedValue as Record<string, unknown>);\n }\n return false;\n });\n};\n\n/**\n * Recursively checks if any child field with an error is also touched.\n * Returns true if at least one touched child has an error.\n */\nexport const hasVisibleChildErrors = (\n errors: Record<string, unknown> | undefined,\n touched: Record<string, unknown> | undefined,\n): boolean => {\n if (!errors || !touched) {\n return false;\n }\n\n return Object.keys(errors)\n .filter((key) => {\n // Skip object-level errors (_errors) - those are handled separately\n return key !== '_errors';\n })\n .some((key) => {\n const errorValue = errors[key];\n const touchedValue = touched[key];\n\n // If this key doesn't exist in both errors and touched, skip\n if (errorValue === undefined || touchedValue === undefined) {\n return false;\n }\n\n // If errorValue is an array, it's a leaf field error\n if (Array.isArray(errorValue)) {\n // touchedValue being truthy means the field is touched\n return !!touchedValue;\n }\n\n // Recursively check nested objects\n if (typeof errorValue === 'object' && errorValue !== null) {\n return hasVisibleChildErrors(\n errorValue as Record<string, unknown>,\n touchedValue as Record<string, unknown>,\n );\n }\n\n return false;\n });\n};\n\nexport const fieldCardVariants = tv({\n slots: {\n /** base class for the field card wrapper */\n base: [\n // base styles\n 'overflow-hidden rounded-small border bg-content1',\n // animate border color change, respect reduced motion\n 'transition-colors duration-150 motion-reduce:transition-none',\n ],\n /** class for the label/header */\n label: [\n // override HeroUI label positioning and display\n 'pointer-events-auto! static! z-auto! block! w-full!',\n // reset any transforms or translations\n 'translate-x-0! translate-y-0! transform-none!',\n // card header styling - use text-medium (16px) for proper header size\n 'rounded-t-small border-b p-3 font-semibold text-medium',\n // animate border and text color change, respect reduced motion\n 'transition-colors duration-150 motion-reduce:transition-none',\n ],\n /** class for the content */\n content: [\n // same as p-3 of Card component\n 'p-3',\n // default grid for form components (see Grid component)\n 'grid gap-4',\n ],\n /** class for the error footer wrapper */\n errorFooter: [\n 'border-t',\n // force helper to be visible and add padding (pt-1 to compensate for inner content's top padding)\n 'block px-3 pb-2 pt-1',\n // animate border color change, respect reduced motion\n 'transition-colors duration-150 motion-reduce:transition-none',\n ],\n /** class for the error text (empty base, color controlled by variant) */\n errorText: [],\n },\n variants: {\n invalid: {\n true: {\n base: 'border-danger-200',\n label: 'border-danger-200 text-danger',\n errorFooter: 'border-danger-200',\n errorText: '!text-danger text-tiny',\n },\n false: {\n base: 'border-divider',\n label: 'border-divider text-foreground',\n errorFooter: 'border-divider',\n errorText: '!text-foreground-500 text-tiny',\n },\n },\n },\n defaultVariants: {\n invalid: false,\n },\n});\n\ntype ClassName = TVClassName<typeof fieldCardVariants>;\n\nexport interface FieldCardProps {\n /** Content to render inside the card */\n children: ReactNode;\n /** CSS class name */\n className?: ClassName;\n /** Label content for the card header */\n label: ReactNode;\n /** Field name for validation */\n name: string;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\n/**\n * FieldCard component - A card-styled container with label header and error footer\n *\n * Displays form field content in a card layout with:\n * - Label/title in the header\n * - Content in the body\n * - Validation errors in the footer\n * - Danger outline when validation errors exist\n */\nconst FieldCard = ({\n children,\n className: _className = undefined,\n name,\n ...uniformFieldProps\n}: FieldCardProps) => {\n const { error, getLabelProps, label } = useUniformField({\n name,\n ...uniformFieldProps,\n });\n\n const {\n control,\n formState: { touchedFields, submitCount },\n validation,\n } = useFormContext();\n\n // Check if any registered child field is required\n const validationInstance = validation?.baseInstance ?? validation?.instance;\n const registeredFields: string[] = Array.from(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (control as any)._names?.mount ?? [],\n );\n const childFieldPrefix = `${name}.`;\n const isRequired = validationInstance\n ? registeredFields\n .filter((f) => {\n return f.startsWith(childFieldPrefix);\n })\n .some((f) => {\n return checkFieldIsRequired(\n validationInstance,\n f.split('.').filter((k) => {\n return k !== '';\n }),\n );\n })\n : false;\n\n // Get touched state for this field's children by traversing the path\n const getNestedValue = (\n obj: Record<string, unknown> | undefined,\n path: string,\n ): Record<string, unknown> | undefined => {\n if (!obj) {\n return undefined;\n }\n const keys = path.split('.');\n let current: unknown = obj;\n keys.every((key) => {\n if (current && typeof current === 'object') {\n current = (current as Record<string, unknown>)[key];\n return true;\n }\n current = undefined;\n return false;\n });\n return current as Record<string, unknown> | undefined;\n };\n\n const fieldTouched = getNestedValue(touchedFields, name);\n\n // Check for object-level errors (_errors)\n // @ts-expect-error - error._errors exists but not typed\n const hasObjectErrors = !!error?._errors;\n\n const errorRecord = error as unknown as Record<string, unknown>;\n\n // Check if any child field has errors (regardless of touched state)\n const hasChildErrors = hasAnyChildErrors(errorRecord);\n // Check if any child field is touched\n const isAnyChildTouched = hasAnyChildTouched(fieldTouched);\n\n // Show invalid styling (danger border/header/error text) when:\n // 1. Any child field has an error AND (it's touched OR form was submitted), OR\n // 2. Object-level _errors exists AND no child errors AND (any child touched OR submitted)\n const rawShowInvalid =\n (hasChildErrors &&\n (hasVisibleChildErrors(errorRecord, fieldTouched) || submitCount > 0)) ||\n (hasObjectErrors &&\n !hasChildErrors &&\n (isAnyChildTouched || submitCount > 0));\n\n // Debounce to prevent flickering during rapid state changes\n const showInvalid = useDebounce(rawShowInvalid, 200);\n\n // className from slots\n const variants = fieldCardVariants({ invalid: showInvalid });\n const className = variantsToClassNames(variants, _className, 'base');\n\n return (\n <div className={className.base}>\n {/* card header with label */}\n {label ? (\n <div\n {...getLabelProps()}\n aria-level={3}\n // Override getLabelProps className to use our own invalid styling based on hasErrors,\n // not HeroUI's which is based on any child field being invalid\n className={className.label}\n role=\"heading\"\n >\n {label}\n {/* Manual asterisk: getLabelProps uses schema-required for the object itself,\n but FieldCard needs asterisk based on whether any CHILD field is required */}\n {isRequired ? (\n <span aria-hidden=\"true\" className=\"ml-0.5 text-danger\">\n *\n </span>\n ) : null}\n </div>\n ) : null}\n\n {/* card content */}\n <div className={className.content}>{children}</div>\n\n {/* card footer with validation errors - always show _errors, but danger styling controlled by showInvalid */}\n <FieldCardValidationError\n className={className.errorFooter}\n error={error}\n errorTextClassName={className.errorText}\n name={name}\n />\n </div>\n );\n};\n\nexport default FieldCard;\n","import FieldCard from './FieldCard';\n\nexport type { FieldCardProps } from './FieldCard';\n\nexport { fieldCardVariants } from './FieldCard';\n\nexport default FieldCard;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiCA,MAAM,4BAA4B,EAChC,YAAY,KAAA,GACZ,QAAQ,KAAA,GACR,qBAAqB,KAAA,GACrB,WACmC;CACnC,MAAM,EAAE,sBAAsB,uBAAuB,WACnD,gBAAgB,EACd,KACF,CAAC;CAGH,MAAM,mBAAmB,iBAAiB;CAI1C,MAAM,YAAY,CAAC,CAAC,OAAO;CAE3B,OACE,oBAAC,iBAAD;EAAiB,SAAS,CAAC;EACxB,UAAA,YACC,oBAAC,OAAO,KAAR;GAEE,SACE,mBAAmB,KAAA,IAAY;IAAE,SAAS;IAAG,QAAQ;GAAO;GAE9D,MAAM,mBAAmB,KAAA,IAAY;IAAE,SAAS;IAAG,QAAQ;GAAE;GAC7D,SAAS,mBAAmB,QAAQ;IAAE,QAAQ;IAAG,SAA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ils";
|
|
2
2
|
import { Button } from "@fuf-stack/pixels";
|
|
3
|
-
import { FaBullseye } from "react-icons/fa6";
|
|
4
3
|
import { jsx } from "react/jsx-runtime";
|
|
5
|
-
|
|
4
|
+
import { FaBullseye } from "react-icons/fa6";
|
|
5
|
+
// src/partials/FieldCopyTestIdButton/FieldCopyTestIdButton.tsx
|
|
6
6
|
const FieldCopyTestIdButton = ({ className = void 0, testId }) => {
|
|
7
7
|
const copyToClipboard = () => {
|
|
8
8
|
navigator.clipboard.writeText(testId).catch((err) => {
|
|
@@ -17,10 +17,8 @@ const FieldCopyTestIdButton = ({ className = void 0, testId }) => {
|
|
|
17
17
|
variant: "light"
|
|
18
18
|
});
|
|
19
19
|
};
|
|
20
|
-
|
|
21
|
-
//#region src/partials/FieldCopyTestIdButton/index.ts
|
|
20
|
+
// src/partials/FieldCopyTestIdButton/index.ts
|
|
22
21
|
var FieldCopyTestIdButton_default = FieldCopyTestIdButton;
|
|
23
|
-
//#endregion
|
|
24
22
|
export { FieldCopyTestIdButton_default as t };
|
|
25
23
|
|
|
26
|
-
//# sourceMappingURL=FieldCopyTestIdButton-
|
|
24
|
+
//# sourceMappingURL=FieldCopyTestIdButton-Y9SfvaM9.mjs.map
|