[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:
Lucas Bordeau
2025-11-01 18:31:24 +01:00
committed by GitHub
parent 3a203040f7
commit afeb505eed
122 changed files with 3958 additions and 2109 deletions
@@ -10,8 +10,8 @@ import { ObjectFilterDropdownBooleanSelect } from '@/object-record/object-filter
import { ObjectFilterDropdownCountrySelect } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownCountrySelect';
import { ObjectFilterDropdownCurrencySelect } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownCurrencySelect';
import { ObjectFilterDropdownDateInput } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownDateInput';
import { ObjectFilterDropdownDateTimeInput } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownDateTimeInput';
import { ObjectFilterDropdownTextInput } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownTextInput';
import { DATE_FILTER_TYPES } from '@/object-record/object-filter-dropdown/constants/DateFilterTypes';
import { subFieldNameUsedInDropdownComponentState } from '@/object-record/object-filter-dropdown/states/subFieldNameUsedInDropdownComponentState';
import { isFilterOnActorSourceSubField } from '@/object-record/object-filter-dropdown/utils/isFilterOnActorSourceSubField';
import { type RecordFilter } from '@/object-record/record-filter/types/RecordFilter';
@@ -49,9 +49,8 @@ export const AdvancedFilterDropdownFilterInput = ({
<AdvancedFilterDropdownTextInput recordFilter={recordFilter} />
))}
{filterType === 'RATING' && <ObjectFilterDropdownRatingInput />}
{DATE_FILTER_TYPES.includes(filterType) && (
<ObjectFilterDropdownDateInput />
)}
{filterType === 'DATE_TIME' && <ObjectFilterDropdownDateTimeInput />}
{filterType === 'DATE' && <ObjectFilterDropdownDateInput />}
{filterType === 'RELATION' && (
<DropdownContent widthInPixels={GenericDropdownContentWidth.ExtraLarge}>
<ObjectFilterDropdownSearchInput />
@@ -1,10 +1,10 @@
import { useGetFieldMetadataItemByIdOrThrow } from '@/object-metadata/hooks/useGetFieldMetadataItemById';
import { useGetInitialFilterValue } from '@/object-record/object-filter-dropdown/hooks/useGetInitialFilterValue';
import { fieldMetadataItemIdUsedInDropdownComponentState } from '@/object-record/object-filter-dropdown/states/fieldMetadataItemIdUsedInDropdownComponentState';
import { objectFilterDropdownCurrentRecordFilterComponentState } from '@/object-record/object-filter-dropdown/states/objectFilterDropdownCurrentRecordFilterComponentState';
import { objectFilterDropdownSearchInputComponentState } from '@/object-record/object-filter-dropdown/states/objectFilterDropdownSearchInputComponentState';
import { selectedOperandInDropdownComponentState } from '@/object-record/object-filter-dropdown/states/selectedOperandInDropdownComponentState';
import { subFieldNameUsedInDropdownComponentState } from '@/object-record/object-filter-dropdown/states/subFieldNameUsedInDropdownComponentState';
import { getInitialFilterValue } from '@/object-record/object-filter-dropdown/utils/getInitialFilterValue';
import { isCompositeFieldType } from '@/object-record/object-filter-dropdown/utils/isCompositeFieldType';
import { useUpsertRecordFilter } from '@/object-record/record-filter/hooks/useUpsertRecordFilter';
import { currentRecordFiltersComponentState } from '@/object-record/record-filter/states/currentRecordFiltersComponentState';
@@ -56,6 +56,7 @@ export const useSelectFieldUsedInAdvancedFilterDropdown = () => {
);
const { upsertRecordFilter } = useUpsertRecordFilter();
const { getInitialFilterValue } = useGetInitialFilterValue();
const selectFieldUsedInAdvancedFilterDropdown = ({
fieldMetadataItemId,
@@ -1,29 +1,41 @@
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
import { CalendarStartDay } from '@/localization/constants/CalendarStartDay';
import {
detectCalendarStartDay,
type NonSystemCalendarStartDay,
} from '@/localization/utils/detection/detectCalendarStartDay';
import { useApplyObjectFilterDropdownFilterValue } from '@/object-record/object-filter-dropdown/hooks/useApplyObjectFilterDropdownFilterValue';
import { fieldMetadataItemUsedInDropdownComponentSelector } from '@/object-record/object-filter-dropdown/states/fieldMetadataItemUsedInDropdownComponentSelector';
import { useGetNowInUserTimezoneForRelativeFilter } from '@/object-record/object-filter-dropdown/hooks/useGetNowInUserTimezoneForRelativeFilter';
import { objectFilterDropdownCurrentRecordFilterComponentState } from '@/object-record/object-filter-dropdown/states/objectFilterDropdownCurrentRecordFilterComponentState';
import { selectedOperandInDropdownComponentState } from '@/object-record/object-filter-dropdown/states/selectedOperandInDropdownComponentState';
import { getRelativeDateDisplayValue } from '@/object-record/object-filter-dropdown/utils/getRelativeDateDisplayValue';
import { DateTimePicker } from '@/ui/input/components/internal/date/components/InternalDatePicker';
import { DatePicker } from '@/ui/input/components/internal/date/components/DatePicker';
import { useRecoilComponentValue } from '@/ui/utilities/state/component-state/hooks/useRecoilComponentValue';
import { computeVariableDateViewFilterValue } from '@/views/view-filter-value/utils/computeVariableDateViewFilterValue';
import { useState } from 'react';
import { UserContext } from '@/users/contexts/UserContext';
import { stringifyRelativeDateFilter } from '@/views/view-filter-value/utils/stringifyRelativeDateFilter';
import { useContext } from 'react';
import { useRecoilValue } from 'recoil';
import { ViewFilterOperand } from 'twenty-shared/types';
import {
ViewFilterOperand,
type VariableDateViewFilterValueDirection,
type VariableDateViewFilterValueUnit,
} from 'twenty-shared/types';
import { isDefined, resolveDateViewFilterValue } from 'twenty-shared/utils';
import { FieldMetadataType } from '~/generated-metadata/graphql';
isDefined,
type RelativeDateFilter,
resolveDateFilter,
} from 'twenty-shared/utils';
import { dateLocaleState } from '~/localization/states/dateLocaleState';
import { formatDateString } from '~/utils/string/formatDateString';
export const ObjectFilterDropdownDateInput = () => {
const fieldMetadataItemUsedInDropdown = useRecoilComponentValue(
fieldMetadataItemUsedInDropdownComponentSelector,
);
const { dateFormat, timeZone } = useContext(UserContext);
const dateLocale = useRecoilValue(dateLocaleState);
const currentWorkspaceMember = useRecoilValue(currentWorkspaceMemberState);
const selectedOperandInDropdown = useRecoilComponentValue(
selectedOperandInDropdownComponentState,
);
const { getNowInUserTimezoneForRelativeFilter } =
useGetNowInUserTimezoneForRelativeFilter();
const objectFilterDropdownCurrentRecordFilter = useRecoilComponentValue(
objectFilterDropdownCurrentRecordFilterComponentState,
);
@@ -31,43 +43,46 @@ export const ObjectFilterDropdownDateInput = () => {
const { applyObjectFilterDropdownFilterValue } =
useApplyObjectFilterDropdownFilterValue();
const initialFilterValue = isDefined(objectFilterDropdownCurrentRecordFilter)
? resolveDateViewFilterValue(objectFilterDropdownCurrentRecordFilter)
: null;
const handleAbsoluteDateChange = (newPlainDate: string | null) => {
const newFilterValue = newPlainDate ?? '';
const [internalDate, setInternalDate] = useState<Date | null>(
initialFilterValue instanceof Date ? initialFilterValue : null,
);
const formattedDate = formatDateString({
value: newPlainDate,
timeZone,
dateFormat,
localeCatalog: dateLocale.localeCatalog,
});
const isDateTimeInput =
fieldMetadataItemUsedInDropdown?.type === FieldMetadataType.DATE_TIME;
const handleAbsoluteDateChange = (newDate: Date | null) => {
setInternalDate(newDate);
const newFilterValue = newDate?.toISOString() ?? '';
const newDisplayValue = isDefined(newDate)
? isDateTimeInput
? newDate.toLocaleString()
: newDate.toLocaleDateString()
: '';
const newDisplayValue = isDefined(newPlainDate) ? formattedDate : '';
applyObjectFilterDropdownFilterValue(newFilterValue, newDisplayValue);
};
const handleRelativeDateChange = (
relativeDate: {
direction: VariableDateViewFilterValueDirection;
amount?: number;
unit: VariableDateViewFilterValueUnit;
} | null,
relativeDate: RelativeDateFilter | null,
) => {
const { dayAsStringInUserTimezone } =
getNowInUserTimezoneForRelativeFilter();
const userDefinedCalendarStartDay =
CalendarStartDay[
currentWorkspaceMember?.calendarStartDay ?? CalendarStartDay.SYSTEM
];
const defaultSystemCalendarStartDay = detectCalendarStartDay();
const resolvedCalendarStartDay = (
userDefinedCalendarStartDay === CalendarStartDay[CalendarStartDay.SYSTEM]
? defaultSystemCalendarStartDay
: userDefinedCalendarStartDay
) as NonSystemCalendarStartDay;
const newFilterValue = relativeDate
? computeVariableDateViewFilterValue(
relativeDate.direction,
relativeDate.amount,
relativeDate.unit,
)
? stringifyRelativeDateFilter({
...relativeDate,
timezone: timeZone,
referenceDayAsString: dayAsStringInUserTimezone,
firstDayOfTheWeek: resolvedCalendarStartDay,
})
: '';
const newDisplayValue = relativeDate
@@ -86,23 +101,26 @@ export const ObjectFilterDropdownDateInput = () => {
: handleAbsoluteDateChange(null);
};
const resolvedValue = objectFilterDropdownCurrentRecordFilter
? resolveDateViewFilterValue(objectFilterDropdownCurrentRecordFilter)
? resolveDateFilter(objectFilterDropdownCurrentRecordFilter)
: null;
const relativeDate =
resolvedValue && !(resolvedValue instanceof Date)
resolvedValue && typeof resolvedValue === 'object'
? resolvedValue
: undefined;
const plainDateValue =
resolvedValue && typeof resolvedValue === 'string'
? resolvedValue
: undefined;
return (
<DateTimePicker
<DatePicker
relativeDate={relativeDate}
highlightedDateRange={relativeDate}
isRelative={isRelativeOperand}
date={internalDate}
date={plainDateValue ?? null}
onChange={handleAbsoluteDateChange}
onRelativeDateChange={handleRelativeDateChange}
isDateTimeInput={isDateTimeInput}
onClear={handleClear}
/>
);
@@ -0,0 +1,134 @@
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
import { CalendarStartDay } from '@/localization/constants/CalendarStartDay';
import {
detectCalendarStartDay,
type NonSystemCalendarStartDay,
} from '@/localization/utils/detection/detectCalendarStartDay';
import { useApplyObjectFilterDropdownFilterValue } from '@/object-record/object-filter-dropdown/hooks/useApplyObjectFilterDropdownFilterValue';
import { useGetNowInUserTimezoneForRelativeFilter } from '@/object-record/object-filter-dropdown/hooks/useGetNowInUserTimezoneForRelativeFilter';
import { objectFilterDropdownCurrentRecordFilterComponentState } from '@/object-record/object-filter-dropdown/states/objectFilterDropdownCurrentRecordFilterComponentState';
import { selectedOperandInDropdownComponentState } from '@/object-record/object-filter-dropdown/states/selectedOperandInDropdownComponentState';
import { getRelativeDateDisplayValue } from '@/object-record/object-filter-dropdown/utils/getRelativeDateDisplayValue';
import { DateTimePicker } from '@/ui/input/components/internal/date/components/DateTimePicker';
import { useRecoilComponentValue } from '@/ui/utilities/state/component-state/hooks/useRecoilComponentValue';
import { UserContext } from '@/users/contexts/UserContext';
import { stringifyRelativeDateFilter } from '@/views/view-filter-value/utils/stringifyRelativeDateFilter';
import { useContext, useState } from 'react';
import { useRecoilValue } from 'recoil';
import { ViewFilterOperand } from 'twenty-shared/types';
import {
isDefined,
resolveDateTimeFilter,
type RelativeDateFilter,
} from 'twenty-shared/utils';
import { dateLocaleState } from '~/localization/states/dateLocaleState';
import { formatDateTimeString } from '~/utils/string/formatDateTimeString';
export const ObjectFilterDropdownDateTimeInput = () => {
const { dateFormat, timeFormat, timeZone } = useContext(UserContext);
const dateLocale = useRecoilValue(dateLocaleState);
const currentWorkspaceMember = useRecoilValue(currentWorkspaceMemberState);
const selectedOperandInDropdown = useRecoilComponentValue(
selectedOperandInDropdownComponentState,
);
const objectFilterDropdownCurrentRecordFilter = useRecoilComponentValue(
objectFilterDropdownCurrentRecordFilterComponentState,
);
const { applyObjectFilterDropdownFilterValue } =
useApplyObjectFilterDropdownFilterValue();
const initialFilterValue = isDefined(objectFilterDropdownCurrentRecordFilter)
? resolveDateTimeFilter(objectFilterDropdownCurrentRecordFilter)
: null;
const { getNowInUserTimezoneForRelativeFilter } =
useGetNowInUserTimezoneForRelativeFilter();
const [internalDate, setInternalDate] = useState<Date | null>(
initialFilterValue instanceof Date ? initialFilterValue : null,
);
const handleAbsoluteDateChange = (newDate: Date | null) => {
setInternalDate(newDate);
const newFilterValue = newDate?.toISOString() ?? '';
const formattedDateTime = formatDateTimeString({
value: newDate?.toISOString(),
timeZone,
dateFormat,
timeFormat,
localeCatalog: dateLocale.localeCatalog,
});
const newDisplayValue = isDefined(newDate) ? formattedDateTime : '';
applyObjectFilterDropdownFilterValue(newFilterValue, newDisplayValue);
};
const handleRelativeDateChange = (
relativeDate: RelativeDateFilter | null,
) => {
const { dayAsStringInUserTimezone } =
getNowInUserTimezoneForRelativeFilter();
const userDefinedCalendarStartDay =
CalendarStartDay[
currentWorkspaceMember?.calendarStartDay ?? CalendarStartDay.SYSTEM
];
const defaultSystemCalendarStartDay = detectCalendarStartDay();
const resolvedCalendarStartDay = (
userDefinedCalendarStartDay === CalendarStartDay[CalendarStartDay.SYSTEM]
? defaultSystemCalendarStartDay
: userDefinedCalendarStartDay
) as NonSystemCalendarStartDay;
const newFilterValue = relativeDate
? stringifyRelativeDateFilter({
...relativeDate,
timezone: timeZone,
referenceDayAsString: dayAsStringInUserTimezone,
firstDayOfTheWeek: resolvedCalendarStartDay,
})
: '';
const newDisplayValue = relativeDate
? getRelativeDateDisplayValue(relativeDate)
: '';
applyObjectFilterDropdownFilterValue(newFilterValue, newDisplayValue);
};
const isRelativeOperand =
selectedOperandInDropdown === ViewFilterOperand.IS_RELATIVE;
const handleClear = () => {
isRelativeOperand
? handleRelativeDateChange(null)
: handleAbsoluteDateChange(null);
};
const resolvedValue = objectFilterDropdownCurrentRecordFilter
? resolveDateTimeFilter(objectFilterDropdownCurrentRecordFilter)
: null;
const relativeDate =
resolvedValue && !(resolvedValue instanceof Date)
? resolvedValue
: undefined;
return (
<DateTimePicker
relativeDate={relativeDate}
isRelative={isRelativeOperand}
date={internalDate}
onChange={handleAbsoluteDateChange}
onRelativeDateChange={handleRelativeDateChange}
onClear={handleClear}
/>
);
};
@@ -9,10 +9,10 @@ import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownM
import { ViewFilterOperand } from 'twenty-shared/types';
import { ObjectFilterDropdownBooleanSelect } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownBooleanSelect';
import { ObjectFilterDropdownDateTimeInput } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownDateTimeInput';
import { ObjectFilterDropdownInnerSelectOperandDropdown } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownInnerSelectOperandDropdown';
import { ObjectFilterDropdownTextInput } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownTextInput';
import { ObjectFilterDropdownVectorSearchInput } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownVectorSearchInput';
import { DATE_FILTER_TYPES } from '@/object-record/object-filter-dropdown/constants/DateFilterTypes';
import { NUMBER_FILTER_TYPES } from '@/object-record/object-filter-dropdown/constants/NumberFilterTypes';
import { TEXT_FILTER_TYPES } from '@/object-record/object-filter-dropdown/constants/TextFilterTypes';
import { fieldMetadataItemUsedInDropdownComponentSelector } from '@/object-record/object-filter-dropdown/states/fieldMetadataItemUsedInDropdownComponentSelector';
@@ -69,7 +69,6 @@ export const ObjectFilterDropdownFilterInput = ({
fieldMetadataItemUsedInDropdown.type,
);
const isDateFilter = DATE_FILTER_TYPES.includes(filterType);
const isOnlyOperand = !isOperandWithFilterValue;
if (isOnlyOperand) {
@@ -78,7 +77,7 @@ export const ObjectFilterDropdownFilterInput = ({
<ObjectFilterDropdownInnerSelectOperandDropdown />
</>
);
} else if (isDateFilter) {
} else if (filterType === 'DATE') {
return (
<>
<ObjectFilterDropdownInnerSelectOperandDropdown />
@@ -86,6 +85,14 @@ export const ObjectFilterDropdownFilterInput = ({
<ObjectFilterDropdownDateInput />
</>
);
} else if (filterType === 'DATE_TIME') {
return (
<>
<ObjectFilterDropdownInnerSelectOperandDropdown />
<DropdownMenuSeparator />
<ObjectFilterDropdownDateTimeInput />
</>
);
} else {
return (
<>
@@ -1,4 +1,6 @@
import { DATE_OPERANDS_THAT_SHOULD_BE_INITIALIZED_WITH_NOW } from '@/object-record/object-filter-dropdown/constants/DateOperandsThatShouldBeInitializedWithNow';
import { useGetInitialFilterValue } from '@/object-record/object-filter-dropdown/hooks/useGetInitialFilterValue';
import { useGetNowInUserTimezoneForRelativeFilter } from '@/object-record/object-filter-dropdown/hooks/useGetNowInUserTimezoneForRelativeFilter';
import { useUpsertObjectFilterDropdownCurrentFilter } from '@/object-record/object-filter-dropdown/hooks/useUpsertObjectFilterDropdownCurrentFilter';
import { fieldMetadataItemUsedInDropdownComponentSelector } from '@/object-record/object-filter-dropdown/states/fieldMetadataItemUsedInDropdownComponentSelector';
import { objectFilterDropdownCurrentRecordFilterComponentState } from '@/object-record/object-filter-dropdown/states/objectFilterDropdownCurrentRecordFilterComponentState';
@@ -7,15 +9,18 @@ import { getRelativeDateDisplayValue } from '@/object-record/object-filter-dropd
import { useCreateEmptyRecordFilterFromFieldMetadataItem } from '@/object-record/record-filter/hooks/useCreateEmptyRecordFilterFromFieldMetadataItem';
import { type RecordFilter } from '@/object-record/record-filter/types/RecordFilter';
import { RecordFilterOperand } from '@/object-record/record-filter/types/RecordFilterOperand';
import { getDateFilterDisplayValue } from '@/object-record/record-filter/utils/getDateFilterDisplayValue';
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
import { useRecoilComponentValue } from '@/ui/utilities/state/component-state/hooks/useRecoilComponentValue';
import { useSetRecoilComponentState } from '@/ui/utilities/state/component-state/hooks/useSetRecoilComponentState';
import { computeVariableDateViewFilterValue } from '@/views/view-filter-value/utils/computeVariableDateViewFilterValue';
import { stringifyRelativeDateFilter } from '@/views/view-filter-value/utils/stringifyRelativeDateFilter';
import {
type VariableDateViewFilterValueDirection,
type VariableDateViewFilterValueUnit,
} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
isDefined,
type RelativeDateFilter,
type RelativeDateFilterDirection,
type RelativeDateFilterUnit,
} from 'twenty-shared/utils';
export const useApplyObjectFilterDropdownOperand = () => {
const objectFilterDropdownCurrentRecordFilter = useRecoilComponentValue(
@@ -40,6 +45,13 @@ export const useApplyObjectFilterDropdownOperand = () => {
const { createEmptyRecordFilterFromFieldMetadataItem } =
useCreateEmptyRecordFilterFromFieldMetadataItem();
const { getInitialFilterValue } = useGetInitialFilterValue();
const { userTimezone } = useUserTimezone();
const { getNowInUserTimezoneForRelativeFilter } =
useGetNowInUserTimezoneForRelativeFilter();
const applyObjectFilterDropdownOperand = (
newOperand: RecordFilterOperand,
) => {
@@ -84,27 +96,35 @@ export const useApplyObjectFilterDropdownOperand = () => {
if (
DATE_OPERANDS_THAT_SHOULD_BE_INITIALIZED_WITH_NOW.includes(newOperand)
) {
const newDateValue = new Date();
// TODO: allow to keep same value when switching between is after, is before, is and is not
// For now we reset with now each time we switch operand
recordFilterToUpsert.value = newDateValue.toISOString();
const { displayValue } = getDateFilterDisplayValue(
newDateValue,
const dateToUseAsISOString = new Date().toISOString();
const { displayValue, value } = getInitialFilterValue(
recordFilterToUpsert.type,
newOperand,
dateToUseAsISOString,
);
recordFilterToUpsert.value = value;
recordFilterToUpsert.displayValue = displayValue;
} else if (newOperand === RecordFilterOperand.IS_RELATIVE) {
const defaultRelativeDate = {
direction: 'THIS' as VariableDateViewFilterValueDirection,
const { dayAsStringInUserTimezone } =
getNowInUserTimezoneForRelativeFilter();
const defaultRelativeDate: RelativeDateFilter = {
direction: 'THIS' as RelativeDateFilterDirection,
amount: 1,
unit: 'DAY' as VariableDateViewFilterValueUnit,
unit: 'DAY' as RelativeDateFilterUnit,
timezone: userTimezone,
referenceDayAsString: dayAsStringInUserTimezone,
};
recordFilterToUpsert.value = computeVariableDateViewFilterValue(
defaultRelativeDate.direction,
defaultRelativeDate.amount,
defaultRelativeDate.unit,
);
recordFilterToUpsert.value =
stringifyRelativeDateFilter(defaultRelativeDate);
recordFilterToUpsert.displayValue =
getRelativeDateDisplayValue(defaultRelativeDate);
} else {
@@ -0,0 +1,49 @@
import { getDateFormatFromWorkspaceDateFormat } from '@/localization/utils/format-preferences/getDateFormatFromWorkspaceDateFormat';
import { getTimeFormatFromWorkspaceTimeFormat } from '@/localization/utils/format-preferences/getTimeFormatFromWorkspaceTimeFormat';
import { useUserDateFormat } from '@/ui/input/components/internal/date/hooks/useUserDateFormat';
import { useUserTimeFormat } from '@/ui/input/components/internal/date/hooks/useUserTimeFormat';
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
import { format } from 'date-fns';
import { shiftPointInTimeFromTimezoneDifferenceInMinutesWithSystemTimezone } from 'twenty-shared/utils';
export const useGetDateTimeFilterDisplayValue = () => {
const {
userTimezone,
isSystemTimezone,
getTimezoneAbbreviationForPointInTime,
} = useUserTimezone();
const { userDateFormat } = useUserDateFormat();
const { userTimeFormat } = useUserTimeFormat();
const getDateTimeFilterDisplayValue = (correctPointInTime: Date) => {
const shiftedDate =
shiftPointInTimeFromTimezoneDifferenceInMinutesWithSystemTimezone(
correctPointInTime,
userTimezone,
'sub',
);
const dateFormatString =
getDateFormatFromWorkspaceDateFormat(userDateFormat);
const timeFormatString =
getTimeFormatFromWorkspaceTimeFormat(userTimeFormat);
const formatToUse = `${dateFormatString} ${timeFormatString}`;
const timezoneSuffix = !isSystemTimezone
? ` (${getTimezoneAbbreviationForPointInTime(shiftedDate)})`
: '';
const displayValue = `${format(shiftedDate, formatToUse)}${timezoneSuffix}`;
return {
correctPointInTime,
displayValue,
};
};
return {
getDateTimeFilterDisplayValue,
};
};
@@ -0,0 +1,115 @@
import { getDateFormatFromWorkspaceDateFormat } from '@/localization/utils/format-preferences/getDateFormatFromWorkspaceDateFormat';
import { getTimeFormatFromWorkspaceTimeFormat } from '@/localization/utils/format-preferences/getTimeFormatFromWorkspaceTimeFormat';
import { type RecordFilter } from '@/object-record/record-filter/types/RecordFilter';
import { RecordFilterOperand } from '@/object-record/record-filter/types/RecordFilterOperand';
import { useUserDateFormat } from '@/ui/input/components/internal/date/hooks/useUserDateFormat';
import { useUserTimeFormat } from '@/ui/input/components/internal/date/hooks/useUserTimeFormat';
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
import { TZDate } from '@date-fns/tz';
import { isNonEmptyString } from '@sniptt/guards';
import { format } from 'date-fns';
import { DATE_TYPE_FORMAT } from 'twenty-shared/constants';
import { type FilterableAndTSVectorFieldType } from 'twenty-shared/types';
const activeDatePickerOperands = [
RecordFilterOperand.IS_BEFORE,
RecordFilterOperand.IS,
RecordFilterOperand.IS_AFTER,
];
export const useGetInitialFilterValue = () => {
const {
userTimezone,
isSystemTimezone,
getTimezoneAbbreviationForPointInTime,
} = useUserTimezone();
const { userDateFormat } = useUserDateFormat();
const { userTimeFormat } = useUserTimeFormat();
const getInitialFilterValue = (
newType: FilterableAndTSVectorFieldType,
newOperand: RecordFilterOperand,
alreadyExistingISODate?: string,
): Pick<RecordFilter, 'value' | 'displayValue'> | Record<string, never> => {
switch (newType) {
case 'DATE': {
if (activeDatePickerOperands.includes(newOperand)) {
const referenceDate = isNonEmptyString(alreadyExistingISODate)
? new Date(alreadyExistingISODate)
: new Date();
const shiftedDate = new TZDate(
referenceDate.getFullYear(),
referenceDate.getMonth(),
referenceDate.getDate(),
userTimezone,
);
const dateFormatString =
getDateFormatFromWorkspaceDateFormat(userDateFormat);
shiftedDate.setSeconds(0);
shiftedDate.setMilliseconds(0);
const value = format(shiftedDate, DATE_TYPE_FORMAT);
const displayValue = format(shiftedDate, dateFormatString);
return { value, displayValue };
}
break;
}
case 'DATE_TIME': {
if (activeDatePickerOperands.includes(newOperand)) {
const referenceDate = isNonEmptyString(alreadyExistingISODate)
? new Date(alreadyExistingISODate)
: new Date();
const shiftedDate = new TZDate(
referenceDate.getFullYear(),
referenceDate.getMonth(),
referenceDate.getDate(),
referenceDate.getHours(),
referenceDate.getMinutes(),
userTimezone,
);
shiftedDate.setSeconds(0);
shiftedDate.setMilliseconds(0);
const dateFormatString =
getDateFormatFromWorkspaceDateFormat(userDateFormat);
const timeFormatString =
getTimeFormatFromWorkspaceTimeFormat(userTimeFormat);
const formatToUse = `${dateFormatString} ${timeFormatString}`;
const timezoneSuffix = !isSystemTimezone
? ` (${getTimezoneAbbreviationForPointInTime(shiftedDate)})`
: '';
const value = shiftedDate.toISOString();
const displayValue = `${format(shiftedDate, formatToUse)}${timezoneSuffix}`;
return { value, displayValue };
}
if (newOperand === RecordFilterOperand.IS_RELATIVE) {
return { value: '', displayValue: '' };
}
break;
}
}
return {
value: '',
displayValue: '',
};
};
return {
getInitialFilterValue,
};
};
@@ -0,0 +1,33 @@
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
import { TZDate } from '@date-fns/tz';
import { format } from 'date-fns';
import { DATE_TYPE_FORMAT } from 'twenty-shared/constants';
export const useGetNowInUserTimezoneForRelativeFilter = () => {
const { userTimezone } = useUserTimezone();
const getNowInUserTimezoneForRelativeFilter = () => {
const now = new Date();
const nowInUserTimezone = new TZDate(
now.getFullYear(),
now.getMonth(),
now.getDate(),
userTimezone,
);
const dayAsStringInUserTimezone = format(
nowInUserTimezone,
DATE_TYPE_FORMAT,
);
return {
nowInUserTimezone,
dayAsStringInUserTimezone,
};
};
return {
getNowInUserTimezoneForRelativeFilter,
};
};
@@ -1,40 +0,0 @@
import { type RecordFilter } from '@/object-record/record-filter/types/RecordFilter';
import { RecordFilterOperand } from '@/object-record/record-filter/types/RecordFilterOperand';
import { getDateFilterDisplayValue } from '@/object-record/record-filter/utils/getDateFilterDisplayValue';
import { type FilterableAndTSVectorFieldType } from 'twenty-shared/types';
export const getInitialFilterValue = (
newType: FilterableAndTSVectorFieldType,
newOperand: RecordFilterOperand,
): Pick<RecordFilter, 'value' | 'displayValue'> | Record<string, never> => {
switch (newType) {
case 'DATE':
case 'DATE_TIME': {
const activeDatePickerOperands = [
RecordFilterOperand.IS_BEFORE,
RecordFilterOperand.IS,
RecordFilterOperand.IS_AFTER,
];
if (activeDatePickerOperands.includes(newOperand)) {
const date = new Date();
const value = date.toISOString();
const { displayValue } = getDateFilterDisplayValue(date, newType);
return { value, displayValue };
}
if (newOperand === RecordFilterOperand.IS_RELATIVE) {
return { value: '', displayValue: '' };
}
break;
}
}
return {
value: '',
displayValue: '',
};
};
@@ -1,16 +1,9 @@
import { plural } from 'pluralize';
import {
type VariableDateViewFilterValueDirection,
type VariableDateViewFilterValueUnit,
} from 'twenty-shared/types';
import { capitalize } from 'twenty-shared/utils';
import { capitalize, type RelativeDateFilter } from 'twenty-shared/utils';
export const getRelativeDateDisplayValue = (
relativeDate: {
direction: VariableDateViewFilterValueDirection;
amount?: number;
unit: VariableDateViewFilterValueUnit;
} | null,
relativeDate: RelativeDateFilter | null,
) => {
if (!relativeDate) return '';
const { direction, amount, unit } = relativeDate;
@@ -28,7 +28,6 @@ export const RecordBoardCardCellEditModePortal = () => {
return (
<RecordInlineCellAnchoredPortal
position={editModePosition}
fieldMetadataItem={editedFieldMetadataItem}
objectMetadataItem={objectMetadataItem}
recordId={recordId}
@@ -1,12 +1,9 @@
import { useRecoilComponentValue } from '@/ui/utilities/state/component-state/hooks/useRecoilComponentValue';
import { RecordBoardContext } from '@/object-record/record-board/contexts/RecordBoardContext';
import { RecordBoardCardCellHoveredPortalContent } from '@/object-record/record-board/record-board-card/anchored-portal/components/RecordBoardCardCellHoveredPortalContent';
import { RecordBoardCardInputContextProvider } from '@/object-record/record-board/record-board-card/anchored-portal/components/RecordBoardCardInputContextProvider';
import { RECORD_BOARD_CARD_INPUT_ID_PREFIX } from '@/object-record/record-board/record-board-card/constants/RecordBoardCardInputIdPrefix';
import { RecordBoardCardContext } from '@/object-record/record-board/record-board-card/contexts/RecordBoardCardContext';
import { useRecordBoardCardMetadataFromPosition } from '@/object-record/record-board/record-board-card/hooks/useRecordBoardCardMetadataFromPosition';
import { recordBoardCardHoverPositionComponentState } from '@/object-record/record-board/record-board-card/states/recordBoardCardHoverPositionComponentState';
import { RecordInlineCellAnchoredPortal } from '@/object-record/record-inline-cell/components/RecordInlineCellAnchoredPortal';
import { useContext } from 'react';
import { isDefined } from 'twenty-shared/utils';
@@ -15,19 +12,14 @@ export const RecordBoardCardCellHoveredPortal = () => {
const { objectMetadataItem } = useContext(RecordBoardContext);
const { recordId } = useContext(RecordBoardCardContext);
const hoverPosition = useRecoilComponentValue(
recordBoardCardHoverPositionComponentState,
);
const { hoveredFieldMetadataItem } = useRecordBoardCardMetadataFromPosition();
if (!isDefined(hoverPosition) || !isDefined(hoveredFieldMetadataItem)) {
if (!isDefined(hoveredFieldMetadataItem)) {
return null;
}
return (
<RecordInlineCellAnchoredPortal
position={hoverPosition}
fieldMetadataItem={hoveredFieldMetadataItem}
objectMetadataItem={objectMetadataItem}
recordId={recordId}
@@ -1,7 +1,7 @@
import { RecordCalendarComponentInstanceContext } from '@/object-record/record-calendar/states/contexts/RecordCalendarComponentInstanceContext';
import { recordCalendarSelectedDateComponentState } from '@/object-record/record-calendar/states/recordCalendarSelectedDateComponentState';
import { recordIndexCalendarLayoutState } from '@/object-record/record-index/states/recordIndexCalendarLayoutState';
import { DateTimePicker } from '@/ui/input/components/internal/date/components/InternalDatePicker';
import { DateTimePicker } from '@/ui/input/components/internal/date/components/DateTimePicker';
import { Select } from '@/ui/input/components/Select';
import { SelectControl } from '@/ui/input/components/SelectControl';
import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
@@ -121,7 +121,6 @@ export const RecordCalendarTopBar = () => {
<DropdownContent widthInPixels={280}>
<DateTimePicker
date={recordCalendarSelectedDate}
isDateTimeInput={false}
onChange={handleDateChange}
onClose={handleDateChange}
onEnter={handleDateChange}
@@ -2,6 +2,7 @@ import { RecordCalendarMonthBodyWeek } from '@/object-record/record-calendar/mon
import { useRecordCalendarMonthContextOrThrow } from '@/object-record/record-calendar/month/contexts/RecordCalendarMonthContext';
import styled from '@emotion/styled';
import { format } from 'date-fns';
import { DATE_TYPE_FORMAT } from 'twenty-shared/constants';
const StyledContainer = styled.div`
display: flex;
@@ -19,7 +20,7 @@ export const RecordCalendarMonthBody = () => {
<StyledContainer>
{weekFirstDays.map((weekFirstDay) => (
<RecordCalendarMonthBodyWeek
key={`week-${format(weekFirstDay, 'yyyy-MM-dd')}`}
key={`week-${format(weekFirstDay, DATE_TYPE_FORMAT)}`}
startDayOfWeek={weekFirstDay}
/>
))}
@@ -8,6 +8,7 @@ import styled from '@emotion/styled';
import { Droppable } from '@hello-pangea/dnd';
import { format, isSameDay, isSameMonth, isWeekend } from 'date-fns';
import { useState } from 'react';
import { DATE_TYPE_FORMAT } from 'twenty-shared/constants';
import { RecordCalendarAddNew } from '../../components/RecordCalendarAddNew';
const StyledContainer = styled.div<{
@@ -103,7 +104,7 @@ export const RecordCalendarMonthBodyDay = ({
recordCalendarSelectedDateComponentState,
);
const dayKey = format(day, 'yyyy-MM-dd');
const dayKey = format(day, DATE_TYPE_FORMAT);
const recordIds = useRecoilComponentFamilyValue(
calendarDayRecordIdsComponentFamilySelector,
@@ -32,7 +32,6 @@ export const RecordCalendarCardCellEditModePortal = ({
return (
<RecordInlineCellAnchoredPortal
position={editModePosition}
fieldMetadataItem={editedFieldMetadataItem}
objectMetadataItem={objectMetadataItem}
recordId={recordId}
@@ -31,7 +31,6 @@ export const RecordCalendarCardCellHoveredPortal = ({
return (
<RecordInlineCellAnchoredPortal
position={hoverPosition}
fieldMetadataItem={hoveredFieldMetadataItem}
objectMetadataItem={objectMetadataItem}
recordId={recordId}
@@ -38,7 +38,6 @@ export const RecordFieldListCellEditModePortal = ({
return (
<RecordInlineCellAnchoredPortal
position={editModePosition}
fieldMetadataItem={editedFieldMetadataItem}
objectMetadataItem={objectMetadataItem}
recordId={recordId}
@@ -37,7 +37,6 @@ export const RecordFieldListCellHoveredPortal = ({
return (
<RecordInlineCellAnchoredPortal
position={hoverPosition}
fieldMetadataItem={hoveredFieldMetadataItem}
objectMetadataItem={objectMetadataItem}
recordId={recordId}
@@ -1,13 +1,89 @@
import { FormDateTimeFieldInput } from '@/object-record/record-field/ui/form-types/components/FormDateTimeFieldInput';
import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';
import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { DatePicker } from '@/ui/input/components/internal/date/components/DatePicker';
import {
MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID,
MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID,
} from '@/ui/input/components/internal/date/components/DateTimePicker';
import { useParseDateInputStringToPlainDate } from '@/ui/input/components/internal/date/hooks/useParseDateInputStringToPlainDate';
import { useParsePlainDateToDateInputString } from '@/ui/input/components/internal/date/hooks/useParsePlainDateToDateInputString';
import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContainer';
import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';
import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
import { css } from '@emotion/react';
import styled from '@emotion/styled';
import { isNonEmptyString } from '@sniptt/guards';
import {
useId,
useRef,
useState,
type ChangeEvent,
type KeyboardEvent,
} from 'react';
import { Key } from 'ts-key-enum';
import { isDefined } from 'twenty-shared/utils';
import { TEXT_INPUT_STYLE } from 'twenty-ui/theme';
import { type Nullable } from 'twenty-ui/utilities';
import { getDateFormatStringForDatePickerInputMask } from '~/utils/date-utils';
const StyledInputContainer = styled(FormFieldInputInnerContainer)`
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr 0;
overflow: visible;
position: relative;
`;
const StyledDateInputAbsoluteContainer = styled.div`
position: absolute;
top: ${({ theme }) => theme.spacing(1)};
`;
const StyledDateInput = styled.input<{ hasError?: boolean }>`
${TEXT_INPUT_STYLE}
&:disabled {
color: ${({ theme }) => theme.font.color.tertiary};
}
${({ hasError, theme }) =>
hasError &&
css`
color: ${theme.color.red};
`};
`;
const StyledDateInputContainer = styled.div`
position: relative;
z-index: 1;
`;
type DraftValue =
| {
type: 'static';
value: string | null;
mode: 'view' | 'edit';
}
| {
type: 'variable';
value: string;
};
type FormDateFieldInputProps = {
label?: string;
defaultValue: string | undefined;
onChange: (value: string | null) => void;
placeholder?: string;
VariablePicker?: VariablePickerComponent;
readonly?: boolean;
placeholder?: string;
};
export const FormDateFieldInput = ({
@@ -18,15 +94,277 @@ export const FormDateFieldInput = ({
readonly,
placeholder,
}: FormDateFieldInputProps) => {
const instanceId = useId();
const { dateFormat } = useDateTimeFormat();
const { parsePlainDateToDateInputString } =
useParsePlainDateToDateInputString();
const { parseDateInputStringToPlainDate } =
useParseDateInputStringToPlainDate();
const [draftValue, setDraftValue] = useState<DraftValue>(
isStandaloneVariableString(defaultValue)
? {
type: 'variable',
value: defaultValue,
}
: {
type: 'static',
value: defaultValue ?? null,
mode: 'view',
},
);
const draftValueAsDate =
isDefined(draftValue.value) &&
isNonEmptyString(draftValue.value) &&
draftValue.type === 'static'
? draftValue.value
: null;
const [pickerDate, setPickerDate] =
useState<Nullable<string>>(draftValueAsDate);
const datePickerWrapperRef = useRef<HTMLDivElement>(null);
const [inputDate, setInputDate] = useState(
isDefined(draftValueAsDate) && !isStandaloneVariableString(defaultValue)
? parsePlainDateToDateInputString(draftValueAsDate)
: '',
);
const persistDate = (newDate: Nullable<string>) => {
if (!isDefined(newDate)) {
onChange(null);
} else {
onChange(newDate);
}
};
const { closeDropdown: closeDropdownMonthSelect } = useCloseDropdown();
const { closeDropdown: closeDropdownYearSelect } = useCloseDropdown();
const displayDatePicker =
draftValue.type === 'static' && draftValue.mode === 'edit';
const defaultPlaceHolder =
getDateFormatStringForDatePickerInputMask(dateFormat);
const placeholderToDisplay = placeholder ?? defaultPlaceHolder;
useListenClickOutside({
refs: [datePickerWrapperRef],
listenerId: 'FormDateTimeFieldInputBase',
callback: (event) => {
event.stopImmediatePropagation();
closeDropdownYearSelect(MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID);
closeDropdownMonthSelect(MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID);
handlePickerClickOutside();
},
enabled: displayDatePicker,
excludedClickOutsideIds: [
MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID,
MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID,
],
});
const handlePickerChange = (newDate: Nullable<string>) => {
setDraftValue({
type: 'static',
mode: 'edit',
value: newDate ?? null,
});
setInputDate(
isDefined(newDate) ? parsePlainDateToDateInputString(newDate) : '',
);
setPickerDate(newDate);
persistDate(newDate);
};
const handlePickerEnter = () => {};
const handlePickerEscape = () => {
// FIXME: Escape key is not handled properly by the underlying DateInput component. We need to solve that.
setDraftValue({
type: 'static',
value: draftValue.value,
mode: 'view',
});
};
const handlePickerClickOutside = () => {
setDraftValue({
type: 'static',
value: draftValue.value,
mode: 'view',
});
};
const handlePickerClear = () => {
setDraftValue({
type: 'static',
value: null,
mode: 'view',
});
setPickerDate(null);
setInputDate('');
persistDate(null);
};
const handlePickerMouseSelect = (newDate: Nullable<string>) => {
setDraftValue({
type: 'static',
value: newDate ?? null,
mode: 'view',
});
setPickerDate(newDate);
setInputDate(
isDefined(newDate) ? parsePlainDateToDateInputString(newDate) : '',
);
persistDate(newDate);
};
const handleInputFocus = () => {
setDraftValue({
type: 'static',
mode: 'edit',
value: draftValue.value,
});
};
const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
setInputDate(event.target.value);
};
const handleInputKeydown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key !== 'Enter') {
return;
}
const inputDateTime = inputDate.trim();
if (inputDateTime === '') {
handlePickerClear();
return;
}
const parsedInputPlainDate = parseDateInputStringToPlainDate(inputDateTime);
if (!isDefined(parsedInputPlainDate)) {
return;
}
let validatedDate = parsedInputPlainDate;
setDraftValue({
type: 'static',
value: validatedDate,
mode: 'edit',
});
setPickerDate(validatedDate);
setInputDate(parsePlainDateToDateInputString(validatedDate));
persistDate(validatedDate);
};
const handleVariableTagInsert = (variableName: string) => {
setDraftValue({
type: 'variable',
value: variableName,
});
setInputDate('');
onChange(variableName);
};
const handleUnlinkVariable = () => {
setDraftValue({
type: 'static',
value: null,
mode: 'view',
});
setPickerDate(null);
onChange(null);
};
useHotkeysOnFocusedElement({
keys: [Key.Escape],
callback: handlePickerEscape,
focusId: instanceId,
dependencies: [handlePickerEscape],
});
return (
<FormDateTimeFieldInput
dateOnly
label={label}
defaultValue={defaultValue}
onChange={onChange}
VariablePicker={VariablePicker}
readonly={readonly}
placeholder={placeholder}
/>
<FormFieldInputContainer>
{label ? <InputLabel>{label}</InputLabel> : null}
<FormFieldInputRowContainer>
<StyledInputContainer
formFieldInputInstanceId={instanceId}
ref={datePickerWrapperRef}
hasRightElement={isDefined(VariablePicker) && !readonly}
>
{draftValue.type === 'static' ? (
<>
<StyledDateInput
type="text"
placeholder={placeholderToDisplay}
value={inputDate}
onFocus={handleInputFocus}
onChange={handleInputChange}
onKeyDown={handleInputKeydown}
disabled={readonly}
/>
{draftValue.mode === 'edit' ? (
<StyledDateInputContainer>
<StyledDateInputAbsoluteContainer>
<OverlayContainer>
<DatePicker
date={pickerDate}
onChange={handlePickerChange}
onClose={handlePickerMouseSelect}
onEnter={handlePickerEnter}
onEscape={handlePickerEscape}
onClear={handlePickerClear}
hideHeaderInput
/>
</OverlayContainer>
</StyledDateInputAbsoluteContainer>
</StyledDateInputContainer>
) : null}
</>
) : (
<VariableChipStandalone
rawVariableName={draftValue.value}
onRemove={readonly ? undefined : handleUnlinkVariable}
/>
)}
</StyledInputContainer>
{VariablePicker && !readonly ? (
<VariablePicker
instanceId={instanceId}
onVariableSelect={handleVariableTagInsert}
/>
) : null}
</FormFieldInputRowContainer>
</FormFieldInputContainer>
);
};
@@ -8,10 +8,12 @@ import {
DateTimePicker,
MONTH_AND_YEAR_DROPDOWN_MONTH_SELECT_ID,
MONTH_AND_YEAR_DROPDOWN_YEAR_SELECT_ID,
} from '@/ui/input/components/internal/date/components/InternalDatePicker';
} from '@/ui/input/components/internal/date/components/DateTimePicker';
import { MAX_DATE } from '@/ui/input/components/internal/date/constants/MaxDate';
import { MIN_DATE } from '@/ui/input/components/internal/date/constants/MinDate';
import { useDateParser } from '@/ui/input/components/internal/hooks/useDateParser';
import { useParseDateTimeInputStringToJSDate } from '@/ui/input/components/internal/date/hooks/useParseDateTimeInputStringToJSDate';
import { useParseJSDateToIMaskDateTimeInputString } from '@/ui/input/components/internal/date/hooks/useParseJSDateToIMaskDateTimeInputString';
import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContainer';
import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';
@@ -76,7 +78,6 @@ type DraftValue =
};
type FormDateTimeFieldInputProps = {
dateOnly?: boolean;
label?: string;
defaultValue: string | undefined;
onChange: (value: string | null) => void;
@@ -86,7 +87,6 @@ type FormDateTimeFieldInputProps = {
};
export const FormDateTimeFieldInput = ({
dateOnly,
label,
defaultValue,
onChange,
@@ -94,12 +94,13 @@ export const FormDateTimeFieldInput = ({
readonly,
placeholder,
}: FormDateTimeFieldInputProps) => {
const { parseToString, parseToDate } = useDateParser({
isDateTimeInput: !dateOnly,
});
const instanceId = useId();
const { parseJSDateToDateTimeInputString: parseDateTimeToString } =
useParseJSDateToIMaskDateTimeInputString();
const { parseDateTimeInputStringToJSDate: parseStringToDateTime } =
useParseDateTimeInputStringToJSDate();
const [draftValue, setDraftValue] = useState<DraftValue>(
isStandaloneVariableString(defaultValue)
? {
@@ -127,7 +128,7 @@ export const FormDateTimeFieldInput = ({
const [inputDateTime, setInputDateTime] = useState(
isDefined(draftValueAsDate) && !isStandaloneVariableString(defaultValue)
? parseToString(draftValueAsDate)
? parseDateTimeToString(draftValueAsDate)
: '',
);
@@ -147,8 +148,7 @@ export const FormDateTimeFieldInput = ({
const displayDatePicker =
draftValue.type === 'static' && draftValue.mode === 'edit';
const placeholderToDisplay =
placeholder ?? (dateOnly ? 'mm/dd/yyyy' : 'mm/dd/yyyy hh:mm');
const placeholderToDisplay = placeholder ?? 'mm/dd/yyyy hh:mm';
useListenClickOutside({
refs: [datePickerWrapperRef],
@@ -174,7 +174,7 @@ export const FormDateTimeFieldInput = ({
value: newDate?.toDateString() ?? null,
});
setInputDateTime(isDefined(newDate) ? parseToString(newDate) : '');
setInputDateTime(isDefined(newDate) ? parseDateTimeToString(newDate) : '');
setPickerDate(newDate);
@@ -224,7 +224,7 @@ export const FormDateTimeFieldInput = ({
setPickerDate(newDate);
setInputDateTime(isDefined(newDate) ? parseToString(newDate) : '');
setInputDateTime(isDefined(newDate) ? parseDateTimeToString(newDate) : '');
persistDate(newDate);
};
@@ -253,7 +253,7 @@ export const FormDateTimeFieldInput = ({
return;
}
const parsedInputDateTime = parseToDate(inputDateTimeTrimmed);
const parsedInputDateTime = parseStringToDateTime(inputDateTimeTrimmed);
if (!isDefined(parsedInputDateTime)) {
return;
@@ -274,7 +274,7 @@ export const FormDateTimeFieldInput = ({
setPickerDate(validatedDate);
setInputDateTime(parseToString(validatedDate));
setInputDateTime(parseDateTimeToString(validatedDate));
persistDate(validatedDate);
};
@@ -337,7 +337,6 @@ export const FormDateTimeFieldInput = ({
<OverlayContainer>
<DateTimePicker
date={pickerDate ?? new Date()}
isDateTimeInput={false}
onChange={handlePickerChange}
onClose={handlePickerMouseSelect}
onEnter={handlePickerEnter}
@@ -1,11 +1,12 @@
import { RelativeDatePickerHeader } from '@/ui/input/components/internal/date/components/RelativeDatePickerHeader';
import { isNonEmptyString, isString } from '@sniptt/guards';
import { DEFAULT_RELATIVE_DATE_FILTER_VALUE } from 'twenty-shared/constants';
import {
DEFAULT_RELATIVE_DATE_VALUE,
type VariableDateViewFilterValue,
} from 'twenty-shared/types';
import { safeParseRelativeDateFilterValue } from 'twenty-shared/utils';
type RelativeDateFilter,
safeParseRelativeDateFilterJSONStringified,
} from 'twenty-shared/utils';
import { type JsonValue } from 'type-fest';
export type FormRelativeDatePickerProps = {
@@ -22,10 +23,10 @@ export const FormRelativeDatePicker = ({
}: FormRelativeDatePickerProps) => {
const value =
isString(defaultValue) && isNonEmptyString(defaultValue)
? safeParseRelativeDateFilterValue(defaultValue)
: DEFAULT_RELATIVE_DATE_VALUE;
? safeParseRelativeDateFilterJSONStringified(defaultValue)
: DEFAULT_RELATIVE_DATE_FILTER_VALUE;
const handleValueChange = (newValue: VariableDateViewFilterValue) => {
const handleValueChange = (newValue: RelativeDateFilter) => {
onChange(JSON.stringify(newValue));
};
@@ -34,7 +35,7 @@ export const FormRelativeDatePicker = ({
onChange={handleValueChange}
direction={value?.direction ?? 'THIS'}
unit={value?.unit ?? 'DAY'}
amount={value?.amount}
amount={value?.amount ?? undefined}
isFormField={true}
readonly={readonly}
unitDropdownWidth={150}
@@ -1,409 +0,0 @@
import { MAX_DATE } from '@/ui/input/components/internal/date/constants/MaxDate';
import { MIN_DATE } from '@/ui/input/components/internal/date/constants/MinDate';
import { parseDateToString } from '@/ui/input/components/internal/date/utils/parseDateToString';
import { type Meta, type StoryObj } from '@storybook/react';
import {
expect,
fn,
userEvent,
waitFor,
waitForElementToBeRemoved,
within,
} from '@storybook/test';
import { I18nFrontDecorator } from '~/testing/decorators/I18nFrontDecorator';
import { WorkflowStepDecorator } from '~/testing/decorators/WorkflowStepDecorator';
import { MOCKED_STEP_ID } from '~/testing/mock-data/workflow';
import { FormDateFieldInput } from '../FormDateFieldInput';
const meta: Meta<typeof FormDateFieldInput> = {
title: 'UI/Data/Field/Form/Input/FormDateFieldInput',
component: FormDateFieldInput,
args: {},
argTypes: {},
decorators: [I18nFrontDecorator, WorkflowStepDecorator],
};
export default meta;
type Story = StoryObj<typeof FormDateFieldInput>;
const currentYear = new Date().getFullYear();
export const Default: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await canvas.findByText('Created At');
await canvas.findByDisplayValue('12/09/' + currentYear);
},
};
export const WithDefaultEmptyValue: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await canvas.findByText('Created At');
await canvas.findByDisplayValue('');
await canvas.findByPlaceholderText('mm/dd/yyyy');
},
};
export const SetsDateWithInput: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy');
await userEvent.click(input);
const dialog = await canvas.findByRole('dialog');
expect(dialog).toBeVisible();
await userEvent.type(input, `12/08/${currentYear}{enter}`);
await waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(
`${currentYear}-12-08T00:00:00.000Z`,
);
});
expect(dialog).toBeVisible();
},
};
export const SetsDateWithDatePicker: Story = {
args: {
label: 'Created At',
defaultValue: `2024-12-09T13:20:19.631Z`,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy');
expect(input).toBeVisible();
await userEvent.click(input);
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
const dayToChoose = await within(datePicker).findByRole('option', {
name: `Choose Saturday, December 7th, 2024`,
});
await Promise.all([
userEvent.click(dayToChoose),
waitForElementToBeRemoved(datePicker),
waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(
expect.stringMatching(new RegExp(`^2024-12-07`)),
);
}),
waitFor(() => {
expect(canvas.getByDisplayValue(`12/07/2024`)).toBeVisible();
}),
]);
},
};
export const ResetsDateByClickingButton: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy');
expect(input).toBeVisible();
await userEvent.click(input);
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
const clearButton = await canvas.findByText('Clear');
await Promise.all([
userEvent.click(clearButton),
waitForElementToBeRemoved(datePicker),
waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(null);
}),
waitFor(() => {
expect(input).toHaveDisplayValue('');
}),
]);
},
};
export const ResetsDateByErasingInputContent: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy');
expect(input).toBeVisible();
expect(input).toHaveDisplayValue(`12/09/${currentYear}`);
await userEvent.clear(input);
await userEvent.type(input, '{Enter}');
expect(args.onChange).toHaveBeenCalledWith(null);
expect(input).toHaveDisplayValue('');
},
};
export const DefaultsToMinValueWhenTypingReallyOldDate: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy');
expect(input).toBeVisible();
await userEvent.click(input);
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
await userEvent.type(input, '02/02/1500{Enter}');
await waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(MIN_DATE.toISOString());
});
expect(input).toHaveDisplayValue(
parseDateToString({
date: MIN_DATE,
isDateTimeInput: false,
userTimezone: undefined,
}),
);
const expectedDate = new Date(
MIN_DATE.getUTCFullYear(),
MIN_DATE.getUTCMonth(),
MIN_DATE.getUTCDate(),
0,
0,
0,
0,
);
const selectedDay = within(datePicker).getByRole('option', {
selected: true,
name: (accessibleName) => {
// The name looks like "Choose Sunday, December 31st, 1899"
return accessibleName.includes(expectedDate.getFullYear().toString());
},
});
expect(selectedDay).toBeVisible();
},
};
export const DefaultsToMaxValueWhenTypingReallyFarDate: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy');
expect(input).toBeVisible();
await userEvent.click(input);
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
await Promise.all([
userEvent.type(input, '02/02/2500{Enter}'),
waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(MAX_DATE.toISOString());
}),
waitFor(() => {
expect(input).toHaveDisplayValue(
parseDateToString({
date: MAX_DATE,
isDateTimeInput: false,
userTimezone: undefined,
}),
);
}),
waitFor(() => {
const expectedDate = new Date(
MAX_DATE.getUTCFullYear(),
MAX_DATE.getUTCMonth(),
MAX_DATE.getUTCDate(),
0,
0,
0,
0,
);
const selectedDay = within(datePicker).getByRole('option', {
selected: true,
name: (accessibleName) => {
// The name looks like "Choose Thursday, December 30th, 2100"
return accessibleName.includes(
expectedDate.getFullYear().toString(),
);
},
});
expect(selectedDay).toBeVisible();
}),
]);
},
};
export const SwitchesToStandaloneVariable: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
onChange: fn(),
VariablePicker: ({ onVariableSelect }) => {
return (
<button
onClick={() => {
onVariableSelect(`{{${MOCKED_STEP_ID}.createdAt}}`);
}}
>
Add variable
</button>
);
},
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const addVariableButton = await canvas.findByText('Add variable');
await userEvent.click(addVariableButton);
const variableTag = await canvas.findByText('Creation date');
expect(variableTag).toBeVisible();
const removeVariableButton = canvas.getByLabelText('Remove variable');
await Promise.all([
userEvent.click(removeVariableButton),
waitForElementToBeRemoved(variableTag),
waitFor(() => {
const input = canvas.getByPlaceholderText('mm/dd/yyyy');
expect(input).toBeVisible();
}),
]);
},
};
export const ClickingOutsideDoesNotResetInputState: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
if (!args.defaultValue) {
throw new Error('This test requires a defaultValue');
}
const defaultValueAsDisplayString = parseDateToString({
date: new Date(args.defaultValue),
isDateTimeInput: false,
userTimezone: undefined,
});
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy');
expect(input).toBeVisible();
expect(input).toHaveDisplayValue(defaultValueAsDisplayString);
await userEvent.type(input, '{Backspace}{Backspace}');
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
await Promise.all([
userEvent.click(canvasElement),
waitForElementToBeRemoved(datePicker),
]);
expect(args.onChange).not.toHaveBeenCalled();
expect(input).toHaveDisplayValue(defaultValueAsDisplayString.slice(0, -2));
},
};
export const Disabled: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
onChange: fn(),
readonly: true,
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const input = await canvas.findByDisplayValue('12/09/' + currentYear);
expect(input).toBeDisabled();
},
};
export const DisabledWithVariable: Story = {
args: {
label: 'Created At',
defaultValue: `{{${MOCKED_STEP_ID}.createdAt}}`,
onChange: fn(),
readonly: true,
VariablePicker: ({ onVariableSelect }) => {
return (
<button
onClick={() => {
onVariableSelect(`{{${MOCKED_STEP_ID}.createdAt}}`);
}}
>
Add variable
</button>
);
},
},
decorators: [WorkflowStepDecorator],
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const variableChip = await canvas.findByText('Creation date');
expect(variableChip).toBeVisible();
},
};
@@ -1,463 +0,0 @@
import { FormDateTimeFieldInput } from '@/object-record/record-field/ui/form-types/components/FormDateTimeFieldInput';
import { MAX_DATE } from '@/ui/input/components/internal/date/constants/MaxDate';
import { MIN_DATE } from '@/ui/input/components/internal/date/constants/MinDate';
import { parseDateToString } from '@/ui/input/components/internal/date/utils/parseDateToString';
import { type Meta, type StoryObj } from '@storybook/react';
import {
expect,
fn,
userEvent,
waitFor,
waitForElementToBeRemoved,
within,
} from '@storybook/test';
import { I18nFrontDecorator } from '~/testing/decorators/I18nFrontDecorator';
import { WorkflowStepDecorator } from '~/testing/decorators/WorkflowStepDecorator';
import { MOCKED_STEP_ID } from '~/testing/mock-data/workflow';
const meta: Meta<typeof FormDateTimeFieldInput> = {
title: 'UI/Data/Field/Form/Input/FormDateTimeFieldInput',
component: FormDateTimeFieldInput,
args: {},
argTypes: {},
decorators: [I18nFrontDecorator, WorkflowStepDecorator],
};
export default meta;
type Story = StoryObj<typeof FormDateTimeFieldInput>;
const currentYear = new Date().getFullYear();
export const Default: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await canvas.findByText('Created At');
await canvas.findByDisplayValue(
new RegExp(`12/09/${currentYear} \\d{2}:20`),
);
},
};
export const WithDefaultEmptyValue: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await canvas.findByText('Created At');
await canvas.findByDisplayValue('');
await canvas.findByPlaceholderText('mm/dd/yyyy hh:mm');
},
};
export const SetsDateTimeWithInput: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy hh:mm');
await userEvent.click(input);
const dialog = await canvas.findByRole('dialog');
expect(dialog).toBeVisible();
await userEvent.type(input, `12/08/${currentYear} 12:10{enter}`);
await waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(
expect.stringMatching(new RegExp(`^${currentYear}-12-08`)),
);
});
expect(dialog).toBeVisible();
},
};
export const DoesNotSetDateWithoutTime: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy hh:mm');
await userEvent.click(input);
const dialog = await canvas.findByRole('dialog');
expect(dialog).toBeVisible();
await userEvent.type(input, `12/08/${currentYear}{enter}`);
expect(args.onChange).not.toHaveBeenCalled();
expect(dialog).toBeVisible();
},
};
export const SetsDateTimeWithDatePicker: Story = {
args: {
label: 'Created At',
defaultValue: `2024-12-09T13:20:19.631Z`,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy hh:mm');
expect(input).toBeVisible();
await userEvent.click(input);
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
const dayToChoose = await within(datePicker).findByRole('option', {
name: 'Choose Saturday, December 7th, 2024',
});
await Promise.all([
userEvent.click(dayToChoose),
waitForElementToBeRemoved(datePicker),
waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(
expect.stringMatching(/^2024-12-07/),
);
}),
waitFor(() => {
expect(
canvas.getByDisplayValue(new RegExp(`12/07/2024 \\d{2}:\\d{2}`)),
).toBeVisible();
}),
]);
},
};
export const ResetsDateByClickingButton: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy hh:mm');
expect(input).toBeVisible();
await userEvent.click(input);
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
const clearButton = await canvas.findByText('Clear');
await Promise.all([
userEvent.click(clearButton),
waitForElementToBeRemoved(datePicker),
waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(null);
}),
waitFor(() => {
expect(input).toHaveDisplayValue('');
}),
]);
},
};
export const ResetsDateByErasingInputContent: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy hh:mm');
expect(input).toBeVisible();
expect(input).toHaveDisplayValue(
new RegExp(`12/09/${currentYear} \\d{2}:\\d{2}`),
);
await userEvent.click(input);
await waitFor(() => {
expect(canvas.getByRole('dialog')).toBeVisible();
});
await userEvent.clear(input);
const waitForDialogToBeRemoved = waitForElementToBeRemoved(() =>
canvas.queryByRole('dialog'),
);
await Promise.all([
userEvent.type(input, '{Enter}'),
waitForDialogToBeRemoved,
waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(null);
}),
waitFor(() => {
expect(input).toHaveDisplayValue('');
}),
]);
},
};
export const DefaultsToMinValueWhenTypingReallyOldDate: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy hh:mm');
expect(input).toBeVisible();
await userEvent.click(input);
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
await Promise.all([
userEvent.type(input, '02/02/1500 10:10{Enter}'),
waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(MIN_DATE.toISOString());
}),
waitFor(() => {
expect(input).toHaveDisplayValue(
parseDateToString({
date: MIN_DATE,
isDateTimeInput: true,
userTimezone: undefined,
}),
);
}),
waitFor(() => {
const expectedDate = new Date(
MIN_DATE.getUTCFullYear(),
MIN_DATE.getUTCMonth(),
MIN_DATE.getUTCDate(),
0,
0,
0,
0,
);
const selectedDay = within(datePicker).getByRole('option', {
selected: true,
name: (accessibleName) => {
// The name looks like "Choose Sunday, December 31st, 1899"
return accessibleName.includes(
expectedDate.getFullYear().toString(),
);
},
});
expect(selectedDay).toBeVisible();
}),
]);
},
};
export const DefaultsToMaxValueWhenTypingReallyFarDate: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy hh:mm');
expect(input).toBeVisible();
await userEvent.click(input);
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
await Promise.all([
userEvent.type(input, '02/02/2500 10:10{Enter}'),
waitFor(() => {
expect(args.onChange).toHaveBeenCalledWith(MAX_DATE.toISOString());
}),
waitFor(() => {
expect(input).toHaveDisplayValue(
parseDateToString({
date: MAX_DATE,
isDateTimeInput: true,
userTimezone: undefined,
}),
);
}),
waitFor(() => {
const expectedDate = new Date(
MAX_DATE.getUTCFullYear(),
MAX_DATE.getUTCMonth(),
MAX_DATE.getUTCDate(),
0,
0,
0,
0,
);
const selectedDay = within(datePicker).getByRole('option', {
selected: true,
name: (accessibleName) => {
// The name looks like "Choose Thursday, December 30th, 2100"
return accessibleName.includes(
expectedDate.getFullYear().toString(),
);
},
});
expect(selectedDay).toBeVisible();
}),
]);
},
};
export const SwitchesToStandaloneVariable: Story = {
args: {
label: 'Created At',
defaultValue: undefined,
onChange: fn(),
VariablePicker: ({ onVariableSelect }) => {
return (
<button
onClick={() => {
onVariableSelect(`{{${MOCKED_STEP_ID}.createdAt}}`);
}}
>
Add variable
</button>
);
},
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const addVariableButton = await canvas.findByText('Add variable');
await userEvent.click(addVariableButton);
const variableTag = await canvas.findByText('Creation date');
expect(variableTag).toBeVisible();
const removeVariableButton = canvas.getByLabelText('Remove variable');
await Promise.all([
userEvent.click(removeVariableButton),
waitForElementToBeRemoved(variableTag),
waitFor(() => {
const input = canvas.getByPlaceholderText('mm/dd/yyyy hh:mm');
expect(input).toBeVisible();
}),
]);
},
};
export const ClickingOutsideDoesNotResetInputState: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
onChange: fn(),
},
play: async ({ canvasElement, args }) => {
if (!args.defaultValue) {
throw new Error('This test requires a defaultValue');
}
const defaultValueAsDisplayString = parseDateToString({
date: new Date(args.defaultValue),
isDateTimeInput: true,
userTimezone: undefined,
});
const canvas = within(canvasElement);
const input = await canvas.findByPlaceholderText('mm/dd/yyyy hh:mm');
expect(input).toBeVisible();
expect(input).toHaveDisplayValue(defaultValueAsDisplayString);
await userEvent.type(input, '{Backspace}{Backspace}');
const datePicker = await canvas.findByRole('dialog');
expect(datePicker).toBeVisible();
await Promise.all([
userEvent.click(canvasElement),
waitForElementToBeRemoved(datePicker),
]);
expect(args.onChange).not.toHaveBeenCalled();
expect(input).toHaveDisplayValue(defaultValueAsDisplayString.slice(0, -2));
},
};
export const Disabled: Story = {
args: {
label: 'Created At',
defaultValue: `${currentYear}-12-09T13:20:19.631Z`,
onChange: fn(),
readonly: true,
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const input = await canvas.findByDisplayValue(
new RegExp(`12/09/${currentYear} \\d{2}:20`),
);
expect(input).toBeDisabled();
},
};
export const DisabledWithVariable: Story = {
args: {
label: 'Created At',
defaultValue: `{{${MOCKED_STEP_ID}.createdAt}}`,
onChange: fn(),
readonly: true,
VariablePicker: ({ onVariableSelect }) => {
return (
<button
onClick={() => {
onVariableSelect(`{{${MOCKED_STEP_ID}.createdAt}}`);
}}
>
Add variable
</button>
);
},
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const variableChip = await canvas.findByText('Creation date');
expect(variableChip).toBeVisible();
},
};
@@ -50,7 +50,7 @@ export const Elipsis: Story = {
export const Performance = getProfilingStory({
componentName: 'DateTimeFieldDisplay',
averageThresholdInMs: 0.1,
averageThresholdInMs: 0.15,
numberOfRuns: 30,
numberOfTestsPerRun: 30,
});
@@ -5,7 +5,6 @@ import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts
import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';
import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
import { useContext } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { type Nullable } from 'twenty-ui/utilities';
export const DateFieldInput = () => {
@@ -19,48 +18,34 @@ export const DateFieldInput = () => {
RecordFieldComponentInstanceContext,
);
const getDateToPersist = (newDate: Nullable<Date>) => {
if (!isDefined(newDate)) {
return null;
} else {
const newDateWithoutTime = `${newDate?.getFullYear()}-${(
newDate?.getMonth() + 1
)
.toString()
.padStart(2, '0')}-${newDate?.getDate().toString().padStart(2, '0')}`;
return newDateWithoutTime;
}
const handleEnter = (newDate: Nullable<string>) => {
onEnter?.({ newValue: newDate });
};
const handleEnter = (newDate: Nullable<Date>) => {
onEnter?.({ newValue: getDateToPersist(newDate) });
const handleSubmit = (newDate: Nullable<string>) => {
onSubmit?.({ newValue: newDate });
};
const handleSubmit = (newDate: Nullable<Date>) => {
onSubmit?.({ newValue: getDateToPersist(newDate) });
};
const handleEscape = (newDate: Nullable<Date>) => {
onEscape?.({ newValue: getDateToPersist(newDate) });
const handleEscape = (newDate: Nullable<string>) => {
onEscape?.({ newValue: newDate });
};
const handleClickOutside = (
event: MouseEvent | TouchEvent,
newDate: Nullable<Date>,
newDate: Nullable<string>,
) => {
onClickOutside?.({ newValue: getDateToPersist(newDate), event });
onClickOutside?.({ newValue: newDate, event });
};
const handleChange = (newDate: Nullable<Date>) => {
setDraftValue(newDate?.toDateString() ?? '');
const handleChange = (newDate: Nullable<string>) => {
setDraftValue(newDate ?? '');
};
const handleClear = () => {
onSubmit?.({ newValue: null });
};
const dateValue = fieldValue ? new Date(fieldValue) : null;
const dateValue = fieldValue ?? null;
return (
<DateInput
@@ -1,7 +1,6 @@
import { DateInput } from '@/ui/field/input/components/DateInput';
import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';
import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';
import { DateTimeInput } from '@/ui/field/input/components/DateTimeInput';
import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
import { useContext } from 'react';
import { type Nullable } from 'twenty-ui/utilities';
@@ -58,7 +57,7 @@ export const DateTimeFieldInput = () => {
const dateValue = fieldValue ? new Date(fieldValue) : null;
return (
<DateInput
<DateTimeInput
instanceId={instanceId}
onClickOutside={handleClickOutside}
onEnter={handleEnter}
@@ -66,7 +65,6 @@ export const DateTimeFieldInput = () => {
value={dateValue}
clearable
onChange={handleChange}
isDateTimeInput
onClear={handleClear}
onSubmit={handleSubmit}
/>
@@ -1,5 +1,5 @@
import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';
import { getInitialFilterValue } from '@/object-record/object-filter-dropdown/utils/getInitialFilterValue';
import { useGetInitialFilterValue } from '@/object-record/object-filter-dropdown/hooks/useGetInitialFilterValue';
import { type RecordFilter } from '@/object-record/record-filter/types/RecordFilter';
import { getDefaultSubFieldNameForCompositeFilterableFieldType } from '@/object-record/record-filter/utils/getDefaultSubFieldNameForCompositeFilterableFieldType';
import { getRecordFilterOperands } from '@/object-record/record-filter/utils/getRecordFilterOperands';
@@ -7,6 +7,8 @@ import { getFilterTypeFromFieldType } from 'twenty-shared/utils';
import { v4 } from 'uuid';
export const useCreateEmptyRecordFilterFromFieldMetadataItem = () => {
const { getInitialFilterValue } = useGetInitialFilterValue();
const createEmptyRecordFilterFromFieldMetadataItem = (
fieldMetadataItem: FieldMetadataItem,
) => {
@@ -1108,12 +1108,12 @@ describe('should work as expected for the different field types', () => {
and: [
{
createdAt: {
lte: '2024-09-17T23:59:59.999Z',
lte: '2024-09-17T20:46:59.999Z',
},
},
{
createdAt: {
gte: '2024-09-17T00:00:00.000Z',
gte: '2024-09-17T20:46:00.000Z',
},
},
],
@@ -1,31 +0,0 @@
import { getDateFilterDisplayValue } from '../getDateFilterDisplayValue';
describe('getDateFilterDisplayValue', () => {
beforeAll(() => {
const mockDate = new Date('2025-06-13T14:30:00Z');
// Mocking responses for date methods to avoid timezone issues
jest
.spyOn(mockDate, 'toLocaleString')
.mockReturnValue('6/13/2025, 2:30:00 PM');
jest.spyOn(mockDate, 'toLocaleDateString').mockReturnValue('6/13/2025');
global.Date = jest.fn(() => mockDate) as any;
});
afterAll(() => {
jest.restoreAllMocks();
});
it('should return date and time for DATE_TIME field type', () => {
const date = new Date('2025-06-13T14:30:00Z');
const result = getDateFilterDisplayValue(date, 'DATE_TIME');
expect(result).toEqual({ displayValue: '6/13/2025, 2:30:00 PM' });
});
it('should return only date for DATE field type', () => {
const date = new Date('2025-06-13T14:30:00Z');
const result = getDateFilterDisplayValue(date, 'DATE');
expect(result).toEqual({ displayValue: '6/13/2025' });
});
});
@@ -1,13 +0,0 @@
import { type FilterableAndTSVectorFieldType } from 'twenty-shared/types';
export const getDateFilterDisplayValue = (
value: Date,
fieldType: FilterableAndTSVectorFieldType,
) => {
const displayValue =
fieldType === 'DATE_TIME'
? value.toLocaleString()
: value.toLocaleDateString();
return { displayValue };
};
@@ -17,7 +17,6 @@ import { createPortal } from 'react-dom';
import { isDefined } from 'twenty-shared/utils';
type RecordInlineCellAnchoredPortalProps = {
position: number;
fieldMetadataItem: Pick<
FieldMetadataItem,
'id' | 'name' | 'type' | 'createdAt' | 'updatedAt' | 'label'