Skip to content

The open alternative to Salesforce, designed for AI.

Fix input selection and Autocomplete (#27275)

Raphaël Bosid5c5f3630fba
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiAutocomplete.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiAutocomplete.stories.tsx
new file mode 100644
index 00000000000..b7232be4781
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiAutocomplete.stories.tsx
@@ -0,0 +1,58 @@
+import { type Meta } from '@storybook/react-vite';
+
+import {
+ FRONT_COMPONENT_STORY_DEFAULT_ARGS,
+ resetFrontComponentStoryMocks,
+} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
+import { type TwentyUiGalleryStory } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryStory';
+import { autocompleteCompositionTest } from '@/__stories__/twenty-ui-gallery/utils/autocompleteCompositionTest';
+import { autocompleteEmptyTest } from '@/__stories__/twenty-ui-gallery/utils/autocompleteEmptyTest';
+import { autocompleteInputTest } from '@/__stories__/twenty-ui-gallery/utils/autocompleteInputTest';
+import { createGalleryStory } from '@/__stories__/twenty-ui-gallery/utils/createGalleryStory';
+import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';
+
+const meta: Meta<typeof FrontComponentRenderer> = {
+ title: 'FrontComponent/Twenty UI Autocomplete',
+ component: FrontComponentRenderer,
+ parameters: { layout: 'centered' },
+ args: FRONT_COMPONENT_STORY_DEFAULT_ARGS,
+ beforeEach: resetFrontComponentStoryMocks,
+};
+
+export default meta;
+
+export const InputReact: TwentyUiGalleryStory = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-autocomplete',
+ runtime: 'react',
+ play: autocompleteInputTest,
+});
+
+export const InputPreact: TwentyUiGalleryStory = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-autocomplete',
+ runtime: 'preact',
+ play: autocompleteInputTest,
+});
+
+export const CompositionReact: TwentyUiGalleryStory = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-autocomplete',
+ runtime: 'react',
+ play: autocompleteCompositionTest,
+});
+
+export const CompositionPreact: TwentyUiGalleryStory = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-autocomplete',
+ runtime: 'preact',
+ play: autocompleteCompositionTest,
+});
+
+export const EmptyReact: TwentyUiGalleryStory = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-autocomplete',
+ runtime: 'react',
+ play: autocompleteEmptyTest,
+});
+
+export const EmptyPreact: TwentyUiGalleryStory = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-autocomplete',
+ runtime: 'preact',
+ play: autocompleteEmptyTest,
+});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
index 39c08aaac57..ee7cd10d73f 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
@@ -15,7 +15,7 @@ import { animatedIconCrossfadeTest } from '@/__stories__/twenty-ui-gallery/utils
import { progressTest } from '@/__stories__/twenty-ui-gallery/utils/progressTest';
import { inputTest } from '@/__stories__/twenty-ui-gallery/utils/inputTest';
import { numberStepperTest } from '@/__stories__/twenty-ui-gallery/utils/numberStepperTest';
-import { numberStepperSandboxFailureTest } from '@/__stories__/twenty-ui-gallery/utils/numberStepperSandboxFailureTest';
+import { numberStepperSelectionTest } from '@/__stories__/twenty-ui-gallery/utils/numberStepperSelectionTest';
import { settingsRowTest } from '@/__stories__/twenty-ui-gallery/utils/settingsRowTest';
import { layoutTest } from '@/__stories__/twenty-ui-gallery/utils/layoutTest';
import { listItemTest } from '@/__stories__/twenty-ui-gallery/utils/listItemTest';
@@ -146,16 +146,16 @@ export const NumberStepperPreact: Story = createGalleryStory({
play: numberStepperTest,
});
-export const NumberStepperInteractionGapsReact: Story = createGalleryStory({
+export const NumberStepperSelectionReact: Story = createGalleryStory({
frontComponentBundleName: 'twenty-ui-number-stepper',
runtime: 'react',
- play: numberStepperSandboxFailureTest,
+ play: numberStepperSelectionTest,
});
-export const NumberStepperInteractionGapsPreact: Story = createGalleryStory({
+export const NumberStepperSelectionPreact: Story = createGalleryStory({
frontComponentBundleName: 'twenty-ui-number-stepper',
runtime: 'preact',
- play: numberStepperSandboxFailureTest,
+ play: numberStepperSelectionTest,
});
export const JsonVisualizerReact: Story = createGalleryStory({
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
index 70670bac266..597575175ad 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
@@ -23,7 +23,8 @@ effect within the interaction timeout.
| Fixture | Components |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `twenty-ui-field-controls` | Field, Input, InputGroup, Textarea |
-| `twenty-ui-number-stepper` | NumberStepper (keyboard bounds, disabled/read-only state, named form values and submission) |
+| `twenty-ui-number-stepper` | NumberStepper (pointer stepping, selected-range paste, caret restoration, keyboard bounds, disabled/read-only state and forms) |
+| `twenty-ui-autocomplete` | Autocomplete (caret keys, controlled editing, composition, filtering, disabled state, Empty; `TwentyUiAutocomplete.stories.tsx`) |
| `twenty-ui-display-helpers` | Text |
| `twenty-ui-avatar-controls` | Avatar (fallback, pointer/keyboard activation and disabled state) |
| `twenty-ui-avatar-image` | Avatar (decoded images, broken-source fallback, replacement and unmount/remount) |
@@ -67,6 +68,12 @@ responses and closes them on teardown or timeout. These delayed-response steps
run only in test mode; the regular and static stories use data images and
retain working source controls, fallback, replacement and unmount/remount checks.
+The Autocomplete fixture uses the public inline list interface to isolate input
+behavior from popup support. Its Empty section runs Base UI's live-region marker
+through a narrow worker TreeWalker that supports SHOW_TEXT, nextNode and
+currentNode without callback filters; document Selection and DOM Range are
+outside this scope.
+
## Known sandbox limitations
These are compatibility regression stories, not assertions that the components
@@ -79,9 +86,8 @@ expected-to-fail by the runner.
| Component | Current limitation |
| --- | --- |
-| NumberStepper | Pointer stepping fails because the worker input does not implement `setSelectionRange`. Pasting is not covered: without `selectionStart`/`selectionEnd`, Base UI inserts the pasted text around the whole value and reports that number, then its caret restore throws from a layout effect, which unmounts the React tree. Separate React and Preact stories assert the pointer gap and successful typing, keyboard bounds, disabled/read-only state, named form values and submission. |
| ImageInput | Native file picker activation and usable file contents are unavailable in the sandbox. The fixture checks forwarded file metadata, preview recovery, action callbacks, and supplied error changes. See the [ImageInput documentation](../../../../twenty-docs/ui/components/input/image-input.mdx). |
-| Popover, Dialog, AlertDialog, Menu, Select, Dropdown, CurrencyPicker, PhoneCountryPicker, CountrySelect (React and Preact) | The trigger opens the overlay, but the popup portals into the sandbox `document.body`, which never reaches the host, so its content stays invisible. Search, selection, dismissal and focus restoration are not covered yet. |
+| Popover, Dialog, AlertDialog, Menu, Select, Dropdown, CurrencyPicker, PhoneCountryPicker, CountrySelect, Autocomplete (React and Preact) | The trigger opens the overlay, but the popup portals into the sandbox `document.body`, which never reaches the host, so its content stays invisible. Search, selection, dismissal and focus restoration are not covered yet. |
| Slider | Thumbs stay hidden because the sandbox has no `ResizeObserver` to re-measure after the first geometry batch. |
| Responsive hooks | The sandbox `window.matchMedia` answers for the widget's own box, so `useIsMobile` follows the widget width rather than the browser viewport: a widget 768px wide or narrower gets the mobile layout, and Button drops its hotkey hint, on any screen. `useIsTouchDevice` follows the primary input of the host device, so it is `false` under the desktop Chromium that runs these stories. The fixture asserts both at a 1024px and a 400px widget width. |
@@ -149,10 +155,11 @@ Then, from `packages/twenty-front-component-renderer`, run:
npx vitest run --config vitest.storybook.config.ts TwentyUiGallery.stories.tsx
```
-The CountrySelect and reading-directions fixtures live in their own story
-files, so run them separately:
+The Autocomplete, CountrySelect and reading-directions fixtures live in their
+own story files, so run them separately:
```sh
+npx vitest run --config vitest.storybook.config.ts TwentyUiAutocomplete.stories.tsx
npx vitest run --config vitest.storybook.config.ts TwentyUiCountrySelect.stories.tsx
npx vitest run --config vitest.storybook.config.ts TwentyUiReadingDirections.stories.tsx
```
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-autocomplete.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-autocomplete.front-component.tsx
new file mode 100644
index 00000000000..a5d0e2e7c31
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-autocomplete.front-component.tsx
@@ -0,0 +1,111 @@
+import { useState } from 'react';
+import { defineFrontComponent } from 'twenty-sdk/define';
+import { Autocomplete, Button } from 'twenty-ui/primitives/input';
+import { Text } from 'twenty-ui/primitives/typography';
+import { ThemeProvider } from 'twenty-ui/theme';
+
+import { TwentyUiGalleryCard } from '@/__stories__/shared/front-components/twenty-ui-gallery-card';
+
+const FRUITS = ['Apple', 'Banana', 'Cherry', 'かき'];
+
+const AutocompleteExample = () => {
+ const [query, setQuery] = useState('Apple');
+ const [changes, setChanges] = useState(0);
+ const [submissions, setSubmissions] = useState(0);
+ const [composingConfirmations, setComposingConfirmations] = useState(0);
+ const [selectedFruit, setSelectedFruit] = useState('None');
+ const [selections, setSelections] = useState(0);
+ const [isFruitAutocompleteMounted, setIsFruitAutocompleteMounted] =
+ useState(true);
+
+ return (
+ <TwentyUiGalleryCard title="Autocomplete">
+ <ThemeProvider colorScheme="light" applyToRoot={false}>
+ <form
+ aria-label="Fruit search"
+ onSubmit={(event) => {
+ event.preventDefault();
+ setSubmissions((count) => count + 1);
+ }}
+ >
+ {isFruitAutocompleteMounted && (
+ <Autocomplete.Root
+ inline
+ open
+ items={FRUITS}
+ autoHighlight="always"
+ value={query}
+ onValueChange={(value) => {
+ setQuery(value);
+ setChanges((count) => count + 1);
+ }}
+ >
+ <Autocomplete.Input
+ aria-label="Fruit"
+ onKeyUp={(event) => {
+ if (event.key === 'Enter' && event.nativeEvent.isComposing) {
+ setComposingConfirmations((count) => count + 1);
+ }
+ }}
+ />
+ <Autocomplete.Empty aria-label="Matching fruits">
+ <Text>No matching fruits.</Text>
+ </Autocomplete.Empty>
+ <Autocomplete.List aria-label="Fruits">
+ {(fruit: string) => (
+ <Autocomplete.Item
+ key={fruit}
+ value={fruit}
+ onClick={() => {
+ setSelectedFruit(fruit);
+ setSelections((count) => count + 1);
+ }}
+ >
+ {fruit}
+ </Autocomplete.Item>
+ )}
+ </Autocomplete.List>
+ </Autocomplete.Root>
+ )}
+ <Autocomplete.Root disabled items={FRUITS} defaultValue="Cherry">
+ <Autocomplete.Input aria-label="Disabled fruit" />
+ </Autocomplete.Root>
+ <Button type="button" onClick={() => setQuery('')}>
+ Reset search
+ </Button>
+ <Button
+ type="button"
+ onClick={() => setIsFruitAutocompleteMounted(false)}
+ >
+ Remove autocomplete
+ </Button>
+ <Text role="status" aria-label="Autocomplete state">
+ Query: {query || 'empty'}; Changes: {changes}; Submissions:{' '}
+ {submissions}
+ </Text>
+ <Text role="status" aria-label="Composition confirmations">
+ {composingConfirmations}
+ </Text>
+ <Text role="status" aria-label="Selected fruit">
+ {selectedFruit}; Selections: {selections}
+ </Text>
+ </form>
+ <Autocomplete.Root inline open items={[]}>
+ <Autocomplete.Empty aria-label="Empty announcement">
+ <Text>
+ No <Text>matching</Text> fruits.
+ </Text>
+ <Text>Try another search.</Text>
+ </Autocomplete.Empty>
+ </Autocomplete.Root>
+ </ThemeProvider>
+ </TwentyUiGalleryCard>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: 'c6782912-3d64-47ec-a19b-f2ea293196b0',
+ name: 'twenty-ui-autocomplete',
+ description: 'Autocomplete input selection, composition and empty results',
+ component: AutocompleteExample,
+});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-number-stepper.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-number-stepper.front-component.tsx
index 25772ed5469..e1fc3769105 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-number-stepper.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-number-stepper.front-component.tsx
@@ -9,6 +9,8 @@ const NumberStepperExample = () => {
const [value, setValue] = useState<number | null>(3);
const [changes, setChanges] = useState(0);
const [submissions, setSubmissions] = useState(0);
+ const [editableValue, setEditableValue] = useState<number | null>(1234);
+ const [editChanges, setEditChanges] = useState(0);
return (
<TwentyUiGalleryCard title="NumberStepper">
@@ -51,11 +53,23 @@ const NumberStepperExample = () => {
onValueChange={() => setChanges((count) => count + 1)}
/>
<Button type="submit">Save quantity</Button>
- <Text role="status">
+ <Text role="status" aria-label="Quantity state">
Value: {value ?? 'empty'}; Changes: {changes}; Submissions:{' '}
{submissions}
</Text>
</form>
+ <NumberStepper
+ aria-label="Editable amount"
+ value={editableValue}
+ showButtons={false}
+ onValueChange={(nextValue) => {
+ setEditableValue(nextValue);
+ setEditChanges((count) => count + 1);
+ }}
+ />
+ <Text role="status" aria-label="Editing state">
+ Amount: {editableValue ?? 'empty'}; Changes: {editChanges}
+ </Text>
</TwentyUiGalleryCard>
);
};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/autocompleteCompositionTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/autocompleteCompositionTest.ts
new file mode 100644
index 00000000000..6f43cf55ab0
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/autocompleteCompositionTest.ts
@@ -0,0 +1,78 @@
+import { expect, fireEvent, userEvent, waitFor, within } from 'storybook/test';
+
+import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+import { dispatchComposingEnterKeyPress } from '@/__stories__/twenty-ui-gallery/utils/dispatchComposingEnterKeyPress';
+
+export const autocompleteCompositionTest: TwentyUiGalleryPlayFunction = async ({
+ canvasElement,
+}) => {
+ const canvas = within(canvasElement);
+ await expectFrontComponentMounted(canvas);
+
+ const input = canvas.getByRole<HTMLInputElement>('combobox', {
+ name: 'Fruit',
+ });
+ const autocompleteState = canvas.getByRole('status', {
+ name: 'Autocomplete state',
+ });
+ const selectedFruitState = canvas.getByRole('status', {
+ name: 'Selected fruit',
+ });
+ const compositionConfirmations = canvas.getByRole('status', {
+ name: 'Composition confirmations',
+ });
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Reset search' }));
+ await waitFor(() => expect(input).toHaveValue(''));
+ await userEvent.click(input);
+ const apple = await canvas.findByRole('option', { name: 'Apple' });
+ await waitFor(() =>
+ expect(input).toHaveAttribute('aria-activedescendant', apple.id),
+ );
+
+ input.dispatchEvent(
+ new CompositionEvent('compositionstart', { bubbles: true }),
+ );
+ await fireEvent.input(input, {
+ target: { value: 'か' },
+ data: 'か',
+ inputType: 'insertCompositionText',
+ isComposing: true,
+ });
+ await waitFor(() => expect(input).toHaveValue('か'));
+ dispatchComposingEnterKeyPress(input);
+ await waitFor(() => expect(compositionConfirmations).toHaveTextContent('1'));
+ await expect(autocompleteState).toHaveTextContent(
+ 'Query: empty; Changes: 0; Submissions: 0',
+ );
+ await expect(input).toHaveValue('か');
+ await expect(selectedFruitState).toHaveTextContent('None; Selections: 0');
+ await expect(apple).toBeVisible();
+
+ input.dispatchEvent(
+ new CompositionEvent('compositionend', { bubbles: true, data: 'か' }),
+ );
+ await waitFor(() =>
+ expect(autocompleteState).toHaveTextContent(
+ 'Query: か; Changes: 1; Submissions: 0',
+ ),
+ );
+ const persimmon = await canvas.findByRole('option', { name: 'かき' });
+ await waitFor(() =>
+ expect(input).toHaveAttribute('aria-activedescendant', persimmon.id),
+ );
+ await expect(input).toHaveFocus();
+ await userEvent.keyboard('{ArrowDown}');
+ await waitFor(() => expect(persimmon).toHaveAttribute('data-highlighted'));
+ await userEvent.keyboard('{Enter}');
+ await waitFor(() =>
+ expect(selectedFruitState).toHaveTextContent('かき; Selections: 1'),
+ );
+ await expect(autocompleteState).toHaveTextContent(
+ 'Query: か; Changes: 1; Submissions: 0',
+ );
+ await expect(input).toHaveValue('か');
+ await expect(errorHandler).not.toHaveBeenCalled();
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/autocompleteEmptyTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/autocompleteEmptyTest.ts
new file mode 100644
index 00000000000..5b0557b58af
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/autocompleteEmptyTest.ts
@@ -0,0 +1,32 @@
+import { expect, fireEvent, waitFor, within } from 'storybook/test';
+
+import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+
+export const autocompleteEmptyTest: TwentyUiGalleryPlayFunction = async ({
+ canvasElement,
+}) => {
+ const canvas = within(canvasElement);
+ await expectFrontComponentMounted(canvas);
+
+ const input = canvas.getByRole('combobox', { name: 'Fruit' });
+ const empty = canvas.getByRole('status', { name: 'Matching fruits' });
+ await fireEvent.input(input, { target: { value: 'Kiwi' } });
+ await waitFor(() => expect(empty).toHaveTextContent('No matching fruits.'));
+ await expect(canvas.queryAllByRole('option')).toHaveLength(0);
+ await fireEvent.input(input, { target: { value: 'Cherry' } });
+ await canvas.findByRole('option', { name: 'Cherry' });
+ await expect(empty).toBeEmptyDOMElement();
+
+ const announcement = canvas.getByRole('status', {
+ name: 'Empty announcement',
+ });
+ await waitFor(() =>
+ expect(announcement.textContent).toBe(
+ 'No matching fruits.Try another search.',
+ ),
+ );
+ await expect(input).toHaveValue('Cherry');
+ await expect(errorHandler).not.toHaveBeenCalled();
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/autocompleteInputTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/autocompleteInputTest.ts
new file mode 100644
index 00000000000..4d835831376
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/autocompleteInputTest.ts
@@ -0,0 +1,44 @@
+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 { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+import { expectCaretAt } from '@/__stories__/twenty-ui-gallery/utils/expectCaretAt';
+
+export const autocompleteInputTest: TwentyUiGalleryPlayFunction = async ({
+ canvasElement,
+}) => {
+ const canvas = within(canvasElement);
+ await expectFrontComponentMounted(canvas);
+
+ const input = canvas.getByRole<HTMLInputElement>('combobox', {
+ name: 'Fruit',
+ });
+ const autocompleteState = canvas.getByRole('status', {
+ name: 'Autocomplete state',
+ });
+ const disabledInput = canvas.getByLabelText('Disabled fruit');
+
+ await expect(disabledInput).toBeDisabled();
+ await userEvent.type(disabledInput, 'Banana');
+ await expect(disabledInput).toHaveValue('Cherry');
+ await userEvent.click(input);
+ await userEvent.keyboard('{Home}');
+ await expectCaretAt({ input, offset: 0 });
+ await userEvent.keyboard('{End}');
+ await expectCaretAt({ input, offset: 5 });
+ await userEvent.keyboard('{ArrowLeft}{ArrowLeft}x');
+ await waitFor(() => expect(input).toHaveValue('Appxle'));
+ await expectCaretAt({ input, offset: 4 });
+ await expect(autocompleteState).toHaveTextContent(
+ 'Query: Appxle; Changes: 1; Submissions: 0',
+ );
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Remove autocomplete' }),
+ );
+ await waitFor(() =>
+ expect(canvas.queryByRole('combobox', { name: 'Fruit' })).toBeNull(),
+ );
+ await expect(disabledInput).toHaveValue('Cherry');
+ await expect(errorHandler).not.toHaveBeenCalled();
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/dispatchComposingEnterKeyPress.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/dispatchComposingEnterKeyPress.ts
new file mode 100644
index 00000000000..67e36532205
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/dispatchComposingEnterKeyPress.ts
@@ -0,0 +1,22 @@
+const IME_PROCESS_KEY_CODE = 229;
+
+const COMPOSING_ENTER_KEYBOARD_EVENT_INIT: KeyboardEventInit = {
+ bubbles: true,
+ key: 'Enter',
+ code: 'Enter',
+ keyCode: IME_PROCESS_KEY_CODE,
+ which: IME_PROCESS_KEY_CODE,
+ isComposing: true,
+};
+
+export const dispatchComposingEnterKeyPress = (input: HTMLElement): void => {
+ input.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ ...COMPOSING_ENTER_KEYBOARD_EVENT_INIT,
+ cancelable: true,
+ }),
+ );
+ input.dispatchEvent(
+ new KeyboardEvent('keyup', COMPOSING_ENTER_KEYBOARD_EVENT_INIT),
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/expectCaretAt.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/expectCaretAt.ts
new file mode 100644
index 00000000000..370a0e1869e
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/expectCaretAt.ts
@@ -0,0 +1,16 @@
+import { expect, waitFor } from 'storybook/test';
+
+type ExpectCaretAtParams = {
+ input: HTMLInputElement;
+ offset: number;
+};
+
+export const expectCaretAt = async ({
+ input,
+ offset,
+}: ExpectCaretAtParams): Promise<void> => {
+ await waitFor(() => {
+ expect(input.selectionStart).toBe(offset);
+ expect(input.selectionEnd).toBe(offset);
+ });
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperSandboxFailureTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperSandboxFailureTest.ts
deleted file mode 100644
index dc7f0f6b97b..00000000000
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperSandboxFailureTest.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { expect, userEvent, within } from 'storybook/test';
-
-import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
-import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
-import { expectSandboxErrors } from '@/__stories__/twenty-ui-gallery/utils/expectSandboxErrors';
-
-const MISSING_SELECTION_RANGE_ERROR =
- /^Uncaught TypeError: .+\.setSelectionRange is not a function$/;
-
-export const numberStepperSandboxFailureTest: TwentyUiGalleryPlayFunction =
- async ({ canvasElement }) => {
- const canvas = within(canvasElement);
- await expectFrontComponentMounted(canvas);
-
- const status = canvas.getByRole('status');
- await userEvent.click(
- canvas.getByRole('button', { name: 'Increase value' }),
- );
- await expectSandboxErrors({
- requiredErrors: [MISSING_SELECTION_RANGE_ERROR],
- });
- expect(status).toHaveTextContent('Value: 3; Changes: 0; Submissions: 0');
- };
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperSelectionTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperSelectionTest.ts
new file mode 100644
index 00000000000..f07a41f1fbe
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperSelectionTest.ts
@@ -0,0 +1,46 @@
+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 { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+import { expectCaretAt } from '@/__stories__/twenty-ui-gallery/utils/expectCaretAt';
+
+export const numberStepperSelectionTest: TwentyUiGalleryPlayFunction = async ({
+ canvasElement,
+}) => {
+ const canvas = within(canvasElement);
+ await expectFrontComponentMounted(canvas);
+
+ const quantityState = canvas.getByRole('status', { name: 'Quantity state' });
+ await userEvent.click(canvas.getByRole('button', { name: 'Increase value' }));
+ await waitFor(() =>
+ expect(quantityState).toHaveTextContent(
+ 'Value: 4; Changes: 1; Submissions: 0',
+ ),
+ );
+ await userEvent.click(canvas.getByRole('button', { name: 'Decrease value' }));
+ await waitFor(() =>
+ expect(quantityState).toHaveTextContent(
+ 'Value: 3; Changes: 2; Submissions: 0',
+ ),
+ );
+
+ const amount = canvas.getByRole<HTMLInputElement>('textbox', {
+ name: 'Editable amount',
+ });
+ const editingState = canvas.getByRole('status', { name: 'Editing state' });
+ await userEvent.click(amount);
+ amount.setSelectionRange(1, 3, 'backward');
+ await userEvent.paste('6');
+ await waitFor(() =>
+ expect(editingState).toHaveTextContent('Amount: 164; Changes: 1'),
+ );
+ await waitFor(() => expect(amount).toHaveValue('164'));
+ await expectCaretAt({ input: amount, offset: 2 });
+ await userEvent.keyboard('7');
+ await waitFor(() =>
+ expect(editingState).toHaveTextContent('Amount: 1674; Changes: 2'),
+ );
+ await expectCaretAt({ input: amount, offset: 3 });
+ expect(errorHandler).not.toHaveBeenCalled();
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperTest.ts
index 49ba2c68c6b..0e8f1c5e3c5 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/numberStepperTest.ts
@@ -13,7 +13,7 @@ export const numberStepperTest: TwentyUiGalleryPlayFunction = async ({
const input = canvas.getByRole('textbox', { name: 'Quantity' });
const increment = canvas.getByRole('button', { name: 'Increase value' });
const decrement = canvas.getByRole('button', { name: 'Decrease value' });
- const status = canvas.getByRole('status');
+ const status = canvas.getByRole('status', { name: 'Quantity state' });
expect(input).toHaveValue('3');
expect(input).toHaveAccessibleDescription('Choose up to five items');
diff --git a/packages/twenty-front-component-renderer/src/constants/InputSelectionBridgeProperties.ts b/packages/twenty-front-component-renderer/src/constants/InputSelectionBridgeProperties.ts
new file mode 100644
index 00000000000..0371e22d7a7
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/constants/InputSelectionBridgeProperties.ts
@@ -0,0 +1,4 @@
+export const INPUT_SELECTION_BRIDGE_PROPERTIES = {
+ request: '__twentyInputSelectionRequest',
+ update: '__twentyInputSelectionUpdate',
+} as const;
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 e4a0d16054a..109dc430525 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
@@ -1,37 +1,66 @@
-import { isNumber, isString } from '@sniptt/guards';
import { useLayoutEffect, useRef, useState } from 'react';
-import { isDefined } from 'twenty-shared/utils';
-import { type ElementRefCallback } from '@/host/elements/types/ElementRefCallback';
+import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
+import { applyNewInputSelectionCommands } from '@/host/caret/utils/applyNewInputSelectionCommands';
+import { createInputSelectionListenerRef } from '@/host/caret/utils/createInputSelectionListenerRef';
+import { createInputSelectionPublisher } from '@/host/caret/utils/createInputSelectionPublisher';
import { syncValuePreservingCaret } from '@/host/caret/utils/syncValuePreservingCaret';
+import { type ElementRefCallback } from '@/host/elements/types/ElementRefCallback';
-export const useCaretPreservingElementRef = (
- composedElementRef: ElementRefCallback,
- value: unknown,
-): ElementRefCallback => {
+export const useCaretPreservingElementRef = ({
+ composedElementRef,
+ value,
+ selectionCommands,
+ onSelectionUpdate,
+}: {
+ composedElementRef: ElementRefCallback;
+ value: unknown;
+ selectionCommands?: unknown;
+ onSelectionUpdate?: unknown;
+}): ElementRefCallback => {
const latestComposedElementRefRef = useRef(composedElementRef);
latestComposedElementRefRef.current = composedElementRef;
+ const latestOnSelectionUpdateRef = useRef(onSelectionUpdate);
+ latestOnSelectionUpdateRef.current = onSelectionUpdate;
+ const attachedElementRef = useRef<CaretPreservingElement | null>(null);
+ const appliedSelectionSequenceRef = useRef(0);
+
+ const [publishInputSelection] = useState(() =>
+ createInputSelectionPublisher({
+ attachedElementRef,
+ latestOnSelectionUpdateRef,
+ appliedSelectionSequenceRef,
+ }),
+ );
- const attachedElementRef = useRef<Element | null>(null);
+ const [caretPreservingElementRef] = useState(() => {
+ const inputSelectionListenerRef = createInputSelectionListenerRef({
+ onSelectionChange: () =>
+ publishInputSelection({ shouldSkipUnchanged: false }),
+ });
- const [caretPreservingElementRef] = useState(
- () => (element: Element | null) => {
- attachedElementRef.current = element;
+ return (element: Element | null) => {
+ attachedElementRef.current = element as CaretPreservingElement | null;
+ inputSelectionListenerRef(element);
latestComposedElementRefRef.current(element);
- },
- );
+ };
+ });
useLayoutEffect(() => {
const attachedElement = attachedElementRef.current;
- if (!isDefined(attachedElement) || (!isString(value) && !isNumber(value))) {
- return;
- }
+ const didWriteValue = syncValuePreservingCaret({
+ element: attachedElement,
+ remoteValue: value,
+ });
+
+ applyNewInputSelectionCommands({
+ element: attachedElement,
+ selectionCommands,
+ appliedSelectionSequenceRef,
+ });
- syncValuePreservingCaret(
- attachedElement as HTMLInputElement | HTMLTextAreaElement,
- String(value),
- );
+ publishInputSelection({ shouldSkipUnchanged: !didWriteValue });
});
return caretPreservingElementRef;
diff --git a/packages/twenty-front-component-renderer/src/host/caret/types/CaretPreservingElement.ts b/packages/twenty-front-component-renderer/src/host/caret/types/CaretPreservingElement.ts
new file mode 100644
index 00000000000..249ed5e18dc
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/types/CaretPreservingElement.ts
@@ -0,0 +1 @@
+export type CaretPreservingElement = HTMLInputElement | HTMLTextAreaElement;
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/applyInputSelectionRequest.test.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/applyInputSelectionRequest.test.ts
new file mode 100644
index 00000000000..c72879fd7b0
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/applyInputSelectionRequest.test.ts
@@ -0,0 +1,66 @@
+import { applyInputSelectionRequest } from '../applyInputSelectionRequest';
+
+const createConnectedInput = ({
+ type,
+ value,
+}: {
+ type: string;
+ value: string;
+}): HTMLInputElement => {
+ const input = document.createElement('input');
+ input.type = type;
+ input.value = value;
+ document.body.appendChild(input);
+
+ return input;
+};
+
+describe('applyInputSelectionRequest', () => {
+ afterEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ it('should ignore an element that is not connected', () => {
+ const input = document.createElement('input');
+ input.value = 'hello';
+
+ applyInputSelectionRequest({
+ element: input,
+ request: { method: 'select' },
+ });
+
+ expect(input.selectionStart).toBe(5);
+ });
+
+ it.each([
+ { method: 'setSelectionRange', start: 0, end: 1, direction: 'none' },
+ { property: 'selectionStart', value: 0 },
+ { property: 'selectionDirection', value: 'backward' },
+ ])(
+ 'should ignore the range request %p on an input without a selection range',
+ (request) => {
+ const input = createConnectedInput({ type: 'number', value: '42' });
+
+ expect(() =>
+ applyInputSelectionRequest({ element: input, request }),
+ ).not.toThrow();
+ },
+ );
+
+ it.each([
+ null,
+ 'select',
+ { method: 'setSelectionRange', start: '1', end: 2 },
+ { property: 'selectionEnd', value: '2' },
+ { property: 'selectionDirection', value: 'sideways' },
+ ])('should ignore the malformed request %p', (request) => {
+ const input = createConnectedInput({ type: 'text', value: 'hello world' });
+ input.setSelectionRange(2, 5, 'backward');
+
+ applyInputSelectionRequest({ element: input, request });
+
+ expect(input.selectionStart).toBe(2);
+ expect(input.selectionEnd).toBe(5);
+ expect(input.selectionDirection).toBe('backward');
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/applyNewInputSelectionCommands.test.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/applyNewInputSelectionCommands.test.ts
new file mode 100644
index 00000000000..ebb279941fb
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/applyNewInputSelectionCommands.test.ts
@@ -0,0 +1,59 @@
+import { applyNewInputSelectionCommands } from '../applyNewInputSelectionCommands';
+
+const createConnectedTextInput = (value: string): HTMLInputElement => {
+ const input = document.createElement('input');
+ input.value = value;
+ document.body.appendChild(input);
+
+ return input;
+};
+
+describe('applyNewInputSelectionCommands', () => {
+ afterEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ it('should apply only the commands newer than the applied sequence', () => {
+ const input = createConnectedTextInput('hello world');
+ const appliedSelectionSequenceRef = { current: 1 };
+
+ applyNewInputSelectionCommands({
+ element: input,
+ selectionCommands: [
+ { sequence: 1, request: { method: 'select' } },
+ { sequence: 2, request: { property: 'selectionEnd', value: 4 } },
+ ],
+ appliedSelectionSequenceRef,
+ });
+
+ expect(input.selectionStart).toBe(4);
+ expect(input.selectionEnd).toBe(4);
+ expect(appliedSelectionSequenceRef.current).toBe(2);
+ });
+
+ it.each([
+ {
+ selectionCommands: [
+ null,
+ 'select',
+ { sequence: '7', request: { method: 'select' } },
+ ],
+ },
+ { selectionCommands: { sequence: 1, request: { method: 'select' } } },
+ ])(
+ 'should ignore the malformed selection commands $selectionCommands',
+ ({ selectionCommands }) => {
+ const input = createConnectedTextInput('hello world');
+ const appliedSelectionSequenceRef = { current: 0 };
+
+ applyNewInputSelectionCommands({
+ element: input,
+ selectionCommands,
+ appliedSelectionSequenceRef,
+ });
+
+ expect(input.selectionStart).toBe(11);
+ expect(appliedSelectionSequenceRef.current).toBe(0);
+ },
+ );
+});
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/syncValuePreservingCaret.test.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/syncValuePreservingCaret.test.ts
index a072f9c5782..32e20193857 100644
--- a/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/syncValuePreservingCaret.test.ts
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/syncValuePreservingCaret.test.ts
@@ -9,18 +9,26 @@ describe('syncValuePreservingCaret', () => {
const input = document.createElement('input');
input.value = 'old';
- syncValuePreservingCaret(input, 'new');
+ const didWriteValue = syncValuePreservingCaret({
+ element: input,
+ remoteValue: 'new',
+ });
expect(input.value).toBe('new');
+ expect(didWriteValue).toBe(true);
});
it('should do nothing when the value is already equal', () => {
const input = document.createElement('input');
input.value = 'same';
- syncValuePreservingCaret(input, 'same');
+ const didWriteValue = syncValuePreservingCaret({
+ element: input,
+ remoteValue: 'same',
+ });
expect(input.value).toBe('same');
+ expect(didWriteValue).toBe(false);
});
it('should preserve the caret selection when the element is focused', () => {
@@ -28,12 +36,13 @@ describe('syncValuePreservingCaret', () => {
document.body.appendChild(input);
input.value = 'hello world';
input.focus();
- input.setSelectionRange(2, 5);
+ input.setSelectionRange(2, 5, 'backward');
- syncValuePreservingCaret(input, 'HELLO world');
+ syncValuePreservingCaret({ element: input, remoteValue: 'HELLO world' });
expect(input.value).toBe('HELLO world');
expect(input.selectionStart).toBe(2);
expect(input.selectionEnd).toBe(5);
+ expect(input.selectionDirection).toBe('backward');
});
});
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/applyInputSelectionRequest.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/applyInputSelectionRequest.ts
new file mode 100644
index 00000000000..305feb5de09
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/applyInputSelectionRequest.ts
@@ -0,0 +1,58 @@
+import { isNull, isNumber } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
+import { isInputSelectionDirection } from '@/utils/isInputSelectionDirection';
+import { normalizeInputSelectionDirection } from '@/utils/normalizeInputSelectionDirection';
+
+export const applyInputSelectionRequest = ({
+ element,
+ request,
+}: {
+ element: CaretPreservingElement | null;
+ request: unknown;
+}): void => {
+ if (!isDefined(element) || !element.isConnected || !isPlainObject(request)) {
+ return;
+ }
+
+ if (request.method === 'select') {
+ element.select();
+ return;
+ }
+
+ const supportsSelectionRange = !isNull(element.selectionStart);
+
+ if (!supportsSelectionRange) {
+ return;
+ }
+
+ if (
+ request.method === 'setSelectionRange' &&
+ isNumber(request.start) &&
+ isNumber(request.end)
+ ) {
+ element.setSelectionRange(
+ request.start,
+ request.end,
+ normalizeInputSelectionDirection(request.direction),
+ );
+ return;
+ }
+
+ if (
+ (request.property === 'selectionStart' ||
+ request.property === 'selectionEnd') &&
+ isNumber(request.value)
+ ) {
+ element[request.property] = request.value;
+ return;
+ }
+
+ if (
+ request.property === 'selectionDirection' &&
+ isInputSelectionDirection(request.value)
+ ) {
+ element.selectionDirection = request.value;
+ }
+};
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
new file mode 100644
index 00000000000..92ac95e39ab
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/applyNewInputSelectionCommands.ts
@@ -0,0 +1,38 @@
+import { isArray, isNumber } from '@sniptt/guards';
+import { type RefObject } from 'react';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
+import { applyInputSelectionRequest } from '@/host/caret/utils/applyInputSelectionRequest';
+
+export const applyNewInputSelectionCommands = ({
+ element,
+ selectionCommands,
+ appliedSelectionSequenceRef,
+}: {
+ element: CaretPreservingElement | null;
+ selectionCommands: unknown;
+ appliedSelectionSequenceRef: RefObject<number>;
+}): void => {
+ if (!isArray(selectionCommands)) {
+ return;
+ }
+
+ for (const selectionCommand of selectionCommands) {
+ if (!isPlainObject(selectionCommand)) {
+ continue;
+ }
+
+ const { sequence, request } = selectionCommand;
+
+ if (
+ !isNumber(sequence) ||
+ sequence <= appliedSelectionSequenceRef.current
+ ) {
+ continue;
+ }
+
+ appliedSelectionSequenceRef.current = sequence;
+ 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 640dd4a80b1..345fc2a30fd 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
@@ -1,11 +1,10 @@
import { isFunction, isNonEmptyString, isNumber } from '@sniptt/guards';
import React from 'react';
+import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
import { type SetEditableFocused } from '@/host/caret/types/SetEditableFocused';
import { type ElementRefCallback } from '@/host/elements/types/ElementRefCallback';
-type CaretPreservingElement = HTMLInputElement | HTMLTextAreaElement;
-
const resolveInitialValue = (candidate: unknown): string | undefined => {
if (isNonEmptyString(candidate)) {
return candidate;
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/createInputSelectionListenerRef.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/createInputSelectionListenerRef.ts
new file mode 100644
index 00000000000..4368a984141
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/createInputSelectionListenerRef.ts
@@ -0,0 +1,50 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ElementRefCallback } from '@/host/elements/types/ElementRefCallback';
+
+export const createInputSelectionListenerRef = ({
+ onSelectionChange,
+}: {
+ onSelectionChange: () => void;
+}): ElementRefCallback => {
+ let attachedElement: Element | null = null;
+
+ const handleDocumentSelectionChange = (event: Event) => {
+ if (!isDefined(attachedElement)) {
+ return;
+ }
+
+ const { ownerDocument } = attachedElement;
+ const isBubbledElementSelectionChange = event.target !== ownerDocument;
+ const isAttachedElementFocused =
+ ownerDocument.activeElement === attachedElement;
+
+ if (isBubbledElementSelectionChange || !isAttachedElementFocused) {
+ return;
+ }
+
+ onSelectionChange();
+ };
+
+ return (element: Element | null) => {
+ if (isDefined(attachedElement)) {
+ attachedElement.removeEventListener('selectionchange', onSelectionChange);
+ attachedElement.ownerDocument.removeEventListener(
+ 'selectionchange',
+ handleDocumentSelectionChange,
+ );
+ }
+
+ attachedElement = element;
+
+ if (!isDefined(element)) {
+ return;
+ }
+
+ element.addEventListener('selectionchange', onSelectionChange);
+ element.ownerDocument.addEventListener(
+ 'selectionchange',
+ handleDocumentSelectionChange,
+ );
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/createInputSelectionPublisher.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/createInputSelectionPublisher.ts
new file mode 100644
index 00000000000..c8e6cfc2826
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/createInputSelectionPublisher.ts
@@ -0,0 +1,52 @@
+import { isFunction } from '@sniptt/guards';
+import { type RefObject } from 'react';
+import { fastDeepEqual } from 'twenty-shared/utils';
+
+import { type InputSelectionSnapshot } from '@/types/InputSelectionSnapshot';
+import { type InputSelectionState } from '@/types/InputSelectionState';
+import { readInputSelectionState } from '@/utils/readInputSelectionState';
+
+const UNSUPPORTED_INPUT_SELECTION_STATE: InputSelectionState = {
+ selectionStart: null,
+ selectionEnd: null,
+ selectionDirection: null,
+};
+
+export const createInputSelectionPublisher = ({
+ attachedElementRef,
+ latestOnSelectionUpdateRef,
+ appliedSelectionSequenceRef,
+}: {
+ attachedElementRef: RefObject<Element | null>;
+ latestOnSelectionUpdateRef: RefObject<unknown>;
+ appliedSelectionSequenceRef: RefObject<number>;
+}) => {
+ let lastSubscriber: unknown;
+ let lastSnapshot: InputSelectionSnapshot | undefined;
+
+ return ({ shouldSkipUnchanged }: { shouldSkipUnchanged: boolean }) => {
+ const subscriber = latestOnSelectionUpdateRef.current;
+
+ if (!isFunction(subscriber)) {
+ return;
+ }
+
+ const snapshot: InputSelectionSnapshot = {
+ ...(readInputSelectionState(attachedElementRef.current) ??
+ UNSUPPORTED_INPUT_SELECTION_STATE),
+ selectionCommandSequence: appliedSelectionSequenceRef.current,
+ };
+
+ if (
+ shouldSkipUnchanged &&
+ subscriber === lastSubscriber &&
+ fastDeepEqual(snapshot, lastSnapshot)
+ ) {
+ return;
+ }
+
+ lastSubscriber = subscriber;
+ lastSnapshot = snapshot;
+ subscriber(snapshot);
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/isTextLikeInputType.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/isTextLikeInputType.ts
deleted file mode 100644
index d50177dcdf1..00000000000
--- a/packages/twenty-front-component-renderer/src/host/caret/utils/isTextLikeInputType.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { isString } from '@sniptt/guards';
-
-const TEXT_LIKE_INPUT_TYPES = new Set([
- 'text',
- 'search',
- 'url',
- 'tel',
- 'password',
- 'email',
- 'number',
- '',
-]);
-
-export const isTextLikeInputType = (type: unknown): boolean => {
- const inputType = isString(type) ? type.toLowerCase() : '';
- return TEXT_LIKE_INPUT_TYPES.has(inputType);
-};
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/syncValuePreservingCaret.ts b/packages/twenty-front-component-renderer/src/host/caret/utils/syncValuePreservingCaret.ts
index 1306fe88b4b..035d65665e4 100644
--- a/packages/twenty-front-component-renderer/src/host/caret/utils/syncValuePreservingCaret.ts
+++ b/packages/twenty-front-component-renderer/src/host/caret/utils/syncValuePreservingCaret.ts
@@ -1,24 +1,40 @@
+import { isNumber, isString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
-type CaretPreservingElement = HTMLInputElement | HTMLTextAreaElement;
+import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
+
+export const syncValuePreservingCaret = ({
+ element,
+ remoteValue,
+}: {
+ element: CaretPreservingElement | null;
+ remoteValue: unknown;
+}): boolean => {
+ if (
+ !isDefined(element) ||
+ (!isString(remoteValue) && !isNumber(remoteValue))
+ ) {
+ return false;
+ }
+
+ const nextValue = String(remoteValue);
-export const syncValuePreservingCaret = (
- element: CaretPreservingElement,
- nextValue: string,
-): void => {
if (element.value === nextValue) {
- return;
+ return false;
}
const isFocused = document.activeElement === element;
const start = isFocused ? element.selectionStart : null;
const end = isFocused ? element.selectionEnd : null;
+ const direction = isFocused ? element.selectionDirection : null;
element.value = nextValue;
if (isFocused && isDefined(start) && isDefined(end)) {
try {
- element.setSelectionRange(start, end);
+ element.setSelectionRange(start, end, direction ?? undefined);
} catch {}
}
+
+ return true;
};
diff --git a/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapper.test.ts b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapper.test.ts
index 05f47be5573..e6979e2e4b4 100644
--- a/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapper.test.ts
+++ b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapper.test.ts
@@ -466,6 +466,40 @@ describe('createHtmlHostWrapper client events', () => {
);
});
+ it('should forward the input type and data of a typed input event', () => {
+ const handleInput = jest.fn();
+ const Wrapper = createHtmlHostWrapper('input');
+
+ act(() => {
+ root.render(
+ createElement(Wrapper, { onInput: handleInput, type: 'text' }),
+ );
+ });
+
+ const node = container.firstElementChild as HTMLInputElement;
+ node.value = 'a';
+ act(() => {
+ node.dispatchEvent(
+ new InputEvent('input', {
+ bubbles: true,
+ inputType: 'insertText',
+ data: 'a',
+ }),
+ );
+ });
+
+ expect(handleInput).toHaveBeenCalledTimes(1);
+ expect(handleInput).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'input',
+ inputType: 'insertText',
+ data: 'a',
+ isComposing: false,
+ value: 'a',
+ }),
+ );
+ });
+
it('should prevent default on dragover when a remote drop handler exists', () => {
const handleDrop = jest.fn();
const Wrapper = createHtmlHostWrapper('div');
diff --git a/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapperInputSelectionListeners.test.ts b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapperInputSelectionListeners.test.ts
new file mode 100644
index 00000000000..ce50fc1c717
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapperInputSelectionListeners.test.ts
@@ -0,0 +1,177 @@
+import '@/testing/setupServerRenderingGlobals';
+
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+
+import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';
+
+import { createHtmlHostWrapper } from '../createHtmlHostWrapper';
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('createHtmlHostWrapper input selection listeners', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let Wrapper: ReturnType<typeof createHtmlHostWrapper>;
+
+ beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ Wrapper = createHtmlHostWrapper('input');
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ const renderInput = (props: Record<string, unknown>) => {
+ act(() => {
+ root.render(createElement(Wrapper, props));
+ });
+
+ return container.querySelector('input') as HTMLInputElement;
+ };
+
+ it('should publish caret moves after the input switches from a non text-like type', () => {
+ const onSelectionUpdate = jest.fn();
+
+ renderInput({
+ type: 'date',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ const input = renderInput({
+ type: 'text',
+ value: 'hello world',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ onSelectionUpdate.mockClear();
+
+ input.setSelectionRange(2, 4);
+ input.dispatchEvent(new Event('selectionchange', { bubbles: true }));
+
+ expect(onSelectionUpdate).toHaveBeenCalledTimes(1);
+ expect(onSelectionUpdate).toHaveBeenLastCalledWith(
+ expect.objectContaining({ selectionStart: 2, selectionEnd: 4 }),
+ );
+ });
+
+ it('should publish a document selectionchange only for the focused control', () => {
+ const onSelectionUpdate = jest.fn();
+ const input = renderInput({
+ type: 'text',
+ value: 'hello world',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ onSelectionUpdate.mockClear();
+
+ input.setSelectionRange(3, 3);
+ document.dispatchEvent(new Event('selectionchange'));
+
+ expect(onSelectionUpdate).not.toHaveBeenCalled();
+
+ input.focus();
+ onSelectionUpdate.mockClear();
+ input.setSelectionRange(5, 5);
+ document.dispatchEvent(new Event('selectionchange'));
+
+ expect(onSelectionUpdate).toHaveBeenCalledTimes(1);
+ expect(onSelectionUpdate).toHaveBeenLastCalledWith(
+ expect.objectContaining({ selectionStart: 5, selectionEnd: 5 }),
+ );
+ });
+
+ it('should publish a bubbling element selectionchange once', () => {
+ const onSelectionUpdate = jest.fn();
+ const input = renderInput({
+ type: 'text',
+ value: 'hello world',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ input.focus();
+ onSelectionUpdate.mockClear();
+
+ input.setSelectionRange(1, 2);
+ input.dispatchEvent(new Event('selectionchange', { bubbles: true }));
+
+ expect(onSelectionUpdate).toHaveBeenCalledTimes(1);
+ });
+
+ it('should remove its document selectionchange listener on unmount', () => {
+ const addDocumentListener = jest.spyOn(document, 'addEventListener');
+ const removeDocumentListener = jest.spyOn(document, 'removeEventListener');
+
+ renderInput({
+ type: 'text',
+ value: 'hello world',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: jest.fn(),
+ });
+ const documentSelectionChangeListeners = addDocumentListener.mock.calls
+ .filter(([eventType]) => eventType === 'selectionchange')
+ .map(([, listener]) => listener);
+
+ act(() => {
+ root.render(null);
+ });
+
+ expect(documentSelectionChangeListeners).toHaveLength(1);
+ expect(removeDocumentListener).toHaveBeenCalledWith(
+ 'selectionchange',
+ documentSelectionChangeListeners[0],
+ );
+ });
+
+ it('should stop publishing once the caret ref detaches', () => {
+ const onSelectionUpdate = jest.fn();
+ const input = renderInput({
+ type: 'text',
+ value: 'hello world',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ renderInput({
+ type: 'date',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ input.focus();
+ onSelectionUpdate.mockClear();
+
+ document.dispatchEvent(new Event('selectionchange'));
+ input.dispatchEvent(new Event('selectionchange', { bubbles: true }));
+
+ expect(onSelectionUpdate).not.toHaveBeenCalled();
+ });
+
+ it('should publish every selectionchange even when the selection is unchanged', () => {
+ const onSelectionUpdate = jest.fn();
+ const input = renderInput({
+ type: 'text',
+ value: 'hello',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ onSelectionUpdate.mockClear();
+
+ input.dispatchEvent(new Event('selectionchange', { bubbles: true }));
+
+ expect(onSelectionUpdate).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not publish on input events', () => {
+ const onSelectionUpdate = jest.fn();
+ const input = renderInput({
+ type: 'text',
+ value: 'hello',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ onSelectionUpdate.mockClear();
+
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+
+ expect(onSelectionUpdate).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapperInputSelectionPublishing.test.ts b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapperInputSelectionPublishing.test.ts
new file mode 100644
index 00000000000..5afae6a556b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/createHtmlHostWrapperInputSelectionPublishing.test.ts
@@ -0,0 +1,175 @@
+import '@/testing/setupServerRenderingGlobals';
+
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+
+import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';
+
+import { createHtmlHostWrapper } from '../createHtmlHostWrapper';
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('createHtmlHostWrapper input selection publishing on render', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let Wrapper: ReturnType<typeof createHtmlHostWrapper>;
+
+ beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ Wrapper = createHtmlHostWrapper('input');
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ const renderInput = (props: Record<string, unknown>) => {
+ act(() => {
+ root.render(createElement(Wrapper, props));
+ });
+
+ return container.querySelector('input') as HTMLInputElement;
+ };
+
+ it('should not republish an unchanged selection when the host re-renders', () => {
+ const onSelectionUpdate = jest.fn();
+
+ renderInput({
+ type: 'text',
+ value: 'hello',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ renderInput({
+ type: 'text',
+ value: 'hello',
+ placeholder: 'first',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ renderInput({
+ type: 'text',
+ value: 'hello',
+ placeholder: 'second',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+
+ expect(onSelectionUpdate).toHaveBeenCalledTimes(1);
+ });
+
+ it('should republish when a command is acknowledged without moving the selection', () => {
+ const onSelectionUpdate = jest.fn();
+
+ renderInput({
+ type: 'text',
+ value: 'hello',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ onSelectionUpdate.mockClear();
+ renderInput({
+ type: 'text',
+ value: 'hello',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.request]: [
+ {
+ sequence: 1,
+ request: {
+ method: 'setSelectionRange',
+ start: 5,
+ end: 5,
+ direction: 'none',
+ },
+ },
+ ],
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+
+ expect(onSelectionUpdate).toHaveBeenCalledTimes(1);
+ expect(onSelectionUpdate).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ selectionStart: 5,
+ selectionEnd: 5,
+ selectionCommandSequence: 1,
+ }),
+ );
+
+ renderInput({
+ type: 'text',
+ value: 'hello',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.request]: [],
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+
+ expect(onSelectionUpdate).toHaveBeenCalledTimes(1);
+ });
+
+ it('should republish an unchanged selection to a new subscriber', () => {
+ const onSelectionUpdate = jest.fn();
+ const nextOnSelectionUpdate = jest.fn();
+
+ renderInput({
+ type: 'text',
+ value: 'hello',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ renderInput({
+ type: 'text',
+ value: 'hello',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: nextOnSelectionUpdate,
+ });
+
+ expect(onSelectionUpdate).toHaveBeenCalledTimes(1);
+ expect(nextOnSelectionUpdate).toHaveBeenCalledTimes(1);
+ });
+
+ it('should republish a focused value write that keeps the caret', () => {
+ const onSelectionUpdate = jest.fn();
+ const input = renderInput({
+ type: 'text',
+ value: 'hello',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+ input.focus();
+ input.setSelectionRange(2, 2);
+ input.dispatchEvent(new Event('selectionchange', { bubbles: true }));
+ onSelectionUpdate.mockClear();
+
+ renderInput({
+ type: 'text',
+ value: 'HELLO',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+
+ expect(input.value).toBe('HELLO');
+ expect(onSelectionUpdate).toHaveBeenCalledTimes(1);
+ expect(onSelectionUpdate).toHaveBeenLastCalledWith(
+ expect.objectContaining({ selectionStart: 2, selectionEnd: 2 }),
+ );
+ });
+
+ it('should acknowledge commands while the input renders without a caret ref', () => {
+ const onSelectionUpdate = jest.fn();
+ const select = jest.spyOn(HTMLInputElement.prototype, 'select');
+
+ renderInput({
+ type: 'checkbox',
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.request]: [
+ { sequence: 3, request: { method: 'select' } },
+ ],
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ });
+
+ expect(select).not.toHaveBeenCalled();
+ expect(onSelectionUpdate).toHaveBeenCalledWith({
+ selectionStart: null,
+ selectionEnd: null,
+ selectionDirection: null,
+ selectionCommandSequence: 3,
+ });
+ });
+});
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 4681e36d5f4..233dfd2b6ba 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,12 +1,13 @@
import { isArray } from '@sniptt/guards';
import React from 'react';
+import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';
import { useCaretPreservingElementRef } from '@/host/caret/hooks/useCaretPreservingElementRef';
import { useHtmlHostElementProps } from '@/host/elements/hooks/useHtmlHostElementProps';
import { createCaretPreservingElement } from '@/host/caret/utils/createCaretPreservingElement';
import { createPlainHostElement } from '@/host/elements/utils/createPlainHostElement';
import { isFileInputType } from '@/host/elements/utils/isFileInputType';
-import { isTextLikeInputType } from '@/host/caret/utils/isTextLikeInputType';
+import { isTextLikeInputType } from '@/utils/isTextLikeInputType';
const VOID_ELEMENTS = new Set([
'area',
@@ -58,7 +59,12 @@ export const createHtmlHostWrapper = (htmlTag: string) => {
const caretPreservingTag = htmlTag as 'input' | 'textarea';
- return ({ children, ...props }: WrapperProps) => {
+ return ({
+ children,
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.request]: selectionCommands,
+ [INPUT_SELECTION_BRIDGE_PROPERTIES.update]: onSelectionUpdate,
+ ...props
+ }: WrapperProps) => {
const {
setEditableFocused,
reactBindableProps,
@@ -72,10 +78,12 @@ export const createHtmlHostWrapper = (htmlTag: string) => {
const shouldClearFileInputSelection = isFileInput && value === '';
- const caretPreservingElementRef = useCaretPreservingElementRef(
+ const caretPreservingElementRef = useCaretPreservingElementRef({
composedElementRef,
- isFileInput && !shouldClearFileInputSelection ? undefined : value,
- );
+ value: isFileInput && !shouldClearFileInputSelection ? undefined : value,
+ selectionCommands,
+ onSelectionUpdate,
+ });
if (
caretPreservingTag === 'textarea' ||
diff --git a/packages/twenty-front-component-renderer/src/host/events/utils/__tests__/serializeEvent.test.ts b/packages/twenty-front-component-renderer/src/host/events/utils/__tests__/serializeEvent.test.ts
index f4ecde7831e..5648877d63a 100644
--- a/packages/twenty-front-component-renderer/src/host/events/utils/__tests__/serializeEvent.test.ts
+++ b/packages/twenty-front-component-renderer/src/host/events/utils/__tests__/serializeEvent.test.ts
@@ -138,6 +138,34 @@ describe('serializeEvent', () => {
expect(result).toEqual({ type: 'compositionupdate', data: 'か' });
});
+ it.each([true, false])(
+ 'should forward input composition state when isComposing is %s',
+ (isComposing) => {
+ expect(
+ serializeEvent({
+ type: 'input',
+ inputType: 'insertCompositionText',
+ isComposing,
+ }),
+ ).toEqual({
+ type: 'input',
+ inputType: 'insertCompositionText',
+ isComposing,
+ });
+ },
+ );
+
+ it('should ignore invalid composition and keyboard state', () => {
+ expect(
+ serializeEvent({
+ type: 'keydown',
+ which: '229',
+ keyCode: '229',
+ nativeEvent: { isComposing: 'true' },
+ }),
+ ).toEqual({ type: 'keydown' });
+ });
+
it('should forward the clipboard text of a paste event', () => {
const result = serializeEvent({
type: 'paste',
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 88db5510a65..d4526a00b18 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
@@ -5,6 +5,7 @@ import { CHECKED_STATE_SETTLED_EVENT_TYPES } from '@/host/events/constants/Check
import { FORM_CONTROL_VALUE_SETTLED_EVENT_TYPES } from '@/host/events/constants/FormControlValueSettledEventTypes';
import { serializeFileList } from '@/host/events/utils/serializeFileList';
import { serializeSelectedOptionIndexes } from '@/host/events/utils/serializeSelectedOptionIndexes';
+import { readInputSelectionState } from '@/utils/readInputSelectionState';
import { type SerializedEventData } from '@/types/SerializedEventData';
export const applyFormControlTargetProperties = ({
@@ -14,6 +15,12 @@ export const applyFormControlTargetProperties = ({
serializedEvent: SerializedEventData;
target: Record<string, unknown>;
}): void => {
+ const inputSelectionState = readInputSelectionState(target);
+
+ if (isDefined(inputSelectionState)) {
+ Object.assign(serializedEvent, inputSelectionState);
+ }
+
if (
CHECKED_STATE_SETTLED_EVENT_TYPES.has(serializedEvent.type) &&
isBoolean(target.checked)
diff --git a/packages/twenty-front-component-renderer/src/host/events/utils/applyInputEventProperties.ts b/packages/twenty-front-component-renderer/src/host/events/utils/applyInputEventProperties.ts
index 08490f9ae30..6d7338eb9b2 100644
--- a/packages/twenty-front-component-renderer/src/host/events/utils/applyInputEventProperties.ts
+++ b/packages/twenty-front-component-renderer/src/host/events/utils/applyInputEventProperties.ts
@@ -1,7 +1,8 @@
-import { isString } from '@sniptt/guards';
+import { isBoolean, isString } from '@sniptt/guards';
import { MAX_SERIALIZED_EVENT_TEXT_LENGTH } from '@/host/events/constants/MaxSerializedEventTextLength';
import { applyPasteClipboardText } from '@/host/events/utils/applyPasteClipboardText';
+import { resolveNativeHostEvent } from '@/host/events/utils/resolveNativeHostEvent';
import { type SerializedEventData } from '@/types/SerializedEventData';
export const applyInputEventProperties = ({
@@ -11,11 +12,19 @@ export const applyInputEventProperties = ({
serializedEvent: SerializedEventData;
domEvent: Record<string, unknown>;
}): void => {
- if (isString(domEvent.inputType)) {
- serializedEvent.inputType = domEvent.inputType;
+ const nativeEvent = resolveNativeHostEvent(domEvent) as Record<
+ string,
+ unknown
+ >;
+
+ if (isBoolean(nativeEvent.isComposing)) {
+ serializedEvent.isComposing = nativeEvent.isComposing;
+ }
+ if (isString(nativeEvent.inputType)) {
+ serializedEvent.inputType = nativeEvent.inputType;
}
- if (isString(domEvent.data)) {
- serializedEvent.data = domEvent.data.slice(
+ if (isString(nativeEvent.data)) {
+ serializedEvent.data = nativeEvent.data.slice(
0,
MAX_SERIALIZED_EVENT_TEXT_LENGTH,
);
diff --git a/packages/twenty-front-component-renderer/src/host/events/utils/applyKeyboardEventProperties.ts b/packages/twenty-front-component-renderer/src/host/events/utils/applyKeyboardEventProperties.ts
index 1548bd98d7f..e6f2395b143 100644
--- a/packages/twenty-front-component-renderer/src/host/events/utils/applyKeyboardEventProperties.ts
+++ b/packages/twenty-front-component-renderer/src/host/events/utils/applyKeyboardEventProperties.ts
@@ -1,4 +1,4 @@
-import { isBoolean, isString } from '@sniptt/guards';
+import { isBoolean, isNumber, isString } from '@sniptt/guards';
import { type SerializedEventData } from '@/types/SerializedEventData';
@@ -15,6 +15,12 @@ export const applyKeyboardEventProperties = ({
if (isString(domEvent.code)) {
serializedEvent.code = domEvent.code;
}
+ if (isNumber(domEvent.which)) {
+ serializedEvent.which = domEvent.which;
+ }
+ if (isNumber(domEvent.keyCode)) {
+ serializedEvent.keyCode = domEvent.keyCode;
+ }
if (isBoolean(domEvent.repeat)) {
serializedEvent.repeat = domEvent.repeat;
}
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeFilter.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeFilter.ts
new file mode 100644
index 00000000000..874b782bc1f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeFilter.ts
@@ -0,0 +1,18 @@
+export const NODE_FILTER = Object.freeze({
+ FILTER_ACCEPT: 1,
+ FILTER_REJECT: 2,
+ FILTER_SKIP: 3,
+ SHOW_ALL: 0xffffffff,
+ SHOW_ELEMENT: 0x1,
+ SHOW_ATTRIBUTE: 0x2,
+ SHOW_TEXT: 0x4,
+ SHOW_CDATA_SECTION: 0x8,
+ SHOW_ENTITY_REFERENCE: 0x10,
+ SHOW_ENTITY: 0x20,
+ SHOW_PROCESSING_INSTRUCTION: 0x40,
+ SHOW_COMMENT: 0x80,
+ SHOW_DOCUMENT: 0x100,
+ SHOW_DOCUMENT_TYPE: 0x200,
+ SHOW_DOCUMENT_FRAGMENT: 0x400,
+ SHOW_NOTATION: 0x800,
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeTypeByName.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeTypeByName.ts
index e995868f8f6..21bf9e642ae 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeTypeByName.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeTypeByName.ts
@@ -1,5 +1,6 @@
export const NODE_TYPE_BY_NAME = {
ELEMENT: 1,
+ TEXT: 3,
COMMENT: 8,
DOCUMENT: 9,
} as const;
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerTextTreeWalker.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerTextTreeWalker.ts
new file mode 100644
index 00000000000..3ec585c6fb5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerTextTreeWalker.ts
@@ -0,0 +1,4 @@
+export type WorkerTextTreeWalker = Pick<
+ TreeWalker,
+ 'root' | 'whatToShow' | 'filter' | 'currentNode' | 'nextNode'
+>;
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/autocompleteEmptyTextTraversal.test.tsx b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/autocompleteEmptyTextTraversal.test.tsx
new file mode 100644
index 00000000000..9937063a325
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/autocompleteEmptyTextTraversal.test.tsx
@@ -0,0 +1,118 @@
+import { Autocomplete } from '@base-ui/react/autocomplete';
+import { Window } from '@remote-dom/polyfill';
+import { act, type Ref, useImperativeHandle } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+
+import { installTextTreeWalkerPolyfill } from '../installTextTreeWalkerPolyfill';
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const LIVE_REGION_MARKER = '\u2060';
+const LIVE_REGION_RESET_DELAY = 200;
+
+const RemoteEmptyElementEffect = ({
+ element,
+ ref,
+}: {
+ element: HTMLDivElement;
+ ref?: Ref<HTMLDivElement>;
+}) => {
+ useImperativeHandle(ref, () => element, [element]);
+
+ return null;
+};
+
+describe('Autocomplete Empty text traversal', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let remoteDocument: Document;
+
+ beforeEach(() => {
+ jest.useFakeTimers();
+
+ const polyfillWindow = new Window();
+
+ installTextTreeWalkerPolyfill({
+ globalScope: { window: polyfillWindow },
+ });
+
+ remoteDocument = polyfillWindow.document as unknown as Document;
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ jest.useRealTimers();
+ });
+
+ const renderEmpty = () => {
+ const emptyElement = remoteDocument.createElement('div');
+ const nestedElement = remoteDocument.createElement('strong');
+ const firstText = remoteDocument.createTextNode('No matching ');
+ const lastText = remoteDocument.createTextNode('items');
+
+ nestedElement.append(lastText);
+ emptyElement.append(
+ firstText,
+ nestedElement,
+ remoteDocument.createTextNode(''),
+ );
+
+ act(() => {
+ root.render(
+ <Autocomplete.Root items={[]}>
+ <Autocomplete.Empty
+ render={<RemoteEmptyElementEffect element={emptyElement} />}
+ >
+ No matching items
+ </Autocomplete.Empty>
+ </Autocomplete.Root>,
+ );
+ });
+
+ return { firstText, lastText };
+ };
+
+ it('should mark the last nonempty nested text and restore it after the announcement', () => {
+ const { firstText, lastText } = renderEmpty();
+
+ expect(firstText.nodeValue).toBe('No matching ');
+ expect(lastText.nodeValue).toBe(`items${LIVE_REGION_MARKER}`);
+
+ act(() => jest.advanceTimersByTime(LIVE_REGION_RESET_DELAY));
+
+ expect(lastText.nodeValue).toBe('items');
+ });
+
+ it('should preserve text changed while the announcement timer is pending', () => {
+ const { lastText } = renderEmpty();
+
+ lastText.nodeValue = 'updated results';
+
+ act(() => jest.advanceTimersByTime(LIVE_REGION_RESET_DELAY));
+
+ expect(lastText.nodeValue).toBe('updated results');
+ });
+
+ it('should restore the marker on unmount and cancel later restoration', () => {
+ const { lastText } = renderEmpty();
+
+ expect(lastText.nodeValue).toBe(`items${LIVE_REGION_MARKER}`);
+
+ act(() => root.render(null));
+
+ expect(lastText.nodeValue).toBe('items');
+ expect(jest.getTimerCount()).toBe(0);
+
+ lastText.nodeValue = 'detached';
+
+ act(() => jest.advanceTimersByTime(LIVE_REGION_RESET_DELAY));
+
+ expect(lastText.nodeValue).toBe('detached');
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/createWorkerTextTreeWalker.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/createWorkerTextTreeWalker.test.ts
new file mode 100644
index 00000000000..ed3d4005b8c
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/createWorkerTextTreeWalker.test.ts
@@ -0,0 +1,87 @@
+import { Window } from '@remote-dom/polyfill';
+
+import { createWorkerTextTreeWalker } from '../createWorkerTextTreeWalker';
+
+const createPolyfillDocument = (): Document =>
+ new Window().document as unknown as Document;
+
+describe('createWorkerTextTreeWalker', () => {
+ it('should traverse nested text in DOM order without leaving the root', () => {
+ const document = createPolyfillDocument();
+ const root = document.createElement('div');
+ const nested = document.createElement('span');
+ const deeplyNested = document.createElement('strong');
+ const firstText = document.createTextNode('No ');
+ const nestedText = document.createTextNode('matching ');
+ const lastText = document.createTextNode('items');
+ const emptyText = document.createTextNode('');
+
+ deeplyNested.append(lastText);
+ nested.append(nestedText, deeplyNested);
+ root.append(
+ firstText,
+ document.createComment('ignored'),
+ nested,
+ emptyText,
+ );
+ document.body.append(root, document.createTextNode('outside'));
+
+ const walker = createWorkerTextTreeWalker(root);
+
+ expect(walker.root).toBe(root);
+ expect(walker.currentNode).toBe(root);
+ expect(walker.nextNode()).toBe(firstText);
+ expect(walker.currentNode).toBe(firstText);
+ expect(walker.nextNode()).toBe(nestedText);
+ expect(walker.nextNode()).toBe(lastText);
+ expect(walker.nextNode()).toBe(emptyText);
+ expect(walker.nextNode()).toBeNull();
+ expect(walker.currentNode).toBe(emptyText);
+ expect(walker.nextNode()).toBeNull();
+ });
+
+ it('should reflect inserted and removed text before advancing', () => {
+ const document = createPolyfillDocument();
+ const root = document.createElement('div');
+ const firstText = document.createTextNode('First');
+ const removedText = document.createTextNode('Removed');
+ const insertedText = document.createTextNode('Inserted');
+
+ root.append(firstText, removedText);
+
+ const walker = createWorkerTextTreeWalker(root);
+
+ expect(walker.nextNode()).toBe(firstText);
+
+ removedText.remove();
+ root.append(insertedText);
+
+ expect(walker.nextNode()).toBe(insertedText);
+ expect(walker.nextNode()).toBeNull();
+ });
+
+ it('should resume from an explicitly assigned current node', () => {
+ const document = createPolyfillDocument();
+ const root = document.createElement('div');
+ const nested = document.createElement('span');
+ const nestedText = document.createTextNode('Nested');
+
+ nested.append(nestedText);
+ root.append(document.createTextNode('First'), nested);
+
+ const walker = createWorkerTextTreeWalker(root);
+
+ walker.currentNode = nested;
+
+ expect(walker.nextNode()).toBe(nestedText);
+ });
+
+ it('should not include a text root among its descendants', () => {
+ const document = createPolyfillDocument();
+ const root = document.createTextNode('Root');
+ const walker = createWorkerTextTreeWalker(root);
+
+ expect(walker.nextNode()).toBeNull();
+ expect(walker.currentNode).toBe(root);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installTextTreeWalkerPolyfill.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installTextTreeWalkerPolyfill.test.ts
new file mode 100644
index 00000000000..4314fbc1d63
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installTextTreeWalkerPolyfill.test.ts
@@ -0,0 +1,70 @@
+import { Window } from '@remote-dom/polyfill';
+
+import { installTextTreeWalkerPolyfill } from '../installTextTreeWalkerPolyfill';
+
+const createPolyfillDocument = () => {
+ const polyfillWindow = new Window();
+ const globalScope: Record<string, unknown> = { window: polyfillWindow };
+
+ installTextTreeWalkerPolyfill({ globalScope });
+
+ return {
+ document: polyfillWindow.document as unknown as Document,
+ nodeFilter: globalScope.NodeFilter as typeof NodeFilter,
+ };
+};
+
+describe('installTextTreeWalkerPolyfill', () => {
+ it('should create a worker text walker for a SHOW_TEXT request', () => {
+ const { document, nodeFilter } = createPolyfillDocument();
+ const root = document.createElement('div');
+ const text = document.createTextNode('Text');
+
+ root.append(text);
+
+ const walker = document.createTreeWalker(root, nodeFilter.SHOW_TEXT);
+
+ expect(walker.root).toBe(root);
+ expect(walker.whatToShow).toBe(nodeFilter.SHOW_TEXT);
+ expect(walker.nextNode()).toBe(text);
+ });
+
+ it('should expose the standard NodeFilter constants', () => {
+ const { nodeFilter } = createPolyfillDocument();
+
+ expect(Object.keys(nodeFilter)).toHaveLength(16);
+
+ for (const [constantName, constantValue] of Object.entries(nodeFilter)) {
+ expect(constantValue).toBe(Reflect.get(NodeFilter, constantName));
+ }
+ });
+
+ it('should reject unsupported node masks and callback filters', () => {
+ const { document, nodeFilter } = createPolyfillDocument();
+ const root = document.createElement('div');
+
+ expect(() => document.createTreeWalker(root, NodeFilter.SHOW_ALL)).toThrow(
+ 'Worker TreeWalker supports SHOW_TEXT without a callback filter',
+ );
+ expect(() =>
+ document.createTreeWalker(
+ root,
+ nodeFilter.SHOW_TEXT,
+ () => NodeFilter.FILTER_ACCEPT,
+ ),
+ ).toThrow('Worker TreeWalker supports SHOW_TEXT without a callback filter');
+ });
+
+ it('should preserve an existing TreeWalker implementation', () => {
+ const createTreeWalker = jest.fn();
+ const globalScope = {
+ document: { createTreeWalker },
+ NodeFilter,
+ };
+
+ installTextTreeWalkerPolyfill({ globalScope });
+
+ expect(globalScope.document.createTreeWalker).toBe(createTreeWalker);
+ expect(globalScope.NodeFilter).toBe(NodeFilter);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/remoteDomPolyfillHooksContract.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/remoteDomPolyfillHooksContract.test.ts
index 16772cd7a16..6648c45821f 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/remoteDomPolyfillHooksContract.test.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/remoteDomPolyfillHooksContract.test.ts
@@ -27,6 +27,10 @@ const createHookRecorder = () => {
document: polyfillWindow.document as unknown as Document,
callsNamed: (hookName: keyof Hooks) =>
calls.filter((call) => call.name === hookName),
+ clearCalls: () => {
+ calls.length = 0;
+ },
+ callNames: () => calls.map((call) => call.name),
};
};
@@ -105,6 +109,21 @@ describe('@remote-dom/polyfill mutation hooks contract the worker MutationObserv
expect(callsNamed('removeChild')[0].args[2]).toBe(1);
});
+ it('calls removeChild then insertChild when an attached node moves', () => {
+ const { document, callNames, clearCalls } = createHookRecorder();
+
+ const parent = document.createElement('div');
+ const firstChild = document.createElement('span');
+ const secondChild = document.createElement('span');
+
+ parent.appendChild(firstChild);
+ parent.appendChild(secondChild);
+ clearCalls();
+ parent.insertBefore(secondChild, firstChild);
+
+ expect(callNames()).toEqual(['removeChild', 'insertChild']);
+ });
+
it('skips insertChild and removeChild when the parent is not an element node', () => {
const { document, callsNamed } = createHookRecorder();
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerTextTreeWalker.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerTextTreeWalker.ts
new file mode 100644
index 00000000000..8d96fb31b35
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerTextTreeWalker.ts
@@ -0,0 +1,45 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { NODE_FILTER } from '@/polyfills/dom/constants/NodeFilter';
+import { NODE_TYPE_BY_NAME } from '@/polyfills/dom/constants/NodeTypeByName';
+import { type WorkerTextTreeWalker } from '@/polyfills/dom/types/WorkerTextTreeWalker';
+import { findNextNodeInTreeOrderWithinRoot } from '@/polyfills/dom/utils/findNextNodeInTreeOrderWithinRoot';
+
+export const createWorkerTextTreeWalker = (
+ root: Node,
+): WorkerTextTreeWalker => {
+ let currentNode = root;
+
+ return {
+ root,
+ whatToShow: NODE_FILTER.SHOW_TEXT,
+ filter: null,
+ get currentNode() {
+ return currentNode;
+ },
+ set currentNode(node: Node) {
+ currentNode = node;
+ },
+ nextNode: () => {
+ let candidateNode = findNextNodeInTreeOrderWithinRoot({
+ node: currentNode,
+ root,
+ });
+
+ while (isDefined(candidateNode)) {
+ if (candidateNode.nodeType === NODE_TYPE_BY_NAME.TEXT) {
+ currentNode = candidateNode;
+
+ return candidateNode;
+ }
+
+ candidateNode = findNextNodeInTreeOrderWithinRoot({
+ node: candidateNode,
+ root,
+ });
+ }
+
+ return null;
+ },
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/findNextNodeInTreeOrderWithinRoot.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/findNextNodeInTreeOrderWithinRoot.ts
new file mode 100644
index 00000000000..5bc236a0420
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/findNextNodeInTreeOrderWithinRoot.ts
@@ -0,0 +1,25 @@
+import { isDefined } from 'twenty-shared/utils';
+
+export const findNextNodeInTreeOrderWithinRoot = ({
+ node,
+ root,
+}: {
+ node: Node;
+ root: Node;
+}): Node | null => {
+ if (isDefined(node.firstChild)) {
+ return node.firstChild;
+ }
+
+ let ancestorOrSelf: Node | null = node;
+
+ while (isDefined(ancestorOrSelf) && ancestorOrSelf !== root) {
+ if (isDefined(ancestorOrSelf.nextSibling)) {
+ return ancestorOrSelf.nextSibling;
+ }
+
+ ancestorOrSelf = ancestorOrSelf.parentNode;
+ }
+
+ return null;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installTextTreeWalkerPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installTextTreeWalkerPolyfill.ts
new file mode 100644
index 00000000000..2523e8d16eb
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installTextTreeWalkerPolyfill.ts
@@ -0,0 +1,50 @@
+import { isFunction } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { NODE_FILTER } from '@/polyfills/dom/constants/NodeFilter';
+import { type WorkerTextTreeWalker } from '@/polyfills/dom/types/WorkerTextTreeWalker';
+import { createWorkerTextTreeWalker } from '@/polyfills/dom/utils/createWorkerTextTreeWalker';
+import { resolvePolyfillDocument } from '@/polyfills/dom/utils/resolvePolyfillDocument';
+import { resolveGlobalScopeInstallTargets } from '@/polyfills/utils/resolveGlobalScopeInstallTargets';
+
+type InstallTextTreeWalkerPolyfillInput = {
+ globalScope: Record<string, unknown>;
+};
+
+export const installTextTreeWalkerPolyfill = ({
+ globalScope,
+}: InstallTextTreeWalkerPolyfillInput): void => {
+ const installTargets = resolveGlobalScopeInstallTargets(globalScope);
+ const documentTarget = resolvePolyfillDocument(installTargets);
+
+ if (!isDefined(documentTarget)) {
+ return;
+ }
+
+ if (isFunction(documentTarget.createTreeWalker)) {
+ return;
+ }
+
+ for (const installTarget of installTargets) {
+ if (!isDefined(installTarget.NodeFilter)) {
+ installTarget.NodeFilter = NODE_FILTER;
+ }
+ }
+
+ documentTarget.createTreeWalker = (
+ root: Node,
+ whatToShow?: number,
+ filter?: NodeFilter | null,
+ ): WorkerTextTreeWalker => {
+ const isUnsupportedTreeWalkerConfiguration =
+ whatToShow !== NODE_FILTER.SHOW_TEXT || isDefined(filter);
+
+ if (isUnsupportedTreeWalkerConfiguration) {
+ throw new TypeError(
+ 'Worker TreeWalker supports SHOW_TEXT without a callback filter',
+ );
+ }
+
+ return createWorkerTextTreeWalker(root);
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/states/workerInputSelectionStore.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/states/workerInputSelectionStore.ts
new file mode 100644
index 00000000000..99c11c08128
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/states/workerInputSelectionStore.ts
@@ -0,0 +1,3 @@
+import { createWorkerInputSelectionStore } from '@/polyfills/input-selection/utils/createWorkerInputSelectionStore';
+
+export const workerInputSelectionStore = createWorkerInputSelectionStore();
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/types/WorkerInputSelectionStore.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/types/WorkerInputSelectionStore.ts
new file mode 100644
index 00000000000..03ec1196717
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/types/WorkerInputSelectionStore.ts
@@ -0,0 +1,13 @@
+import { type InputSelectionRequest } from '@/types/InputSelectionRequest';
+import { type InputSelectionState } from '@/types/InputSelectionState';
+
+export type WorkerInputSelectionStore = {
+ setRootElement: (rootElement: object) => void;
+ applySnapshot: (input: {
+ element: object;
+ state: InputSelectionState;
+ }) => void;
+ scheduleDetachedElementSweep: () => void;
+ read: (element: object) => InputSelectionState;
+ request: (input: { element: object; request: InputSelectionRequest }) => void;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/applyInputSelectionRequestToRange.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/applyInputSelectionRequestToRange.test.ts
new file mode 100644
index 00000000000..d80be93de35
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/applyInputSelectionRequestToRange.test.ts
@@ -0,0 +1,52 @@
+import { applyInputSelectionRequestToRange } from '../applyInputSelectionRequestToRange';
+
+const VALUE_LENGTH = 'abcdef'.length;
+
+describe('applyInputSelectionRequestToRange', () => {
+ it('should move the end with the start setter and keep the direction', () => {
+ const rangeAfterStart = applyInputSelectionRequestToRange({
+ range: {
+ selectionStart: 1,
+ selectionEnd: 3,
+ selectionDirection: 'backward',
+ },
+ request: { property: 'selectionStart', value: 4 },
+ valueLength: VALUE_LENGTH,
+ });
+
+ expect(rangeAfterStart).toEqual({
+ selectionStart: 4,
+ selectionEnd: 4,
+ selectionDirection: 'backward',
+ });
+ expect(
+ applyInputSelectionRequestToRange({
+ range: rangeAfterStart,
+ request: { property: 'selectionEnd', value: 2 },
+ valueLength: VALUE_LENGTH,
+ }),
+ ).toEqual({
+ selectionStart: 2,
+ selectionEnd: 2,
+ selectionDirection: 'backward',
+ });
+ });
+
+ it('should change only the direction with the direction setter', () => {
+ expect(
+ applyInputSelectionRequestToRange({
+ range: {
+ selectionStart: 1,
+ selectionEnd: 3,
+ selectionDirection: 'none',
+ },
+ request: { property: 'selectionDirection', value: 'forward' },
+ valueLength: VALUE_LENGTH,
+ }),
+ ).toEqual({
+ selectionStart: 1,
+ selectionEnd: 3,
+ selectionDirection: 'forward',
+ });
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/createInputSelectionCommandQueue.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/createInputSelectionCommandQueue.test.ts
new file mode 100644
index 00000000000..15345b00783
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/createInputSelectionCommandQueue.test.ts
@@ -0,0 +1,67 @@
+import { updateRemoteElementProperty } from '@remote-dom/core/elements';
+
+import { createInputSelectionCommandQueue } from '../createInputSelectionCommandQueue';
+
+jest.mock('@remote-dom/core/elements', () => ({
+ updateRemoteElementProperty: jest.fn(),
+}));
+
+const updateRemoteElementPropertyMock = jest.mocked(
+ updateRemoteElementProperty,
+);
+
+describe('createInputSelectionCommandQueue', () => {
+ beforeEach(() => {
+ updateRemoteElementPropertyMock.mockClear();
+ });
+
+ it('should number commands in request order across elements', () => {
+ const commandQueue = createInputSelectionCommandQueue();
+ const firstElement = {};
+ const secondElement = {};
+
+ commandQueue.enqueueCommand({
+ element: firstElement,
+ request: { method: 'select' },
+ });
+ commandQueue.enqueueCommand({
+ element: secondElement,
+ request: { method: 'select' },
+ });
+ commandQueue.enqueueCommand({
+ element: firstElement,
+ request: { property: 'selectionEnd', value: 2 },
+ });
+
+ expect(commandQueue.readPendingCommands(firstElement)).toEqual([
+ { sequence: 1, request: { method: 'select' } },
+ { sequence: 3, request: { property: 'selectionEnd', value: 2 } },
+ ]);
+ expect(commandQueue.readPendingCommands(secondElement)).toEqual([
+ { sequence: 2, request: { method: 'select' } },
+ ]);
+ });
+
+ it('should not resend the queue when the host acknowledges no new command', () => {
+ const commandQueue = createInputSelectionCommandQueue();
+ const element = {};
+
+ commandQueue.enqueueCommand({ element, request: { method: 'select' } });
+ updateRemoteElementPropertyMock.mockClear();
+ commandQueue.acknowledgeCommands({
+ element,
+ acknowledgedCommandSequence: 0,
+ });
+
+ expect(updateRemoteElementPropertyMock).not.toHaveBeenCalled();
+ expect(commandQueue.readPendingCommands(element)).toHaveLength(1);
+ });
+
+ it('should send nothing when discarding an element without pending commands', () => {
+ const commandQueue = createInputSelectionCommandQueue();
+
+ commandQueue.discardPendingCommands({});
+
+ expect(updateRemoteElementPropertyMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/forwardInputSelectionToHostCommands.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/forwardInputSelectionToHostCommands.test.ts
new file mode 100644
index 00000000000..2a354e62e3d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/forwardInputSelectionToHostCommands.test.ts
@@ -0,0 +1,196 @@
+import '@/remote/generated/remote-elements';
+
+import { act } from 'react';
+
+import { createRemoteTextControlRenderer } from '@/testing/createRemoteTextControlRenderer';
+import { readRemoteSelectionCommands } from '@/testing/readRemoteSelectionCommands';
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('forwarding input selection commands to the host', () => {
+ const { renderRemoteControl, unmountRenderedRemoteControls } =
+ createRemoteTextControlRenderer();
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ unmountRenderedRemoteControls();
+ });
+
+ it.each(['input', 'textarea'] as const)(
+ 'should apply a controlled %s value before its range request in the same batch',
+ (htmlTag) => {
+ const { connection, hostControl, remoteControl } = renderRemoteControl({
+ htmlTag,
+ });
+
+ remoteControl.setSelectionRange(8, 11, 'backward');
+ remoteControl.value = 'updated text';
+
+ act(() => connection.flush());
+
+ expect(hostControl.value).toBe('updated text');
+ expect(hostControl.selectionStart).toBe(8);
+ expect(hostControl.selectionEnd).toBe(11);
+ expect(hostControl.selectionDirection).toBe('backward');
+ expect(remoteControl.selectionStart).toBe(8);
+ expect(remoteControl.selectionEnd).toBe(11);
+ expect(remoteControl.selectionDirection).toBe('backward');
+ },
+ );
+
+ it('should select again after the host user moves the caret', () => {
+ const { connection, hostControl, remoteControl } = renderRemoteControl({
+ htmlTag: 'input',
+ });
+
+ remoteControl.select();
+ act(() => connection.flush());
+
+ expect(hostControl.selectionStart).toBe(0);
+ expect(hostControl.selectionEnd).toBe(hostControl.value.length);
+
+ hostControl.setSelectionRange(2, 2);
+ hostControl.dispatchEvent(new Event('selectionchange'));
+
+ expect(remoteControl.selectionStart).toBe(2);
+
+ remoteControl.select();
+ act(() => connection.flush());
+
+ expect(hostControl.selectionStart).toBe(0);
+ expect(hostControl.selectionEnd).toBe(hostControl.value.length);
+ });
+
+ it('should preserve sequential selection setters in one batch', () => {
+ const { connection, hostControl, remoteControl } = renderRemoteControl({
+ htmlTag: 'input',
+ });
+
+ remoteControl.selectionStart = 1;
+ remoteControl.selectionEnd = 5;
+ remoteControl.selectionDirection = 'backward';
+
+ act(() => connection.flush());
+
+ expect(hostControl.selectionStart).toBe(1);
+ expect(hostControl.selectionEnd).toBe(5);
+ expect(hostControl.selectionDirection).toBe('backward');
+ });
+
+ it('should retain newer commands when a previous host snapshot arrives', () => {
+ const { connection, hostControl, remoteControl } = renderRemoteControl({
+ htmlTag: 'input',
+ });
+
+ remoteControl.select();
+ act(() => connection.flush());
+ remoteControl.setSelectionRange(2, 4);
+ hostControl.dispatchEvent(new Event('selectionchange'));
+
+ act(() => connection.flush());
+
+ expect(hostControl.selectionStart).toBe(2);
+ expect(hostControl.selectionEnd).toBe(4);
+ });
+
+ it('should convert offsets and directions the way the DOM does', () => {
+ const { connection, hostControl, remoteControl } = renderRemoteControl({
+ htmlTag: 'input',
+ });
+
+ remoteControl.setSelectionRange(-1, 2);
+
+ expect(remoteControl.selectionStart).toBe(2);
+ expect(remoteControl.selectionEnd).toBe(2);
+
+ act(() => connection.flush());
+
+ expect(hostControl.selectionStart).toBe(2);
+ expect(hostControl.selectionEnd).toBe(2);
+
+ remoteControl.selectionStart = '3' as never;
+
+ expect(remoteControl.selectionStart).toBe(3);
+
+ remoteControl.selectionDirection = 'sideways' as never;
+
+ expect(remoteControl.selectionDirection).toBe('none');
+
+ act(() => connection.flush());
+
+ expect(hostControl.selectionStart).toBe(3);
+ expect(hostControl.selectionDirection).toBe('none');
+ });
+
+ it('should not queue selection commands for controls without selectable text', () => {
+ const { connection, remoteControl } = renderRemoteControl({
+ htmlTag: 'input',
+ type: 'checkbox',
+ shouldReadBeforeConnect: false,
+ });
+ const selectHost = jest.spyOn(HTMLInputElement.prototype, 'select');
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+
+ expect(remoteControl.selectionStart).toBeNull();
+ expect(remoteControl.selectionEnd).toBeNull();
+ expect(remoteControl.selectionDirection).toBeNull();
+ expect(() => remoteControl.setSelectionRange(0, 1)).toThrow(
+ expect.objectContaining({ name: 'InvalidStateError' }),
+ );
+ expect(() => {
+ remoteControl.selectionStart = 1;
+ }).toThrow(expect.objectContaining({ name: 'InvalidStateError' }));
+
+ remoteControl.select();
+ remoteControl.select();
+ act(() => connection.flush());
+
+ expect(readRemoteSelectionCommands(remoteControl)).toBeUndefined();
+
+ remoteControl.setAttribute('type', 'text');
+ act(() => connection.flush());
+
+ expect(selectHost).not.toHaveBeenCalled();
+ });
+
+ it('should acknowledge commands without replaying them when the type leaves selectable text', () => {
+ const { connection, remoteControl } = renderRemoteControl({
+ htmlTag: 'input',
+ });
+ const selectHost = jest.spyOn(HTMLInputElement.prototype, 'select');
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+
+ remoteControl.select();
+ remoteControl.setAttribute('type', 'checkbox');
+ act(() => connection.flush());
+
+ expect(readRemoteSelectionCommands(remoteControl)).toEqual([]);
+
+ remoteControl.setAttribute('type', 'text');
+ act(() => connection.flush());
+
+ expect(selectHost).not.toHaveBeenCalled();
+ });
+
+ it.each(['email', 'number'])(
+ 'should select the text of a %s input without exposing its range',
+ (type) => {
+ const { connection, hostControl, remoteControl } = renderRemoteControl({
+ htmlTag: 'input',
+ type,
+ });
+ const selectHost = jest.spyOn(hostControl, 'select');
+
+ remoteControl.select();
+ act(() => connection.flush());
+
+ expect(selectHost).toHaveBeenCalledTimes(1);
+ expect(remoteControl.selectionStart).toBeNull();
+ expect(() => remoteControl.setSelectionRange(0, 1)).toThrow(
+ expect.objectContaining({ name: 'InvalidStateError' }),
+ );
+ },
+ );
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/forwardInputSelectionToHostDetachment.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/forwardInputSelectionToHostDetachment.test.ts
new file mode 100644
index 00000000000..59d129858eb
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/forwardInputSelectionToHostDetachment.test.ts
@@ -0,0 +1,224 @@
+import '@/remote/generated/remote-elements';
+
+import { type RemoteElementSerialization } from '@remote-dom/core';
+import {
+ type BatchingRemoteConnection,
+ serializeRemoteNode,
+} from '@remote-dom/core/elements';
+import { act } from 'react';
+
+import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';
+import { createRemoteTextControlRenderer } from '@/testing/createRemoteTextControlRenderer';
+import { readRemoteSelectionCommands } from '@/testing/readRemoteSelectionCommands';
+import { type InputSelectionState } from '@/types/InputSelectionState';
+
+import { createWorkerInputSelectionStore } from '../createWorkerInputSelectionStore';
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const flushRemoteMutations = async (connection: BatchingRemoteConnection) => {
+ await act(async () => {
+ await Promise.resolve();
+ connection.flush();
+ });
+};
+
+describe('forwarding input selection when the remote control moves, detaches or remounts', () => {
+ const { renderRemoteControl, unmountRenderedRemoteControls } =
+ createRemoteTextControlRenderer();
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ unmountRenderedRemoteControls();
+ });
+
+ it('should keep a pending selection command when the control moves within its parent', async () => {
+ const {
+ connection,
+ container,
+ hostControl,
+ remoteControl,
+ remoteRoot,
+ selectionStore,
+ } = renderRemoteControl({ htmlTag: 'input' });
+ const selectHost = jest.spyOn(hostControl, 'select');
+
+ remoteControl.select();
+ remoteControl.remove();
+ selectionStore.scheduleDetachedElementSweep();
+ remoteRoot.appendChild(remoteControl);
+
+ expect(remoteControl.selectionStart).toBe(0);
+ expect(remoteControl.selectionEnd).toBe(7);
+
+ await flushRemoteMutations(connection);
+
+ expect(container.querySelector('input')).toBe(hostControl);
+ expect(selectHost).toHaveBeenCalledTimes(1);
+ });
+
+ it('should keep the selection readable while the control moves', async () => {
+ const {
+ connection,
+ hostControl,
+ remoteControl,
+ remoteRoot,
+ selectionStore,
+ } = renderRemoteControl({ htmlTag: 'input' });
+
+ hostControl.setSelectionRange(2, 4, 'backward');
+ hostControl.dispatchEvent(new Event('selectionchange'));
+ remoteControl.remove();
+ selectionStore.scheduleDetachedElementSweep();
+ remoteRoot.appendChild(remoteControl);
+
+ expect(remoteControl.selectionStart).toBe(2);
+ expect(remoteControl.selectionEnd).toBe(4);
+ expect(remoteControl.selectionDirection).toBe('backward');
+
+ await flushRemoteMutations(connection);
+
+ expect(remoteControl.selectionStart).toBe(2);
+ expect(remoteControl.selectionEnd).toBe(4);
+ expect(remoteControl.selectionDirection).toBe('backward');
+ });
+
+ it('should ignore detached controls and controls owned by another renderer', async () => {
+ const first = renderRemoteControl({ htmlTag: 'input' });
+ const second = renderRemoteControl({
+ htmlTag: 'textarea',
+ selectionStore: createWorkerInputSelectionStore(),
+ });
+ const selectSecondHost = jest.spyOn(second.hostControl, 'select');
+ const selectFirstHost = jest.spyOn(first.hostControl, 'select');
+
+ first.selectionStore.request({
+ element: second.remoteControl,
+ request: { method: 'select' },
+ });
+ first.remoteControl.remove();
+ first.remoteControl.select();
+
+ await act(async () => {
+ await Promise.resolve();
+ first.connection.flush();
+ second.connection.flush();
+ });
+
+ expect(selectFirstHost).not.toHaveBeenCalled();
+ expect(selectSecondHost).not.toHaveBeenCalled();
+ });
+
+ it('should discard pending commands when the control unmounts', async () => {
+ const { connection, hostControl, remoteControl, selectionStore } =
+ renderRemoteControl({ htmlTag: 'input' });
+ const selectHost = jest.spyOn(hostControl, 'select');
+
+ remoteControl.select();
+ remoteControl.remove();
+ selectionStore.scheduleDetachedElementSweep();
+
+ await flushRemoteMutations(connection);
+
+ expect(selectHost).not.toHaveBeenCalled();
+ expect(readRemoteSelectionCommands(remoteControl)).toEqual([]);
+ });
+
+ it('should not replay an acknowledged command when a control is remounted', async () => {
+ const {
+ connection,
+ hostControl,
+ remoteControl,
+ remoteRoot,
+ selectionStore,
+ } = renderRemoteControl({ htmlTag: 'input' });
+
+ remoteControl.select();
+ act(() => connection.flush());
+ hostControl.setSelectionRange(2, 2);
+ hostControl.dispatchEvent(new Event('selectionchange'));
+ remoteControl.remove();
+ selectionStore.scheduleDetachedElementSweep();
+
+ await flushRemoteMutations(connection);
+
+ const selectHost = jest.spyOn(HTMLInputElement.prototype, 'select');
+
+ remoteRoot.append(remoteControl);
+
+ await flushRemoteMutations(connection);
+
+ expect(selectHost).not.toHaveBeenCalled();
+ });
+
+ it('should clear pending commands throughout a detached subtree before remounting', async () => {
+ const {
+ connection,
+ remoteControl,
+ remoteRoot,
+ remoteSibling,
+ selectionStore,
+ } = renderRemoteControl({ htmlTag: 'input' });
+ const selectHost = jest.spyOn(HTMLInputElement.prototype, 'select');
+
+ remoteSibling.append(remoteControl);
+
+ await flushRemoteMutations(connection);
+
+ remoteControl.select();
+ remoteSibling.remove();
+ selectionStore.scheduleDetachedElementSweep();
+
+ await flushRemoteMutations(connection);
+
+ remoteRoot.append(remoteControl);
+
+ await flushRemoteMutations(connection);
+
+ expect(selectHost).not.toHaveBeenCalled();
+ });
+
+ it('should reject delayed snapshots from an earlier mount without requiring another selection read', async () => {
+ const {
+ connection,
+ container,
+ hostControl,
+ remoteControl,
+ remoteRoot,
+ selectionStore,
+ } = renderRemoteControl({ htmlTag: 'input' });
+ const serializedControl = serializeRemoteNode(
+ remoteControl,
+ ) as RemoteElementSerialization;
+ const deliverDelayedSnapshot = serializedControl.properties?.[
+ INPUT_SELECTION_BRIDGE_PROPERTIES.update
+ ] as (state: InputSelectionState) => void;
+
+ hostControl.setSelectionRange(1, 1);
+ hostControl.dispatchEvent(new Event('selectionchange'));
+ remoteControl.remove();
+ selectionStore.scheduleDetachedElementSweep();
+
+ await flushRemoteMutations(connection);
+
+ remoteRoot.append(remoteControl);
+
+ await flushRemoteMutations(connection);
+
+ const remountedHostControl = container.querySelector('input')!;
+
+ remountedHostControl.setSelectionRange(4, 5, 'backward');
+ remountedHostControl.dispatchEvent(new Event('selectionchange'));
+ deliverDelayedSnapshot({
+ selectionStart: 1,
+ selectionEnd: 1,
+ selectionDirection: 'none',
+ });
+
+ expect(remoteControl.selectionStart).toBe(4);
+ expect(remoteControl.selectionEnd).toBe(5);
+ expect(remoteControl.selectionDirection).toBe('backward');
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/forwardInputSelectionToHostWorkerReads.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/forwardInputSelectionToHostWorkerReads.test.ts
new file mode 100644
index 00000000000..4e588673012
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/forwardInputSelectionToHostWorkerReads.test.ts
@@ -0,0 +1,128 @@
+import '@/remote/generated/remote-elements';
+
+import { act } from 'react';
+
+import { applySerializedEventTargetProperties } from '@/remote/elements/utils/applySerializedEventTargetProperties';
+import { createRemoteTextControlRenderer } from '@/testing/createRemoteTextControlRenderer';
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('reading forwarded input selection in the worker', () => {
+ const { renderRemoteControl, unmountRenderedRemoteControls } =
+ createRemoteTextControlRenderer();
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ unmountRenderedRemoteControls();
+ });
+
+ it('should publish host and form event snapshots without echoing selection commands', () => {
+ const { connection, hostControl, remoteControl, scheduleBatch } =
+ renderRemoteControl({ htmlTag: 'textarea' });
+ const setHostSelection = jest.spyOn(hostControl, 'setSelectionRange');
+
+ hostControl.setSelectionRange(1, 5, 'backward');
+ hostControl.dispatchEvent(new Event('selectionchange'));
+
+ expect(remoteControl.selectionStart).toBe(1);
+ expect(remoteControl.selectionEnd).toBe(5);
+ expect(remoteControl.selectionDirection).toBe('backward');
+
+ setHostSelection.mockClear();
+ applySerializedEventTargetProperties({
+ element: remoteControl,
+ eventData: {
+ type: 'input',
+ selectionStart: 3,
+ selectionEnd: 4,
+ selectionDirection: 'forward',
+ },
+ });
+
+ expect(remoteControl.selectionStart).toBe(3);
+ expect(remoteControl.selectionEnd).toBe(4);
+ expect(remoteControl.selectionDirection).toBe('forward');
+ expect(scheduleBatch).not.toHaveBeenCalled();
+
+ act(() => connection.flush());
+
+ expect(setHostSelection).not.toHaveBeenCalled();
+ });
+
+ it('should read its own writes before the host acknowledges them', () => {
+ const { connection, hostControl, remoteControl } = renderRemoteControl({
+ htmlTag: 'input',
+ });
+
+ remoteControl.setSelectionRange(2, 4, 'backward');
+
+ expect(remoteControl.selectionStart).toBe(2);
+ expect(remoteControl.selectionEnd).toBe(4);
+ expect(remoteControl.selectionDirection).toBe('backward');
+
+ remoteControl.selectionStart = 5;
+
+ expect(remoteControl.selectionStart).toBe(5);
+ expect(remoteControl.selectionEnd).toBe(5);
+ expect(remoteControl.selectionDirection).toBe('backward');
+
+ remoteControl.setSelectionRange(3, 100);
+
+ expect(remoteControl.selectionStart).toBe(3);
+ expect(remoteControl.selectionEnd).toBe(7);
+ expect(remoteControl.selectionDirection).toBe('none');
+
+ remoteControl.select();
+
+ expect(remoteControl.selectionStart).toBe(0);
+ expect(remoteControl.selectionEnd).toBe(7);
+
+ act(() => connection.flush());
+
+ expect(hostControl.selectionStart).toBe(0);
+ expect(hostControl.selectionEnd).toBe(7);
+ expect(remoteControl.selectionStart).toBe(0);
+ expect(remoteControl.selectionEnd).toBe(7);
+ });
+
+ it('should keep an optimistic write when a stale event snapshot arrives', () => {
+ const { connection, hostControl, remoteControl, selectionStore } =
+ renderRemoteControl({ htmlTag: 'input' });
+
+ remoteControl.setSelectionRange(2, 4);
+ selectionStore.applySnapshot({
+ element: remoteControl,
+ state: { selectionStart: 6, selectionEnd: 6, selectionDirection: 'none' },
+ });
+
+ expect(remoteControl.selectionStart).toBe(2);
+ expect(remoteControl.selectionEnd).toBe(4);
+
+ act(() => connection.flush());
+ hostControl.setSelectionRange(6, 6);
+ hostControl.dispatchEvent(new Event('selectionchange'));
+
+ expect(remoteControl.selectionStart).toBe(6);
+ expect(remoteControl.selectionEnd).toBe(6);
+ });
+
+ it('should read its own writes on an input whose value is a number', () => {
+ const { remoteControl } = renderRemoteControl({
+ htmlTag: 'input',
+ shouldReadBeforeConnect: false,
+ });
+
+ (remoteControl as unknown as { value: unknown }).value = 1234567;
+
+ expect(remoteControl.selectionStart).toBe(7);
+ expect(remoteControl.selectionEnd).toBe(7);
+
+ remoteControl.setSelectionRange(1, 3, 'backward');
+
+ expect(remoteControl.selectionStart).toBe(1);
+ expect(remoteControl.selectionEnd).toBe(3);
+ expect(remoteControl.selectionDirection).toBe('backward');
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/installInputSelectionPolyfill.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/installInputSelectionPolyfill.test.ts
new file mode 100644
index 00000000000..65b834d5631
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/installInputSelectionPolyfill.test.ts
@@ -0,0 +1,25 @@
+import { createWorkerInputSelectionStore } from '../createWorkerInputSelectionStore';
+import { installInputSelectionPolyfill } from '../installInputSelectionPolyfill';
+
+describe('installInputSelectionPolyfill', () => {
+ it.each(['select', 'setSelectionRange'])(
+ 'should let an element override %s like a native method',
+ (methodName) => {
+ const elementPrototype = {};
+
+ installInputSelectionPolyfill({
+ elementPrototypes: [elementPrototype],
+ selectionStore: createWorkerInputSelectionStore(),
+ });
+
+ const element: Record<string, unknown> = Object.create(elementPrototype);
+ const overridingMethod = jest.fn();
+
+ expect(element[methodName]).toEqual(expect.any(Function));
+
+ element[methodName] = overridingMethod;
+
+ expect(element[methodName]).toBe(overridingMethod);
+ },
+ );
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/normalizeSelectionOffset.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/normalizeSelectionOffset.test.ts
new file mode 100644
index 00000000000..48cc66548fb
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/normalizeSelectionOffset.test.ts
@@ -0,0 +1,22 @@
+import { normalizeSelectionOffset } from '../normalizeSelectionOffset';
+
+describe('normalizeSelectionOffset', () => {
+ it.each([
+ [3, 3],
+ ['3', 3],
+ [2.9, 2],
+ [null, 0],
+ [undefined, 0],
+ [Number.NaN, 0],
+ [-1, 4294967295],
+ ])(
+ 'should convert %p to %p like an unsigned long',
+ (offset, expectedOffset) => {
+ expect(normalizeSelectionOffset(offset)).toBe(expectedOffset);
+ },
+ );
+
+ it('should reject a BigInt like the DOM does', () => {
+ expect(() => normalizeSelectionOffset(BigInt(1))).toThrow(TypeError);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/resolveOptimisticInputSelectionState.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/resolveOptimisticInputSelectionState.test.ts
new file mode 100644
index 00000000000..f6521bb858b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/resolveOptimisticInputSelectionState.test.ts
@@ -0,0 +1,35 @@
+import { resolveOptimisticInputSelectionState } from '../resolveOptimisticInputSelectionState';
+
+describe('resolveOptimisticInputSelectionState', () => {
+ it('should return the host state without replaying commands when the value is not text', () => {
+ expect(
+ resolveOptimisticInputSelectionState({
+ hostState: {
+ selectionStart: 1,
+ selectionEnd: 2,
+ selectionDirection: 'forward',
+ },
+ pendingCommands: [{ sequence: 1, request: { method: 'select' } }],
+ value: undefined,
+ }),
+ ).toEqual({
+ selectionStart: 1,
+ selectionEnd: 2,
+ selectionDirection: 'forward',
+ });
+ });
+
+ it('should collapse the selection at the start when neither the value nor the host state is known', () => {
+ expect(
+ resolveOptimisticInputSelectionState({
+ hostState: undefined,
+ pendingCommands: [],
+ value: undefined,
+ }),
+ ).toEqual({
+ selectionStart: 0,
+ selectionEnd: 0,
+ selectionDirection: 'none',
+ });
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/supportsInputSelectionRange.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/supportsInputSelectionRange.test.ts
new file mode 100644
index 00000000000..d24b128a7fb
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/supportsInputSelectionRange.test.ts
@@ -0,0 +1,25 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+
+import { supportsInputSelectionRange } from '../supportsInputSelectionRange';
+
+const createRemoteInput = (type: string): SelectorElementLike => ({
+ localName: 'html-input',
+ getAttribute: (attributeName: string) =>
+ attributeName === 'type' ? type : null,
+});
+
+describe('supportsInputSelectionRange', () => {
+ it.each(['text', 'search', 'url', 'tel', 'password'])(
+ 'should support the range API on an input of type %s',
+ (type) => {
+ expect(supportsInputSelectionRange(createRemoteInput(type))).toBe(true);
+ },
+ );
+
+ it.each(['email', 'number', 'checkbox', 'date'])(
+ 'should not support the range API on an input of type %s',
+ (type) => {
+ expect(supportsInputSelectionRange(createRemoteInput(type))).toBe(false);
+ },
+ );
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/applyInputSelectionRequestToRange.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/applyInputSelectionRequestToRange.ts
new file mode 100644
index 00000000000..3afa59bc46d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/applyInputSelectionRequestToRange.ts
@@ -0,0 +1,72 @@
+import { type InputSelectionRange } from '@/types/InputSelectionRange';
+import { type InputSelectionRequest } from '@/types/InputSelectionRequest';
+
+const resolveRequestedRange = ({
+ range,
+ request,
+ valueLength,
+}: {
+ range: InputSelectionRange;
+ request: InputSelectionRequest;
+ valueLength: number;
+}): InputSelectionRange => {
+ if ('method' in request && request.method === 'select') {
+ return {
+ selectionStart: 0,
+ selectionEnd: valueLength,
+ selectionDirection: 'none',
+ };
+ }
+
+ if ('method' in request) {
+ return {
+ selectionStart: request.start,
+ selectionEnd: request.end,
+ selectionDirection: request.direction,
+ };
+ }
+
+ if (request.property === 'selectionDirection') {
+ return { ...range, selectionDirection: request.value };
+ }
+
+ if (request.property === 'selectionEnd') {
+ return { ...range, selectionEnd: request.value };
+ }
+
+ return {
+ ...range,
+ selectionStart: request.value,
+ selectionEnd: Math.max(range.selectionEnd, request.value),
+ };
+};
+
+const clampInputSelectionRange = ({
+ range,
+ valueLength,
+}: {
+ range: InputSelectionRange;
+ valueLength: number;
+}): InputSelectionRange => {
+ const selectionEnd = Math.min(range.selectionEnd, valueLength);
+
+ return {
+ selectionStart: Math.min(range.selectionStart, selectionEnd),
+ selectionEnd,
+ selectionDirection: range.selectionDirection,
+ };
+};
+
+export const applyInputSelectionRequestToRange = ({
+ range,
+ request,
+ valueLength,
+}: {
+ range: InputSelectionRange;
+ request: InputSelectionRequest;
+ valueLength: number;
+}): InputSelectionRange =>
+ clampInputSelectionRange({
+ range: resolveRequestedRange({ range, request, valueLength }),
+ valueLength,
+ });
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
new file mode 100644
index 00000000000..9de7fcad9d5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createInputSelectionCommandQueue.ts
@@ -0,0 +1,104 @@
+import { updateRemoteElementProperty } from '@remote-dom/core/elements';
+import { isDefined } from 'twenty-shared/utils';
+
+import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';
+import { type InputSelectionCommand } from '@/types/InputSelectionCommand';
+import { type InputSelectionRequest } from '@/types/InputSelectionRequest';
+
+export const createInputSelectionCommandQueue = () => {
+ const pendingCommandsByElement = new WeakMap<
+ object,
+ InputSelectionCommand[]
+ >();
+
+ let lastCommandSequence = 0;
+
+ const sendPendingCommandsToHost = ({
+ element,
+ commands,
+ }: {
+ element: object;
+ commands: InputSelectionCommand[];
+ }): void => {
+ updateRemoteElementProperty(
+ element as Element,
+ INPUT_SELECTION_BRIDGE_PROPERTIES.request,
+ commands,
+ );
+ };
+
+ const updatePendingCommands = ({
+ element,
+ commands,
+ }: {
+ element: object;
+ commands: InputSelectionCommand[];
+ }): void => {
+ pendingCommandsByElement.set(element, commands);
+ sendPendingCommandsToHost({ element, commands });
+ };
+
+ const readPendingCommands = (element: object): InputSelectionCommand[] =>
+ pendingCommandsByElement.get(element) ?? [];
+
+ const enqueueCommand = ({
+ element,
+ request,
+ }: {
+ element: object;
+ request: InputSelectionRequest;
+ }): void => {
+ lastCommandSequence += 1;
+
+ updatePendingCommands({
+ element,
+ commands: [
+ ...readPendingCommands(element),
+ { sequence: lastCommandSequence, request },
+ ],
+ });
+ };
+
+ const acknowledgeCommands = ({
+ element,
+ acknowledgedCommandSequence,
+ }: {
+ element: object;
+ acknowledgedCommandSequence: number;
+ }): void => {
+ const pendingCommands = pendingCommandsByElement.get(element);
+
+ if (!isDefined(pendingCommands)) {
+ return;
+ }
+
+ const unacknowledgedCommands = pendingCommands.filter(
+ ({ sequence }) => sequence > acknowledgedCommandSequence,
+ );
+ const hasAcknowledgedAnyCommand =
+ unacknowledgedCommands.length < pendingCommands.length;
+
+ if (!hasAcknowledgedAnyCommand) {
+ return;
+ }
+
+ updatePendingCommands({ element, commands: unacknowledgedCommands });
+ };
+
+ const discardPendingCommands = (element: object): void => {
+ const hadPendingCommands = pendingCommandsByElement.delete(element);
+
+ if (!hadPendingCommands) {
+ return;
+ }
+
+ sendPendingCommandsToHost({ element, commands: [] });
+ };
+
+ return {
+ readPendingCommands,
+ enqueueCommand,
+ acknowledgeCommands,
+ discardPendingCommands,
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createUnsupportedInputSelectionError.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createUnsupportedInputSelectionError.ts
new file mode 100644
index 00000000000..bd5658e333c
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createUnsupportedInputSelectionError.ts
@@ -0,0 +1,11 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+import { createDomException } from '@/polyfills/utils/createDomException';
+
+export const createUnsupportedInputSelectionError = (
+ element: SelectorElementLike,
+): Error =>
+ createDomException(
+ `The input element's type ('${resolveInputTypeOfElement(element)}') does not support selection.`,
+ 'InvalidStateError',
+ );
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createWorkerInputSelectionStore.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createWorkerInputSelectionStore.ts
new file mode 100644
index 00000000000..8592d436320
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createWorkerInputSelectionStore.ts
@@ -0,0 +1,145 @@
+import { updateRemoteElementProperty } from '@remote-dom/core/elements';
+
+import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';
+import { isElementUnderRemoteRoot } from '@/polyfills/geometry/utils/isElementUnderRemoteRoot';
+import { type WorkerInputSelectionStore } from '@/polyfills/input-selection/types/WorkerInputSelectionStore';
+import { createInputSelectionCommandQueue } from '@/polyfills/input-selection/utils/createInputSelectionCommandQueue';
+import { resolveOptimisticInputSelectionState } from '@/polyfills/input-selection/utils/resolveOptimisticInputSelectionState';
+import { type InputSelectionRequest } from '@/types/InputSelectionRequest';
+import { type InputSelectionSnapshot } from '@/types/InputSelectionSnapshot';
+import { type InputSelectionState } from '@/types/InputSelectionState';
+
+export const createWorkerInputSelectionStore =
+ (): WorkerInputSelectionStore => {
+ const commandQueue = createInputSelectionCommandQueue();
+ const hostSelectionStates = new WeakMap<object, InputSelectionState>();
+ const hostSelectionSubscriptions = new WeakMap<
+ object,
+ (snapshot: InputSelectionSnapshot) => void
+ >();
+ const trackedElements = new Set<object>();
+
+ let rootElement: object | null = null;
+ let hasScheduledDetachedElementSweep = false;
+
+ const renewHostSelectionSubscription = (element: object): void => {
+ const handleSelectionUpdate = (snapshot: InputSelectionSnapshot) => {
+ const isLatestSubscription =
+ hostSelectionSubscriptions.get(element) === handleSelectionUpdate;
+
+ if (
+ !isLatestSubscription ||
+ !isElementUnderRemoteRoot(element, rootElement)
+ ) {
+ return;
+ }
+
+ hostSelectionStates.set(element, snapshot);
+ trackedElements.add(element);
+ commandQueue.acknowledgeCommands({
+ element,
+ acknowledgedCommandSequence: snapshot.selectionCommandSequence ?? 0,
+ });
+ };
+
+ hostSelectionSubscriptions.set(element, handleSelectionUpdate);
+ updateRemoteElementProperty(
+ element as Element,
+ INPUT_SELECTION_BRIDGE_PROPERTIES.update,
+ handleSelectionUpdate,
+ );
+ };
+
+ const subscribeToHostSelection = (element: object): boolean => {
+ if (!isElementUnderRemoteRoot(element, rootElement)) {
+ return false;
+ }
+
+ trackedElements.add(element);
+
+ if (!hostSelectionSubscriptions.has(element)) {
+ renewHostSelectionSubscription(element);
+ }
+
+ return true;
+ };
+
+ const forgetDetachedElement = (element: object): void => {
+ trackedElements.delete(element);
+ hostSelectionStates.delete(element);
+ commandQueue.discardPendingCommands(element);
+
+ if (hostSelectionSubscriptions.has(element)) {
+ renewHostSelectionSubscription(element);
+ }
+ };
+
+ const sweepDetachedElements = (): void => {
+ hasScheduledDetachedElementSweep = false;
+
+ for (const element of trackedElements) {
+ if (isElementUnderRemoteRoot(element, rootElement)) {
+ continue;
+ }
+
+ forgetDetachedElement(element);
+ }
+ };
+
+ const scheduleDetachedElementSweep = (): void => {
+ if (hasScheduledDetachedElementSweep || trackedElements.size === 0) {
+ return;
+ }
+
+ hasScheduledDetachedElementSweep = true;
+ queueMicrotask(sweepDetachedElements);
+ };
+
+ const applySnapshot = ({
+ element,
+ state,
+ }: {
+ element: object;
+ state: InputSelectionState;
+ }): void => {
+ hostSelectionStates.set(element, state);
+
+ if (isElementUnderRemoteRoot(element, rootElement)) {
+ trackedElements.add(element);
+ }
+ };
+
+ const readSelection = (element: object): InputSelectionState => {
+ subscribeToHostSelection(element);
+
+ return resolveOptimisticInputSelectionState({
+ hostState: hostSelectionStates.get(element),
+ pendingCommands: commandQueue.readPendingCommands(element),
+ value: (element as { value?: unknown }).value,
+ });
+ };
+
+ const requestSelection = ({
+ element,
+ request,
+ }: {
+ element: object;
+ request: InputSelectionRequest;
+ }): void => {
+ if (!subscribeToHostSelection(element)) {
+ return;
+ }
+
+ commandQueue.enqueueCommand({ element, request });
+ };
+
+ return {
+ setRootElement: (nextRootElement: object) => {
+ rootElement = nextRootElement;
+ },
+ applySnapshot,
+ scheduleDetachedElementSweep,
+ read: readSelection,
+ request: requestSelection,
+ };
+ };
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/defineInputSelectionPropertyAccessor.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/defineInputSelectionPropertyAccessor.ts
new file mode 100644
index 00000000000..3e0f53ea2d7
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/defineInputSelectionPropertyAccessor.ts
@@ -0,0 +1,39 @@
+import { type WorkerInputSelectionStore } from '@/polyfills/input-selection/types/WorkerInputSelectionStore';
+import { createUnsupportedInputSelectionError } from '@/polyfills/input-selection/utils/createUnsupportedInputSelectionError';
+import { supportsInputSelectionRange } from '@/polyfills/input-selection/utils/supportsInputSelectionRange';
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { type InputSelectionRequest } from '@/types/InputSelectionRequest';
+import { type InputSelectionState } from '@/types/InputSelectionState';
+
+export const defineInputSelectionPropertyAccessor = ({
+ elementPrototype,
+ propertyName,
+ selectionStore,
+ createSelectionRequest,
+}: {
+ elementPrototype: object;
+ propertyName: keyof InputSelectionState;
+ selectionStore: WorkerInputSelectionStore;
+ createSelectionRequest: (value: unknown) => InputSelectionRequest;
+}): void => {
+ Object.defineProperty(elementPrototype, propertyName, {
+ configurable: true,
+ get(this: SelectorElementLike) {
+ if (!supportsInputSelectionRange(this)) {
+ return null;
+ }
+
+ return selectionStore.read(this)[propertyName];
+ },
+ set(this: SelectorElementLike, value: unknown) {
+ if (!supportsInputSelectionRange(this)) {
+ throw createUnsupportedInputSelectionError(this);
+ }
+
+ selectionStore.request({
+ element: this,
+ request: createSelectionRequest(value),
+ });
+ },
+ });
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/installInputSelectionPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/installInputSelectionPolyfill.ts
new file mode 100644
index 00000000000..8a6512e9109
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/installInputSelectionPolyfill.ts
@@ -0,0 +1,80 @@
+import { type WorkerInputSelectionStore } from '@/polyfills/input-selection/types/WorkerInputSelectionStore';
+import { createUnsupportedInputSelectionError } from '@/polyfills/input-selection/utils/createUnsupportedInputSelectionError';
+import { defineInputSelectionPropertyAccessor } from '@/polyfills/input-selection/utils/defineInputSelectionPropertyAccessor';
+import { normalizeSelectionOffset } from '@/polyfills/input-selection/utils/normalizeSelectionOffset';
+import { supportsInputSelectionRange } from '@/polyfills/input-selection/utils/supportsInputSelectionRange';
+import { supportsInputSelectMethod } from '@/polyfills/input-selection/utils/supportsInputSelectMethod';
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { definePolyfillMethod } from '@/polyfills/utils/definePolyfillMethod';
+import { normalizeInputSelectionDirection } from '@/utils/normalizeInputSelectionDirection';
+
+const SELECTION_OFFSET_PROPERTIES = ['selectionStart', 'selectionEnd'] as const;
+
+export const installInputSelectionPolyfill = ({
+ elementPrototypes,
+ selectionStore,
+}: {
+ elementPrototypes: object[];
+ selectionStore: WorkerInputSelectionStore;
+}): void => {
+ for (const elementPrototype of elementPrototypes) {
+ for (const property of SELECTION_OFFSET_PROPERTIES) {
+ defineInputSelectionPropertyAccessor({
+ elementPrototype,
+ propertyName: property,
+ selectionStore,
+ createSelectionRequest: (value) => ({
+ property,
+ value: normalizeSelectionOffset(value),
+ }),
+ });
+ }
+
+ defineInputSelectionPropertyAccessor({
+ elementPrototype,
+ propertyName: 'selectionDirection',
+ selectionStore,
+ createSelectionRequest: (value) => ({
+ property: 'selectionDirection',
+ value: normalizeInputSelectionDirection(value),
+ }),
+ });
+
+ definePolyfillMethod({
+ target: elementPrototype,
+ methodName: 'select',
+ method: (element: SelectorElementLike): void => {
+ if (!supportsInputSelectMethod(element)) {
+ return;
+ }
+
+ selectionStore.request({ element, request: { method: 'select' } });
+ },
+ });
+
+ definePolyfillMethod({
+ target: elementPrototype,
+ methodName: 'setSelectionRange',
+ method: (
+ element: SelectorElementLike,
+ start: unknown,
+ end: unknown,
+ direction?: unknown,
+ ): void => {
+ if (!supportsInputSelectionRange(element)) {
+ throw createUnsupportedInputSelectionError(element);
+ }
+
+ selectionStore.request({
+ element,
+ request: {
+ method: 'setSelectionRange',
+ start: normalizeSelectionOffset(start),
+ end: normalizeSelectionOffset(end),
+ direction: normalizeInputSelectionDirection(direction),
+ },
+ });
+ },
+ });
+ }
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/normalizeSelectionOffset.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/normalizeSelectionOffset.ts
new file mode 100644
index 00000000000..b8e94f4e42b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/normalizeSelectionOffset.ts
@@ -0,0 +1,9 @@
+import { isBigInt } from '@sniptt/guards';
+
+export const normalizeSelectionOffset = (offset: unknown): number => {
+ if (isBigInt(offset)) {
+ throw new TypeError('Cannot convert a BigInt value to a number');
+ }
+
+ return Number(offset) >>> 0;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/resolveOptimisticInputSelectionState.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/resolveOptimisticInputSelectionState.ts
new file mode 100644
index 00000000000..8fbc6a2a85f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/resolveOptimisticInputSelectionState.ts
@@ -0,0 +1,44 @@
+import { isNumber, isString } from '@sniptt/guards';
+
+import { applyInputSelectionRequestToRange } from '@/polyfills/input-selection/utils/applyInputSelectionRequestToRange';
+import { type InputSelectionCommand } from '@/types/InputSelectionCommand';
+import { type InputSelectionRange } from '@/types/InputSelectionRange';
+import { type InputSelectionState } from '@/types/InputSelectionState';
+
+const UNKNOWN_VALUE_INPUT_SELECTION_STATE: InputSelectionState = {
+ selectionStart: 0,
+ selectionEnd: 0,
+ selectionDirection: 'none',
+};
+
+export const resolveOptimisticInputSelectionState = ({
+ hostState,
+ pendingCommands,
+ value,
+}: {
+ hostState: InputSelectionState | undefined;
+ pendingCommands: InputSelectionCommand[];
+ value: unknown;
+}): InputSelectionState => {
+ const valueText = isNumber(value) ? String(value) : value;
+
+ if (!isString(valueText)) {
+ return hostState ?? UNKNOWN_VALUE_INPUT_SELECTION_STATE;
+ }
+
+ let range: InputSelectionRange = {
+ selectionStart: hostState?.selectionStart ?? valueText.length,
+ selectionEnd: hostState?.selectionEnd ?? valueText.length,
+ selectionDirection: hostState?.selectionDirection ?? 'none',
+ };
+
+ for (const { request } of pendingCommands) {
+ range = applyInputSelectionRequestToRange({
+ range,
+ request,
+ valueLength: valueText.length,
+ });
+ }
+
+ return range;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/supportsInputSelectMethod.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/supportsInputSelectMethod.ts
new file mode 100644
index 00000000000..97ff39f5547
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/supportsInputSelectMethod.ts
@@ -0,0 +1,10 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+import { isTextLikeInputType } from '@/utils/isTextLikeInputType';
+
+export const supportsInputSelectMethod = (
+ element: SelectorElementLike,
+): boolean =>
+ resolveHtmlTagNameOfElement(element) === 'textarea' ||
+ isTextLikeInputType(resolveInputTypeOfElement(element));
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/supportsInputSelectionRange.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/supportsInputSelectionRange.ts
new file mode 100644
index 00000000000..f6770c7c308
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/supportsInputSelectionRange.ts
@@ -0,0 +1,20 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+import { resolveInputTypeState } from '@/utils/resolveInputTypeState';
+
+const SELECTION_RANGE_INPUT_TYPES = new Set([
+ 'text',
+ 'search',
+ 'url',
+ 'tel',
+ 'password',
+]);
+
+export const supportsInputSelectionRange = (
+ element: SelectorElementLike,
+): boolean =>
+ resolveHtmlTagNameOfElement(element) === 'textarea' ||
+ SELECTION_RANGE_INPUT_TYPES.has(
+ resolveInputTypeState(resolveInputTypeOfElement(element)),
+ );
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/constants/SerializedEventPropertyKeys.ts b/packages/twenty-front-component-renderer/src/remote/elements/constants/SerializedEventPropertyKeys.ts
index bac10e969f2..d8aa3a90598 100644
--- a/packages/twenty-front-component-renderer/src/remote/elements/constants/SerializedEventPropertyKeys.ts
+++ b/packages/twenty-front-component-renderer/src/remote/elements/constants/SerializedEventPropertyKeys.ts
@@ -32,6 +32,9 @@ export const SERIALIZED_EVENT_PROPERTY_KEYS = [
'isPrimary',
'key',
'code',
+ 'which',
+ 'keyCode',
+ 'isComposing',
'repeat',
'inputType',
'data',
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/createWorkerEventFromSerializedEvent.test.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/createWorkerEventFromSerializedEvent.test.ts
index 6461ae690b8..7e9d8700988 100644
--- a/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/createWorkerEventFromSerializedEvent.test.ts
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/createWorkerEventFromSerializedEvent.test.ts
@@ -3,6 +3,7 @@ import '@/remote/generated/remote-elements';
import { remoteId } from '@remote-dom/core/elements';
import { Window } from '@remote-dom/polyfill';
+import { serializeEvent } from '@/host/events/utils/serializeEvent';
import { installEventConstructorPolyfills } from '@/polyfills/events/utils/installEventConstructorPolyfills';
import { installHostEventRetargetingPolyfill } from '@/polyfills/events/utils/installHostEventRetargetingPolyfill';
import { isHostOriginatedEvent } from '@/polyfills/events/utils/isHostOriginatedEvent';
@@ -109,6 +110,49 @@ describe('createWorkerEventFromSerializedEvent', () => {
expect(isHostOriginatedEvent(event)).toBe(true);
});
+ it('should preserve the IME confirmation guard through host serialization and worker dispatch', () => {
+ const listeningElement = createListeningElement();
+ const confirmedValues: string[] = [];
+ const composingStates: boolean[] = [];
+ const keyboardCodes: number[] = [];
+
+ listeningElement.addEventListener('keydown', (event) => {
+ composingStates.push(event.isComposing);
+ keyboardCodes.push(event.keyCode);
+
+ if (event.which === 229) {
+ return;
+ }
+
+ if (event.key === 'Enter') {
+ confirmedValues.push('selected');
+ }
+ });
+
+ for (const keyboardState of [
+ { keyCode: 229, which: 229, isComposing: true },
+ { keyCode: 13, which: 13, isComposing: false },
+ ]) {
+ const event = createWorkerEventFromSerializedEvent({
+ listeningElement,
+ eventType: 'keydown',
+ eventData: serializeEvent({
+ type: 'keydown',
+ key: 'Enter',
+ keyCode: keyboardState.keyCode,
+ which: keyboardState.which,
+ nativeEvent: { isComposing: keyboardState.isComposing },
+ }),
+ });
+
+ listeningElement.dispatchEvent(event);
+ }
+
+ expect(confirmedValues).toEqual(['selected']);
+ expect(composingStates).toEqual([true, false]);
+ expect(keyboardCodes).toEqual([229, 13]);
+ });
+
it.each([
['keydown', KeyboardEvent, { key: 'Escape' }],
['beforeinput', InputEvent, { inputType: 'insertText', data: 'a' }],
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 8c8f04da484..5a535f8eec5 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
@@ -3,6 +3,8 @@ import { isDefined } from 'twenty-shared/utils';
import { SERIALIZED_EVENT_TARGET_PROPERTY_KEYS } from '@/remote/elements/constants/SerializedEventTargetPropertyKeys';
import { applySelectedOptionIndexes } from '@/remote/elements/utils/applySelectedOptionIndexes';
import { uncheckOtherRadioButtons } from '@/remote/elements/utils/uncheckOtherRadioButtons';
+import { workerInputSelectionStore } from '@/polyfills/input-selection/states/workerInputSelectionStore';
+import { readInputSelectionState } from '@/utils/readInputSelectionState';
import { type SerializedEventData } from '@/types/SerializedEventData';
export const applySerializedEventTargetProperties = ({
@@ -18,6 +20,11 @@ export const applySerializedEventTargetProperties = ({
}
}
+ const selectionState = readInputSelectionState(eventData);
+ if (isDefined(selectionState)) {
+ workerInputSelectionStore.applySnapshot({ element, state: selectionState });
+ }
+
if (eventData.checked) {
uncheckOtherRadioButtons(element);
}
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts
index 070f838dcf2..74c1ba5dcbe 100644
--- a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts
+++ b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts
@@ -1,7 +1,10 @@
import '@remote-dom/core/polyfill';
import '@remote-dom/react/polyfill';
-import { HtmlInputElement } from '../generated/remote-elements';
+import {
+ HtmlInputElement,
+ HtmlTextareaElement,
+} from '../generated/remote-elements';
import { ThreadMessagePort } from '@quilted/threads';
@@ -12,6 +15,9 @@ import { HTML_TAG_TO_CUSTOM_ELEMENT_TAG } from '@/constants/HtmlTagToCustomEleme
import { installClipboardPolyfill } from '@/polyfills/clipboard/utils/installClipboardPolyfill';
import { installImageLoadingPolyfill } from '@/polyfills/image/utils/installImageLoadingPolyfill';
import { workerActiveElementStore } from '@/polyfills/dom/states/workerActiveElementStore';
+import { installTextTreeWalkerPolyfill } from '@/polyfills/dom/utils/installTextTreeWalkerPolyfill';
+import { installInputSelectionPolyfill } from '@/polyfills/input-selection/utils/installInputSelectionPolyfill';
+import { workerInputSelectionStore } from '@/polyfills/input-selection/states/workerInputSelectionStore';
import { workerFocusTransport } from '@/polyfills/dom/states/workerFocusTransport';
import { installActiveElementDetachmentHook } from '@/polyfills/dom/utils/installActiveElementDetachmentHook';
import { installClassAttributeAccessors } from '@/polyfills/dom/utils/installClassAttributeAccessors';
@@ -65,6 +71,14 @@ patchRemoteElementAttributes();
installAriaBooleanPropertyAccessors();
installErrorEventBridge();
+installTextTreeWalkerPolyfill({ globalScope: toGlobalScopeRecord(globalThis) });
+installInputSelectionPolyfill({
+ elementPrototypes: [
+ HtmlInputElement.prototype,
+ HtmlTextareaElement.prototype,
+ ],
+ selectionStore: workerInputSelectionStore,
+});
installDocumentGetElementById(document);
installGetElementsByClassName(Element.prototype);
installGetElementsByClassName(document);
@@ -106,7 +120,10 @@ installActiveElementDetachmentHook({
resolveGlobalScopeInstallTargets(toGlobalScopeRecord(globalThis)),
),
activeElementStore: workerActiveElementStore,
- onRemoveSubtree: workerFocusTransport.blurFocusedElementWithinSubtree,
+ onRemoveSubtree: (node) => {
+ workerFocusTransport.blurFocusedElementWithinSubtree(node);
+ workerInputSelectionStore.scheduleDetachedElementSweep();
+ },
});
installHostEventRetargetingPolyfill(HTMLElement.prototype);
installElementClickMethodPolyfill(HTMLElement.prototype);
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/attachRemoteRenderRootToWorkerDocument.ts b/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/attachRemoteRenderRootToWorkerDocument.ts
index 7e73413b619..4d1050e62a7 100644
--- a/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/attachRemoteRenderRootToWorkerDocument.ts
+++ b/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/attachRemoteRenderRootToWorkerDocument.ts
@@ -5,6 +5,7 @@ import {
} from '@remote-dom/core/elements';
import { workerGeometryStore } from '@/polyfills/geometry/states/workerGeometryStore';
+import { workerInputSelectionStore } from '@/polyfills/input-selection/states/workerInputSelectionStore';
import { workerFocusTransport } from '@/polyfills/dom/states/workerFocusTransport';
import { installStyleBridge } from '@/polyfills/style/utils/installStyleBridge';
@@ -20,6 +21,7 @@ export const attachRemoteRenderRootToWorkerDocument = (
document.body.append(remoteRoot);
workerGeometryStore.setRootElement(remoteRoot);
workerFocusTransport.setRootElement(remoteRoot);
+ workerInputSelectionStore.setRootElement(remoteRoot);
installStyleBridge(remoteRoot);
return renderContainer;
diff --git a/packages/twenty-front-component-renderer/src/testing/createRemoteTextControlRenderer.tsx b/packages/twenty-front-component-renderer/src/testing/createRemoteTextControlRenderer.tsx
new file mode 100644
index 00000000000..b04927c23c6
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/testing/createRemoteTextControlRenderer.tsx
@@ -0,0 +1,136 @@
+import '@/remote/generated/remote-elements';
+
+import {
+ BatchingRemoteConnection,
+ RemoteMutationObserver,
+ type RemoteRootElement,
+} from '@remote-dom/core/elements';
+import { RemoteReceiver } from '@remote-dom/core/receivers';
+import {
+ createRemoteComponentRenderer,
+ RemoteRootRenderer,
+} from '@remote-dom/react/host';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { isDefined } from 'twenty-shared/utils';
+
+import { createHtmlHostWrapper } from '@/host/elements/utils/createHtmlHostWrapper';
+import { workerInputSelectionStore } from '@/polyfills/input-selection/states/workerInputSelectionStore';
+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';
+
+export const createRemoteTextControlRenderer = () => {
+ const mountedRoots: Root[] = [];
+ const appendedElements: Element[] = [];
+ const remoteMutationObservers: RemoteMutationObserver[] = [];
+
+ const renderRemoteControl = ({
+ htmlTag,
+ type,
+ selectionStore = workerInputSelectionStore,
+ shouldReadBeforeConnect = true,
+ }: {
+ htmlTag: 'input' | 'textarea';
+ type?: string;
+ selectionStore?: WorkerInputSelectionStore;
+ shouldReadBeforeConnect?: boolean;
+ }) => {
+ const container = document.createElement('div');
+ const remoteRoot = document.createElement(
+ 'remote-root',
+ ) as RemoteRootElement;
+ const remoteControl = document.createElement(
+ `html-${htmlTag}`,
+ ) as unknown as CaretPreservingElement;
+ const remoteSibling = document.createElement(
+ 'html-div',
+ ) as unknown as HTMLElement;
+ const root = createRoot(container);
+ const receiver = new RemoteReceiver();
+ const scheduleBatch = jest.fn();
+ const connection = new BatchingRemoteConnection(receiver.connection, {
+ batch: scheduleBatch,
+ });
+ const remoteMutationObserver = new RemoteMutationObserver(connection);
+
+ document.body.append(container, remoteRoot);
+ mountedRoots.push(root);
+ appendedElements.push(container, remoteRoot);
+ remoteMutationObservers.push(remoteMutationObserver);
+
+ if (isDefined(type)) {
+ remoteControl.setAttribute('type', type);
+ }
+
+ remoteControl.value = 'initial';
+ remoteControl.addEventListener('change', jest.fn());
+ remoteRoot.append(remoteControl, remoteSibling);
+ selectionStore.setRootElement(remoteRoot);
+ installInputSelectionPolyfill({
+ elementPrototypes: [remoteControl],
+ selectionStore,
+ });
+
+ if (shouldReadBeforeConnect) {
+ selectionStore.read(remoteControl);
+ }
+
+ remoteRoot.connect(connection);
+ remoteMutationObserver.observe(remoteRoot, { initial: false });
+
+ act(() => {
+ connection.flush();
+ root.render(
+ <RemoteRootRenderer
+ receiver={receiver}
+ components={
+ new Map([
+ [
+ `html-${htmlTag}`,
+ createRemoteComponentRenderer(createHtmlHostWrapper(htmlTag)),
+ ],
+ [
+ 'html-div',
+ createRemoteComponentRenderer(createHtmlHostWrapper('div')),
+ ],
+ ])
+ }
+ />,
+ );
+ });
+
+ const hostControl = container.querySelector(
+ htmlTag,
+ ) as CaretPreservingElement;
+
+ scheduleBatch.mockClear();
+
+ return {
+ container,
+ connection,
+ hostControl,
+ remoteControl,
+ remoteRoot,
+ remoteSibling,
+ scheduleBatch,
+ selectionStore,
+ };
+ };
+
+ const unmountRenderedRemoteControls = (): void => {
+ for (const remoteMutationObserver of remoteMutationObservers.splice(0)) {
+ remoteMutationObserver.disconnect();
+ }
+
+ for (const root of mountedRoots.splice(0)) {
+ act(() => root.unmount());
+ }
+
+ for (const appendedElement of appendedElements.splice(0)) {
+ appendedElement.remove();
+ }
+ };
+
+ return { renderRemoteControl, unmountRenderedRemoteControls };
+};
diff --git a/packages/twenty-front-component-renderer/src/testing/readRemoteSelectionCommands.ts b/packages/twenty-front-component-renderer/src/testing/readRemoteSelectionCommands.ts
new file mode 100644
index 00000000000..1b036cee516
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/testing/readRemoteSelectionCommands.ts
@@ -0,0 +1,11 @@
+import { type RemoteElementSerialization } from '@remote-dom/core';
+import { serializeRemoteNode } from '@remote-dom/core/elements';
+
+import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';
+import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
+
+export const readRemoteSelectionCommands = (
+ remoteControl: CaretPreservingElement,
+) =>
+ (serializeRemoteNode(remoteControl) as RemoteElementSerialization)
+ .properties?.[INPUT_SELECTION_BRIDGE_PROPERTIES.request];
diff --git a/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts b/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts
new file mode 100644
index 00000000000..96eca4f5d6e
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts
@@ -0,0 +1,6 @@
+import { type InputSelectionRequest } from '@/types/InputSelectionRequest';
+
+export type InputSelectionCommand = {
+ sequence: number;
+ request: InputSelectionRequest;
+};
diff --git a/packages/twenty-front-component-renderer/src/types/InputSelectionDirection.ts b/packages/twenty-front-component-renderer/src/types/InputSelectionDirection.ts
new file mode 100644
index 00000000000..e859971f78d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/InputSelectionDirection.ts
@@ -0,0 +1 @@
+export type InputSelectionDirection = 'forward' | 'backward' | 'none';
diff --git a/packages/twenty-front-component-renderer/src/types/InputSelectionRange.ts b/packages/twenty-front-component-renderer/src/types/InputSelectionRange.ts
new file mode 100644
index 00000000000..5a7e3e10d6a
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/InputSelectionRange.ts
@@ -0,0 +1,7 @@
+import { type InputSelectionDirection } from '@/types/InputSelectionDirection';
+
+export type InputSelectionRange = {
+ selectionStart: number;
+ selectionEnd: number;
+ selectionDirection: InputSelectionDirection;
+};
diff --git a/packages/twenty-front-component-renderer/src/types/InputSelectionRequest.ts b/packages/twenty-front-component-renderer/src/types/InputSelectionRequest.ts
new file mode 100644
index 00000000000..3346a5137d5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/InputSelectionRequest.ts
@@ -0,0 +1,12 @@
+import { type InputSelectionDirection } from '@/types/InputSelectionDirection';
+
+export type InputSelectionRequest =
+ | { method: 'select' }
+ | {
+ method: 'setSelectionRange';
+ start: number;
+ end: number;
+ direction: InputSelectionDirection;
+ }
+ | { property: 'selectionStart' | 'selectionEnd'; value: number }
+ | { property: 'selectionDirection'; value: InputSelectionDirection };
diff --git a/packages/twenty-front-component-renderer/src/types/InputSelectionSnapshot.ts b/packages/twenty-front-component-renderer/src/types/InputSelectionSnapshot.ts
new file mode 100644
index 00000000000..d2d982c91f5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/InputSelectionSnapshot.ts
@@ -0,0 +1,5 @@
+import { type InputSelectionState } from '@/types/InputSelectionState';
+
+export type InputSelectionSnapshot = InputSelectionState & {
+ selectionCommandSequence?: number;
+};
diff --git a/packages/twenty-front-component-renderer/src/types/InputSelectionState.ts b/packages/twenty-front-component-renderer/src/types/InputSelectionState.ts
new file mode 100644
index 00000000000..661d4eadf0f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/InputSelectionState.ts
@@ -0,0 +1,7 @@
+import { type InputSelectionDirection } from '@/types/InputSelectionDirection';
+
+export type InputSelectionState = {
+ selectionStart: number | null;
+ selectionEnd: number | null;
+ selectionDirection: InputSelectionDirection | null;
+};
diff --git a/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts b/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts
index d4493d6a2bc..e05f641e8cf 100644
--- a/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts
+++ b/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts
@@ -1,3 +1,4 @@
+import { type InputSelectionDirection } from '@/types/InputSelectionDirection';
import { type SerializedFileData } from '@/types/SerializedFileData';
export type SerializedEventData = {
@@ -36,11 +37,17 @@ export type SerializedEventData = {
isPrimary?: boolean;
key?: string;
code?: string;
+ which?: number;
+ keyCode?: number;
+ isComposing?: boolean;
repeat?: boolean;
inputType?: string;
data?: string;
clipboardText?: string;
value?: string;
+ selectionStart?: number;
+ selectionEnd?: number;
+ selectionDirection?: InputSelectionDirection;
checked?: boolean;
selectedOptionIndexes?: number[];
scrollTop?: number;
diff --git a/packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/isTextLikeInputType.test.ts b/packages/twenty-front-component-renderer/src/utils/__tests__/isTextLikeInputType.test.ts
similarity index 100%
rename from packages/twenty-front-component-renderer/src/host/caret/utils/__tests__/isTextLikeInputType.test.ts
rename to packages/twenty-front-component-renderer/src/utils/__tests__/isTextLikeInputType.test.ts
diff --git a/packages/twenty-front-component-renderer/src/utils/__tests__/resolveInputTypeState.test.ts b/packages/twenty-front-component-renderer/src/utils/__tests__/resolveInputTypeState.test.ts
new file mode 100644
index 00000000000..513e53df2cb
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/utils/__tests__/resolveInputTypeState.test.ts
@@ -0,0 +1,18 @@
+import { resolveInputTypeState } from '../resolveInputTypeState';
+
+describe('resolveInputTypeState', () => {
+ it.each([
+ ['checkbox', 'checkbox'],
+ ['EMAIL', 'email'],
+ ['datetime-local', 'datetime-local'],
+ ])('should keep the known type %s as %s', (type, expectedState) => {
+ expect(resolveInputTypeState(type)).toBe(expectedState);
+ });
+
+ it.each([undefined, null, '', 'datetime', 'bogus', 3])(
+ 'should fall back to text for %p',
+ (type) => {
+ expect(resolveInputTypeState(type)).toBe('text');
+ },
+ );
+});
diff --git a/packages/twenty-front-component-renderer/src/utils/isInputSelectionDirection.ts b/packages/twenty-front-component-renderer/src/utils/isInputSelectionDirection.ts
new file mode 100644
index 00000000000..8b40f1d23fa
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/utils/isInputSelectionDirection.ts
@@ -0,0 +1,11 @@
+import { type InputSelectionDirection } from '@/types/InputSelectionDirection';
+
+const INPUT_SELECTION_DIRECTIONS = new Set<unknown>([
+ 'forward',
+ 'backward',
+ 'none',
+]);
+
+export const isInputSelectionDirection = (
+ value: unknown,
+): value is InputSelectionDirection => INPUT_SELECTION_DIRECTIONS.has(value);
diff --git a/packages/twenty-front-component-renderer/src/utils/isTextLikeInputType.ts b/packages/twenty-front-component-renderer/src/utils/isTextLikeInputType.ts
new file mode 100644
index 00000000000..1d75c0ac248
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/utils/isTextLikeInputType.ts
@@ -0,0 +1,14 @@
+import { resolveInputTypeState } from '@/utils/resolveInputTypeState';
+
+const TEXT_LIKE_INPUT_TYPES = new Set([
+ 'text',
+ 'search',
+ 'url',
+ 'tel',
+ 'password',
+ 'email',
+ 'number',
+]);
+
+export const isTextLikeInputType = (type: unknown): boolean =>
+ TEXT_LIKE_INPUT_TYPES.has(resolveInputTypeState(type));
diff --git a/packages/twenty-front-component-renderer/src/utils/normalizeInputSelectionDirection.ts b/packages/twenty-front-component-renderer/src/utils/normalizeInputSelectionDirection.ts
new file mode 100644
index 00000000000..132d5d72354
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/utils/normalizeInputSelectionDirection.ts
@@ -0,0 +1,7 @@
+import { type InputSelectionDirection } from '@/types/InputSelectionDirection';
+import { isInputSelectionDirection } from '@/utils/isInputSelectionDirection';
+
+export const normalizeInputSelectionDirection = (
+ direction: unknown,
+): InputSelectionDirection =>
+ isInputSelectionDirection(direction) ? direction : 'none';
diff --git a/packages/twenty-front-component-renderer/src/utils/readInputSelectionState.ts b/packages/twenty-front-component-renderer/src/utils/readInputSelectionState.ts
new file mode 100644
index 00000000000..6963e977fa2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/utils/readInputSelectionState.ts
@@ -0,0 +1,25 @@
+import { isNumber } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { type InputSelectionRange } from '@/types/InputSelectionRange';
+import { isInputSelectionDirection } from '@/utils/isInputSelectionDirection';
+
+export const readInputSelectionState = (
+ target: unknown,
+): InputSelectionRange | undefined => {
+ if (!isPlainObject(target)) {
+ return undefined;
+ }
+
+ const { selectionStart, selectionEnd, selectionDirection } = target;
+
+ if (
+ !isNumber(selectionStart) ||
+ !isNumber(selectionEnd) ||
+ !isInputSelectionDirection(selectionDirection)
+ ) {
+ return undefined;
+ }
+
+ return { selectionStart, selectionEnd, selectionDirection };
+};
diff --git a/packages/twenty-front-component-renderer/src/utils/resolveInputTypeState.ts b/packages/twenty-front-component-renderer/src/utils/resolveInputTypeState.ts
new file mode 100644
index 00000000000..8d02f098ad4
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/utils/resolveInputTypeState.ts
@@ -0,0 +1,32 @@
+import { isString } from '@sniptt/guards';
+
+const INPUT_TYPE_KEYWORDS = new Set([
+ 'button',
+ 'checkbox',
+ 'color',
+ 'date',
+ 'datetime-local',
+ 'email',
+ 'file',
+ 'hidden',
+ 'image',
+ 'month',
+ 'number',
+ 'password',
+ 'radio',
+ 'range',
+ 'reset',
+ 'search',
+ 'submit',
+ 'tel',
+ 'text',
+ 'time',
+ 'url',
+ 'week',
+]);
+
+export const resolveInputTypeState = (type: unknown): string => {
+ const lowerCasedType = isString(type) ? type.toLowerCase() : '';
+
+ return INPUT_TYPE_KEYWORDS.has(lowerCasedType) ? lowerCasedType : 'text';
+};