[Breaking Change] Implement reliable date picker utils to handle all timezone combinations (#15377)
This PR implements the necessary tools to have `react-datepicker` calendar and our date picker components work reliably no matter the timezone difference between the user execution environment and the user application timezone. Fixes https://github.com/twentyhq/core-team-issues/issues/1781 This PR won't cover everything needed to have Twenty handle timezone properly, here is the follow-up issue : https://github.com/twentyhq/core-team-issues/issues/1807 # Features in this PR This PR brings a lot of features that have to be merged together. - DATE field type is now handled as string only, because it shouldn't involve timezone nor the JS Date object at all, since it is a day like a birthday date, and not an absolute point in time. - DATE_TIME field wasn't properly handled when the user settings timezone was different from the system one - A timezone abbreviation suffix has been added to most DATE_TIME display component, only when the timezone is different from the system one in the settings. - A lot of bugs, small features and improvements have been made here : https://github.com/twentyhq/core-team-issues/issues/1781 # Handling of timezones ## Essential concepts This topic is so complex and easy to misunderstand that it is necessary to define the precise terms and concepts first. It resembles character encoding and should be treated with the same care. - Wall-clock time : the time expressed in the timezone of a user, it is distinct from the absolute point in time it points to, much like a pointer being a different value than the value that it points to. - Absolute time : a point in time, regardless of the timezone, it is an objective point in time, of course it has to be expressed in a given timezone, because we have to talk about when it is located in time between humans, but it is in fact distinct from any wall clock time, it exists in itself without any clock running on earth. However, by convention the low-level way to store an absolute point in time is in UTC, which is a timezone, because there is no way to store an absolute point in time without a referential, much like a point in space cannot be stored without a referential. - DST : Daylight Save Time, makes the timezone shift in a specific period every year in a given timezone, to make better use of longer days for various reasons, not all timezones have DST. DST can be 1 hour or 30 min, 45 min, which makes computation difficult. - UTC : It is NOT an “absolute timezone”, it is the wall-clock time at 0° longitude without DST, which is an arbitrary and shared human convention. UTC is often used as the standard reference wall-clock time for talking about absolute point in time without having to do timezone and DST arithmetic. PostgreSQL stores everything in UTC by convention, but outputs everything in the server’s SESSION TIMEZONE. ## How should an absolute point in time be stored ? Since an absolute point in time is essentially distinct from its timezone it could be stored in an absolute way, but in practice it is impossible to store an absolute point in time without a referential. We have to say that a rocket launched at X given time, in UTC, EST, CET, etc. And of course, someone in China will say that it launched at 10:30, while in San Francisco it will have launched at 19:30, but it is THE SAME absolute point in time. Let’s take a related example in computer science with character encoding. If a text is stored without the associated encoding table, the correct meaning associated to the bits stored in memory can be lost forever. It can become impossible for a program to guess what encoding table should be used for a given text stored as bits, thus the glitches that appeared a lot back in the early days of internet and document processing. The same can happen with date time storing, if we don’t have the timezone associated with the absolute point in time, the information of when it absolutely happened is lost. It is NOT necessary to store an absolute point in time in UTC, it is more of a standard and practical wall-clock time to be associated with an absolute point in time. But an absolute point in time MUST be store with a timezone, with its time referential, otherwise the information of when it absolutely happened is lost. For example, it is easier to pass around a date as a string in UTC, like `2024-01-02T00:00:00Z` because it allows front-end and back-end code to “talk” in the same standard and DST-free wall-clock time, BUT it is not necessary. Because we have date libraries that operate on the standard ISO timezone tables, we can talk in different timezone and let the libraries handle the conversion internally. It is false to say that UTC is an absolute timezone or an absolute point in time, it is just the standard, conventional time referential, because one can perfectly store every absolute points in time in UTC+10 with a complex DST table and have the exactly correct absolute points in time, without any loss of information, without having any UTC+0 dates involved. Thus storing an absolute point in time without a timezone associated, for example with `timestamp` PostgreSQL data type, is equivalent to storing a wall-clock time and then throwing away voluntarily the information that allows to know when it absolutely happened, which is a voluntary data-loss if the code that stores and retrieves those wall-clock points in time don’t store the associated timezone somewhere. This is why we use `timestamptz` type in PostgreSQL, so that we make sure that the correct absolute point in time is stored at the exact time we send it to PostgreSQL server, no matter the front-end, back-end and SQL server's timezone differences. ## The JavaScript Date object The native JavaScript Date object is now officially considered legacy ([source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)), the Date object stores an absolute point in time BUT it forces the storage to use its execution environment timezone, and one CANNOT modify this timezone, this is a legacy behavior. To obtain the desired result and store an absolute point in time with an arbitrary timezone there are several options : - The new Temporal API that is the successor of the legacy Date object. - Moment / Luxon / @date-fns/tz that expose objects that allow to use any timezone to store an absolute point in time. ## How PostgreSQL stores absolute point in times PostgreSQL stores absolute points in time internally in UTC ([source](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-INPUT-TIME-STAMPS)), but the output date is expressed in the server’s session timezone ([source](https://www.postgresql.org/docs/current/sql-set.html)) which can be different from UTC. Example with the object companies in Twenty seed database, on a local instance, with a new “datetime” custom column : <img width="374" height="554" alt="image" src="https://github.com/user-attachments/assets/4394cb43-d97e-4479-801d-ca068f800e39" /> <img width="516" height="524" alt="image" src="https://github.com/user-attachments/assets/b652f36a-d2e2-47a4-8950-647ca688cbbd" /> ## Why can’t I just use the JavaScript native Date object with some manual logic ? Because the JavaScript Date object does not allow to change its internal timezone, the libraries that are based on it will behave on the execution environment timezone, thus leading to bugs that appear only on the computers of users in a timezone but not for other in another timezone. In our case the `react-datepicker` library forces to use the `Date` object, thus forcing the calendar to behave in the execution environment system timezone, which causes a lot of problems when we decide to display the Twenty application DATE_TIME values in another timezone than the user system one, the bugs that appear will be of the off-by-one date class, for example clicking on 23 will select 24, thus creating an unreliable feature for some system / application timezone combinations. A solution could be to manually compute the difference of minutes between the application user and the system timezones, but that’s not reliable because of DST which makes this computation unreliable when DST are applied at different period of the year for the two timezones. ## Why can’t I compute the timezone difference manually ? Because of DST, the work to compute the timezone difference reliably, not just for the usual happy path, is equivalent to developing the internal mechanism of a date timezone library, which is equivalent to use a library that handles timezones. ## Using `@date-fns/tz` to solve this problem We could have used `luxon` but it has a heavy bundle size, so instead we rely here on `@date-fns/tz` (~1kB) which gives us a `TZDate` object that allows to use any given timezone to store an absolute point-in-time. The solution here is to trick `react-datepicker` by shifting a Date object by the difference of timezone between the user application timezone and the system timezone. Let’s take a concerte example. System timezone : Midway, ⇒ UTC-11:00, has no DST. User application timezone : Auckland, NZ ⇒ UTC+13:00, has a DST. We’ll take the NZ daylight time, so that will make a timezone difference of 24 hours ! Let’s take an error-prone date : `2025-01-01T00:00:00` . This date is usually a good test-case because it can generate three classes of bugs : off-by-one day bugs, off-by-one month bugs and off-by-one year bugs, at the same time. Here is the absolute point in time we take expressed in the different wall-clock time points we manipulate Case | In system timezone ⇒ UTC-11 | In UTC | In user application timezone ⇒ UTC+13 -- | -- | -- | -- Original date | `2024-12-31T00:00:00-11:00` | `2024-12-31T11:00:00Z` | `2025-01-01T00:00:00+13:00` Date shifted for react-datepicker | `2025-01-01T00:00:00-11:00` | `2025-01-01T11:00:00Z` | `2025-01-02T00:00:00+13:00` We can see with this table that we have the number part of the date that is the same (`2025-01-01T00:00:00`) but with a different timezone to “trick” `react-datepicker` and have it display the correct day in its calendar. You can find the code in the hooks `useTurnPointInTimeIntoReactDatePickerShiftedDate` and `useTurnReactDatePickerShiftedDateBackIntoPointInTime` that contain the logic that produces the above table internally. ## Miscellaneous Removed FormDateFieldInput and FormDateTimeFieldInput stories as they do not behave the same depending of the execution environment and it would be easier to put them back after having refactored FormDateFieldInput and FormDateTimeFieldInput --------- Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
+82
-110
@@ -1,5 +1,4 @@
|
||||
import styled from '@emotion/styled';
|
||||
import { addMonths, setDate, setMonth, setYear, subMonths } from 'date-fns';
|
||||
import { lazy, Suspense, type ComponentType } from 'react';
|
||||
import type { ReactDatePickerProps as ReactDatePickerLibProps } from 'react-datepicker';
|
||||
import Skeleton, { SkeletonTheme } from 'react-loading-skeleton';
|
||||
@@ -8,19 +7,23 @@ import { SKELETON_LOADER_HEIGHT_SIZES } from '@/activities/components/SkeletonLo
|
||||
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
|
||||
import { CalendarStartDay } from '@/localization/constants/CalendarStartDay';
|
||||
import { detectCalendarStartDay } from '@/localization/utils/detection/detectCalendarStartDay';
|
||||
import { AbsoluteDatePickerHeader } from '@/ui/input/components/internal/date/components/AbsoluteDatePickerHeader';
|
||||
import { DateTimeInput } from '@/ui/input/components/internal/date/components/DateTimeInput';
|
||||
import { DatePickerHeader } from '@/ui/input/components/internal/date/components/DatePickerHeader';
|
||||
import { RelativeDatePickerHeader } from '@/ui/input/components/internal/date/components/RelativeDatePickerHeader';
|
||||
import { getHighlightedDates } from '@/ui/input/components/internal/date/utils/getHighlightedDates';
|
||||
import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
|
||||
import { useTheme } from '@emotion/react';
|
||||
import { t } from '@lingui/core/macro';
|
||||
import { addMonths, setMonth, setYear, subMonths } from 'date-fns';
|
||||
import 'react-datepicker/dist/react-datepicker.css';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
|
||||
import { type Nullable } from 'twenty-shared/types';
|
||||
import {
|
||||
type VariableDateViewFilterValueDirection,
|
||||
type VariableDateViewFilterValueUnit,
|
||||
} from 'twenty-shared/types';
|
||||
getDateFromPlainDate,
|
||||
getPlainDateFromDate,
|
||||
isDefined,
|
||||
type RelativeDateFilter,
|
||||
} from 'twenty-shared/utils';
|
||||
import { IconCalendarX } from 'twenty-ui/display';
|
||||
import {
|
||||
MenuItemLeftContent,
|
||||
@@ -32,8 +35,10 @@ export const MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID =
|
||||
export const MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID =
|
||||
'date-picker-month-and-year-dropdown-year-select';
|
||||
|
||||
const DATE_PICKER_CONTAINER_WIDTH = 280;
|
||||
|
||||
const StyledContainer = styled.div<{ calendarDisabled?: boolean }>`
|
||||
width: 280px;
|
||||
width: ${DATE_PICKER_CONTAINER_WIDTH}px;
|
||||
|
||||
& .react-datepicker {
|
||||
border-color: ${({ theme }) => theme.border.color.light};
|
||||
@@ -295,32 +300,22 @@ const StyledDatePickerFallback = styled.div`
|
||||
width: 280px;
|
||||
`;
|
||||
|
||||
type DateTimePickerProps = {
|
||||
type DatePickerProps = {
|
||||
isRelative?: boolean;
|
||||
hideHeaderInput?: boolean;
|
||||
date: Date | null;
|
||||
relativeDate?: {
|
||||
direction: VariableDateViewFilterValueDirection;
|
||||
amount?: number;
|
||||
unit: VariableDateViewFilterValueUnit;
|
||||
date: Nullable<string>;
|
||||
relativeDate?: RelativeDateFilter & {
|
||||
start: string;
|
||||
end: string;
|
||||
};
|
||||
highlightedDateRange?: {
|
||||
start: Date;
|
||||
end: Date;
|
||||
};
|
||||
onClose?: (date: Date | null) => void;
|
||||
onChange?: (date: Date | null) => void;
|
||||
onClose?: (date: string | null) => void;
|
||||
onChange?: (date: string | null) => void;
|
||||
onRelativeDateChange?: (
|
||||
relativeDate: {
|
||||
direction: VariableDateViewFilterValueDirection;
|
||||
amount?: number;
|
||||
unit: VariableDateViewFilterValueUnit;
|
||||
} | null,
|
||||
relativeDateFilter: RelativeDateFilter | null,
|
||||
) => void;
|
||||
clearable?: boolean;
|
||||
isDateTimeInput?: boolean;
|
||||
onEnter?: (date: Date | null) => void;
|
||||
onEscape?: (date: Date | null) => void;
|
||||
onEnter?: (date: string | null) => void;
|
||||
onEscape?: (date: string | null) => void;
|
||||
keyboardEventsDisabled?: boolean;
|
||||
onClear?: () => void;
|
||||
};
|
||||
@@ -336,20 +331,19 @@ const ReactDatePicker = lazy<ComponentType<DatePickerPropsType>>(() =>
|
||||
})),
|
||||
);
|
||||
|
||||
export const DateTimePicker = ({
|
||||
export const DatePicker = ({
|
||||
date,
|
||||
onChange,
|
||||
onClose,
|
||||
clearable = true,
|
||||
isDateTimeInput,
|
||||
onClear,
|
||||
isRelative,
|
||||
relativeDate,
|
||||
onRelativeDateChange,
|
||||
highlightedDateRange,
|
||||
hideHeaderInput,
|
||||
}: DateTimePickerProps) => {
|
||||
const internalDate = date ?? new Date();
|
||||
}: DatePickerProps) => {
|
||||
const dateOrToday = date ?? getPlainDateFromDate(new Date());
|
||||
const shiftedDateForReactPicker = getDateFromPlainDate(dateOrToday);
|
||||
|
||||
const theme = useTheme();
|
||||
|
||||
@@ -366,85 +360,76 @@ export const DateTimePicker = ({
|
||||
closeDropdownMonthSelect(MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID);
|
||||
};
|
||||
|
||||
const handleClose = (newDate: Date) => {
|
||||
const handleClose = (newDate: string) => {
|
||||
closeDropdowns();
|
||||
onClose?.(newDate);
|
||||
};
|
||||
|
||||
const handleChangeMonth = (month: number) => {
|
||||
const newDate = new Date(internalDate);
|
||||
newDate.setMonth(month);
|
||||
onChange?.(newDate);
|
||||
const newDate = setMonth(shiftedDateForReactPicker, month);
|
||||
|
||||
const plainDate = getPlainDateFromDate(newDate);
|
||||
|
||||
onChange?.(plainDate);
|
||||
};
|
||||
|
||||
const handleAddMonth = () => {
|
||||
const dateParsed = addMonths(internalDate, 1);
|
||||
onChange?.(dateParsed);
|
||||
const dateParsed = addMonths(shiftedDateForReactPicker, 1);
|
||||
|
||||
const plainDate = getPlainDateFromDate(dateParsed);
|
||||
|
||||
onChange?.(plainDate);
|
||||
};
|
||||
|
||||
const handleSubtractMonth = () => {
|
||||
const dateParsed = subMonths(internalDate, 1);
|
||||
onChange?.(dateParsed);
|
||||
const dateParsed = subMonths(shiftedDateForReactPicker, 1);
|
||||
|
||||
const plainDate = getPlainDateFromDate(dateParsed);
|
||||
|
||||
onChange?.(plainDate);
|
||||
};
|
||||
|
||||
const handleChangeYear = (year: number) => {
|
||||
const dateParsed = setYear(internalDate, year);
|
||||
onChange?.(dateParsed);
|
||||
const dateParsed = setYear(shiftedDateForReactPicker, year);
|
||||
|
||||
const plainDate = getPlainDateFromDate(dateParsed);
|
||||
|
||||
onChange?.(plainDate);
|
||||
};
|
||||
|
||||
const handleDateChange = (date: Date) => {
|
||||
let dateParsed = setYear(internalDate, date.getFullYear());
|
||||
dateParsed = setMonth(dateParsed, date.getMonth());
|
||||
dateParsed = setDate(dateParsed, date.getDate());
|
||||
const plainDate = getPlainDateFromDate(date);
|
||||
|
||||
onChange?.(dateParsed);
|
||||
onChange?.(plainDate);
|
||||
};
|
||||
|
||||
const handleDateSelect = (date: Date) => {
|
||||
let dateParsed = setYear(internalDate, date.getFullYear());
|
||||
dateParsed = setMonth(dateParsed, date.getMonth());
|
||||
dateParsed = setDate(dateParsed, date.getDate());
|
||||
const plainDate = getPlainDateFromDate(date);
|
||||
|
||||
handleClose?.(dateParsed);
|
||||
handleClose?.(plainDate);
|
||||
};
|
||||
|
||||
const dateWithoutTime = new Date(
|
||||
internalDate.getUTCFullYear(),
|
||||
internalDate.getUTCMonth(),
|
||||
internalDate.getUTCDate(),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
const highlightedDates =
|
||||
isRelative && isDefined(relativeDate?.end) && isDefined(relativeDate?.start)
|
||||
? getHighlightedDates({
|
||||
start: getDateFromPlainDate(relativeDate.start),
|
||||
end: getDateFromPlainDate(relativeDate.end),
|
||||
})
|
||||
: [];
|
||||
|
||||
// We have to force a end of day on the computer local timezone with the given date
|
||||
// Because JS Date API cannot hold a timezone other than the local one
|
||||
// And if we don't do that workaround we will have problems when changing the date
|
||||
// Because the shown date will have 1 day more or less than the real date
|
||||
// Leading to bugs where we select 1st of January and it shows 31st of December for example
|
||||
const endOfDayInLocalTimezone = new Date(
|
||||
internalDate.getFullYear(),
|
||||
internalDate.getMonth(),
|
||||
internalDate.getDate(),
|
||||
23,
|
||||
59,
|
||||
59,
|
||||
999,
|
||||
);
|
||||
|
||||
const dateToUse = isDateTimeInput ? endOfDayInLocalTimezone : dateWithoutTime;
|
||||
|
||||
const highlightedDates = getHighlightedDates(highlightedDateRange);
|
||||
|
||||
const hasDate = date != null;
|
||||
const dateAsDate = isDefined(date) ? getDateFromPlainDate(date) : undefined;
|
||||
|
||||
const selectedDates = isRelative
|
||||
? highlightedDates
|
||||
: hasDate
|
||||
? [dateToUse]
|
||||
: isDefined(dateAsDate)
|
||||
? [dateAsDate]
|
||||
: [];
|
||||
|
||||
const calendarStartDay =
|
||||
currentWorkspaceMember?.calendarStartDay === CalendarStartDay.SYSTEM
|
||||
? CalendarStartDay[detectCalendarStartDay()]
|
||||
: (currentWorkspaceMember?.calendarStartDay ?? undefined);
|
||||
|
||||
return (
|
||||
<StyledContainer calendarDisabled={isRelative}>
|
||||
<div className={clearable ? 'clearable ' : ''}>
|
||||
@@ -454,23 +439,23 @@ export const DateTimePicker = ({
|
||||
<SkeletonTheme
|
||||
baseColor={theme.background.tertiary}
|
||||
highlightColor={theme.background.transparent.lighter}
|
||||
borderRadius={4}
|
||||
borderRadius={2}
|
||||
>
|
||||
<Skeleton
|
||||
width={200}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.m}
|
||||
/>
|
||||
<Skeleton
|
||||
width={240}
|
||||
width={DATE_PICKER_CONTAINER_WIDTH - 16}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.l}
|
||||
/>
|
||||
<Skeleton
|
||||
width={220}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.m}
|
||||
width={DATE_PICKER_CONTAINER_WIDTH - 16}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.l}
|
||||
/>
|
||||
<Skeleton
|
||||
width={180}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.s}
|
||||
width={DATE_PICKER_CONTAINER_WIDTH - 16}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.l}
|
||||
/>
|
||||
<Skeleton
|
||||
width={DATE_PICKER_CONTAINER_WIDTH - 16}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.l}
|
||||
/>
|
||||
</SkeletonTheme>
|
||||
</StyledDatePickerFallback>
|
||||
@@ -478,24 +463,12 @@ export const DateTimePicker = ({
|
||||
>
|
||||
<ReactDatePicker
|
||||
open={true}
|
||||
selected={hasDate ? dateToUse : undefined}
|
||||
selected={shiftedDateForReactPicker}
|
||||
selectedDates={selectedDates}
|
||||
openToDate={hasDate ? dateToUse : new Date()}
|
||||
openToDate={shiftedDateForReactPicker}
|
||||
disabledKeyboardNavigation
|
||||
onChange={handleDateChange as any}
|
||||
calendarStartDay={
|
||||
currentWorkspaceMember?.calendarStartDay ===
|
||||
CalendarStartDay.SYSTEM
|
||||
? CalendarStartDay[detectCalendarStartDay()]
|
||||
: (currentWorkspaceMember?.calendarStartDay ?? undefined)
|
||||
}
|
||||
customInput={
|
||||
<DateTimeInput
|
||||
date={internalDate}
|
||||
isDateTimeInput={isDateTimeInput}
|
||||
onChange={onChange}
|
||||
/>
|
||||
}
|
||||
onChange={handleDateChange}
|
||||
calendarStartDay={calendarStartDay}
|
||||
renderCustomHeader={({
|
||||
prevMonthButtonDisabled,
|
||||
nextMonthButtonDisabled,
|
||||
@@ -508,8 +481,8 @@ export const DateTimePicker = ({
|
||||
onChange={onRelativeDateChange}
|
||||
/>
|
||||
) : (
|
||||
<AbsoluteDatePickerHeader
|
||||
date={internalDate}
|
||||
<DatePickerHeader
|
||||
date={dateOrToday}
|
||||
onChange={onChange}
|
||||
onChangeMonth={handleChangeMonth}
|
||||
onChangeYear={handleChangeYear}
|
||||
@@ -517,7 +490,6 @@ export const DateTimePicker = ({
|
||||
onSubtractMonth={handleSubtractMonth}
|
||||
prevMonthButtonDisabled={prevMonthButtonDisabled}
|
||||
nextMonthButtonDisabled={nextMonthButtonDisabled}
|
||||
isDateTimeInput={isDateTimeInput}
|
||||
hideInput={hideHeaderInput}
|
||||
/>
|
||||
)
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import styled from '@emotion/styled';
|
||||
|
||||
import { Select } from '@/ui/input/components/Select';
|
||||
|
||||
import { DatePickerInput } from '@/ui/input/components/internal/date/components/DatePickerInput';
|
||||
import { getMonthSelectOptions } from '@/ui/input/components/internal/date/utils/getMonthSelectOptions';
|
||||
import { ClickOutsideListenerContext } from '@/ui/utilities/pointer-event/contexts/ClickOutsideListenerContext';
|
||||
import { IconChevronLeft, IconChevronRight } from 'twenty-ui/display';
|
||||
import { LightIconButton } from 'twenty-ui/input';
|
||||
import {
|
||||
MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID,
|
||||
MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID,
|
||||
} from './DateTimePicker';
|
||||
|
||||
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
|
||||
import { parse } from 'date-fns';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import { DATE_TYPE_FORMAT } from 'twenty-shared/constants';
|
||||
import { SOURCE_LOCALE } from 'twenty-shared/translations';
|
||||
|
||||
const StyledCustomDatePickerHeader = styled.div`
|
||||
align-items: center;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
padding-left: ${({ theme }) => theme.spacing(2)};
|
||||
padding-right: ${({ theme }) => theme.spacing(2)};
|
||||
padding-top: ${({ theme }) => theme.spacing(2)};
|
||||
|
||||
gap: ${({ theme }) => theme.spacing(1)};
|
||||
`;
|
||||
|
||||
const years = Array.from(
|
||||
{ length: 200 },
|
||||
(_, i) => new Date().getFullYear() + 50 - i,
|
||||
).map((year) => ({ label: year.toString(), value: year }));
|
||||
|
||||
type DatePickerHeaderProps = {
|
||||
date: string | null;
|
||||
onChange?: (date: string | null) => void;
|
||||
onChangeMonth: (month: number) => void;
|
||||
onChangeYear: (year: number) => void;
|
||||
onAddMonth: () => void;
|
||||
onSubtractMonth: () => void;
|
||||
prevMonthButtonDisabled: boolean;
|
||||
nextMonthButtonDisabled: boolean;
|
||||
hideInput?: boolean;
|
||||
};
|
||||
|
||||
export const DatePickerHeader = ({
|
||||
date,
|
||||
onChange,
|
||||
onChangeMonth,
|
||||
onChangeYear,
|
||||
onAddMonth,
|
||||
onSubtractMonth,
|
||||
prevMonthButtonDisabled,
|
||||
nextMonthButtonDisabled,
|
||||
hideInput = false,
|
||||
}: DatePickerHeaderProps) => {
|
||||
const currentWorkspaceMember = useRecoilValue(currentWorkspaceMemberState);
|
||||
const userLocale = currentWorkspaceMember?.locale ?? SOURCE_LOCALE;
|
||||
|
||||
const dateParsed = date ? parse(date, DATE_TYPE_FORMAT, new Date()) : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{!hideInput && <DatePickerInput date={date} onChange={onChange} />}
|
||||
<StyledCustomDatePickerHeader>
|
||||
<ClickOutsideListenerContext.Provider
|
||||
value={{
|
||||
excludedClickOutsideId: MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID,
|
||||
}}
|
||||
>
|
||||
<Select
|
||||
dropdownId={MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID}
|
||||
options={getMonthSelectOptions(userLocale)}
|
||||
onChange={onChangeMonth}
|
||||
value={dateParsed?.getMonth()}
|
||||
fullWidth
|
||||
/>
|
||||
</ClickOutsideListenerContext.Provider>
|
||||
<ClickOutsideListenerContext.Provider
|
||||
value={{
|
||||
excludedClickOutsideId: MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID,
|
||||
}}
|
||||
>
|
||||
<Select
|
||||
dropdownId={MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID}
|
||||
onChange={onChangeYear}
|
||||
value={dateParsed?.getFullYear()}
|
||||
options={years}
|
||||
fullWidth
|
||||
/>
|
||||
</ClickOutsideListenerContext.Provider>
|
||||
<LightIconButton
|
||||
Icon={IconChevronLeft}
|
||||
onClick={onSubtractMonth}
|
||||
size="medium"
|
||||
disabled={prevMonthButtonDisabled}
|
||||
/>
|
||||
<LightIconButton
|
||||
Icon={IconChevronRight}
|
||||
onClick={onAddMonth}
|
||||
size="medium"
|
||||
disabled={nextMonthButtonDisabled}
|
||||
/>
|
||||
</StyledCustomDatePickerHeader>
|
||||
</>
|
||||
);
|
||||
};
|
||||
+37
-38
@@ -5,14 +5,15 @@ import { useIMask } from 'react-imask';
|
||||
|
||||
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
|
||||
import { DATE_BLOCKS } from '@/ui/input/components/internal/date/constants/DateBlocks';
|
||||
import { DATE_TIME_BLOCKS } from '@/ui/input/components/internal/date/constants/DateTimeBlocks';
|
||||
import { MAX_DATE } from '@/ui/input/components/internal/date/constants/MaxDate';
|
||||
import { MIN_DATE } from '@/ui/input/components/internal/date/constants/MinDate';
|
||||
import { useParseDateInputStringToJSDate } from '@/ui/input/components/internal/date/hooks/useParseDateInputStringToJSDate';
|
||||
import { useParsePlainDateToDateInputString } from '@/ui/input/components/internal/date/hooks/useParsePlainDateToDateInputString';
|
||||
import { getDateMask } from '@/ui/input/components/internal/date/utils/getDateMask';
|
||||
import { getDateTimeMask } from '@/ui/input/components/internal/date/utils/getDateTimeMask';
|
||||
import { isNull } from '@sniptt/guards';
|
||||
|
||||
import { useParseDateInputStringToPlainDate } from '@/ui/input/components/internal/date/hooks/useParseDateInputStringToPlainDate';
|
||||
import { useParseJSDateToIMaskDateInputString } from '@/ui/input/components/internal/date/hooks/useParseJSDateToIMaskDateInputString';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { useDateParser } from '../../hooks/useDateParser';
|
||||
|
||||
const StyledInputContainer = styled.div`
|
||||
align-items: center;
|
||||
@@ -40,35 +41,37 @@ const StyledInput = styled.input<{ hasError?: boolean }>`
|
||||
`};
|
||||
`;
|
||||
|
||||
type DateTimeInputProps = {
|
||||
onChange?: (date: Date | null) => void;
|
||||
date: Date | null;
|
||||
isDateTimeInput?: boolean;
|
||||
type DatePickerInputProps = {
|
||||
onChange?: (date: string | null) => void;
|
||||
date: string | null;
|
||||
};
|
||||
|
||||
export const DateTimeInput = ({
|
||||
date,
|
||||
onChange,
|
||||
isDateTimeInput,
|
||||
}: DateTimeInputProps) => {
|
||||
const [hasError, setHasError] = useState(false);
|
||||
export const DatePickerInput = ({ date, onChange }: DatePickerInputProps) => {
|
||||
const { dateFormat } = useDateTimeFormat();
|
||||
const { parseToString, parseToDate } = useDateParser({
|
||||
isDateTimeInput: isDateTimeInput === true,
|
||||
});
|
||||
|
||||
const handleParseStringToDate = (str: string) => {
|
||||
const date = parseToDate(str);
|
||||
const [internalDate, setInternalDate] = useState(date);
|
||||
|
||||
setHasError(isNull(date) === true);
|
||||
const { parseDateInputStringToPlainDate } =
|
||||
useParseDateInputStringToPlainDate();
|
||||
const { parseDateInputStringToJSDate } = useParseDateInputStringToJSDate();
|
||||
const { parsePlainDateToDateInputString } =
|
||||
useParsePlainDateToDateInputString();
|
||||
|
||||
return date;
|
||||
const { parseIMaskJSDateIMaskDateInputString } =
|
||||
useParseJSDateToIMaskDateInputString();
|
||||
|
||||
const parseIMaskDateInputStringToJSDate = (newDateAsString: string) => {
|
||||
const newDate = parseDateInputStringToJSDate(newDateAsString);
|
||||
|
||||
return newDate;
|
||||
};
|
||||
|
||||
const pattern = isDateTimeInput
|
||||
? getDateTimeMask(dateFormat)
|
||||
: getDateMask(dateFormat);
|
||||
const blocks = isDateTimeInput ? DATE_TIME_BLOCKS : DATE_BLOCKS;
|
||||
const pattern = getDateMask(dateFormat);
|
||||
const blocks = DATE_BLOCKS;
|
||||
|
||||
const defaultValue = internalDate
|
||||
? (parsePlainDateToDateInputString(internalDate) ?? undefined)
|
||||
: undefined;
|
||||
|
||||
const { ref, setValue, value } = useIMask(
|
||||
{
|
||||
@@ -77,30 +80,27 @@ export const DateTimeInput = ({
|
||||
blocks,
|
||||
min: MIN_DATE,
|
||||
max: MAX_DATE,
|
||||
format: (date: any) => parseToString(date),
|
||||
parse: handleParseStringToDate,
|
||||
format: (date: any) => parseIMaskJSDateIMaskDateInputString(date),
|
||||
parse: parseIMaskDateInputStringToJSDate,
|
||||
lazy: false,
|
||||
autofix: true,
|
||||
},
|
||||
{
|
||||
onComplete: (value) => {
|
||||
const parsedDate = parseToDate(value);
|
||||
defaultValue,
|
||||
onComplete: (newValue) => {
|
||||
const parsedDate = parseDateInputStringToPlainDate(newValue);
|
||||
|
||||
onChange?.(parsedDate);
|
||||
},
|
||||
onAccept: () => {
|
||||
setHasError(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDefined(date)) {
|
||||
return;
|
||||
if (isDefined(date) && internalDate !== date) {
|
||||
setInternalDate(date);
|
||||
setValue(parsePlainDateToDateInputString(date));
|
||||
}
|
||||
|
||||
setValue(parseToString(date));
|
||||
}, [date, setValue, parseToString]);
|
||||
}, [date, internalDate, parsePlainDateToDateInputString, setValue]);
|
||||
|
||||
return (
|
||||
<StyledInputContainer>
|
||||
@@ -109,7 +109,6 @@ export const DateTimeInput = ({
|
||||
ref={ref as any}
|
||||
value={value}
|
||||
onChange={() => {}} // Prevent React warning
|
||||
hasError={hasError}
|
||||
/>
|
||||
</StyledInputContainer>
|
||||
);
|
||||
+519
@@ -0,0 +1,519 @@
|
||||
import { SKELETON_LOADER_HEIGHT_SIZES } from '@/activities/components/SkeletonLoader';
|
||||
import { CalendarStartDay } from '@/localization/constants/CalendarStartDay';
|
||||
import { detectCalendarStartDay } from '@/localization/utils/detection/detectCalendarStartDay';
|
||||
import { DateTimePickerHeader } from '@/ui/input/components/internal/date/components/DateTimePickerHeader';
|
||||
import { RelativeDatePickerHeader } from '@/ui/input/components/internal/date/components/RelativeDatePickerHeader';
|
||||
import { getHighlightedDates } from '@/ui/input/components/internal/date/utils/getHighlightedDates';
|
||||
import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
|
||||
import { useTheme } from '@emotion/react';
|
||||
import styled from '@emotion/styled';
|
||||
import { t } from '@lingui/core/macro';
|
||||
import { addMonths, setMonth, setYear, subMonths } from 'date-fns';
|
||||
import { lazy, Suspense, type ComponentType } from 'react';
|
||||
import type { ReactDatePickerProps as ReactDatePickerLibProps } from 'react-datepicker';
|
||||
import Skeleton, { SkeletonTheme } from 'react-loading-skeleton';
|
||||
|
||||
import 'react-datepicker/dist/react-datepicker.css';
|
||||
|
||||
import { IconCalendarX } from 'twenty-ui/display';
|
||||
import {
|
||||
MenuItemLeftContent,
|
||||
StyledHoverableMenuItemBase,
|
||||
} from 'twenty-ui/navigation';
|
||||
|
||||
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
|
||||
import { useTurnPointInTimeIntoReactDatePickerShiftedDate } from '@/ui/input/components/internal/date/hooks/useTurnPointInTimeIntoReactDatePickerShiftedDate';
|
||||
import { useTurnReactDatePickerShiftedDateBackIntoPointInTime } from '@/ui/input/components/internal/date/hooks/useTurnReactDatePickerShiftedDateBackIntoPointInTime';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import { isDefined, type RelativeDateFilter } from 'twenty-shared/utils';
|
||||
|
||||
export const MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID =
|
||||
'date-picker-month-and-year-dropdown-month-select';
|
||||
export const MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID =
|
||||
'date-picker-month-and-year-dropdown-year-select';
|
||||
|
||||
const StyledContainer = styled.div<{
|
||||
calendarDisabled?: boolean;
|
||||
}>`
|
||||
width: 280px;
|
||||
|
||||
& .react-datepicker {
|
||||
border-color: ${({ theme }) => theme.border.color.light};
|
||||
background: transparent;
|
||||
font-family: 'Inter';
|
||||
font-size: ${({ theme }) => theme.font.size.md};
|
||||
border: none;
|
||||
display: block;
|
||||
font-weight: ${({ theme }) => theme.font.weight.regular};
|
||||
}
|
||||
|
||||
& .react-datepicker-popper {
|
||||
position: relative !important;
|
||||
inset: auto !important;
|
||||
transform: none !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
& .react-datepicker__triangle {
|
||||
display: none;
|
||||
}
|
||||
|
||||
& .react-datepicker__triangle::after {
|
||||
display: none;
|
||||
}
|
||||
|
||||
& .react-datepicker__triangle::before {
|
||||
display: none;
|
||||
}
|
||||
|
||||
& .react-datepicker-wrapper {
|
||||
display: none;
|
||||
}
|
||||
|
||||
// Header
|
||||
|
||||
& .react-datepicker__header {
|
||||
background: transparent;
|
||||
border: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
&
|
||||
.react-datepicker__input-time-container
|
||||
.react-datepicker-time__input-container
|
||||
.react-datepicker-time__input {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
& .react-datepicker__header__dropdown {
|
||||
display: flex;
|
||||
color: ${({ theme }) => theme.font.color.primary};
|
||||
margin-left: ${({ theme }) => theme.spacing(1)};
|
||||
margin-bottom: ${({ theme }) => theme.spacing(10)};
|
||||
}
|
||||
|
||||
& .react-datepicker__month-dropdown-container,
|
||||
& .react-datepicker__year-dropdown-container {
|
||||
text-align: left;
|
||||
border-radius: ${({ theme }) => theme.border.radius.sm};
|
||||
margin-left: ${({ theme }) => theme.spacing(1)};
|
||||
margin-right: 0;
|
||||
padding: ${({ theme }) => theme.spacing(2)};
|
||||
padding-right: ${({ theme }) => theme.spacing(4)};
|
||||
background-color: ${({ theme }) => theme.background.tertiary};
|
||||
}
|
||||
|
||||
& .react-datepicker__month-read-view--down-arrow,
|
||||
& .react-datepicker__year-read-view--down-arrow {
|
||||
height: 5px;
|
||||
width: 5px;
|
||||
border-width: 1px 1px 0 0;
|
||||
border-color: ${({ theme }) => theme.border.color.light};
|
||||
top: 3px;
|
||||
right: -6px;
|
||||
}
|
||||
|
||||
& .react-datepicker__year-read-view,
|
||||
& .react-datepicker__month-read-view {
|
||||
padding-right: ${({ theme }) => theme.spacing(2)};
|
||||
}
|
||||
|
||||
& .react-datepicker__month-dropdown-container {
|
||||
width: 80px;
|
||||
}
|
||||
|
||||
& .react-datepicker__year-dropdown-container {
|
||||
width: 50px;
|
||||
}
|
||||
|
||||
& .react-datepicker__month-dropdown,
|
||||
& .react-datepicker__year-dropdown {
|
||||
overflow-y: scroll;
|
||||
top: ${({ theme }) => theme.spacing(2)};
|
||||
}
|
||||
& .react-datepicker__month-dropdown {
|
||||
left: ${({ theme }) => theme.spacing(2)};
|
||||
height: 260px;
|
||||
}
|
||||
|
||||
& .react-datepicker__year-dropdown {
|
||||
left: calc(${({ theme }) => theme.spacing(9)} + 80px);
|
||||
width: 100px;
|
||||
height: 260px;
|
||||
}
|
||||
|
||||
& .react-datepicker__navigation--years {
|
||||
display: none;
|
||||
}
|
||||
|
||||
& .react-datepicker__month-option--selected,
|
||||
& .react-datepicker__year-option--selected {
|
||||
display: none;
|
||||
}
|
||||
|
||||
& .react-datepicker__year-option,
|
||||
& .react-datepicker__month-option {
|
||||
text-align: left;
|
||||
padding: ${({ theme }) => theme.spacing(2)}
|
||||
calc(${({ theme }) => theme.spacing(2)} - 2px);
|
||||
width: calc(100% - ${({ theme }) => theme.spacing(4)});
|
||||
border-radius: ${({ theme }) => theme.border.radius.xs};
|
||||
color: ${({ theme }) => theme.font.color.secondary};
|
||||
cursor: pointer;
|
||||
margin: 2px;
|
||||
|
||||
&:hover {
|
||||
background: ${({ theme }) => theme.background.transparent.light};
|
||||
}
|
||||
}
|
||||
|
||||
& .react-datepicker__year-option {
|
||||
&:first-of-type,
|
||||
&:last-of-type {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
& .react-datepicker__current-month {
|
||||
display: none;
|
||||
}
|
||||
|
||||
& .react-datepicker__day-name {
|
||||
color: ${({ theme }) => theme.font.color.secondary};
|
||||
width: 34px;
|
||||
height: 40px;
|
||||
line-height: 40px;
|
||||
}
|
||||
|
||||
& .react-datepicker__month-container {
|
||||
float: none;
|
||||
}
|
||||
|
||||
// Days
|
||||
|
||||
& .react-datepicker__month {
|
||||
margin-top: 0;
|
||||
|
||||
pointer-events: ${({ calendarDisabled }) =>
|
||||
calendarDisabled ? 'none' : 'auto'};
|
||||
opacity: ${({ calendarDisabled }) => (calendarDisabled ? '0.5' : '1')};
|
||||
}
|
||||
|
||||
& .react-datepicker__day {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
line-height: 34px;
|
||||
}
|
||||
|
||||
& .react-datepicker__navigation--previous,
|
||||
& .react-datepicker__navigation--next {
|
||||
height: 34px;
|
||||
border-radius: ${({ theme }) => theme.border.radius.sm};
|
||||
padding-top: 6px;
|
||||
&:hover {
|
||||
background: ${({ theme }) => theme.background.transparent.light};
|
||||
}
|
||||
}
|
||||
& .react-datepicker__navigation--previous {
|
||||
right: 38px;
|
||||
top: 6px;
|
||||
left: auto;
|
||||
|
||||
& > span {
|
||||
margin-left: -6px;
|
||||
}
|
||||
}
|
||||
|
||||
& .react-datepicker__navigation--next {
|
||||
right: 6px;
|
||||
top: 6px;
|
||||
|
||||
& > span {
|
||||
margin-left: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
& .react-datepicker__navigation-icon::before {
|
||||
height: 7px;
|
||||
width: 7px;
|
||||
border-width: 1px 1px 0 0;
|
||||
border-color: ${({ theme }) => theme.font.color.tertiary};
|
||||
}
|
||||
|
||||
& .react-datepicker__day--keyboard-selected {
|
||||
background-color: inherit;
|
||||
}
|
||||
|
||||
& .react-datepicker__day,
|
||||
.react-datepicker__time-name {
|
||||
color: ${({ theme }) => theme.font.color.primary};
|
||||
}
|
||||
|
||||
& .react-datepicker__day--selected {
|
||||
background-color: ${({ theme }) => theme.color.blue};
|
||||
color: ${({ theme }) => theme.background.primary};
|
||||
|
||||
&.react-datepicker__day:hover {
|
||||
color: ${({ theme }) => theme.background.primary};
|
||||
}
|
||||
}
|
||||
|
||||
& .react-datepicker__day--outside-month {
|
||||
color: ${({ theme }) => theme.font.color.tertiary};
|
||||
}
|
||||
|
||||
& .react-datepicker__day:hover {
|
||||
color: ${({ theme }) => theme.font.color.tertiary};
|
||||
}
|
||||
`;
|
||||
|
||||
const StyledSeparator = styled.div`
|
||||
border-bottom: 1px solid ${({ theme }) => theme.border.color.light};
|
||||
width: 100%;
|
||||
`;
|
||||
|
||||
const StyledButtonContainer = styled(StyledHoverableMenuItemBase)`
|
||||
box-sizing: border-box;
|
||||
height: 32px;
|
||||
margin: ${({ theme }) => theme.spacing(1)};
|
||||
padding: ${({ theme }) => theme.spacing(1)};
|
||||
width: auto;
|
||||
`;
|
||||
|
||||
const StyledButton = styled(MenuItemLeftContent)`
|
||||
justify-content: start;
|
||||
`;
|
||||
|
||||
const StyledDatePickerFallback = styled.div`
|
||||
align-items: center;
|
||||
background: ${({ theme }) => theme.background.secondary};
|
||||
border-radius: ${({ theme }) => theme.border.radius.md};
|
||||
color: ${({ theme }) => theme.font.color.tertiary};
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: ${({ theme }) => theme.spacing(2)};
|
||||
height: 300px;
|
||||
justify-content: center;
|
||||
padding: ${({ theme }) => theme.spacing(4)};
|
||||
width: 280px;
|
||||
`;
|
||||
|
||||
type DateTimePickerProps = {
|
||||
isRelative?: boolean;
|
||||
hideHeaderInput?: boolean;
|
||||
date: Date | null;
|
||||
relativeDate?: RelativeDateFilter & {
|
||||
start: Date;
|
||||
end: Date;
|
||||
};
|
||||
onClose?: (date: Date | null) => void;
|
||||
onChange?: (date: Date | null) => void;
|
||||
onRelativeDateChange?: (
|
||||
relativeDateFilter: RelativeDateFilter | null,
|
||||
) => void;
|
||||
clearable?: boolean;
|
||||
onEnter?: (date: Date | null) => void;
|
||||
onEscape?: (date: Date | null) => void;
|
||||
keyboardEventsDisabled?: boolean;
|
||||
onClear?: () => void;
|
||||
};
|
||||
|
||||
type DatePickerPropsType = ReactDatePickerLibProps<
|
||||
boolean | undefined,
|
||||
boolean | undefined
|
||||
>;
|
||||
|
||||
const ReactDatePicker = lazy<ComponentType<DatePickerPropsType>>(() =>
|
||||
import('react-datepicker').then((mod) => ({
|
||||
default: mod.default as unknown as ComponentType<DatePickerPropsType>,
|
||||
})),
|
||||
);
|
||||
|
||||
export const DateTimePicker = ({
|
||||
date,
|
||||
onChange,
|
||||
onClose,
|
||||
clearable = true,
|
||||
onClear,
|
||||
isRelative,
|
||||
relativeDate,
|
||||
onRelativeDateChange,
|
||||
hideHeaderInput,
|
||||
}: DateTimePickerProps) => {
|
||||
const theme = useTheme();
|
||||
const currentWorkspaceMember = useRecoilValue(currentWorkspaceMemberState);
|
||||
|
||||
const { turnReactDatePickerShiftedDateBackIntoPointInTime } =
|
||||
useTurnReactDatePickerShiftedDateBackIntoPointInTime();
|
||||
const { turnPointInTimeIntoReactDatePickerShiftedDate } =
|
||||
useTurnPointInTimeIntoReactDatePickerShiftedDate();
|
||||
|
||||
const { closeDropdown: closeDropdownMonthSelect } = useCloseDropdown();
|
||||
const { closeDropdown: closeDropdownYearSelect } = useCloseDropdown();
|
||||
|
||||
const handleClear = () => {
|
||||
closeDropdowns();
|
||||
onClear?.();
|
||||
};
|
||||
|
||||
const closeDropdowns = () => {
|
||||
closeDropdownYearSelect(MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID);
|
||||
closeDropdownMonthSelect(MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID);
|
||||
};
|
||||
|
||||
const handleClose = (newDate: Date) => {
|
||||
closeDropdowns();
|
||||
onClose?.(newDate);
|
||||
};
|
||||
|
||||
const handleChangeMonth = (month: number) => {
|
||||
const newDateTz = setMonth(reactPickerShiftedDate, month);
|
||||
|
||||
const normalDate =
|
||||
turnReactDatePickerShiftedDateBackIntoPointInTime(newDateTz);
|
||||
|
||||
onChange?.(normalDate);
|
||||
};
|
||||
|
||||
const handleAddMonth = () => {
|
||||
const newDateTz = addMonths(reactPickerShiftedDate, 1);
|
||||
|
||||
const normalDate =
|
||||
turnReactDatePickerShiftedDateBackIntoPointInTime(newDateTz);
|
||||
|
||||
onChange?.(normalDate);
|
||||
};
|
||||
|
||||
const handleSubtractMonth = () => {
|
||||
const newDateTz = subMonths(reactPickerShiftedDate, 1);
|
||||
|
||||
const normalDate =
|
||||
turnReactDatePickerShiftedDateBackIntoPointInTime(newDateTz);
|
||||
|
||||
onChange?.(normalDate);
|
||||
};
|
||||
|
||||
const handleChangeYear = (year: number) => {
|
||||
const newDateTz = setYear(reactPickerShiftedDate, year);
|
||||
|
||||
const normalDate =
|
||||
turnReactDatePickerShiftedDateBackIntoPointInTime(newDateTz);
|
||||
|
||||
onChange?.(normalDate);
|
||||
};
|
||||
|
||||
const handleDateChange = (newDate: Date) => {
|
||||
const normalDate =
|
||||
turnReactDatePickerShiftedDateBackIntoPointInTime(newDate);
|
||||
|
||||
onChange?.(normalDate);
|
||||
};
|
||||
|
||||
const handleDateSelect = (newReactDatePickerShiftedDateSelected: Date) => {
|
||||
const normalDate = turnReactDatePickerShiftedDateBackIntoPointInTime(
|
||||
newReactDatePickerShiftedDateSelected,
|
||||
);
|
||||
|
||||
handleClose?.(normalDate);
|
||||
};
|
||||
|
||||
const highlightedDates =
|
||||
isRelative && isDefined(relativeDate?.end) && isDefined(relativeDate?.start)
|
||||
? getHighlightedDates({
|
||||
end: turnPointInTimeIntoReactDatePickerShiftedDate(relativeDate?.end),
|
||||
start: turnPointInTimeIntoReactDatePickerShiftedDate(
|
||||
relativeDate?.start,
|
||||
),
|
||||
})
|
||||
: [];
|
||||
|
||||
const reactPickerShiftedDate = turnPointInTimeIntoReactDatePickerShiftedDate(
|
||||
date ?? new Date(),
|
||||
);
|
||||
|
||||
const selectedDates = isRelative
|
||||
? highlightedDates
|
||||
: [reactPickerShiftedDate];
|
||||
|
||||
return (
|
||||
<StyledContainer calendarDisabled={isRelative}>
|
||||
<Suspense
|
||||
fallback={
|
||||
<StyledDatePickerFallback>
|
||||
<SkeletonTheme
|
||||
baseColor={theme.background.tertiary}
|
||||
highlightColor={theme.background.transparent.lighter}
|
||||
borderRadius={4}
|
||||
>
|
||||
<Skeleton
|
||||
width={200}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.m}
|
||||
/>
|
||||
<Skeleton
|
||||
width={240}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.l}
|
||||
/>
|
||||
<Skeleton
|
||||
width={220}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.m}
|
||||
/>
|
||||
<Skeleton
|
||||
width={180}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.s}
|
||||
/>
|
||||
</SkeletonTheme>
|
||||
</StyledDatePickerFallback>
|
||||
}
|
||||
>
|
||||
<ReactDatePicker
|
||||
open={true}
|
||||
selected={reactPickerShiftedDate}
|
||||
selectedDates={selectedDates}
|
||||
openToDate={reactPickerShiftedDate}
|
||||
disabledKeyboardNavigation
|
||||
onChange={handleDateChange}
|
||||
calendarStartDay={
|
||||
currentWorkspaceMember?.calendarStartDay === CalendarStartDay.SYSTEM
|
||||
? CalendarStartDay[detectCalendarStartDay()]
|
||||
: (currentWorkspaceMember?.calendarStartDay ?? undefined)
|
||||
}
|
||||
renderCustomHeader={({
|
||||
prevMonthButtonDisabled,
|
||||
nextMonthButtonDisabled,
|
||||
}) =>
|
||||
isRelative ? (
|
||||
<RelativeDatePickerHeader
|
||||
direction={relativeDate?.direction ?? 'PAST'}
|
||||
amount={relativeDate?.amount}
|
||||
unit={relativeDate?.unit ?? 'DAY'}
|
||||
onChange={onRelativeDateChange}
|
||||
/>
|
||||
) : (
|
||||
<DateTimePickerHeader
|
||||
date={reactPickerShiftedDate}
|
||||
onChange={onChange}
|
||||
onChangeMonth={handleChangeMonth}
|
||||
onChangeYear={handleChangeYear}
|
||||
onAddMonth={handleAddMonth}
|
||||
onSubtractMonth={handleSubtractMonth}
|
||||
prevMonthButtonDisabled={prevMonthButtonDisabled}
|
||||
nextMonthButtonDisabled={nextMonthButtonDisabled}
|
||||
hideInput={hideHeaderInput}
|
||||
/>
|
||||
)
|
||||
}
|
||||
onSelect={handleDateSelect}
|
||||
selectsMultiple={isRelative}
|
||||
/>
|
||||
</Suspense>
|
||||
{clearable && (
|
||||
<>
|
||||
<StyledSeparator />
|
||||
<StyledButtonContainer onClick={handleClear}>
|
||||
<StyledButton LeftIcon={IconCalendarX} text={t`Clear`} />
|
||||
</StyledButtonContainer>
|
||||
</>
|
||||
)}
|
||||
</StyledContainer>
|
||||
);
|
||||
};
|
||||
+8
-27
@@ -3,8 +3,8 @@ import { useRecoilValue } from 'recoil';
|
||||
|
||||
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
|
||||
import { Select } from '@/ui/input/components/Select';
|
||||
import { DateTimeInput } from '@/ui/input/components/internal/date/components/DateTimeInput';
|
||||
|
||||
import { DateTimePickerInput } from '@/ui/input/components/internal/date/components/DateTimePickerInput';
|
||||
import { getMonthSelectOptions } from '@/ui/input/components/internal/date/utils/getMonthSelectOptions';
|
||||
import { ClickOutsideListenerContext } from '@/ui/utilities/pointer-event/contexts/ClickOutsideListenerContext';
|
||||
import { SOURCE_LOCALE } from 'twenty-shared/translations';
|
||||
@@ -13,7 +13,7 @@ import { LightIconButton } from 'twenty-ui/input';
|
||||
import {
|
||||
MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID,
|
||||
MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID,
|
||||
} from './InternalDatePicker';
|
||||
} from './DateTimePicker';
|
||||
|
||||
const StyledCustomDatePickerHeader = styled.div`
|
||||
align-items: center;
|
||||
@@ -31,7 +31,7 @@ const years = Array.from(
|
||||
(_, i) => new Date().getFullYear() + 50 - i,
|
||||
).map((year) => ({ label: year.toString(), value: year }));
|
||||
|
||||
type AbsoluteDatePickerHeaderProps = {
|
||||
type DateTimePickerHeaderProps = {
|
||||
date: Date;
|
||||
onChange?: (date: Date | null) => void;
|
||||
onChangeMonth: (month: number) => void;
|
||||
@@ -40,11 +40,10 @@ type AbsoluteDatePickerHeaderProps = {
|
||||
onSubtractMonth: () => void;
|
||||
prevMonthButtonDisabled: boolean;
|
||||
nextMonthButtonDisabled: boolean;
|
||||
isDateTimeInput?: boolean;
|
||||
hideInput?: boolean;
|
||||
};
|
||||
|
||||
export const AbsoluteDatePickerHeader = ({
|
||||
export const DateTimePickerHeader = ({
|
||||
date,
|
||||
onChange,
|
||||
onChangeMonth,
|
||||
@@ -53,32 +52,14 @@ export const AbsoluteDatePickerHeader = ({
|
||||
onSubtractMonth,
|
||||
prevMonthButtonDisabled,
|
||||
nextMonthButtonDisabled,
|
||||
isDateTimeInput,
|
||||
hideInput = false,
|
||||
}: AbsoluteDatePickerHeaderProps) => {
|
||||
}: DateTimePickerHeaderProps) => {
|
||||
const currentWorkspaceMember = useRecoilValue(currentWorkspaceMemberState);
|
||||
const userLocale = currentWorkspaceMember?.locale ?? SOURCE_LOCALE;
|
||||
|
||||
const endOfDayInLocalTimezone = new Date(
|
||||
date.getFullYear(),
|
||||
date.getMonth(),
|
||||
date.getDate(),
|
||||
23,
|
||||
59,
|
||||
59,
|
||||
999,
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{!hideInput && (
|
||||
<DateTimeInput
|
||||
date={date}
|
||||
isDateTimeInput={isDateTimeInput}
|
||||
onChange={onChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!hideInput && <DateTimePickerInput date={date} onChange={onChange} />}
|
||||
<StyledCustomDatePickerHeader>
|
||||
<ClickOutsideListenerContext.Provider
|
||||
value={{
|
||||
@@ -89,7 +70,7 @@ export const AbsoluteDatePickerHeader = ({
|
||||
dropdownId={MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID}
|
||||
options={getMonthSelectOptions(userLocale)}
|
||||
onChange={onChangeMonth}
|
||||
value={endOfDayInLocalTimezone.getMonth()}
|
||||
value={date.getMonth()}
|
||||
fullWidth
|
||||
/>
|
||||
</ClickOutsideListenerContext.Provider>
|
||||
@@ -101,7 +82,7 @@ export const AbsoluteDatePickerHeader = ({
|
||||
<Select
|
||||
dropdownId={MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID}
|
||||
onChange={onChangeYear}
|
||||
value={endOfDayInLocalTimezone.getFullYear()}
|
||||
value={date.getFullYear()}
|
||||
options={years}
|
||||
fullWidth
|
||||
/>
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
import styled from '@emotion/styled';
|
||||
import { useIMask } from 'react-imask';
|
||||
|
||||
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
|
||||
import { DATE_TIME_BLOCKS } from '@/ui/input/components/internal/date/constants/DateTimeBlocks';
|
||||
import { MAX_DATE } from '@/ui/input/components/internal/date/constants/MaxDate';
|
||||
import { MIN_DATE } from '@/ui/input/components/internal/date/constants/MinDate';
|
||||
import { getDateTimeMask } from '@/ui/input/components/internal/date/utils/getDateTimeMask';
|
||||
|
||||
import { TimeZoneAbbreviation } from '@/ui/input/components/internal/date/components/TimeZoneAbbreviation';
|
||||
import { useParseDateTimeInputStringToJSDate } from '@/ui/input/components/internal/date/hooks/useParseDateTimeInputStringToJSDate';
|
||||
import { useParseJSDateToIMaskDateTimeInputString } from '@/ui/input/components/internal/date/hooks/useParseJSDateToIMaskDateTimeInputString';
|
||||
import { useTurnReactDatePickerShiftedDateBackIntoPointInTime } from '@/ui/input/components/internal/date/hooks/useTurnReactDatePickerShiftedDateBackIntoPointInTime';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
const StyledInputContainer = styled.div`
|
||||
align-items: center;
|
||||
border-bottom: 1px solid ${({ theme }) => theme.border.color.light};
|
||||
border-top-left-radius: ${({ theme }) => theme.border.radius.md};
|
||||
border-top-right-radius: ${({ theme }) => theme.border.radius.md};
|
||||
display: flex;
|
||||
height: ${({ theme }) => theme.spacing(8)};
|
||||
width: 100%;
|
||||
`;
|
||||
|
||||
const StyledInput = styled.input<{ hasError?: boolean }>`
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: ${({ theme }) => theme.font.color.primary};
|
||||
outline: none;
|
||||
padding-left: ${({ theme }) => theme.spacing(2)};
|
||||
font-weight: 500;
|
||||
font-size: ${({ theme }) => theme.font.size.md};
|
||||
width: 105px;
|
||||
`;
|
||||
|
||||
type DateTimePickerInputProps = {
|
||||
onChange?: (date: Date | null) => void;
|
||||
date: Date | null;
|
||||
};
|
||||
|
||||
export const DateTimePickerInput = ({
|
||||
date,
|
||||
onChange,
|
||||
}: DateTimePickerInputProps) => {
|
||||
const { turnReactDatePickerShiftedDateBackIntoPointInTime } =
|
||||
useTurnReactDatePickerShiftedDateBackIntoPointInTime();
|
||||
|
||||
const [internalDate, setInternalDate] = useState(date);
|
||||
|
||||
const { dateFormat } = useDateTimeFormat();
|
||||
|
||||
const { parseDateTimeInputStringToJSDate } =
|
||||
useParseDateTimeInputStringToJSDate();
|
||||
const { parseJSDateToDateTimeInputString } =
|
||||
useParseJSDateToIMaskDateTimeInputString();
|
||||
|
||||
const handleParseStringToDate = (newDateAsString: string) => {
|
||||
const date = parseDateTimeInputStringToJSDate(newDateAsString);
|
||||
|
||||
return date;
|
||||
};
|
||||
|
||||
const pattern = getDateTimeMask(dateFormat);
|
||||
|
||||
const blocks = DATE_TIME_BLOCKS;
|
||||
|
||||
const { ref, setValue } = useIMask(
|
||||
{
|
||||
mask: Date,
|
||||
pattern,
|
||||
blocks,
|
||||
min: MIN_DATE,
|
||||
max: MAX_DATE,
|
||||
format: (date: any) => parseJSDateToDateTimeInputString(date),
|
||||
parse: handleParseStringToDate,
|
||||
lazy: false,
|
||||
autofix: false,
|
||||
},
|
||||
{
|
||||
defaultValue: parseJSDateToDateTimeInputString(
|
||||
internalDate ?? new Date(),
|
||||
),
|
||||
onComplete: (value) => {
|
||||
const parsedDate = parseDateTimeInputStringToJSDate(value);
|
||||
|
||||
if (!isDefined(parsedDate)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pointInTime =
|
||||
turnReactDatePickerShiftedDateBackIntoPointInTime(parsedDate);
|
||||
|
||||
onChange?.(pointInTime);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isDefined(date) && internalDate !== date) {
|
||||
setInternalDate(date);
|
||||
setValue(parseJSDateToDateTimeInputString(date));
|
||||
}
|
||||
}, [date, internalDate, parseJSDateToDateTimeInputString, setValue]);
|
||||
|
||||
return (
|
||||
<StyledInputContainer>
|
||||
<StyledInput type="text" ref={ref as any} />
|
||||
<TimeZoneAbbreviation date={internalDate ?? new Date()} />
|
||||
</StyledInputContainer>
|
||||
);
|
||||
};
|
||||
+41
-49
@@ -2,14 +2,15 @@ import { Select } from '@/ui/input/components/Select';
|
||||
import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
|
||||
import { RELATIVE_DATE_DIRECTION_SELECT_OPTIONS } from '@/ui/input/components/internal/date/constants/RelativeDateDirectionSelectOptions';
|
||||
import { RELATIVE_DATE_UNITS_SELECT_OPTIONS } from '@/ui/input/components/internal/date/constants/RelativeDateUnitSelectOptions';
|
||||
import {
|
||||
type VariableDateViewFilterValueDirection,
|
||||
type VariableDateViewFilterValueUnit,
|
||||
} from 'twenty-shared/types';
|
||||
|
||||
import styled from '@emotion/styled';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { variableDateViewFilterValuePartsSchema } from 'twenty-shared/utils';
|
||||
import { type Nullable } from 'twenty-shared/types';
|
||||
import {
|
||||
relativeDateFilterSchema,
|
||||
type RelativeDateFilter,
|
||||
type RelativeDateFilterDirection,
|
||||
type RelativeDateFilterUnit,
|
||||
} from 'twenty-shared/utils';
|
||||
|
||||
const StyledContainer = styled.div<{ noPadding: boolean }>`
|
||||
display: flex;
|
||||
@@ -20,60 +21,54 @@ const StyledContainer = styled.div<{ noPadding: boolean }>`
|
||||
`;
|
||||
|
||||
type RelativeDatePickerHeaderProps = {
|
||||
direction: VariableDateViewFilterValueDirection;
|
||||
amount?: number;
|
||||
unit: VariableDateViewFilterValueUnit;
|
||||
onChange?: (value: {
|
||||
direction: VariableDateViewFilterValueDirection;
|
||||
amount?: number;
|
||||
unit: VariableDateViewFilterValueUnit;
|
||||
}) => void;
|
||||
direction: RelativeDateFilterDirection;
|
||||
amount?: Nullable<number>;
|
||||
unit: RelativeDateFilterUnit;
|
||||
onChange?: (value: RelativeDateFilter) => void;
|
||||
isFormField?: boolean;
|
||||
readonly?: boolean;
|
||||
unitDropdownWidth?: number;
|
||||
};
|
||||
|
||||
export const RelativeDatePickerHeader = (
|
||||
props: RelativeDatePickerHeaderProps,
|
||||
) => {
|
||||
const [direction, setDirection] = useState(props.direction);
|
||||
const [amountString, setAmountString] = useState(
|
||||
props.amount ? props.amount.toString() : '',
|
||||
);
|
||||
const [unit, setUnit] = useState(props.unit);
|
||||
|
||||
useEffect(() => {
|
||||
setAmountString(props.amount ? props.amount.toString() : '');
|
||||
setUnit(props.unit);
|
||||
setDirection(props.direction);
|
||||
}, [props.amount, props.unit, props.direction]);
|
||||
export const RelativeDatePickerHeader = ({
|
||||
direction,
|
||||
unit,
|
||||
amount,
|
||||
isFormField,
|
||||
onChange,
|
||||
readonly,
|
||||
unitDropdownWidth,
|
||||
}: RelativeDatePickerHeaderProps) => {
|
||||
const amountString = amount?.toString() ?? '';
|
||||
|
||||
const textInputValue = direction === 'THIS' ? '' : amountString;
|
||||
const textInputPlaceholder = direction === 'THIS' ? '-' : 'Number';
|
||||
|
||||
const isUnitPlural = props.amount && props.amount > 1 && direction !== 'THIS';
|
||||
const isUnitPlural = amount && amount > 1 && direction !== 'THIS';
|
||||
const unitSelectOptions = RELATIVE_DATE_UNITS_SELECT_OPTIONS.map((unit) => ({
|
||||
...unit,
|
||||
label: `${unit.label}${isUnitPlural ? 's' : ''}`,
|
||||
}));
|
||||
|
||||
return (
|
||||
<StyledContainer noPadding={props.isFormField ?? false}>
|
||||
<StyledContainer noPadding={isFormField ?? false}>
|
||||
<Select
|
||||
dropdownId="direction-select"
|
||||
value={direction}
|
||||
onChange={(newDirection) => {
|
||||
setDirection(newDirection);
|
||||
if (props.amount === undefined && newDirection !== 'THIS') return;
|
||||
props.onChange?.({
|
||||
if (amount === undefined && newDirection !== 'THIS') {
|
||||
return;
|
||||
}
|
||||
|
||||
onChange?.({
|
||||
direction: newDirection,
|
||||
amount: props.amount,
|
||||
amount: amount,
|
||||
unit: unit,
|
||||
});
|
||||
}}
|
||||
options={RELATIVE_DATE_DIRECTION_SELECT_OPTIONS}
|
||||
fullWidth
|
||||
disabled={props.readonly}
|
||||
disabled={readonly}
|
||||
/>
|
||||
<SettingsTextInput
|
||||
instanceId="relative-date-picker-amount"
|
||||
@@ -83,40 +78,37 @@ export const RelativeDatePickerHeader = (
|
||||
const amountString = text.replace(/[^0-9]|^0+/g, '');
|
||||
const amount = parseInt(amountString);
|
||||
|
||||
setAmountString(amountString);
|
||||
|
||||
const valueParts = {
|
||||
direction,
|
||||
amount,
|
||||
unit,
|
||||
};
|
||||
|
||||
if (
|
||||
variableDateViewFilterValuePartsSchema.safeParse(valueParts)
|
||||
.success === true
|
||||
) {
|
||||
props.onChange?.(valueParts);
|
||||
if (relativeDateFilterSchema.safeParse(valueParts).success === true) {
|
||||
onChange?.(valueParts);
|
||||
}
|
||||
}}
|
||||
placeholder={textInputPlaceholder}
|
||||
disabled={direction === 'THIS' || props.readonly}
|
||||
disabled={direction === 'THIS' || readonly}
|
||||
/>
|
||||
<Select
|
||||
dropdownId="unit-select"
|
||||
value={unit}
|
||||
onChange={(newUnit) => {
|
||||
setUnit(newUnit);
|
||||
if (direction !== 'THIS' && props.amount === undefined) return;
|
||||
props.onChange?.({
|
||||
if (direction !== 'THIS' && amount === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
onChange?.({
|
||||
direction,
|
||||
amount: props.amount,
|
||||
amount: amount,
|
||||
unit: newUnit,
|
||||
});
|
||||
}}
|
||||
fullWidth
|
||||
options={unitSelectOptions}
|
||||
disabled={props.readonly}
|
||||
dropdownWidth={props.unitDropdownWidth}
|
||||
disabled={readonly}
|
||||
dropdownWidth={unitDropdownWidth}
|
||||
/>
|
||||
</StyledContainer>
|
||||
);
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
|
||||
import styled from '@emotion/styled';
|
||||
|
||||
const StyledTimezoneAbbreviation = styled.span<{ hasError?: boolean }>`
|
||||
background: transparent;
|
||||
color: ${({ theme }) => theme.font.color.tertiary};
|
||||
|
||||
font-size: ${({ theme }) => theme.font.size.sm};
|
||||
width: fit-content;
|
||||
|
||||
user-select: none;
|
||||
|
||||
line-height: 0.5px;
|
||||
`;
|
||||
|
||||
export const TimeZoneAbbreviation = ({ date }: { date: Date }) => {
|
||||
const { isSystemTimezone, getTimezoneAbbreviationForPointInTime } =
|
||||
useUserTimezone();
|
||||
|
||||
const shouldShowTimezoneAbbreviation = !isSystemTimezone;
|
||||
const timezoneSuffix = !isSystemTimezone
|
||||
? ` ${getTimezoneAbbreviationForPointInTime(date ?? new Date())}`
|
||||
: '';
|
||||
|
||||
if (!shouldShowTimezoneAbbreviation) {
|
||||
return <></>;
|
||||
}
|
||||
|
||||
return (
|
||||
<StyledTimezoneAbbreviation>{timezoneSuffix}</StyledTimezoneAbbreviation>
|
||||
);
|
||||
};
|
||||
+1
-1
@@ -1,9 +1,9 @@
|
||||
import { useArgs } from '@storybook/preview-api';
|
||||
import { type Meta, type StoryObj } from '@storybook/react';
|
||||
import { expect, userEvent, within } from '@storybook/test';
|
||||
import { DateTimePicker } from '../InternalDatePicker';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { ComponentDecorator } from 'twenty-ui/testing';
|
||||
import { DateTimePicker } from '../DateTimePicker';
|
||||
|
||||
const meta: Meta<typeof DateTimePicker> = {
|
||||
title: 'UI/Input/Internal/InternalDatePicker',
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { type VariableDateViewFilterValueDirection } from 'twenty-shared/types';
|
||||
import { type RelativeDateFilterDirection } from 'twenty-shared/utils';
|
||||
|
||||
type RelativeDateDirectionOption = {
|
||||
value: VariableDateViewFilterValueDirection;
|
||||
value: RelativeDateFilterDirection;
|
||||
label: string;
|
||||
};
|
||||
|
||||
|
||||
+4
-4
@@ -1,11 +1,11 @@
|
||||
import { type VariableDateViewFilterValueUnit } from 'twenty-shared/types';
|
||||
import { type RelativeDateFilterUnit } from 'twenty-shared/utils';
|
||||
|
||||
type RelativeDateUnit = {
|
||||
value: VariableDateViewFilterValueUnit;
|
||||
type RelativeDateUnitOption = {
|
||||
value: RelativeDateFilterUnit;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export const RELATIVE_DATE_UNITS_SELECT_OPTIONS: RelativeDateUnit[] = [
|
||||
export const RELATIVE_DATE_UNITS_SELECT_OPTIONS: RelativeDateUnitOption[] = [
|
||||
{ value: 'DAY', label: 'Day' },
|
||||
{ value: 'WEEK', label: 'Week' },
|
||||
{ value: 'MONTH', label: 'Month' },
|
||||
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
|
||||
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
|
||||
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
|
||||
|
||||
describe('useUserTimezone', () => {
|
||||
const originalIntl = global.Intl;
|
||||
const mockSystemTimezone = 'America/New_York';
|
||||
|
||||
beforeAll(() => {
|
||||
// Mock Intl.DateTimeFormat to return a consistent system timezone
|
||||
global.Intl = {
|
||||
...originalIntl,
|
||||
DateTimeFormat: jest.fn().mockImplementation(() => ({
|
||||
resolvedOptions: () => ({ timeZone: mockSystemTimezone }),
|
||||
})),
|
||||
} as any;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
global.Intl = originalIntl;
|
||||
});
|
||||
|
||||
it('should return system timezone when currentWorkspaceMember is null', () => {
|
||||
const Wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<RecoilRoot>{children}</RecoilRoot>
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useUserTimezone(), {
|
||||
wrapper: Wrapper,
|
||||
});
|
||||
|
||||
expect(result.current.userTimezone).toBe(mockSystemTimezone);
|
||||
expect(result.current.isSystemTimezone).toBe(true);
|
||||
});
|
||||
|
||||
it('should return system timezone when currentWorkspaceMember.timeZone is "system"', () => {
|
||||
const WrapperWithSystemTimezone = ({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) => (
|
||||
<RecoilRoot
|
||||
initializeState={(snapshot) => {
|
||||
snapshot.set(currentWorkspaceMemberState, {
|
||||
id: 'workspace-member-id',
|
||||
name: {
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
},
|
||||
colorScheme: 'Light',
|
||||
locale: 'en-US',
|
||||
userEmail: 'john@example.com',
|
||||
timeZone: 'system',
|
||||
dateFormat: null,
|
||||
timeFormat: null,
|
||||
numberFormat: null,
|
||||
calendarStartDay: null,
|
||||
});
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</RecoilRoot>
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useUserTimezone(), {
|
||||
wrapper: WrapperWithSystemTimezone,
|
||||
});
|
||||
|
||||
expect(result.current.userTimezone).toBe(mockSystemTimezone);
|
||||
expect(result.current.isSystemTimezone).toBe(true);
|
||||
});
|
||||
|
||||
it('should return user-specific timezone when currentWorkspaceMember.timeZone is set', () => {
|
||||
const userTimezone = 'Europe/Paris';
|
||||
|
||||
const WrapperWithUserTimezone = ({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) => (
|
||||
<RecoilRoot
|
||||
initializeState={(snapshot) => {
|
||||
snapshot.set(currentWorkspaceMemberState, {
|
||||
id: 'workspace-member-id',
|
||||
name: {
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
},
|
||||
colorScheme: 'Light',
|
||||
locale: 'en-US',
|
||||
userEmail: 'john@example.com',
|
||||
timeZone: userTimezone,
|
||||
dateFormat: null,
|
||||
timeFormat: null,
|
||||
numberFormat: null,
|
||||
calendarStartDay: null,
|
||||
});
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</RecoilRoot>
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useUserTimezone(), {
|
||||
wrapper: WrapperWithUserTimezone,
|
||||
});
|
||||
|
||||
expect(result.current.userTimezone).toBe(userTimezone);
|
||||
expect(result.current.isSystemTimezone).toBe(false);
|
||||
});
|
||||
});
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
|
||||
import { isValid, parse } from 'date-fns';
|
||||
import { getDateFormatStringForDatePickerInputMask } from '~/utils/date-utils';
|
||||
|
||||
export const useParseDateInputStringToJSDate = () => {
|
||||
const { dateFormat } = useDateTimeFormat();
|
||||
|
||||
const parseDateInputStringToJSDate = (dateAsString: string) => {
|
||||
const parsingFormat = getDateFormatStringForDatePickerInputMask(dateFormat);
|
||||
|
||||
const parsedDate = parse(dateAsString, parsingFormat, new Date());
|
||||
|
||||
if (!isValid(parsedDate)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return parsedDate;
|
||||
};
|
||||
|
||||
return {
|
||||
parseDateInputStringToJSDate,
|
||||
};
|
||||
};
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
|
||||
import { format, isValid, parse } from 'date-fns';
|
||||
import { DATE_TYPE_FORMAT } from 'twenty-shared/constants';
|
||||
import { getDateFormatStringForDatePickerInputMask } from '~/utils/date-utils';
|
||||
|
||||
export const useParseDateInputStringToPlainDate = () => {
|
||||
const { dateFormat } = useDateTimeFormat();
|
||||
|
||||
const parseDateInputStringToPlainDate = (dateAsString: string) => {
|
||||
const parsingFormat = getDateFormatStringForDatePickerInputMask(dateFormat);
|
||||
|
||||
const parsedDate = parse(dateAsString, parsingFormat, new Date());
|
||||
|
||||
if (!isValid(parsedDate)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const formattedDate = format(parsedDate, DATE_TYPE_FORMAT);
|
||||
|
||||
return formattedDate;
|
||||
};
|
||||
|
||||
return {
|
||||
parseDateInputStringToPlainDate,
|
||||
};
|
||||
};
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
|
||||
import { isValid, parse } from 'date-fns';
|
||||
import { getDateTimeFormatStringFoDatePickerInputMask } from '~/utils/date-utils';
|
||||
|
||||
export const useParseDateTimeInputStringToJSDate = () => {
|
||||
const { dateFormat } = useDateTimeFormat();
|
||||
|
||||
const parseDateTimeInputStringToJSDate = (dateAsString: string) => {
|
||||
const parsingFormat =
|
||||
getDateTimeFormatStringFoDatePickerInputMask(dateFormat);
|
||||
const referenceDate = new Date();
|
||||
|
||||
const parsedDate = parse(dateAsString, parsingFormat, referenceDate);
|
||||
|
||||
if (!isValid(parsedDate)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return parsedDate;
|
||||
};
|
||||
|
||||
return {
|
||||
parseDateTimeInputStringToJSDate,
|
||||
};
|
||||
};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
|
||||
|
||||
import { format } from 'date-fns';
|
||||
import { getDateFormatStringForDatePickerInputMask } from '~/utils/date-utils';
|
||||
|
||||
export const useParseJSDateToIMaskDateInputString = () => {
|
||||
const { dateFormat } = useDateTimeFormat();
|
||||
|
||||
const parseIMaskJSDateIMaskDateInputString = (jsDate: Date) => {
|
||||
const parsingFormat = getDateFormatStringForDatePickerInputMask(dateFormat);
|
||||
|
||||
const formattedDate = format(jsDate, parsingFormat);
|
||||
|
||||
return formattedDate;
|
||||
};
|
||||
|
||||
return {
|
||||
parseIMaskJSDateIMaskDateInputString,
|
||||
};
|
||||
};
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
|
||||
import { format } from 'date-fns';
|
||||
import { getDateTimeFormatStringFoDatePickerInputMask } from '~/utils/date-utils';
|
||||
|
||||
export const useParseJSDateToIMaskDateTimeInputString = () => {
|
||||
const { dateFormat } = useDateTimeFormat();
|
||||
|
||||
const parseJSDateToDateTimeInputString = (date: Date) => {
|
||||
const parsingFormat =
|
||||
getDateTimeFormatStringFoDatePickerInputMask(dateFormat);
|
||||
|
||||
return format(date, parsingFormat);
|
||||
};
|
||||
|
||||
return {
|
||||
parseJSDateToDateTimeInputString,
|
||||
};
|
||||
};
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
|
||||
|
||||
import { format, parse } from 'date-fns';
|
||||
import { DATE_TYPE_FORMAT } from 'twenty-shared/constants';
|
||||
import { getDateFormatStringForDatePickerInputMask } from '~/utils/date-utils';
|
||||
|
||||
export const useParsePlainDateToDateInputString = () => {
|
||||
const { dateFormat } = useDateTimeFormat();
|
||||
|
||||
const parsePlainDateToDateInputString = (plainDate: string) => {
|
||||
const parsingFormat = getDateFormatStringForDatePickerInputMask(dateFormat);
|
||||
|
||||
const parsedDate = parse(plainDate, DATE_TYPE_FORMAT, new Date());
|
||||
|
||||
const formattedDate = format(parsedDate, parsingFormat);
|
||||
|
||||
return formattedDate;
|
||||
};
|
||||
|
||||
return {
|
||||
parsePlainDateToDateInputString,
|
||||
};
|
||||
};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
|
||||
import { TZDate } from '@date-fns/tz';
|
||||
|
||||
export const useTurnPointInTimeIntoReactDatePickerShiftedDate = () => {
|
||||
const systemTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
|
||||
const { userTimezone } = useUserTimezone();
|
||||
|
||||
// TODO: replace here with shiftPointInTimeToFromTimezoneDifference
|
||||
const turnPointInTimeIntoReactDatePickerShiftedDate = (pointInTime: Date) => {
|
||||
const dateSure = new TZDate(pointInTime).withTimeZone(userTimezone);
|
||||
|
||||
const shiftedDate = new TZDate(
|
||||
dateSure.getFullYear(),
|
||||
dateSure.getMonth(),
|
||||
dateSure.getDate(),
|
||||
dateSure.getHours(),
|
||||
dateSure.getMinutes(),
|
||||
dateSure.getSeconds(),
|
||||
systemTimeZone,
|
||||
);
|
||||
|
||||
return shiftedDate;
|
||||
};
|
||||
|
||||
return {
|
||||
turnPointInTimeIntoReactDatePickerShiftedDate,
|
||||
};
|
||||
};
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
|
||||
import { TZDate } from '@date-fns/tz';
|
||||
|
||||
export const useTurnReactDatePickerShiftedDateBackIntoPointInTime = () => {
|
||||
const systemTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
|
||||
const { userTimezone } = useUserTimezone();
|
||||
|
||||
// TODO: replace here with shiftPointInTimeToFromTimezoneDifference
|
||||
const turnReactDatePickerShiftedDateBackIntoPointInTime = (
|
||||
reactDatePickerShiftedDate: Date,
|
||||
) => {
|
||||
const dateSure = new TZDate(reactDatePickerShiftedDate).withTimeZone(
|
||||
systemTimeZone,
|
||||
);
|
||||
|
||||
const dateTz = new TZDate(
|
||||
dateSure.getFullYear(),
|
||||
dateSure.getMonth(),
|
||||
dateSure.getDate(),
|
||||
dateSure.getHours(),
|
||||
dateSure.getMinutes(),
|
||||
dateSure.getSeconds(),
|
||||
userTimezone,
|
||||
);
|
||||
|
||||
return dateTz;
|
||||
};
|
||||
|
||||
return {
|
||||
turnReactDatePickerShiftedDateBackIntoPointInTime,
|
||||
};
|
||||
};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import { WorkspaceMemberDateFormatEnum } from '~/generated/graphql';
|
||||
|
||||
export const useUserDateFormat = () => {
|
||||
const currentWorkspaceMember = useRecoilValue(currentWorkspaceMemberState);
|
||||
|
||||
const userDateFormat =
|
||||
currentWorkspaceMember?.dateFormat ?? WorkspaceMemberDateFormatEnum.SYSTEM;
|
||||
|
||||
return {
|
||||
userDateFormat,
|
||||
};
|
||||
};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import { WorkspaceMemberTimeFormatEnum } from '~/generated/graphql';
|
||||
|
||||
export const useUserTimeFormat = () => {
|
||||
const currentWorkspaceMember = useRecoilValue(currentWorkspaceMemberState);
|
||||
|
||||
const userTimeFormat =
|
||||
currentWorkspaceMember?.timeFormat ?? WorkspaceMemberTimeFormatEnum.SYSTEM;
|
||||
|
||||
return {
|
||||
userTimeFormat,
|
||||
};
|
||||
};
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
|
||||
import { tzName } from '@date-fns/tz';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
|
||||
export const useUserTimezone = () => {
|
||||
const currentWorkspaceMember = useRecoilValue(currentWorkspaceMemberState);
|
||||
const systemTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
|
||||
const userTimezone =
|
||||
currentWorkspaceMember?.timeZone !== 'system'
|
||||
? (currentWorkspaceMember?.timeZone ?? systemTimeZone)
|
||||
: systemTimeZone;
|
||||
|
||||
const isSystemTimezone = userTimezone === systemTimeZone;
|
||||
|
||||
const getTimezoneAbbreviationForPointInTime = (date: Date) => {
|
||||
return tzName(userTimezone, date, 'short');
|
||||
};
|
||||
|
||||
return {
|
||||
userTimezone,
|
||||
isSystemTimezone,
|
||||
getTimezoneAbbreviationForPointInTime,
|
||||
};
|
||||
};
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import { DateFormat } from '@/localization/constants/DateFormat';
|
||||
import { format } from 'date-fns';
|
||||
import { formatInTimeZone } from 'date-fns-tz';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { getDateTimeFormatStringFoDatePickerInputMask } from '~/utils/date-utils';
|
||||
|
||||
type ParseDateTimeToStringArgs = {
|
||||
date: Date;
|
||||
userTimezone: string | undefined;
|
||||
dateFormat?: DateFormat;
|
||||
};
|
||||
|
||||
export const parseDateTimeToString = ({
|
||||
date,
|
||||
userTimezone,
|
||||
dateFormat = DateFormat.MONTH_FIRST,
|
||||
}: ParseDateTimeToStringArgs) => {
|
||||
const parsingFormat =
|
||||
getDateTimeFormatStringFoDatePickerInputMask(dateFormat);
|
||||
|
||||
if (isDefined(userTimezone)) {
|
||||
return formatInTimeZone(date, userTimezone, parsingFormat);
|
||||
} else {
|
||||
return format(date, parsingFormat);
|
||||
}
|
||||
};
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
import { DateFormat } from '@/localization/constants/DateFormat';
|
||||
import { format } from 'date-fns';
|
||||
import { formatInTimeZone } from 'date-fns-tz';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { getDateFormatString } from '~/utils/date-utils';
|
||||
|
||||
type ParseDateToStringArgs = {
|
||||
date: Date;
|
||||
isDateTimeInput: boolean;
|
||||
userTimezone: string | undefined;
|
||||
dateFormat?: DateFormat;
|
||||
};
|
||||
|
||||
export const parseDateToString = ({
|
||||
date,
|
||||
isDateTimeInput,
|
||||
userTimezone,
|
||||
dateFormat = DateFormat.MONTH_FIRST,
|
||||
}: ParseDateToStringArgs) => {
|
||||
const parsingFormat = getDateFormatString(dateFormat, isDateTimeInput);
|
||||
|
||||
if (isDateTimeInput && isDefined(userTimezone)) {
|
||||
return formatInTimeZone(date, userTimezone, parsingFormat);
|
||||
} else if (isDateTimeInput) {
|
||||
return format(date, parsingFormat);
|
||||
} else {
|
||||
const dateWithoutTime = new Date(
|
||||
Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()),
|
||||
);
|
||||
return format(dateWithoutTime, parsingFormat);
|
||||
}
|
||||
};
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
import { type DateFormat } from '@/localization/constants/DateFormat';
|
||||
import { isValid, parse } from 'date-fns';
|
||||
import { zonedTimeToUtc } from 'date-fns-tz';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { getDateFormatString } from '~/utils/date-utils';
|
||||
|
||||
type ParseStringToDateArgs = {
|
||||
dateAsString: string;
|
||||
isDateTimeInput: boolean;
|
||||
userTimezone: string | undefined;
|
||||
dateFormat: DateFormat;
|
||||
};
|
||||
|
||||
export const parseStringToDate = ({
|
||||
dateAsString,
|
||||
isDateTimeInput,
|
||||
userTimezone,
|
||||
dateFormat,
|
||||
}: ParseStringToDateArgs) => {
|
||||
const parsingFormat = getDateFormatString(dateFormat, isDateTimeInput);
|
||||
const referenceDate = new Date();
|
||||
|
||||
const parsedDate = parse(dateAsString, parsingFormat, referenceDate);
|
||||
|
||||
if (!isValid(parsedDate)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isDateTimeInput && isDefined(userTimezone)) {
|
||||
return zonedTimeToUtc(parsedDate, userTimezone);
|
||||
}
|
||||
|
||||
return parsedDate;
|
||||
};
|
||||
@@ -1,43 +0,0 @@
|
||||
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
|
||||
import { UserContext } from '@/users/contexts/UserContext';
|
||||
import { useCallback, useContext } from 'react';
|
||||
import { parseDateToString } from '../date/utils/parseDateToString';
|
||||
import { parseStringToDate } from '../date/utils/parseStringToDate';
|
||||
|
||||
type UseDateParserProps = {
|
||||
isDateTimeInput: boolean;
|
||||
};
|
||||
|
||||
export const useDateParser = ({ isDateTimeInput }: UseDateParserProps) => {
|
||||
const { dateFormat } = useDateTimeFormat();
|
||||
const { timeZone } = useContext(UserContext);
|
||||
|
||||
const parseToString = useCallback(
|
||||
(date: Date) => {
|
||||
return parseDateToString({
|
||||
date,
|
||||
isDateTimeInput,
|
||||
userTimezone: timeZone,
|
||||
dateFormat,
|
||||
});
|
||||
},
|
||||
[dateFormat, isDateTimeInput, timeZone],
|
||||
);
|
||||
|
||||
const parseToDate = useCallback(
|
||||
(dateAsString: string) => {
|
||||
return parseStringToDate({
|
||||
dateAsString,
|
||||
isDateTimeInput,
|
||||
userTimezone: timeZone,
|
||||
dateFormat,
|
||||
});
|
||||
},
|
||||
[dateFormat, isDateTimeInput, timeZone],
|
||||
);
|
||||
|
||||
return {
|
||||
parseToString,
|
||||
parseToDate,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user