Skip to content

The open alternative to Salesforce, designed for AI.

Preserve native edits across renderer updates (#27726)

Raphaël Bosibc506d48114a
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipEscapeDismissalTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipEscapeDismissalTest.ts
index 344e32d0ccc..788849bd366 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipEscapeDismissalTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipEscapeDismissalTest.ts
@@ -2,6 +2,7 @@ import { expect, userEvent, waitFor, within } from 'storybook/test';
import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
+import { INTERACTION_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';
import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
const TOOLTIP_CONTENT = 'Download visible records as a CSV file';
@@ -13,50 +14,70 @@ export const tooltipEscapeDismissalTest: TwentyUiGalleryPlayFunction = async ({
const canvas = within(canvasElement);
const page = within(canvasElement.ownerDocument.body);
await expectFrontComponentMounted(canvas);
- await waitFor(() => {
- expect(canvas.getByRole('status')).toHaveAttribute('aria-busy', 'false');
- });
+ await waitFor(
+ () => {
+ expect(canvas.getByRole('status')).toHaveAttribute('aria-busy', 'false');
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
const exportButton = canvas.getByRole('button', { name: 'Export records' });
await user.hover(exportButton);
- await waitFor(() => {
- expect(errorHandler).not.toHaveBeenCalled();
- expect(canvas.getByRole('status')).toHaveTextContent('Export help: open');
- expect(page.getByText(TOOLTIP_CONTENT)).toBeVisible();
- });
+ await waitFor(
+ () => {
+ expect(errorHandler).not.toHaveBeenCalled();
+ expect(canvas.getByRole('status')).toHaveTextContent('Export help: open');
+ expect(page.getByText(TOOLTIP_CONTENT)).toBeVisible();
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
await user.tab();
expect(exportButton).toHaveFocus();
await user.keyboard('{Escape}');
- await waitFor(() =>
- expect(canvas.getByRole('status')).toHaveTextContent('Export help: closed'),
+ await waitFor(
+ () =>
+ expect(canvas.getByRole('status')).toHaveTextContent(
+ 'Export help: closed',
+ ),
+ { timeout: INTERACTION_TIMEOUT },
);
expect(page.queryByText(TOOLTIP_CONTENT)).not.toBeInTheDocument();
await user.tab();
expect(canvas.getByRole('button', { name: 'Export details' })).toHaveFocus();
- await waitFor(() => {
- expect(page.getByText('Export visible records')).toBeVisible();
- expect(page.getByText('Your current filters are applied.')).toBeVisible();
- });
+ await waitFor(
+ () => {
+ expect(page.getByText('Export visible records')).toBeVisible();
+ expect(page.getByText('Your current filters are applied.')).toBeVisible();
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
await user.keyboard('{Escape}');
- await waitFor(() =>
- expect(page.queryByText('Export visible records')).not.toBeInTheDocument(),
+ await waitFor(
+ () =>
+ expect(
+ page.queryByText('Export visible records'),
+ ).not.toBeInTheDocument(),
+ { timeout: INTERACTION_TIMEOUT },
);
await user.tab();
expect(canvas.getByRole('button', { name: 'Detached export' })).toHaveFocus();
- await waitFor(() =>
- expect(page.getByText('Detached export help')).toBeVisible(),
+ await waitFor(
+ () => expect(page.getByText('Detached export help')).toBeVisible(),
+ { timeout: INTERACTION_TIMEOUT },
);
await user.tab();
expect(canvas.getByRole('button', { name: 'Local export' })).toHaveFocus();
- await waitFor(() =>
- expect(page.getByText('Local export help')).toBeVisible(),
+ await waitFor(
+ () => expect(page.getByText('Local export help')).toBeVisible(),
+ { timeout: INTERACTION_TIMEOUT },
);
await user.keyboard('{Escape}');
- await waitFor(() =>
- expect(page.queryByText('Local export help')).not.toBeInTheDocument(),
+ await waitFor(
+ () => expect(page.queryByText('Local export help')).not.toBeInTheDocument(),
+ { timeout: INTERACTION_TIMEOUT },
);
expect(errorHandler).not.toHaveBeenCalled();
};
diff --git a/packages/twenty-front-component-renderer/src/constants/AcknowledgedNativeEditSequenceBridgeProperty.ts b/packages/twenty-front-component-renderer/src/constants/AcknowledgedNativeEditSequenceBridgeProperty.ts
new file mode 100644
index 00000000000..f067374fcee
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/constants/AcknowledgedNativeEditSequenceBridgeProperty.ts
@@ -0,0 +1,2 @@
+export const ACKNOWLEDGED_NATIVE_EDIT_SEQUENCE_BRIDGE_PROPERTY =
+ '__twentyAcknowledgedNativeEditSequence';
diff --git a/packages/twenty-front-component-renderer/src/host/caret/hooks/useCaretPreservingElementRef.ts b/packages/twenty-front-component-renderer/src/host/caret/hooks/useCaretPreservingElementRef.ts
index 109dc430525..d2f00515279 100644
--- a/packages/twenty-front-component-renderer/src/host/caret/hooks/useCaretPreservingElementRef.ts
+++ b/packages/twenty-front-component-renderer/src/host/caret/hooks/useCaretPreservingElementRef.ts
@@ -4,6 +4,7 @@ import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingE
import { applyNewInputSelectionCommands } from '@/host/caret/utils/applyNewInputSelectionCommands';
import { createInputSelectionListenerRef } from '@/host/caret/utils/createInputSelectionListenerRef';
import { createInputSelectionPublisher } from '@/host/caret/utils/createInputSelectionPublisher';
+import { isOlderThanLatestNativeEdit } from '@/host/caret/utils/isOlderThanLatestNativeEdit';
import { syncValuePreservingCaret } from '@/host/caret/utils/syncValuePreservingCaret';
import { type ElementRefCallback } from '@/host/elements/types/ElementRefCallback';
@@ -12,11 +13,13 @@ export const useCaretPreservingElementRef = ({
value,
selectionCommands,
onSelectionUpdate,
+ acknowledgedNativeEditSequence,
}: {
composedElementRef: ElementRefCallback;
value: unknown;
selectionCommands?: unknown;
onSelectionUpdate?: unknown;
+ acknowledgedNativeEditSequence?: unknown;
}): ElementRefCallback => {
const latestComposedElementRefRef = useRef(composedElementRef);
latestComposedElementRefRef.current = composedElementRef;
@@ -49,11 +52,18 @@ export const useCaretPreservingElementRef = ({
useLayoutEffect(() => {
const attachedElement = attachedElementRef.current;
- const didWriteValue = syncValuePreservingCaret({
- element: attachedElement,
- remoteValue: value,
+ const isRemoteValueOlderThanLatestNativeEdit = isOlderThanLatestNativeEdit({
+ hostElement: attachedElement,
+ nativeEditSequence: acknowledgedNativeEditSequence,
});
+ const didWriteValue =
+ !isRemoteValueOlderThanLatestNativeEdit &&
+ syncValuePreservingCaret({
+ element: attachedElement,
+ remoteValue: value,
+ });
+
applyNewInputSelectionCommands({
element: attachedElement,
selectionCommands,
diff --git a/packages/twenty-front-component-renderer/src/host/caret/states/lastNativeEditSequenceAcrossHostElements.ts b/packages/twenty-front-component-renderer/src/host/caret/states/lastNativeEditSequenceAcrossHostElements.ts
new file mode 100644
index 00000000000..7b759bf9278
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/states/lastNativeEditSequenceAcrossHostElements.ts
@@ -0,0 +1,3 @@
+export const lastNativeEditSequenceAcrossHostElements: { current: number } = {
+ current: 0,
+};
diff --git a/packages/twenty-front-component-renderer/src/host/caret/states/latestNativeEditSequenceByHostElement.ts b/packages/twenty-front-component-renderer/src/host/caret/states/latestNativeEditSequenceByHostElement.ts
new file mode 100644
index 00000000000..237b11562f2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/states/latestNativeEditSequenceByHostElement.ts
@@ -0,0 +1,4 @@
+export const latestNativeEditSequenceByHostElement = new WeakMap<
+ object,
+ number
+>();
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/applyNewInputSelectionCommands.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/applyNewInputSelectionCommands.ts
index 92ac95e39ab..1bbaa2dd0f0 100644
--- a/packages/twenty-front-component-renderer/src/host/caret/utils/applyNewInputSelectionCommands.ts
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/applyNewInputSelectionCommands.ts
@@ -4,6 +4,7 @@ import { isPlainObject } from 'twenty-shared/utils';
import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
import { applyInputSelectionRequest } from '@/host/caret/utils/applyInputSelectionRequest';
+import { isOlderThanLatestNativeEdit } from '@/host/caret/utils/isOlderThanLatestNativeEdit';
export const applyNewInputSelectionCommands = ({
element,
@@ -23,7 +24,8 @@ export const applyNewInputSelectionCommands = ({
continue;
}
- const { sequence, request } = selectionCommand;
+ const { sequence, request, acknowledgedNativeEditSequence } =
+ selectionCommand;
if (
!isNumber(sequence) ||
@@ -33,6 +35,16 @@ export const applyNewInputSelectionCommands = ({
}
appliedSelectionSequenceRef.current = sequence;
+
+ const isCommandOlderThanLatestNativeEdit = isOlderThanLatestNativeEdit({
+ hostElement: element,
+ nativeEditSequence: acknowledgedNativeEditSequence,
+ });
+
+ if (isCommandOlderThanLatestNativeEdit) {
+ continue;
+ }
+
applyInputSelectionRequest({ element, request });
}
};
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/createCaretPreservingElement.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/createCaretPreservingElement.ts
index 345fc2a30fd..94dab9c52ff 100644
--- a/packages/twenty-front-component-renderer/src/host/caret/utils/createCaretPreservingElement.ts
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/createCaretPreservingElement.ts
@@ -3,6 +3,7 @@ import React from 'react';
import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
import { type SetEditableFocused } from '@/host/caret/types/SetEditableFocused';
+import { recordNativeEdit } from '@/host/caret/utils/recordNativeEdit';
import { type ElementRefCallback } from '@/host/elements/types/ElementRefCallback';
const resolveInitialValue = (candidate: unknown): string | undefined => {
@@ -37,6 +38,7 @@ export const createCaretPreservingElement = ({
defaultValue,
onFocus: forwardedOnFocus,
onBlur: forwardedOnBlur,
+ onInput: forwardedOnInput,
...rest
} = reactBindableProps;
const initialValue =
@@ -56,12 +58,20 @@ export const createCaretPreservingElement = ({
}
};
+ const handleInput = (event: React.FormEvent<CaretPreservingElement>) => {
+ recordNativeEdit(event.currentTarget);
+ if (isFunction(forwardedOnInput)) {
+ forwardedOnInput(event);
+ }
+ };
+
return React.createElement(htmlTag, {
...rest,
...hostEnforcedProps,
defaultValue: initialValue,
onFocus: handleFocus,
onBlur: handleBlur,
+ onInput: handleInput,
ref: caretPreservingElementRef,
});
};
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/isOlderThanLatestNativeEdit.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/isOlderThanLatestNativeEdit.ts
new file mode 100644
index 00000000000..a8b9cfb5324
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/isOlderThanLatestNativeEdit.ts
@@ -0,0 +1,29 @@
+import { isNumber } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { latestNativeEditSequenceByHostElement } from '@/host/caret/states/latestNativeEditSequenceByHostElement';
+
+export const isOlderThanLatestNativeEdit = ({
+ hostElement,
+ nativeEditSequence,
+}: {
+ hostElement: object | null;
+ nativeEditSequence: unknown;
+}): boolean => {
+ if (!isDefined(hostElement)) {
+ return false;
+ }
+
+ const latestNativeEditSequence =
+ latestNativeEditSequenceByHostElement.get(hostElement);
+
+ if (!isDefined(latestNativeEditSequence)) {
+ return false;
+ }
+
+ if (!isNumber(nativeEditSequence)) {
+ return true;
+ }
+
+ return nativeEditSequence < latestNativeEditSequence;
+};
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/recordNativeEdit.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/recordNativeEdit.ts
new file mode 100644
index 00000000000..69dfc8e207d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/recordNativeEdit.ts
@@ -0,0 +1,10 @@
+import { lastNativeEditSequenceAcrossHostElements } from '@/host/caret/states/lastNativeEditSequenceAcrossHostElements';
+import { latestNativeEditSequenceByHostElement } from '@/host/caret/states/latestNativeEditSequenceByHostElement';
+
+export const recordNativeEdit = (hostElement: object): void => {
+ lastNativeEditSequenceAcrossHostElements.current += 1;
+ latestNativeEditSequenceByHostElement.set(
+ hostElement,
+ lastNativeEditSequenceAcrossHostElements.current,
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/synchronizeControlledFormControlValue.test.tsx b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/synchronizeControlledFormControlValue.test.tsx
new file mode 100644
index 00000000000..c5f701abbc2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/synchronizeControlledFormControlValue.test.tsx
@@ -0,0 +1,355 @@
+import '@/testing/setupServerRenderingGlobals';
+
+import { act } from 'react';
+
+import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
+import { createRemoteTextControlRenderer } from '@/testing/createRemoteTextControlRenderer';
+import { type InputSelectionDirection } from '@/types/InputSelectionDirection';
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const editNativeValue = ({
+ hostControl,
+ value,
+ selectionStart,
+ selectionEnd = selectionStart,
+ selectionDirection,
+}: {
+ hostControl: CaretPreservingElement;
+ value: string;
+ selectionStart: number;
+ selectionEnd?: number;
+ selectionDirection?: InputSelectionDirection;
+}) => {
+ Object.getOwnPropertyDescriptor(
+ Object.getPrototypeOf(hostControl),
+ 'value',
+ )?.set?.call(hostControl, value);
+ hostControl.setSelectionRange(
+ selectionStart,
+ selectionEnd,
+ selectionDirection,
+ );
+ hostControl.dispatchEvent(new Event('input', { bubbles: true }));
+};
+
+describe('controlled form control value synchronization with pending edits', () => {
+ const { renderRemoteControl, unmountRenderedRemoteControls } =
+ createRemoteTextControlRenderer();
+
+ afterEach(unmountRenderedRemoteControls);
+
+ const renderRemoteControlWithDeferredHostEvents = (
+ htmlTag: 'input' | 'textarea',
+ ) => {
+ const pendingHostEvents: (() => void)[] = [];
+ const renderedRemoteControl = renderRemoteControl({
+ htmlTag,
+ deferHostEvent: (dispatchHostEvent) =>
+ pendingHostEvents.push(dispatchHostEvent),
+ });
+
+ const dispatchPendingHostEvents = async (hostEventCount: number) => {
+ await act(async () => {
+ for (const dispatchHostEvent of pendingHostEvents.splice(
+ 0,
+ hostEventCount,
+ )) {
+ dispatchHostEvent();
+ }
+
+ await Promise.resolve();
+ renderedRemoteControl.connection.flush();
+ });
+ };
+
+ return {
+ ...renderedRemoteControl,
+ pendingHostEvents,
+ dispatchNextHostEvent: () => dispatchPendingHostEvents(1),
+ dispatchAllHostEvents: () =>
+ dispatchPendingHostEvents(pendingHostEvents.length),
+ };
+ };
+
+ it.each(['input', 'textarea'] as const)(
+ 'should preserve newer native edits while an older %s value returns',
+ async (htmlTag) => {
+ const {
+ connection,
+ hostControl,
+ remoteControl,
+ pendingHostEvents,
+ dispatchNextHostEvent,
+ } = renderRemoteControlWithDeferredHostEvents(htmlTag);
+
+ hostControl.focus();
+ act(() => {
+ editNativeValue({ hostControl, value: 'Follow', selectionStart: 6 });
+ editNativeValue({
+ hostControl,
+ value: 'Follow up',
+ selectionStart: 6,
+ selectionEnd: 8,
+ selectionDirection: 'backward',
+ });
+ remoteControl.setAttribute('placeholder', 'unrelated update');
+ connection.flush();
+ });
+
+ expect(hostControl.value).toBe('Follow up');
+ expect(hostControl.selectionStart).toBe(6);
+ expect(hostControl.selectionEnd).toBe(8);
+ expect(hostControl.selectionDirection).toBe('backward');
+ expect(pendingHostEvents).toHaveLength(2);
+
+ await dispatchNextHostEvent();
+
+ expect(remoteControl.value).toBe('Follow');
+ expect(hostControl.value).toBe('Follow up');
+ expect(hostControl.selectionStart).toBe(6);
+ expect(hostControl.selectionEnd).toBe(8);
+ expect(hostControl.selectionDirection).toBe('backward');
+
+ await dispatchNextHostEvent();
+
+ expect(remoteControl.value).toBe('Follow up');
+ expect(hostControl.value).toBe('Follow up');
+ expect(hostControl.selectionStart).toBe(6);
+ expect(hostControl.selectionEnd).toBe(8);
+ expect(hostControl.selectionDirection).toBe('backward');
+ },
+ );
+
+ it.each(['input', 'textarea'] as const)(
+ 'should preserve an acknowledged same-length %s transform through a delayed blur snapshot',
+ async (htmlTag) => {
+ const {
+ connection,
+ hostControl,
+ remoteControl,
+ pendingHostEvents,
+ dispatchNextHostEvent,
+ } = renderRemoteControlWithDeferredHostEvents(htmlTag);
+
+ remoteControl.addEventListener('change', () => {
+ remoteControl.value = remoteControl.value.toUpperCase();
+ });
+ remoteControl.addEventListener('blur', () => {});
+ act(() => connection.flush());
+ hostControl.focus();
+ act(() => {
+ editNativeValue({ hostControl, value: 'ab', selectionStart: 1 });
+ hostControl.dispatchEvent(
+ new FocusEvent('focusout', { bubbles: true }),
+ );
+ });
+
+ expect(pendingHostEvents).toHaveLength(2);
+ await dispatchNextHostEvent();
+
+ expect(hostControl.value).toBe('AB');
+ expect(hostControl.selectionStart).toBe(1);
+ expect(hostControl.selectionEnd).toBe(1);
+ await dispatchNextHostEvent();
+
+ expect(remoteControl.value).toBe('AB');
+ expect(hostControl.value).toBe('AB');
+ expect(hostControl.selectionStart).toBe(1);
+ expect(hostControl.selectionEnd).toBe(1);
+
+ act(() => {
+ remoteControl.value = 'xy';
+ connection.flush();
+ });
+
+ expect(hostControl.value).toBe('xy');
+ expect(hostControl.selectionStart).toBe(1);
+ expect(hostControl.selectionEnd).toBe(1);
+ },
+ );
+
+ it.each(['input', 'textarea'] as const)(
+ 'should apply repeated %s resets after acknowledging each native edit',
+ async (htmlTag) => {
+ const { connection, hostControl, remoteControl, dispatchNextHostEvent } =
+ renderRemoteControlWithDeferredHostEvents(htmlTag);
+
+ remoteControl.addEventListener('change', () => {
+ remoteControl.value = '';
+ });
+ act(() => {
+ remoteControl.value = '';
+ connection.flush();
+ });
+ hostControl.focus();
+
+ for (const value of ['abc', 'abc']) {
+ act(() => editNativeValue({ hostControl, value, selectionStart: 3 }));
+ await dispatchNextHostEvent();
+
+ expect(remoteControl.value).toBe('');
+ expect(hostControl.value).toBe('');
+ expect(hostControl.selectionStart).toBe(0);
+ expect(hostControl.selectionEnd).toBe(0);
+ }
+ },
+ );
+
+ it('should discard a selection command from an older edit in a batch acknowledging the latest edit', async () => {
+ const { connection, hostControl, remoteControl, dispatchAllHostEvents } =
+ renderRemoteControlWithDeferredHostEvents('input');
+
+ remoteControl.addEventListener('change', () => {
+ if (remoteControl.value === 'a') {
+ remoteControl.setSelectionRange(0, 0);
+ }
+ });
+ act(() => connection.flush());
+ hostControl.focus();
+ act(() => {
+ editNativeValue({ hostControl, value: 'a', selectionStart: 1 });
+ editNativeValue({ hostControl, value: 'ab', selectionStart: 2 });
+ });
+ await dispatchAllHostEvents();
+
+ expect(hostControl.value).toBe('ab');
+ expect(hostControl.selectionStart).toBe(2);
+ expect(hostControl.selectionEnd).toBe(2);
+ act(() => {
+ remoteControl.setSelectionRange(0, 1, 'backward');
+ connection.flush();
+ });
+
+ expect(hostControl.selectionStart).toBe(0);
+ expect(hostControl.selectionEnd).toBe(1);
+ expect(hostControl.selectionDirection).toBe('backward');
+ });
+
+ it('should apply remote values after a native change commits a transformed value', async () => {
+ const { connection, hostControl, remoteControl, dispatchAllHostEvents } =
+ renderRemoteControlWithDeferredHostEvents('input');
+
+ remoteControl.addEventListener('input', () => {
+ remoteControl.value = remoteControl.value.toUpperCase();
+ });
+ act(() => connection.flush());
+ hostControl.focus();
+ act(() => editNativeValue({ hostControl, value: 'a', selectionStart: 1 }));
+ await dispatchAllHostEvents();
+
+ expect(hostControl.value).toBe('A');
+
+ act(() => {
+ hostControl.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+ await dispatchAllHostEvents();
+ act(() => {
+ remoteControl.value = 'reset';
+ connection.flush();
+ });
+
+ expect(hostControl.value).toBe('reset');
+ });
+
+ it('should apply native edits from a remounted host control after earlier edits were acknowledged', async () => {
+ const {
+ connection,
+ container,
+ hostControl,
+ remoteControl,
+ remoteRoot,
+ dispatchAllHostEvents,
+ } = renderRemoteControlWithDeferredHostEvents('input');
+
+ hostControl.focus();
+ act(() => editNativeValue({ hostControl, value: 'ab', selectionStart: 2 }));
+ await dispatchAllHostEvents();
+
+ expect(remoteControl.value).toBe('ab');
+
+ await act(async () => {
+ remoteControl.remove();
+ await Promise.resolve();
+ connection.flush();
+ });
+ await act(async () => {
+ remoteRoot.prepend(remoteControl);
+ await Promise.resolve();
+ connection.flush();
+ });
+
+ const remountedHostControl = container.querySelector(
+ 'input',
+ ) as CaretPreservingElement;
+
+ expect(remountedHostControl).not.toBe(hostControl);
+
+ remountedHostControl.focus();
+ act(() =>
+ editNativeValue({
+ hostControl: remountedHostControl,
+ value: 'abc',
+ selectionStart: 3,
+ }),
+ );
+ await dispatchAllHostEvents();
+
+ expect(remoteControl.value).toBe('abc');
+ expect(remountedHostControl.value).toBe('abc');
+ });
+
+ it('should forward both input and change callbacks without replaying the native value over a transform', async () => {
+ const { connection, hostControl, remoteControl, dispatchAllHostEvents } =
+ renderRemoteControlWithDeferredHostEvents('input');
+ const receivedEvents: {
+ type: string;
+ target: EventTarget | null;
+ currentTarget: EventTarget | null;
+ value: string;
+ }[] = [];
+
+ remoteControl.addEventListener('input', (event) => {
+ remoteControl.value = remoteControl.value.toUpperCase();
+ receivedEvents.push({
+ type: event.type,
+ target: event.target,
+ currentTarget: event.currentTarget,
+ value: remoteControl.value,
+ });
+ });
+ remoteControl.addEventListener('change', (event) => {
+ receivedEvents.push({
+ type: event.type,
+ target: event.target,
+ currentTarget: event.currentTarget,
+ value: remoteControl.value,
+ });
+ });
+ act(() => connection.flush());
+ hostControl.focus();
+ act(() => editNativeValue({ hostControl, value: 'ab', selectionStart: 1 }));
+ await dispatchAllHostEvents();
+
+ expect(receivedEvents).toEqual([
+ {
+ type: 'input',
+ target: remoteControl,
+ currentTarget: remoteControl,
+ value: 'AB',
+ },
+ {
+ type: 'change',
+ target: remoteControl,
+ currentTarget: remoteControl,
+ value: 'AB',
+ },
+ ]);
+ expect(remoteControl.value).toBe('AB');
+ expect(hostControl.value).toBe('AB');
+ expect(hostControl.selectionStart).toBe(1);
+ expect(hostControl.selectionEnd).toBe(1);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/host/elements/utils/createHtmlHostWrapper.ts b/packages/twenty-front-component-renderer/src/host/elements/utils/createHtmlHostWrapper.ts
index 7ae2610fbfc..439a6d81ee3 100644
--- a/packages/twenty-front-component-renderer/src/host/elements/utils/createHtmlHostWrapper.ts
+++ b/packages/twenty-front-component-renderer/src/host/elements/utils/createHtmlHostWrapper.ts
@@ -1,6 +1,7 @@
import { isArray } from '@sniptt/guards';
import React from 'react';
+import { ACKNOWLEDGED_NATIVE_EDIT_SEQUENCE_BRIDGE_PROPERTY } from '@/constants/AcknowledgedNativeEditSequenceBridgeProperty';
import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';
import { useCaretPreservingElementRef } from '@/host/caret/hooks/useCaretPreservingElementRef';
import { HostImageElement } from '@/host/components/HostImageElement';
@@ -66,6 +67,8 @@ export const createHtmlHostWrapper = (htmlTag: string) => {
return ({
children,
+ [ACKNOWLEDGED_NATIVE_EDIT_SEQUENCE_BRIDGE_PROPERTY]:
+ acknowledgedNativeEditSequence,
[INPUT_SELECTION_BRIDGE_PROPERTIES.request]: selectionCommands,
[INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
...props
@@ -88,6 +91,7 @@ export const createHtmlHostWrapper = (htmlTag: string) => {
value: isFileInput && !shouldClearFileInputSelection ? undefined : value,
selectionCommands,
onSelectionUpdate,
+ acknowledgedNativeEditSequence,
});
if (
diff --git a/packages/twenty-front-component-renderer/src/host/events/utils/applyFormControlTargetProperties.ts b/packages/twenty-front-component-renderer/src/host/events/utils/applyFormControlTargetProperties.ts
index d4526a00b18..ab9eea4d8c2 100644
--- a/packages/twenty-front-component-renderer/src/host/events/utils/applyFormControlTargetProperties.ts
+++ b/packages/twenty-front-component-renderer/src/host/events/utils/applyFormControlTargetProperties.ts
@@ -1,6 +1,7 @@
import { isBoolean, isString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
+import { latestNativeEditSequenceByHostElement } from '@/host/caret/states/latestNativeEditSequenceByHostElement';
import { CHECKED_STATE_SETTLED_EVENT_TYPES } from '@/host/events/constants/CheckedStateSettledEventTypes';
import { FORM_CONTROL_VALUE_SETTLED_EVENT_TYPES } from '@/host/events/constants/FormControlValueSettledEventTypes';
import { serializeFileList } from '@/host/events/utils/serializeFileList';
@@ -36,6 +37,12 @@ export const applyFormControlTargetProperties = ({
serializedEvent.value = target.value;
}
+ const latestNativeEditSequence =
+ latestNativeEditSequenceByHostElement.get(target);
+ if (isDefined(latestNativeEditSequence)) {
+ serializedEvent.nativeEditSequence = latestNativeEditSequence;
+ }
+
const selectedOptionIndexes = serializeSelectedOptionIndexes(target);
if (isDefined(selectedOptionIndexes)) {
serializedEvent.selectedOptionIndexes = selectedOptionIndexes;
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createInputSelectionCommandQueue.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createInputSelectionCommandQueue.ts
index 9de7fcad9d5..73896f1d1a1 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createInputSelectionCommandQueue.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createInputSelectionCommandQueue.ts
@@ -2,6 +2,7 @@ import { updateRemoteElementProperty } from '@remote-dom/core/elements';
import { isDefined } from 'twenty-shared/utils';
import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';
+import { acknowledgedNativeEditSequenceByRemoteElement } from '@/remote/elements/states/acknowledgedNativeEditSequenceByRemoteElement';
import { type InputSelectionCommand } from '@/types/InputSelectionCommand';
import { type InputSelectionRequest } from '@/types/InputSelectionRequest';
@@ -54,7 +55,12 @@ export const createInputSelectionCommandQueue = () => {
element,
commands: [
...readPendingCommands(element),
- { sequence: lastCommandSequence, request },
+ {
+ sequence: lastCommandSequence,
+ request,
+ acknowledgedNativeEditSequence:
+ acknowledgedNativeEditSequenceByRemoteElement.get(element),
+ },
],
});
};
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/states/acknowledgedNativeEditSequenceByRemoteElement.ts b/packages/twenty-front-component-renderer/src/remote/elements/states/acknowledgedNativeEditSequenceByRemoteElement.ts
new file mode 100644
index 00000000000..816e84140d1
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/states/acknowledgedNativeEditSequenceByRemoteElement.ts
@@ -0,0 +1,4 @@
+export const acknowledgedNativeEditSequenceByRemoteElement = new WeakMap<
+ object,
+ number
+>();
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/acknowledgeNativeEdit.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/acknowledgeNativeEdit.ts
new file mode 100644
index 00000000000..f78c83053c5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/acknowledgeNativeEdit.ts
@@ -0,0 +1,22 @@
+import { updateRemoteElementProperty } from '@remote-dom/core/elements';
+
+import { ACKNOWLEDGED_NATIVE_EDIT_SEQUENCE_BRIDGE_PROPERTY } from '@/constants/AcknowledgedNativeEditSequenceBridgeProperty';
+import { acknowledgedNativeEditSequenceByRemoteElement } from '@/remote/elements/states/acknowledgedNativeEditSequenceByRemoteElement';
+
+export const acknowledgeNativeEdit = ({
+ remoteElement,
+ nativeEditSequence,
+}: {
+ remoteElement: object;
+ nativeEditSequence: number;
+}): void => {
+ acknowledgedNativeEditSequenceByRemoteElement.set(
+ remoteElement,
+ nativeEditSequence,
+ );
+ updateRemoteElementProperty(
+ remoteElement as Element,
+ ACKNOWLEDGED_NATIVE_EDIT_SEQUENCE_BRIDGE_PROPERTY,
+ nativeEditSequence,
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/applySerializedEventTargetProperties.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/applySerializedEventTargetProperties.ts
index ba203a489b2..bbeda280538 100644
--- a/packages/twenty-front-component-renderer/src/remote/elements/utils/applySerializedEventTargetProperties.ts
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/applySerializedEventTargetProperties.ts
@@ -1,8 +1,11 @@
+import { isNumber } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
import { SERIALIZED_EVENT_TARGET_PROPERTY_KEYS } from '@/remote/elements/constants/SerializedEventTargetPropertyKeys';
+import { acknowledgeNativeEdit } from '@/remote/elements/utils/acknowledgeNativeEdit';
import { applySelectedOptionIndexes } from '@/remote/elements/utils/applySelectedOptionIndexes';
import { installFilesResetOnValueClear } from '@/remote/elements/utils/installFilesResetOnValueClear';
+import { isNativeEditAcknowledged } from '@/remote/elements/utils/isNativeEditAcknowledged';
import { uncheckOtherRadioButtons } from '@/remote/elements/utils/uncheckOtherRadioButtons';
import { workerInputSelectionStore } from '@/polyfills/input-selection/states/workerInputSelectionStore';
import { readInputSelectionState } from '@/utils/readInputSelectionState';
@@ -15,7 +18,24 @@ export const applySerializedEventTargetProperties = ({
element: object;
eventData: SerializedEventData;
}): void => {
+ const { nativeEditSequence } = eventData;
+ const hasNativeEditSequence = isNumber(nativeEditSequence);
+ const isValueFromAcknowledgedNativeEdit =
+ hasNativeEditSequence &&
+ isNativeEditAcknowledged({ remoteElement: element, nativeEditSequence });
+
+ if (hasNativeEditSequence && !isValueFromAcknowledgedNativeEdit) {
+ acknowledgeNativeEdit({ remoteElement: element, nativeEditSequence });
+ }
+
for (const key of SERIALIZED_EVENT_TARGET_PROPERTY_KEYS) {
+ const shouldKeepCurrentValue =
+ key === 'value' && isValueFromAcknowledgedNativeEdit;
+
+ if (shouldKeepCurrentValue) {
+ continue;
+ }
+
if (key in eventData) {
Reflect.set(element, key, eventData[key]);
}
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/isNativeEditAcknowledged.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/isNativeEditAcknowledged.ts
new file mode 100644
index 00000000000..8d0dc80d5cf
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/isNativeEditAcknowledged.ts
@@ -0,0 +1,20 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { acknowledgedNativeEditSequenceByRemoteElement } from '@/remote/elements/states/acknowledgedNativeEditSequenceByRemoteElement';
+
+export const isNativeEditAcknowledged = ({
+ remoteElement,
+ nativeEditSequence,
+}: {
+ remoteElement: object;
+ nativeEditSequence: number;
+}): boolean => {
+ const acknowledgedNativeEditSequence =
+ acknowledgedNativeEditSequenceByRemoteElement.get(remoteElement);
+
+ if (!isDefined(acknowledgedNativeEditSequence)) {
+ return false;
+ }
+
+ return nativeEditSequence <= acknowledgedNativeEditSequence;
+};
diff --git a/packages/twenty-front-component-renderer/src/testing/createHtmlHostWrapperWithDeferredEvents.ts b/packages/twenty-front-component-renderer/src/testing/createHtmlHostWrapperWithDeferredEvents.ts
new file mode 100644
index 00000000000..1e5f87896ae
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/testing/createHtmlHostWrapperWithDeferredEvents.ts
@@ -0,0 +1,29 @@
+import { isFunction } from '@sniptt/guards';
+import { createElement } from 'react';
+
+import { createHtmlHostWrapper } from '@/host/elements/utils/createHtmlHostWrapper';
+import { isEventHandlerKey } from '@/host/events/utils/isEventHandlerKey';
+
+export const createHtmlHostWrapperWithDeferredEvents = ({
+ htmlTag,
+ deferHostEvent,
+}: {
+ htmlTag: string;
+ deferHostEvent: (dispatchHostEvent: () => void) => void;
+}) => {
+ const HtmlHostWrapper = createHtmlHostWrapper(htmlTag);
+
+ return (props: Record<string, unknown>) =>
+ createElement(
+ HtmlHostWrapper,
+ Object.fromEntries(
+ Object.entries(props).map(([key, value]) => [
+ key,
+ isEventHandlerKey(key) && isFunction(value)
+ ? (...eventArguments: unknown[]) =>
+ deferHostEvent(() => value(...eventArguments))
+ : value,
+ ]),
+ ),
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/testing/createRemoteTextControlRenderer.tsx b/packages/twenty-front-component-renderer/src/testing/createRemoteTextControlRenderer.tsx
index b04927c23c6..b9e4b36c7a3 100644
--- a/packages/twenty-front-component-renderer/src/testing/createRemoteTextControlRenderer.tsx
+++ b/packages/twenty-front-component-renderer/src/testing/createRemoteTextControlRenderer.tsx
@@ -19,6 +19,7 @@ import { workerInputSelectionStore } from '@/polyfills/input-selection/states/wo
import { type WorkerInputSelectionStore } from '@/polyfills/input-selection/types/WorkerInputSelectionStore';
import { installInputSelectionPolyfill } from '@/polyfills/input-selection/utils/installInputSelectionPolyfill';
import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
+import { createHtmlHostWrapperWithDeferredEvents } from '@/testing/createHtmlHostWrapperWithDeferredEvents';
export const createRemoteTextControlRenderer = () => {
const mountedRoots: Root[] = [];
@@ -30,11 +31,13 @@ export const createRemoteTextControlRenderer = () => {
type,
selectionStore = workerInputSelectionStore,
shouldReadBeforeConnect = true,
+ deferHostEvent,
}: {
htmlTag: 'input' | 'textarea';
type?: string;
selectionStore?: WorkerInputSelectionStore;
shouldReadBeforeConnect?: boolean;
+ deferHostEvent?: (dispatchHostEvent: () => void) => void;
}) => {
const container = document.createElement('div');
const remoteRoot = document.createElement(
@@ -53,6 +56,9 @@ export const createRemoteTextControlRenderer = () => {
batch: scheduleBatch,
});
const remoteMutationObserver = new RemoteMutationObserver(connection);
+ const HostControl = isDefined(deferHostEvent)
+ ? createHtmlHostWrapperWithDeferredEvents({ htmlTag, deferHostEvent })
+ : createHtmlHostWrapper(htmlTag);
document.body.append(container, remoteRoot);
mountedRoots.push(root);
@@ -86,10 +92,7 @@ export const createRemoteTextControlRenderer = () => {
receiver={receiver}
components={
new Map([
- [
- `html-${htmlTag}`,
- createRemoteComponentRenderer(createHtmlHostWrapper(htmlTag)),
- ],
+ [`html-${htmlTag}`, createRemoteComponentRenderer(HostControl)],
[
'html-div',
createRemoteComponentRenderer(createHtmlHostWrapper('div')),
diff --git a/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts b/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts
index 96eca4f5d6e..c9c4863b3b3 100644
--- a/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts
+++ b/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts
@@ -2,5 +2,6 @@ import { type InputSelectionRequest } from '@/types/InputSelectionRequest';
export type InputSelectionCommand = {
sequence: number;
+ acknowledgedNativeEditSequence?: number;
request: InputSelectionRequest;
};
diff --git a/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts b/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts
index e05f641e8cf..a4332b444e0 100644
--- a/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts
+++ b/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts
@@ -45,6 +45,7 @@ export type SerializedEventData = {
data?: string;
clipboardText?: string;
value?: string;
+ nativeEditSequence?: number;
selectionStart?: number;
selectionEnd?: number;
selectionDirection?: InputSelectionDirection;