Skip to content

The open alternative to Salesforce, designed for AI.

Use fastDeepEqual when loading records and speed up link detection, formatting and overflowing lists (#27967)

Charles Bochetacb5fcb2c835
diff --git a/packages/twenty-front/src/modules/localization/utils/formatNumber.ts b/packages/twenty-front/src/modules/localization/utils/formatNumber.ts
index 617152f210f..d160ea7f6fe 100644
--- a/packages/twenty-front/src/modules/localization/utils/formatNumber.ts
+++ b/packages/twenty-front/src/modules/localization/utils/formatNumber.ts
@@ -68,6 +68,32 @@ const getLocaleForFormat = (format?: NumberFormat): string => {
);
};
+const numberFormatterByKey = new Map<string, Intl.NumberFormat>();
+
+const getNumberFormatter = ({
+ locale,
+ maximumFractionDigits,
+}: {
+ locale: string;
+ maximumFractionDigits: number;
+}) => {
+ const key = `${locale}-${maximumFractionDigits}`;
+ const cachedFormatter = numberFormatterByKey.get(key);
+
+ if (isDefined(cachedFormatter)) {
+ return cachedFormatter;
+ }
+
+ const formatter = new Intl.NumberFormat(locale, {
+ minimumFractionDigits: 0,
+ maximumFractionDigits,
+ });
+
+ numberFormatterByKey.set(key, formatter);
+
+ return formatter;
+};
+
export const formatNumber = (
value: number,
opts?: FormatNumberOptions,
@@ -89,15 +115,15 @@ export const formatNumber = (
const divisor = getAbbreviationDivisor(roundedAbsoluteValue);
return (
- (value / divisor).toLocaleString(locale, {
- minimumFractionDigits: 0,
+ getNumberFormatter({
+ locale,
maximumFractionDigits: options.decimals,
- }) + ABBREVIATION_SUFFIX_BY_THRESHOLD[divisor]
+ }).format(value / divisor) + ABBREVIATION_SUFFIX_BY_THRESHOLD[divisor]
);
}
- return value.toLocaleString(locale, {
- minimumFractionDigits: 0,
+ return getNumberFormatter({
+ locale,
maximumFractionDigits: options.decimals,
- });
+ }).format(value);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-board/hooks/useSetRecordIdsForColumn.ts b/packages/twenty-front/src/modules/object-record/record-board/hooks/useSetRecordIdsForColumn.ts
index 98260238360..d59856d54ff 100644
--- a/packages/twenty-front/src/modules/object-record/record-board/hooks/useSetRecordIdsForColumn.ts
+++ b/packages/twenty-front/src/modules/object-record/record-board/hooks/useSetRecordIdsForColumn.ts
@@ -9,8 +9,7 @@ import { recordIndexRecordIdsByGroupComponentFamilyState } from '@/object-record
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';
import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';
-import { isDefined } from 'twenty-shared/utils';
-import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
+import { fastDeepEqual, isDefined } from 'twenty-shared/utils';
export const useSetRecordIdsForColumn = (recordBoardId?: string) => {
const store = useStore();
@@ -59,7 +58,7 @@ export const useSetRecordIdsForColumn = (recordBoardId?: string) => {
)
.map((record) => record.id);
- if (!isDeeplyEqual(existingRecordGroupRowIds, recordGroupRowIds)) {
+ if (!fastDeepEqual(existingRecordGroupRowIds, recordGroupRowIds)) {
store.set(
recordIndexRecordIdsByGroupFamilyState(currentRecordGroupId),
recordGroupRowIds,
diff --git a/packages/twenty-front/src/modules/object-record/record-index/hooks/useLoadRecordIndexStates.ts b/packages/twenty-front/src/modules/object-record/record-index/hooks/useLoadRecordIndexStates.ts
index 80d8f5a6e4f..75ce411e02a 100644
--- a/packages/twenty-front/src/modules/object-record/record-index/hooks/useLoadRecordIndexStates.ts
+++ b/packages/twenty-front/src/modules/object-record/record-index/hooks/useLoadRecordIndexStates.ts
@@ -45,9 +45,8 @@ import { mapViewFiltersToFilters } from '@/views/utils/mapViewFiltersToFilters';
import { atom, useStore } from 'jotai';
import { useCallback } from 'react';
import { DEFAULT_VIEW_GROUP_LOAD_LIMIT } from 'twenty-shared/constants';
-import { isDefined } from 'twenty-shared/utils';
+import { fastDeepEqual, isDefined } from 'twenty-shared/utils';
import { ViewCalendarLayout } from '~/generated-metadata/graphql';
-import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
export const useLoadRecordIndexStates = () => {
const store = useStore();
@@ -181,7 +180,7 @@ export const useLoadRecordIndexStates = () => {
atom(null, (get, batchSet) => {
const existingFieldDefs = get(recordIndexFieldDefinitionsAtom);
- if (!isDeeplyEqual(existingFieldDefs, newFieldDefinitions)) {
+ if (!fastDeepEqual(existingFieldDefs, newFieldDefinitions)) {
batchSet(recordIndexFieldDefinitionsAtom, newFieldDefinitions);
}
@@ -217,7 +216,7 @@ export const useLoadRecordIndexStates = () => {
const existingRecordFields = get(currentRecordFieldsAtom);
- if (!isDeeplyEqual(existingRecordFields, recordFields)) {
+ if (!fastDeepEqual(existingRecordFields, recordFields)) {
batchSet(currentRecordFieldsAtom, recordFields);
}
diff --git a/packages/twenty-front/src/modules/object-record/record-store/hooks/useUpsertRecordsInStore.ts b/packages/twenty-front/src/modules/object-record/record-store/hooks/useUpsertRecordsInStore.ts
index bae9906680f..0ceae17b12d 100644
--- a/packages/twenty-front/src/modules/object-record/record-store/hooks/useUpsertRecordsInStore.ts
+++ b/packages/twenty-front/src/modules/object-record/record-store/hooks/useUpsertRecordsInStore.ts
@@ -4,8 +4,7 @@ import { recordStoreFamilyState } from '@/object-record/record-store/states/reco
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
import { useCallback } from 'react';
import { useStore } from 'jotai';
-import { isDefined } from 'twenty-shared/utils';
-import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
+import { fastDeepEqual, isDefined } from 'twenty-shared/utils';
type UpsertRecordsInStoreProps = {
partialRecords: ObjectRecord[];
@@ -49,7 +48,7 @@ export const useUpsertRecordsInStore = () => {
})
: currentRecord;
- if (!isDeeplyEqual(filteredCurrentRecord, filteredPartialRecord)) {
+ if (!fastDeepEqual(filteredCurrentRecord, filteredPartialRecord)) {
const updatedRecord = {
...currentRecord,
...filteredPartialRecord,
diff --git a/packages/twenty-front/src/modules/object-record/record-table/hooks/internal/useSetRecordTableData.ts b/packages/twenty-front/src/modules/object-record/record-table/hooks/internal/useSetRecordTableData.ts
index c4b046e3af6..d3f269c46d6 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/hooks/internal/useSetRecordTableData.ts
+++ b/packages/twenty-front/src/modules/object-record/record-table/hooks/internal/useSetRecordTableData.ts
@@ -21,8 +21,7 @@ import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/h
import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';
import { useAtomComponentSelectorCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorCallbackState';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
-import { isDefined } from 'twenty-shared/utils';
-import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
+import { fastDeepEqual, isDefined } from 'twenty-shared/utils';
type useSetRecordTableDataProps = {
recordTableId?: string;
@@ -103,7 +102,7 @@ export const useSetRecordTableData = ({
const recordIds = records.map((record) => record.id);
- if (!isDeeplyEqual(currentRowIds, recordIds)) {
+ if (!fastDeepEqual(currentRowIds, recordIds)) {
unfocusRecordTableCell();
unfocusRecordTableRow();
setRecordTableHoverPosition(null);
diff --git a/packages/twenty-front/src/modules/ui/field/display/components/DateTimeDisplay.tsx b/packages/twenty-front/src/modules/ui/field/display/components/DateTimeDisplay.tsx
index afa2c0b9716..d18320531f1 100644
--- a/packages/twenty-front/src/modules/ui/field/display/components/DateTimeDisplay.tsx
+++ b/packages/twenty-front/src/modules/ui/field/display/components/DateTimeDisplay.tsx
@@ -6,7 +6,6 @@ import { UserContext } from '@/users/contexts/UserContext';
import { styled } from '@linaria/react';
import { isNonEmptyString } from '@sniptt/guards';
import { useContext } from 'react';
-import { Temporal } from 'temporal-polyfill';
import { themeCssVariables } from 'twenty-ui/theme';
import { dateLocaleState } from '@/localization/states/dateLocaleState';
import { formatDateTimeString } from '@/object-record/record-field/ui/utils/formatDateTimeString';
@@ -43,7 +42,7 @@ export const DateTimeDisplay = ({
{isNonEmptyString(value) && (
<>
<StyledTimeZoneSpacer />
- <TimeZoneAbbreviation instant={Temporal.Instant.from(value)} />
+ <TimeZoneAbbreviation instant={value} />
</>
)}
</EllipsisDisplay>
diff --git a/packages/twenty-front/src/modules/ui/field/display/components/LinkifiedText/linkifyText.ts b/packages/twenty-front/src/modules/ui/field/display/components/LinkifiedText/linkifyText.ts
index ed4041d2d4f..0dfabac739d 100644
--- a/packages/twenty-front/src/modules/ui/field/display/components/LinkifiedText/linkifyText.ts
+++ b/packages/twenty-front/src/modules/ui/field/display/components/LinkifiedText/linkifyText.ts
@@ -1,3 +1,5 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
const URL_REGEX = /https?:\/\/[^\s<>[\]]+[^\s<>[\].,;:!?)]/g;
type LinkifyMatch = {
@@ -6,6 +8,10 @@ type LinkifyMatch = {
};
export const linkifyText = (text: string): LinkifyMatch[] => {
+ if (!text.includes('http')) {
+ return isNonEmptyString(text) ? [{ type: 'text', content: text }] : [];
+ }
+
const parts: LinkifyMatch[] = [];
let lastIndex = 0;
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/date/components/TimeZoneAbbreviation.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/date/components/TimeZoneAbbreviation.tsx
index 338cdfb4a32..3e300b6146b 100644
--- a/packages/twenty-front/src/modules/ui/input/components/internal/date/components/TimeZoneAbbreviation.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/date/components/TimeZoneAbbreviation.tsx
@@ -1,8 +1,8 @@
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
import { getTimezoneAbbreviationForZonedDateTime } from '@/ui/input/components/internal/date/utils/getTimeZoneAbbreviationForZonedDateTime';
import { styled } from '@linaria/react';
-import { isNonEmptyString } from '@sniptt/guards';
-import { type Temporal } from 'temporal-polyfill';
+import { isNonEmptyString, isString } from '@sniptt/guards';
+import { Temporal } from 'temporal-polyfill';
import { themeCssVariables } from 'twenty-ui/theme';
const StyledTimezoneAbbreviation = styled.span<{ hasError?: boolean }>`
@@ -19,28 +19,28 @@ export const TimeZoneAbbreviation = ({
instant,
timeZone,
}: {
- instant: Temporal.Instant;
+ instant: Temporal.Instant | string;
timeZone?: string;
}) => {
const { isSystemTimezone, userTimezone, systemTimeZone } = useUserTimezone();
- const zonedDate = instant.toZonedDateTimeISO(timeZone ?? userTimezone);
-
const shouldUseParamsTimeZone =
isNonEmptyString(timeZone) && systemTimeZone !== timeZone;
const shouldShowTimezoneAbbreviation =
!isSystemTimezone || shouldUseParamsTimeZone;
- const timezoneSuffix = shouldShowTimezoneAbbreviation
- ? ` ${getTimezoneAbbreviationForZonedDateTime(zonedDate)}`
- : '';
-
if (!shouldShowTimezoneAbbreviation) {
return <></>;
}
+ const zonedDate = (
+ isString(instant) ? Temporal.Instant.from(instant) : instant
+ ).toZonedDateTimeISO(timeZone ?? userTimezone);
+
return (
- <StyledTimezoneAbbreviation>{timezoneSuffix}</StyledTimezoneAbbreviation>
+ <StyledTimezoneAbbreviation>
+ {` ${getTimezoneAbbreviationForZonedDateTime(zonedDate)}`}
+ </StyledTimezoneAbbreviation>
);
};
diff --git a/packages/twenty-shared/src/utils/json/__tests__/fast-deep-equal.spec.ts b/packages/twenty-shared/src/utils/json/__tests__/fast-deep-equal.spec.ts
index 54553165feb..f595fb6082d 100644
--- a/packages/twenty-shared/src/utils/json/__tests__/fast-deep-equal.spec.ts
+++ b/packages/twenty-shared/src/utils/json/__tests__/fast-deep-equal.spec.ts
@@ -294,4 +294,24 @@ describe('fastDeepEqual', () => {
expect(fastDeepEqual(workflowState1, workflowState2)).toBe(false);
});
});
+
+ describe('objects with method names as keys', () => {
+ it('compares JSON values with toString and valueOf keys without calling them', () => {
+ expect(
+ fastDeepEqual(
+ { toString: 'foo', valueOf: 'bar' },
+ { toString: 'foo', valueOf: 'bar' },
+ ),
+ ).toBe(true);
+ expect(fastDeepEqual({ toString: 'foo' }, { toString: 'baz' })).toBe(
+ false,
+ );
+ expect(fastDeepEqual({ valueOf: 1 }, { valueOf: 2 })).toBe(false);
+ });
+
+ it('still compares dates by value', () => {
+ expect(fastDeepEqual(new Date(1), new Date(1))).toBe(true);
+ expect(fastDeepEqual(new Date(1), new Date(2))).toBe(false);
+ });
+ });
});
diff --git a/packages/twenty-shared/src/utils/json/fast-deep-equal.ts b/packages/twenty-shared/src/utils/json/fast-deep-equal.ts
index 58d14630f59..ea8c8cc51c9 100644
--- a/packages/twenty-shared/src/utils/json/fast-deep-equal.ts
+++ b/packages/twenty-shared/src/utils/json/fast-deep-equal.ts
@@ -1,5 +1,12 @@
// Source: https://github.com/epoberezkin/fast-deep-equal/blob/master/src/index.jst
+const hasCustomMethod = (
+ value: object,
+ methodName: 'valueOf' | 'toString',
+): boolean =>
+ typeof value[methodName] === 'function' &&
+ value[methodName] !== Object.prototype[methodName];
+
export const fastDeepEqual = (
firstValue: unknown,
secondValue: unknown,
@@ -74,11 +81,17 @@ export const fastDeepEqual = (
);
}
- if (firstValue.valueOf !== Object.prototype.valueOf) {
+ if (
+ hasCustomMethod(firstValue, 'valueOf') &&
+ hasCustomMethod(secondValue, 'valueOf')
+ ) {
return firstValue.valueOf() === secondValue.valueOf();
}
- if (firstValue.toString !== Object.prototype.toString) {
+ if (
+ hasCustomMethod(firstValue, 'toString') &&
+ hasCustomMethod(secondValue, 'toString')
+ ) {
return firstValue.toString() === secondValue.toString();
}
diff --git a/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.tsx b/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.tsx
index 7178bf86713..22dd6a35f3a 100644
--- a/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.tsx
+++ b/packages/twenty-ui/src/components/layout/OverflowingList/OverflowingList.tsx
@@ -78,55 +78,55 @@ export const OverflowingList = ({
}
return (
- <Popover.Root open={isOpen && canExpand} onOpenChange={setIsOpen}>
- <div
- {...props}
- ref={mergedRef}
- className={clsx(styles.root, className)}
- onMouseEnter={(event) => {
- setIsHovered(true);
- onMouseEnter?.(event);
- }}
- onMouseLeave={(event) => {
- setIsHovered(false);
- onMouseLeave?.(event);
- }}
- onFocusCapture={(event) => {
- setHasFocus(true);
+ <div
+ {...props}
+ ref={mergedRef}
+ className={clsx(styles.root, className)}
+ onMouseEnter={(event) => {
+ setIsHovered(true);
+ onMouseEnter?.(event);
+ }}
+ onMouseLeave={(event) => {
+ setIsHovered(false);
+ onMouseLeave?.(event);
+ }}
+ onFocusCapture={(event) => {
+ setHasFocus(true);
- if (itemsRef.current?.contains(event.target)) {
- setFocusedItemCountVisibility(
- (currentVisibility) => currentVisibility ?? isCountVisible,
- );
- }
+ if (itemsRef.current?.contains(event.target)) {
+ setFocusedItemCountVisibility(
+ (currentVisibility) => currentVisibility ?? isCountVisible,
+ );
+ }
- onFocusCapture?.(event);
- }}
- onBlurCapture={(event) => {
- setHasFocus(event.currentTarget.contains(event.relatedTarget));
+ onFocusCapture?.(event);
+ }}
+ onBlurCapture={(event) => {
+ setHasFocus(event.currentTarget.contains(event.relatedTarget));
- if (!itemsRef.current?.contains(event.relatedTarget)) {
- setFocusedItemCountVisibility(undefined);
- }
+ if (!itemsRef.current?.contains(event.relatedTarget)) {
+ setFocusedItemCountVisibility(undefined);
+ }
- onBlurCapture?.(event);
- }}
- >
- <div ref={itemsRef} className={styles.items}>
- {children.slice(0, inlineItemCount).map((child, index) => (
- <OverflowingListItem
- key={child.key ?? index}
- isHidden={index >= displayedItemCount}
- isLastVisible={
- showOverflowCount !== false && index === displayedItemCount - 1
- }
- onFocusedItemUnmount={resetFocusState}
- >
- {child}
- </OverflowingListItem>
- ))}
- </div>
- {canExpand && (
+ onBlurCapture?.(event);
+ }}
+ >
+ <div ref={itemsRef} className={styles.items}>
+ {children.slice(0, inlineItemCount).map((child, index) => (
+ <OverflowingListItem
+ key={child.key ?? index}
+ isHidden={index >= displayedItemCount}
+ isLastVisible={
+ showOverflowCount !== false && index === displayedItemCount - 1
+ }
+ onFocusedItemUnmount={resetFocusState}
+ >
+ {child}
+ </OverflowingListItem>
+ ))}
+ </div>
+ {canExpand && (
+ <Popover.Root open={isOpen} onOpenChange={setIsOpen}>
<Popover.Trigger
ref={mergedTriggerRef}
type="button"
@@ -137,25 +137,25 @@ export const OverflowingList = ({
>
+{hiddenItemCount}
</Popover.Trigger>
- )}
- <Popover.Portal>
- <Popover.Positioner
- anchor={containerRef}
- align="start"
- sideOffset={-9}
- alignOffset={-7}
- >
- <Popover.Popup
- aria-label={overflowLabel}
- className={styles.popup}
- data-overflowing-list-popup=""
- {...STOP_PROPAGATION_PROPS}
+ <Popover.Portal>
+ <Popover.Positioner
+ anchor={containerRef}
+ align="start"
+ sideOffset={-9}
+ alignOffset={-7}
>
- {children}
- </Popover.Popup>
- </Popover.Positioner>
- </Popover.Portal>
- </div>
- </Popover.Root>
+ <Popover.Popup
+ aria-label={overflowLabel}
+ className={styles.popup}
+ data-overflowing-list-popup=""
+ {...STOP_PROPAGATION_PROPS}
+ >
+ {children}
+ </Popover.Popup>
+ </Popover.Positioner>
+ </Popover.Portal>
+ </Popover.Root>
+ )}
+ </div>
);
};