diff --git a/.changeset/stale-olives-hammer.md b/.changeset/stale-olives-hammer.md new file mode 100644 index 0000000..5e02075 --- /dev/null +++ b/.changeset/stale-olives-hammer.md @@ -0,0 +1,5 @@ +--- +"@openfun/cunningham-react": minor +--- + +Introduce a common DatePickerAux component diff --git a/packages/react/src/components/Forms/DatePicker/DatePickerAux.tsx b/packages/react/src/components/Forms/DatePicker/DatePickerAux.tsx new file mode 100644 index 0000000..1d49a00 --- /dev/null +++ b/packages/react/src/components/Forms/DatePicker/DatePickerAux.tsx @@ -0,0 +1,173 @@ +import React, { + forwardRef, + PropsWithChildren, + Ref, + useMemo, + useRef, +} from "react"; +import { + DateRangePickerState, + DatePickerState, +} from "@react-stately/datepicker"; +import { DateRangePickerAria, DatePickerAria } from "@react-aria/datepicker"; +import classNames from "classnames"; +import { Button } from ":/components/Button"; +import { Popover } from ":/components/Popover"; +import { Field, FieldProps } from ":/components/Forms/Field"; +import { useCunningham } from ":/components/Provider"; +import { StringOrDate } from ":/components/Forms/DatePicker/types"; +import { + Calendar, + CalendarRange, +} from ":/components/Forms/DatePicker/Calendar"; + +export type DatePickerAuxSubProps = FieldProps & { + label?: string; + minValue?: StringOrDate; + maxValue?: StringOrDate; + disabled?: boolean; + name?: string; +}; + +export type DatePickerAuxProps = PropsWithChildren & + DatePickerAuxSubProps & { + pickerState: DateRangePickerState | DatePickerState; + pickerProps: Pick< + DateRangePickerAria | DatePickerAria, + "buttonProps" | "groupProps" + >; + calendar: React.ReactElement; + isFocused: boolean; + labelAsPlaceholder: boolean; + optionalClassName?: string; + onClear: () => void; + }; + +/** + * This component is used by date and date range picker components. + * It contains the common logic between the two. + */ +const DatePickerAux = forwardRef( + ( + { + pickerState, + pickerProps, + onClear, + isFocused, + labelAsPlaceholder, + calendar, + children, + name, + disabled = false, + optionalClassName, + ...props + }: DatePickerAuxProps, + ref: Ref + ) => { + const { t } = useCunningham(); + const pickerRef = useRef(null); + + const isDateInvalid = useMemo( + () => + pickerState.validationState === "invalid" || props.state === "error", + [pickerState.validationState, props.state] + ); + + // onPress props don't exist on the