Skip to content

The open alternative to Salesforce, designed for AI.

Support form state and focus in front components (#26519)

Raphaël Bosieddab6c92471
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
index a4ad8dc9122..c77502aaf05 100644
--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
@@ -936,9 +936,10 @@ A `ref` gives you a sandbox element, not an `HTMLElement`.
| What you write | What happens | Use instead |
|----------------|--------------|-------------|
-| `ref.current.focus()`, `.click()`, `.select()`, `.setSelectionRange()`, `.scrollIntoView()`, `video.play()` | Throws | Controlled components; read values from `event.target` |
-| `document.createTreeWalker()` | Throws | `querySelector()` / `querySelectorAll()`, `matches()`, `closest()` (including pseudo-classes such as `:not()`), `getElementById()`, `contains()` and `compareDocumentPosition()` work; `getElementsByClassName()` works too, but returns a static collection, not a live `HTMLCollection` |
-| `document.activeElement` | Always `undefined` | Track focus with `onFocus` / `onBlur` |
+| `ref.current.focus()`, `.blur()` | Forward to the corresponding element on the page and update the sandbox's active element | `onFocus` / `onBlur` to observe focus changes |
+| `ref.current.click()`, `.select()`, `.setSelectionRange()`, `.scrollIntoView()`, `video.play()` | Throws | Controlled components; read values from `event.target` |
+| `document.createTreeWalker()` | Throws | `querySelector()` / `querySelectorAll()`, `matches()`, `closest()` (including pseudo-classes such as `:disabled` and `:not()`), `getElementById()`, `contains()` and `compareDocumentPosition()` work; `getElementsByClassName()` works too, but returns a static collection, not a live `HTMLCollection` |
+| `document.activeElement` | Follows the page's focus inside the component and updates when sandbox code calls `focus()` or `blur()` | `onFocus` / `onBlur` to react to the page's focus |
| `canvas` | Renders nothing, no error | SVG, or draw offscreen and show the result in an `img` element |
| `createPortal(node, document.body)` | Renders nothing, while `isConnected` reports success | Overlays inline with `position: absolute`, or pass the library your own container element |
diff --git a/packages/twenty-front-component-renderer/scripts/remote-dom/generators/remote-elements.generator.ts b/packages/twenty-front-component-renderer/scripts/remote-dom/generators/remote-elements.generator.ts
index b729770ae17..f567221c6d8 100644
--- a/packages/twenty-front-component-renderer/scripts/remote-dom/generators/remote-elements.generator.ts
+++ b/packages/twenty-front-component-renderer/scripts/remote-dom/generators/remote-elements.generator.ts
@@ -67,10 +67,13 @@ const generateCommonPropertiesType = (
});
};
-const generateCommonEventsType = (
- sourceFile: SourceFile,
- events: readonly string[],
-): void => {
+const generateCommonEventsType = ({
+ sourceFile,
+ events,
+}: {
+ sourceFile: SourceFile;
+ events: readonly string[];
+}): void => {
if (events.length === 0) {
return;
}
@@ -122,12 +125,14 @@ const generateCommonEventsType = (
'dispatchEvent(this: Element, eventData: SerializedEventData) {',
);
writer.indent(() => {
- writer.writeLine('applySerializedEventTargetProperties(');
+ writer.writeLine('applySerializedEventTargetProperties({');
writer.indent(() => {
- writer.writeLine('this as unknown as Record<string, unknown>,');
+ writer.writeLine(
+ 'element: this as unknown as Record<string, unknown>,',
+ );
writer.writeLine('eventData,');
});
- writer.writeLine(');');
+ writer.writeLine('});');
writer.blankLine();
writer.writeLine('const event = new CustomEvent(eventType, {');
writer.indent(() => {
@@ -431,7 +436,7 @@ export const generateRemoteElements = (
generateCommonPropertiesType(sourceFile, commonProperties);
if (commonEventNames.size > 0) {
- generateCommonEventsType(sourceFile, commonEvents);
+ generateCommonEventsType({ sourceFile, events: commonEvents });
}
if (shouldUseCommonHtmlPropertiesConfig) {
diff --git a/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx
index c1e0f3064e1..72e3aa6fdbe 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx
@@ -238,6 +238,51 @@ type CreateStoryInput = {
args?: Partial<Story['args']>;
};
+const focusTrackingTest: Story['play'] = async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ const firstTab = await canvas.findByTestId(
+ 'focus-tracking-first-tab',
+ {},
+ { timeout: MOUNT_TIMEOUT },
+ );
+ const secondTab = canvas.getByTestId('focus-tracking-second-tab');
+ const status = canvas.getByTestId('focus-tracking-status');
+
+ await userEvent.click(firstTab);
+
+ await waitFor(
+ () => {
+ expect(status).toHaveAttribute('data-active-element', 'first-tab');
+ expect(status).toHaveAttribute(
+ 'data-focus-handler-active-element',
+ 'first-tab',
+ );
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
+
+ await userEvent.click(secondTab);
+
+ await waitFor(
+ () => {
+ expect(status).toHaveAttribute('data-active-element', 'second-tab');
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
+
+ secondTab.blur();
+
+ await waitFor(
+ () => {
+ expect(status).toHaveAttribute('data-active-element', 'none');
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
+
+ expect(errorHandler).not.toHaveBeenCalled();
+};
+
const createStory = ({
name,
play,
@@ -375,3 +420,13 @@ export const MatchMediaColorSchemeChange: Story = {
expect(errorHandler).not.toHaveBeenCalled();
},
};
+
+export const FocusTrackingReact: Story = createStory({
+ name: 'focus-tracking-example',
+ play: focusTrackingTest,
+});
+export const FocusTrackingPreact: Story = createStory({
+ name: 'focus-tracking-example',
+ play: focusTrackingTest,
+ runtime: 'preact',
+});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/showcase/focus-tracking-example.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/showcase/focus-tracking-example.front-component.tsx
new file mode 100644
index 00000000000..cd77ac0949f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/showcase/focus-tracking-example.front-component.tsx
@@ -0,0 +1,77 @@
+import { defineFrontComponent } from 'twenty-sdk/define';
+import { useState } from 'react';
+
+type FocusReport = {
+ activeElementLabel: string;
+ focusHandlerActiveElementLabel: string;
+};
+
+const NO_FOCUS_LABEL = 'none';
+
+const readActiveElementLabel = (): string =>
+ document.activeElement?.getAttribute('data-focus-label') ?? NO_FOCUS_LABEL;
+
+const FocusTrackingComponent = () => {
+ const [focusReport, setFocusReport] = useState<FocusReport>({
+ activeElementLabel: NO_FOCUS_LABEL,
+ focusHandlerActiveElementLabel: NO_FOCUS_LABEL,
+ });
+
+ const reportActiveElement = () =>
+ setFocusReport((previousFocusReport) => ({
+ ...previousFocusReport,
+ activeElementLabel: readActiveElementLabel(),
+ }));
+
+ return (
+ <div
+ data-testid="focus-tracking-component"
+ style={{ fontFamily: 'system-ui, sans-serif', padding: 16 }}
+ >
+ <div
+ role="tablist"
+ data-focus-label="tab-list"
+ onFocus={reportActiveElement}
+ onBlur={reportActiveElement}
+ >
+ <button
+ role="tab"
+ data-testid="focus-tracking-first-tab"
+ data-focus-label="first-tab"
+ onFocus={() =>
+ setFocusReport({
+ activeElementLabel: readActiveElementLabel(),
+ focusHandlerActiveElementLabel: readActiveElementLabel(),
+ })
+ }
+ >
+ First tab
+ </button>
+ <button
+ role="tab"
+ data-testid="focus-tracking-second-tab"
+ data-focus-label="second-tab"
+ >
+ Second tab
+ </button>
+ </div>
+ <p
+ data-testid="focus-tracking-status"
+ data-active-element={focusReport.activeElementLabel}
+ data-focus-handler-active-element={
+ focusReport.focusHandlerActiveElementLabel
+ }
+ >
+ Active element: {focusReport.activeElementLabel}
+ </p>
+ </div>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: 'test-20ui0-0000-0000-0000-000000000115',
+ name: 'focus-tracking-component',
+ description:
+ 'Asserts document.activeElement follows the page focus inside the sandbox worker',
+ component: FocusTrackingComponent,
+});
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 e08dc720fa8..15121b0ea8e 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
@@ -62,12 +62,16 @@ No stories are skipped or marked as expected-to-fail by the runner.
The worker DOM now provides `Node.contains`, `compareDocumentPosition`,
`getRootNode`, `Element.matches`, `closest`, `querySelector` backed by
-`css-select`, and property accessors for boolean ARIA attributes so React and
-Preact forward `true`/`false` instead of empty strings and remove the attribute
-when the prop is cleared. `getAttribute` and the selector engine read the remote
-properties React and Preact set, and the selector engine matches the sandbox's
-custom element tags by their HTML tag names. `TooltipPreact` therefore covers
-hover opening and Escape dismissal. Pointer leave still needs document-level
+`css-select`, `focus`/`blur` forwarding to page elements with a
+`document.activeElement` that the host keeps in sync with the page's focus
+inside the component and that clears when
+the focused subtree is detached, and property accessors for boolean ARIA
+attributes so React and Preact forward `true`/`false` instead of empty strings
+and remove the attribute when the prop is cleared. `getAttribute` and the
+selector engine read the remote properties React and Preact set, and the
+selector engine matches the sandbox's custom element tags by their HTML tag
+names and reads live control properties. `TooltipPreact` therefore covers hover
+opening and Escape dismissal. Pointer leave still needs document-level
`mousemove` delivery for the safe polygon, and the compound tooltip's title and
description are not covered yet.
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/SANDBOX_ERROR_PATTERNS.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/SANDBOX_ERROR_PATTERNS.ts
index 4365b8056d8..d43db3345b4 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/SANDBOX_ERROR_PATTERNS.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/SANDBOX_ERROR_PATTERNS.ts
@@ -10,9 +10,6 @@ export const SANDBOX_ERROR_PATTERNS = {
ELEMENT_CONTAINS:
/^(?:Uncaught TypeError: )?\w+\.contains is not a function$/,
HOST_EVENT_LISTENER: 'Uncaught TypeError: listener is not a function',
- ELEMENT_REF_FOCUS:
- /^(?:Uncaught TypeError: )?\w+\.current\?\.focus is not a function$/,
- ELEMENT_FOCUS: /^(?:Uncaught TypeError: )?\w+\?\.focus is not a function$/,
POINTER_EVENT_CONSTRUCTOR:
/^Uncaught TypeError: .+\.PointerEvent is not a constructor$/,
};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sandboxFailureTests.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sandboxFailureTests.ts
index a90c510a686..e1dd8c9bedf 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sandboxFailureTests.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sandboxFailureTests.ts
@@ -27,7 +27,6 @@ export const selectTest = createSandboxFailureTest({
allowedAdditionalErrors: [
SANDBOX_ERROR_PATTERNS.VIEWPORT_WIDTH,
SANDBOX_ERROR_PATTERNS.COMPOSED_PATH,
- SANDBOX_ERROR_PATTERNS.ELEMENT_FOCUS,
],
});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/settingsRowTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/settingsRowTest.ts
index d7212d17db8..3b69e3942a1 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/settingsRowTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/settingsRowTest.ts
@@ -26,6 +26,5 @@ export const settingsRowTest: TwentyUiGalleryPlayFunction = async ({
await expectSandboxErrors({
requiredErrors: [SANDBOX_ERROR_PATTERNS.NATIVE_EVENT_DEFAULT_PREVENTED],
- allowedAdditionalErrors: [SANDBOX_ERROR_PATTERNS.ELEMENT_REF_FOCUS],
});
};
diff --git a/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx b/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx
index 781838695a7..9ea50865e21 100644
--- a/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx
+++ b/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx
@@ -1,8 +1,11 @@
import { ROOT_CONTAINER_STYLE } from '@/host/constants/RootContainerStyle';
import { FrontComponentGeometryTrackerContext } from '@/host/geometry/contexts/FrontComponentGeometryTrackerContext';
import { createGeometryTracker } from '@/host/geometry/utils/createGeometryTracker';
+import { FrontComponentHostFocusControllerContext } from '@/host/focus/contexts/FrontComponentHostFocusControllerContext';
+import { createHostFocusController } from '@/host/focus/utils/createHostFocusController';
import { FrontComponentConfirmationModalResultEffect } from '@/host/effect-components/FrontComponentConfirmationModalResultEffect';
import { FrontComponentErrorEffect } from '@/host/effect-components/FrontComponentErrorEffect';
+import { FrontComponentFocusTrackerEffect } from '@/host/effect-components/FrontComponentFocusTrackerEffect';
import { FrontComponentGeometryTrackerEffect } from '@/host/effect-components/FrontComponentGeometryTrackerEffect';
import { FrontComponentInitializeHostCommunicationApiEffect } from '@/host/effect-components/FrontComponentInitializeHostCommunicationApiEffect';
import { FrontComponentMediaSessionEffect } from '@/host/effect-components/FrontComponentMediaSessionEffect';
@@ -69,6 +72,9 @@ export const FrontComponentRenderer = ({
const [isExecutionContextInitialized, setIsExecutionContextInitialized] =
useState(false);
const [geometryTracker] = useState(() => createGeometryTracker());
+ const [hostFocusController] = useState(() =>
+ createHostFocusController({ geometryTracker }),
+ );
const [initialExecutionContext] = useState(executionContext);
const isReady = isDefined(receiver) && isExecutionContextInitialized;
@@ -87,6 +93,7 @@ export const FrontComponentRenderer = ({
storageNamespace={storageNamespace}
initialExecutionContext={initialExecutionContext}
geometryTracker={geometryTracker}
+ hostFocusController={hostFocusController}
mediaSessionHost={mediaSessionHost}
setReceiver={setReceiver}
setThread={setThread}
@@ -115,6 +122,10 @@ export const FrontComponentRenderer = ({
thread={thread}
geometryTracker={geometryTracker}
/>
+ <FrontComponentFocusTrackerEffect
+ thread={thread}
+ geometryTracker={geometryTracker}
+ />
{isDefined(mediaSessionHost) && (
<FrontComponentMediaSessionEffect
thread={thread}
@@ -146,10 +157,14 @@ export const FrontComponentRenderer = ({
resetKeys={[componentUrl]}
fallbackRender={() => null}
>
- <RemoteRootRenderer
- receiver={receiver}
- components={fallbackComponentRegistry}
- />
+ <FrontComponentHostFocusControllerContext.Provider
+ value={hostFocusController}
+ >
+ <RemoteRootRenderer
+ receiver={receiver}
+ components={fallbackComponentRegistry}
+ />
+ </FrontComponentHostFocusControllerContext.Provider>
</ErrorBoundary>
</ThemeProvider>
)}
diff --git a/packages/twenty-front-component-renderer/src/host/constants/FocusTransportFailureWarning.ts b/packages/twenty-front-component-renderer/src/host/constants/FocusTransportFailureWarning.ts
new file mode 100644
index 00000000000..a5556126515
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/constants/FocusTransportFailureWarning.ts
@@ -0,0 +1,2 @@
+export const FOCUS_TRANSPORT_FAILURE_WARNING =
+ '[twenty-front-component] Reporting the focused element to the worker failed. document.activeElement may stay stale inside the front component.';
diff --git a/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentFocusTrackerEffect.tsx b/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentFocusTrackerEffect.tsx
new file mode 100644
index 00000000000..7de7936cd34
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentFocusTrackerEffect.tsx
@@ -0,0 +1,36 @@
+import { useEffect } from 'react';
+
+import { FOCUS_TRANSPORT_FAILURE_WARNING } from '@/host/constants/FocusTransportFailureWarning';
+import { trackHostFocus } from '@/host/focus/utils/trackHostFocus';
+import { type GeometryTracker } from '@/host/geometry/types/GeometryTracker';
+import { type FrontComponentThread } from '@/types/FrontComponentThread';
+
+type FrontComponentFocusTrackerEffectProps = {
+ thread: FrontComponentThread;
+ geometryTracker: GeometryTracker;
+};
+
+export const FrontComponentFocusTrackerEffect = ({
+ thread,
+ geometryTracker,
+}: FrontComponentFocusTrackerEffectProps) => {
+ useEffect(() => {
+ let hasWarnedAboutFocusPushFailure = false;
+
+ return trackHostFocus({
+ geometryTracker,
+ pushFocusUpdate: (update) => {
+ thread.imports.pushFocusUpdate(update).catch(() => {
+ if (hasWarnedAboutFocusPushFailure) {
+ return;
+ }
+
+ hasWarnedAboutFocusPushFailure = true;
+ console.warn(FOCUS_TRANSPORT_FAILURE_WARNING);
+ });
+ },
+ });
+ }, [thread, geometryTracker]);
+
+ return null;
+};
diff --git a/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentWorkerEffect.tsx b/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentWorkerEffect.tsx
index 5a064bd48c7..8e4889dcccf 100644
--- a/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentWorkerEffect.tsx
+++ b/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentWorkerEffect.tsx
@@ -3,6 +3,8 @@ import { RemoteReceiver } from '@remote-dom/core/receivers';
import { useEffect, useRef } from 'react';
import { isDefined } from 'twenty-shared/utils';
+import { type HostFocusController } from '@/host/focus/types/HostFocusController';
+import { createFocusAwareRemoteConnection } from '@/host/focus/utils/createFocusAwareRemoteConnection';
import { buildHostFetchPolicyFromFrontComponentUrls } from '@/host/fetch/utils/buildHostFetchPolicyFromFrontComponentUrls';
import { createFrontComponentHostThread } from '@/host/thread/utils/createFrontComponentHostThread';
import { createHostFetchEnforcingPolicy } from '@/host/fetch/utils/createHostFetchEnforcingPolicy';
@@ -35,11 +37,13 @@ type FrontComponentWorkerEffectProps = {
geometryTracker: GeometryTracker;
mediaSessionHost?: FrontComponentMediaSessionHost;
setReceiver: React.Dispatch<React.SetStateAction<RemoteReceiver | null>>;
+ hostFocusController: HostFocusController;
setThread: React.Dispatch<React.SetStateAction<FrontComponentThread | null>>;
setError: React.Dispatch<React.SetStateAction<Error | null>>;
};
export const FrontComponentWorkerEffect = ({
+ hostFocusController,
componentUrl,
applicationAccessToken,
apiUrl,
@@ -140,22 +144,28 @@ export const FrontComponentWorkerEffect = ({
? buildFrontComponentStorageSnapshots(storageNamespace)
: undefined;
- await thread.imports.render(newReceiver.connection, {
- componentUrl,
- componentSource,
- applicationAccessToken,
- apiUrl,
- functionsBaseUrl,
- sdkClientSources,
- sharedDependenciesSource,
- hostFetchOrigins: hostFetchPolicy.allowedOrigins,
- applicationVariables,
- initialViewportGeometry: geometryTracker.getViewportGeometry(),
- initialExecutionContext,
- storageSnapshots,
- mediaRecorderCapabilities:
- mediaSessionHost?.getRecorderCapabilities(),
- });
+ await thread.imports.render(
+ createFocusAwareRemoteConnection({
+ connection: newReceiver.connection,
+ hostFocusController,
+ }),
+ {
+ componentUrl,
+ componentSource,
+ applicationAccessToken,
+ apiUrl,
+ functionsBaseUrl,
+ sdkClientSources,
+ sharedDependenciesSource,
+ hostFetchOrigins: hostFetchPolicy.allowedOrigins,
+ applicationVariables,
+ initialViewportGeometry: geometryTracker.getViewportGeometry(),
+ initialExecutionContext,
+ storageSnapshots,
+ mediaRecorderCapabilities:
+ mediaSessionHost?.getRecorderCapabilities(),
+ },
+ );
} catch (error) {
if (!isCancelled) {
setError(error instanceof Error ? error : new Error(String(error)));
@@ -170,6 +180,7 @@ export const FrontComponentWorkerEffect = ({
return () => {
isCancelled = true;
+ hostFocusController.reset();
window.removeEventListener('message', handleSandboxMessage);
setThread(null);
channel.port1.close();
@@ -187,6 +198,7 @@ export const FrontComponentWorkerEffect = ({
storageNamespace,
initialExecutionContext,
geometryTracker,
+ hostFocusController,
mediaSessionHost,
setError,
setReceiver,
diff --git a/packages/twenty-front-component-renderer/src/host/elements/hooks/useHtmlHostElementProps.ts b/packages/twenty-front-component-renderer/src/host/elements/hooks/useHtmlHostElementProps.ts
index b00f8828249..9a7f213390f 100644
--- a/packages/twenty-front-component-renderer/src/host/elements/hooks/useHtmlHostElementProps.ts
+++ b/packages/twenty-front-component-renderer/src/host/elements/hooks/useHtmlHostElementProps.ts
@@ -13,6 +13,7 @@ import { extractReactUnsupportedEventHandlers } from '@/host/events/utils/extrac
import { getRemoteElementIdFromProps } from '@/host/elements/utils/getRemoteElementIdFromProps';
import { preventDefaultThenForwardToRemote } from '@/host/events/utils/preventDefaultThenForwardToRemote';
import { sanitizeIframeSandbox } from '@/host/elements/utils/sanitizeIframeSandbox';
+import { useRetryPendingHostFocus } from '@/host/focus/hooks/useRetryPendingHostFocus';
type HtmlHostElementProps = {
setEditableFocused: SetEditableFocused | null;
@@ -43,6 +44,8 @@ export const useHtmlHostElementProps = ({
const geometryNodeRef = useGeometryNodeRef(remoteElementId);
+ useRetryPendingHostFocus();
+
const composedElementRef = useComposedElementRef([
reactUnsupportedEventListenerRef,
geometryNodeRef,
diff --git a/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/synchronizeMultipleSelectState.test.tsx b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/synchronizeMultipleSelectState.test.tsx
new file mode 100644
index 00000000000..17d80e31eb0
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/elements/utils/__tests__/synchronizeMultipleSelectState.test.tsx
@@ -0,0 +1,152 @@
+import '@/remote/generated/remote-elements';
+
+import {
+ BatchingRemoteConnection,
+ type RemoteRootElement,
+} from '@remote-dom/core/elements';
+import { RemoteReceiver } from '@remote-dom/core/receivers';
+import {
+ createRemoteComponentRenderer,
+ RemoteRootRenderer,
+} from '@remote-dom/react/host';
+import { within } from '@testing-library/dom';
+import userEvent from '@testing-library/user-event';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+
+import { installSelectorMethodsPolyfill } from '@/polyfills/selectors/utils/installSelectorMethodsPolyfill';
+import { patchRemoteElementAttributes } from '@/remote/elements/utils/patchRemoteElementAttributes';
+
+import { createHtmlHostWrapper } from '../createHtmlHostWrapper';
+
+type RemoteElementWithProperties = HTMLElement & Record<string, unknown>;
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const createRemoteElement = (tagName: string): RemoteElementWithProperties => {
+ const element = document.createElement(
+ tagName,
+ ) as RemoteElementWithProperties;
+
+ installSelectorMethodsPolyfill({
+ elementPrototype: element,
+ querySelectorTargets: [element],
+ resolveActiveElement: () => null,
+ resolveFocusVisibleElement: () => null,
+ });
+
+ return element;
+};
+
+describe('multiple select state synchronization', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let remoteRoot: RemoteRootElement;
+
+ beforeAll(() => {
+ patchRemoteElementAttributes();
+ });
+
+ beforeEach(() => {
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+ remoteRoot = document.createElement('remote-root');
+ document.body.append(remoteRoot);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ remoteRoot.remove();
+ });
+
+ it('should retain every selected option after the host event returns through the worker', async () => {
+ const user = userEvent.setup();
+ const receiver = new RemoteReceiver();
+ const connection = new BatchingRemoteConnection(receiver.connection, {
+ batch: jest.fn(),
+ });
+ const select = createRemoteElement('html-select');
+ const firstOption = createRemoteElement('html-option');
+ const duplicateOption = createRemoteElement('html-option');
+ const lastOption = createRemoteElement('html-option');
+
+ select.multiple = true;
+ firstOption.value = 'duplicate';
+ firstOption.textContent = 'First';
+ duplicateOption.value = 'duplicate';
+ duplicateOption.textContent = 'Duplicate';
+ lastOption.value = 'last';
+ lastOption.textContent = 'Last';
+ select.append(firstOption, duplicateOption, lastOption);
+ select.addEventListener('change', jest.fn());
+ remoteRoot.append(select);
+ remoteRoot.connect(connection);
+
+ act(() => {
+ root.render(
+ <RemoteRootRenderer
+ receiver={receiver}
+ components={
+ new Map(
+ ['select', 'option'].map((htmlTag) => [
+ `html-${htmlTag}`,
+ createRemoteComponentRenderer(createHtmlHostWrapper(htmlTag)),
+ ]),
+ )
+ }
+ />,
+ );
+ connection.flush();
+ });
+
+ const hostSelect = within(container).getByRole(
+ 'listbox',
+ ) as HTMLSelectElement;
+ const hostOptions = hostSelect.options;
+
+ await act(async () => {
+ await user.selectOptions(hostSelect, [hostOptions[1], hostOptions[2]]);
+ connection.flush();
+ });
+
+ expect(Array.from(hostSelect.selectedOptions)).toEqual([
+ hostOptions[1],
+ hostOptions[2],
+ ]);
+ expect(select.value).toBe('duplicate');
+ expect(Array.from(select.querySelectorAll('option:checked'))).toEqual([
+ duplicateOption,
+ lastOption,
+ ]);
+
+ act(() => {
+ select.className = 'updated';
+ connection.flush();
+ });
+
+ expect(Array.from(hostSelect.selectedOptions)).toEqual([
+ hostOptions[1],
+ hostOptions[2],
+ ]);
+
+ await act(async () => {
+ await user.deselectOptions(hostSelect, [hostOptions[1], hostOptions[2]]);
+ connection.flush();
+ });
+
+ expect(Array.from(hostSelect.selectedOptions)).toEqual([]);
+ expect(select.value).toBe('');
+ expect(Array.from(select.querySelectorAll('option:checked'))).toEqual([]);
+
+ act(() => {
+ select.value = ['last'];
+ connection.flush();
+ });
+
+ expect(Array.from(hostSelect.selectedOptions)).toEqual([hostOptions[2]]);
+ });
+});
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 c1d4b18b6bd..397de8aed4a 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,3 +1,4 @@
+import { isArray } from '@sniptt/guards';
import React from 'react';
import { useCaretPreservingElementRef } from '@/host/caret/hooks/useCaretPreservingElementRef';
@@ -34,10 +35,19 @@ export const createHtmlHostWrapper = (htmlTag: string) => {
const { reactBindableProps, hostEnforcedProps, composedElementRef } =
useHtmlHostElementProps({ props, htmlTag });
+ const { value, ...reactBindablePropsWithoutValue } = reactBindableProps;
+
+ const shouldUseOptionSelectedState =
+ htmlTag === 'select' &&
+ reactBindableProps.multiple === true &&
+ !isArray(value);
+
return createPlainHostElement({
htmlTag,
isVoid,
- reactBindableProps,
+ reactBindableProps: shouldUseOptionSelectedState
+ ? reactBindablePropsWithoutValue
+ : reactBindableProps,
hostEnforcedProps,
composedElementRef,
children,
diff --git a/packages/twenty-front-component-renderer/src/host/events/utils/serializeEvent.ts b/packages/twenty-front-component-renderer/src/host/events/utils/serializeEvent.ts
index 7d1e2d1cb8c..51c38a8fafa 100644
--- a/packages/twenty-front-component-renderer/src/host/events/utils/serializeEvent.ts
+++ b/packages/twenty-front-component-renderer/src/host/events/utils/serializeEvent.ts
@@ -5,6 +5,7 @@ import { MAX_SERIALIZED_EVENT_TEXT_LENGTH } from '@/host/events/constants/MaxSer
import { applyFirstChangedTouchCoordinates } from '@/host/events/utils/applyFirstChangedTouchCoordinates';
import { applyPasteClipboardText } from '@/host/events/utils/applyPasteClipboardText';
import { serializeFileList } from '@/host/events/utils/serializeFileList';
+import { serializeSelectedOptionIndexes } from '@/host/events/utils/serializeSelectedOptionIndexes';
import { type SerializedEventData } from '@/types/SerializedEventData';
export const serializeEvent = (event: unknown): SerializedEventData => {
@@ -147,6 +148,10 @@ export const serializeEvent = (event: unknown): SerializedEventData => {
if (isBoolean(targetRecord.checked)) {
serialized.checked = targetRecord.checked;
}
+ const selectedOptionIndexes = serializeSelectedOptionIndexes(target);
+ if (isDefined(selectedOptionIndexes)) {
+ serialized.selectedOptionIndexes = selectedOptionIndexes;
+ }
if (isNumber(targetRecord.scrollTop)) {
serialized.scrollTop = targetRecord.scrollTop;
}
diff --git a/packages/twenty-front-component-renderer/src/host/events/utils/serializeSelectedOptionIndexes.ts b/packages/twenty-front-component-renderer/src/host/events/utils/serializeSelectedOptionIndexes.ts
new file mode 100644
index 00000000000..6f3d565cf70
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/events/utils/serializeSelectedOptionIndexes.ts
@@ -0,0 +1,20 @@
+import { collectOptionsOfSelect } from '@/polyfills/selectors/utils/collectOptionsOfSelect';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+import { isSelectorElementNode } from '@/polyfills/selectors/utils/isSelectorElementNode';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+
+export const serializeSelectedOptionIndexes = (
+ element: unknown,
+): number[] | undefined => {
+ if (
+ !isSelectorElementNode(element) ||
+ resolveHtmlTagNameOfElement(element) !== 'select' ||
+ !hasElementAttributeIgnoringCase(element, 'multiple')
+ ) {
+ return undefined;
+ }
+
+ return collectOptionsOfSelect(element).flatMap((option, optionIndex) =>
+ option.selected === true ? [optionIndex] : [],
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/host/focus/contexts/FrontComponentHostFocusControllerContext.ts b/packages/twenty-front-component-renderer/src/host/focus/contexts/FrontComponentHostFocusControllerContext.ts
new file mode 100644
index 00000000000..f65409559b8
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/focus/contexts/FrontComponentHostFocusControllerContext.ts
@@ -0,0 +1,6 @@
+import { createContext } from 'react';
+
+import { type HostFocusController } from '@/host/focus/types/HostFocusController';
+
+export const FrontComponentHostFocusControllerContext =
+ createContext<HostFocusController | null>(null);
diff --git a/packages/twenty-front-component-renderer/src/host/focus/hooks/useRetryPendingHostFocus.ts b/packages/twenty-front-component-renderer/src/host/focus/hooks/useRetryPendingHostFocus.ts
new file mode 100644
index 00000000000..0b80be4d9c3
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/focus/hooks/useRetryPendingHostFocus.ts
@@ -0,0 +1,13 @@
+import { useContext, useLayoutEffect } from 'react';
+
+import { FrontComponentHostFocusControllerContext } from '@/host/focus/contexts/FrontComponentHostFocusControllerContext';
+
+export const useRetryPendingHostFocus = (): void => {
+ const hostFocusController = useContext(
+ FrontComponentHostFocusControllerContext,
+ );
+
+ useLayoutEffect(() => {
+ hostFocusController?.retryPendingFocus();
+ });
+};
diff --git a/packages/twenty-front-component-renderer/src/host/focus/types/HostFocusController.ts b/packages/twenty-front-component-renderer/src/host/focus/types/HostFocusController.ts
new file mode 100644
index 00000000000..61f75bf0488
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/focus/types/HostFocusController.ts
@@ -0,0 +1,9 @@
+export type HostFocusController = {
+ callFocusMethod: (input: {
+ remoteElementId: string;
+ methodName: 'focus' | 'blur';
+ options?: FocusOptions;
+ }) => void;
+ retryPendingFocus: () => void;
+ reset: () => void;
+};
diff --git a/packages/twenty-front-component-renderer/src/host/focus/utils/__tests__/createHostFocusController.test.ts b/packages/twenty-front-component-renderer/src/host/focus/utils/__tests__/createHostFocusController.test.ts
new file mode 100644
index 00000000000..83f873aecc3
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/focus/utils/__tests__/createHostFocusController.test.ts
@@ -0,0 +1,126 @@
+import { createGeometryTracker } from '@/host/geometry/utils/createGeometryTracker';
+
+import { createHostFocusController } from '../createHostFocusController';
+
+const createFocusFixture = () => {
+ const geometryTracker = createGeometryTracker();
+
+ return {
+ geometryTracker,
+ controller: createHostFocusController({ geometryTracker }),
+ };
+};
+
+describe('createHostFocusController', () => {
+ afterEach(() => {
+ document.body.replaceChildren();
+ });
+
+ it('should apply only the latest pending focus request as elements mount', () => {
+ const { geometryTracker, controller } = createFocusFixture();
+ const first = document.createElement('button');
+ const second = document.createElement('button');
+
+ document.body.append(first, second);
+ controller.callFocusMethod({
+ remoteElementId: 'first',
+ methodName: 'focus',
+ });
+ controller.callFocusMethod({
+ remoteElementId: 'second',
+ methodName: 'focus',
+ });
+ geometryTracker.registerNode('first', first);
+ controller.retryPendingFocus();
+ expect(document.activeElement).toBe(document.body);
+ geometryTracker.registerNode('second', second);
+ controller.retryPendingFocus();
+ expect(document.activeElement).toBe(second);
+ });
+
+ it('should cancel pending focus when the same element is blurred', () => {
+ const { geometryTracker, controller } = createFocusFixture();
+ const button = document.createElement('button');
+
+ document.body.append(button);
+ controller.callFocusMethod({
+ remoteElementId: 'button',
+ methodName: 'focus',
+ });
+ controller.callFocusMethod({
+ remoteElementId: 'button',
+ methodName: 'blur',
+ });
+ geometryTracker.registerNode('button', button);
+ controller.retryPendingFocus();
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should drop pending focus once the page focus moves to another element', () => {
+ const { geometryTracker, controller } = createFocusFixture();
+ const pendingButton = document.createElement('button');
+ const otherButton = document.createElement('button');
+
+ document.body.append(pendingButton, otherButton);
+ controller.callFocusMethod({
+ remoteElementId: 'pending-button',
+ methodName: 'focus',
+ });
+ otherButton.focus();
+ geometryTracker.registerNode('pending-button', pendingButton);
+ controller.retryPendingFocus();
+
+ expect(document.activeElement).toBe(otherButton);
+ });
+
+ it('should keep pending focus when the focused element is removed', () => {
+ const { geometryTracker, controller } = createFocusFixture();
+ const removedButton = document.createElement('button');
+ const pendingButton = document.createElement('button');
+
+ document.body.append(removedButton, pendingButton);
+ removedButton.focus();
+ controller.callFocusMethod({
+ remoteElementId: 'pending-button',
+ methodName: 'focus',
+ });
+ removedButton.remove();
+ geometryTracker.registerNode('pending-button', pendingButton);
+ controller.retryPendingFocus();
+
+ expect(document.activeElement).toBe(pendingButton);
+ });
+
+ it('should clear pending focus on reset', () => {
+ const { geometryTracker, controller } = createFocusFixture();
+ const button = document.createElement('button');
+
+ document.body.append(button);
+ controller.callFocusMethod({
+ remoteElementId: 'button',
+ methodName: 'focus',
+ });
+ controller.reset();
+ geometryTracker.registerNode('button', button);
+ controller.retryPendingFocus();
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should stop using an unmounted element', () => {
+ const { geometryTracker, controller } = createFocusFixture();
+ const button = document.createElement('button');
+ const focus = jest.spyOn(button, 'focus');
+
+ document.body.append(button);
+ geometryTracker.registerNode('button', button);
+ geometryTracker.unregisterNode('button', button);
+ controller.callFocusMethod({
+ remoteElementId: 'button',
+ methodName: 'focus',
+ });
+
+ expect(focus).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/host/focus/utils/__tests__/trackHostFocus.test.ts b/packages/twenty-front-component-renderer/src/host/focus/utils/__tests__/trackHostFocus.test.ts
new file mode 100644
index 00000000000..ce30eae026b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/focus/utils/__tests__/trackHostFocus.test.ts
@@ -0,0 +1,115 @@
+import { trackHostFocus } from '@/host/focus/utils/trackHostFocus';
+import { createGeometryTrackerStub } from '@/testing/createGeometryTrackerStub';
+
+const createFocusFixture = () => {
+ const geometryTracker = createGeometryTrackerStub();
+ const pushFocusUpdate = jest.fn();
+ const button = document.createElement('button');
+ const input = document.createElement('input');
+
+ button.setAttribute('data-remote-id', 'button');
+ input.setAttribute('data-remote-id', 'input');
+ document.body.append(button, input);
+
+ jest
+ .spyOn(geometryTracker, 'findRemoteElementIdContainingNode')
+ .mockImplementation((node) =>
+ node instanceof Element
+ ? (node.getAttribute('data-remote-id') ?? undefined)
+ : undefined,
+ );
+
+ return {
+ button,
+ input,
+ pushFocusUpdate,
+ startTracking: () => trackHostFocus({ geometryTracker, pushFocusUpdate }),
+ };
+};
+
+describe('trackHostFocus', () => {
+ let stopTracking: (() => void) | undefined;
+
+ afterEach(() => {
+ stopTracking?.();
+ document.body.replaceChildren();
+ jest.restoreAllMocks();
+ });
+
+ it('should forward native focus visibility and update it without a focus change', () => {
+ const { button, pushFocusUpdate, startTracking } = createFocusFixture();
+ const matches = jest.spyOn(button, 'matches').mockReturnValue(false);
+
+ stopTracking = startTracking();
+ button.focus();
+
+ expect(matches).toHaveBeenCalledWith(':focus-visible');
+ expect(pushFocusUpdate).toHaveBeenLastCalledWith({
+ remoteElementId: 'button',
+ isFocusVisible: false,
+ });
+
+ matches.mockReturnValue(true);
+ button.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'a', bubbles: true }),
+ );
+
+ expect(pushFocusUpdate).toHaveBeenLastCalledWith({
+ remoteElementId: 'button',
+ isFocusVisible: true,
+ });
+
+ button.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'b', bubbles: true }),
+ );
+
+ expect(pushFocusUpdate).toHaveBeenCalledTimes(2);
+ });
+
+ it('should preserve native focus visibility when focus moves to a text input', () => {
+ const { button, input, pushFocusUpdate, startTracking } =
+ createFocusFixture();
+
+ jest.spyOn(button, 'matches').mockReturnValue(false);
+ jest.spyOn(input, 'matches').mockReturnValue(true);
+ stopTracking = startTracking();
+ button.focus();
+ input.focus();
+
+ expect(pushFocusUpdate.mock.calls).toEqual([
+ [{ remoteElementId: 'button', isFocusVisible: false }],
+ [{ remoteElementId: 'input', isFocusVisible: true }],
+ ]);
+
+ input.blur();
+
+ expect(pushFocusUpdate).toHaveBeenLastCalledWith({
+ remoteElementId: null,
+ isFocusVisible: false,
+ });
+ });
+
+ it('should synchronize focus present on mount and stop observing on cleanup', () => {
+ const { button, input, pushFocusUpdate, startTracking } =
+ createFocusFixture();
+
+ jest.spyOn(button, 'matches').mockReturnValue(true);
+ button.focus();
+ stopTracking = startTracking();
+
+ expect(pushFocusUpdate).toHaveBeenLastCalledWith({
+ remoteElementId: 'button',
+ isFocusVisible: true,
+ });
+
+ stopTracking();
+ pushFocusUpdate.mockClear();
+ input.focus();
+ input.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'a', bubbles: true }),
+ );
+ input.blur();
+
+ expect(pushFocusUpdate).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/host/focus/utils/createFocusAwareRemoteConnection.ts b/packages/twenty-front-component-renderer/src/host/focus/utils/createFocusAwareRemoteConnection.ts
new file mode 100644
index 00000000000..369e6f00a1c
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/focus/utils/createFocusAwareRemoteConnection.ts
@@ -0,0 +1,25 @@
+import { type RemoteConnection } from '@remote-dom/core/elements';
+
+import { type HostFocusController } from '@/host/focus/types/HostFocusController';
+
+export const createFocusAwareRemoteConnection = ({
+ connection,
+ hostFocusController,
+}: {
+ connection: RemoteConnection;
+ hostFocusController: HostFocusController;
+}): RemoteConnection => ({
+ mutate: connection.mutate,
+ call: (remoteElementId, methodName, ...methodArguments) => {
+ if (methodName === 'focus' || methodName === 'blur') {
+ hostFocusController.callFocusMethod({
+ remoteElementId,
+ methodName,
+ options: methodArguments[0] as FocusOptions | undefined,
+ });
+ return;
+ }
+
+ return connection.call(remoteElementId, methodName, ...methodArguments);
+ },
+});
diff --git a/packages/twenty-front-component-renderer/src/host/focus/utils/createHostFocusController.ts b/packages/twenty-front-component-renderer/src/host/focus/utils/createHostFocusController.ts
new file mode 100644
index 00000000000..114c84c7aa4
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/focus/utils/createHostFocusController.ts
@@ -0,0 +1,70 @@
+import { isFunction } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type HostFocusController } from '@/host/focus/types/HostFocusController';
+import { type GeometryTracker } from '@/host/geometry/types/GeometryTracker';
+
+type PendingFocusRequest = {
+ remoteElementId: string;
+ options?: FocusOptions;
+};
+
+export const createHostFocusController = ({
+ geometryTracker,
+}: {
+ geometryTracker: GeometryTracker;
+}): HostFocusController => {
+ let pendingFocusRequest: PendingFocusRequest | null = null;
+
+ const clearPendingFocusRequest = (): void => {
+ pendingFocusRequest = null;
+ document.removeEventListener('focusin', clearPendingFocusRequest, true);
+ };
+
+ const findRegisteredElement = (remoteElementId: string) =>
+ geometryTracker.getRegisteredNode(remoteElementId) as
+ | HTMLElement
+ | SVGElement
+ | undefined;
+
+ const focusElement = ({ remoteElementId, options }: PendingFocusRequest) => {
+ const element = findRegisteredElement(remoteElementId);
+
+ if (!isDefined(element) || !isFunction(element.focus)) {
+ return;
+ }
+
+ element.focus(options);
+
+ if (element.ownerDocument.activeElement === element) {
+ clearPendingFocusRequest();
+ }
+ };
+
+ return {
+ callFocusMethod: ({ remoteElementId, methodName, options }) => {
+ if (methodName === 'focus') {
+ pendingFocusRequest = { remoteElementId, options };
+ document.addEventListener('focusin', clearPendingFocusRequest, true);
+ focusElement(pendingFocusRequest);
+ return;
+ }
+
+ if (pendingFocusRequest?.remoteElementId === remoteElementId) {
+ clearPendingFocusRequest();
+ }
+
+ const element = findRegisteredElement(remoteElementId);
+
+ if (isDefined(element) && isFunction(element.blur)) {
+ element.blur();
+ }
+ },
+ retryPendingFocus: () => {
+ if (isDefined(pendingFocusRequest)) {
+ focusElement(pendingFocusRequest);
+ }
+ },
+ reset: clearPendingFocusRequest,
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/host/focus/utils/trackHostFocus.ts b/packages/twenty-front-component-renderer/src/host/focus/utils/trackHostFocus.ts
new file mode 100644
index 00000000000..8935cba070b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/focus/utils/trackHostFocus.ts
@@ -0,0 +1,64 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type GeometryTracker } from '@/host/geometry/types/GeometryTracker';
+import { type FocusUpdate } from '@/types/FocusUpdate';
+
+type TrackHostFocusInput = {
+ geometryTracker: GeometryTracker;
+ pushFocusUpdate: (update: FocusUpdate) => void;
+};
+
+export const trackHostFocus = ({
+ geometryTracker,
+ pushFocusUpdate,
+}: TrackHostFocusInput): (() => void) => {
+ let previousUpdate: FocusUpdate = {
+ remoteElementId: null,
+ isFocusVisible: false,
+ };
+
+ const pushFocusedElement = (element: Element | null): void => {
+ const remoteElementId =
+ geometryTracker.findRemoteElementIdContainingNode(element) ?? null;
+ const isFocusVisible =
+ isDefined(remoteElementId) &&
+ (element?.matches(':focus-visible') ?? false);
+
+ if (
+ remoteElementId === previousUpdate.remoteElementId &&
+ isFocusVisible === previousUpdate.isFocusVisible
+ ) {
+ return;
+ }
+
+ previousUpdate = { remoteElementId, isFocusVisible };
+ pushFocusUpdate(previousUpdate);
+ };
+
+ const pushActiveElement = (): void => {
+ pushFocusedElement(document.activeElement);
+ };
+
+ const handleFocusOut = (event: FocusEvent): void => {
+ if (
+ isDefined(
+ geometryTracker.findRemoteElementIdContainingNode(event.relatedTarget),
+ )
+ ) {
+ return;
+ }
+
+ pushFocusedElement(null);
+ };
+
+ document.addEventListener('focusin', pushActiveElement, true);
+ document.addEventListener('focusout', handleFocusOut, true);
+ document.addEventListener('keydown', pushActiveElement, true);
+ pushActiveElement();
+
+ return () => {
+ document.removeEventListener('focusin', pushActiveElement, true);
+ document.removeEventListener('focusout', handleFocusOut, true);
+ document.removeEventListener('keydown', pushActiveElement, true);
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/types/GeometryTracker.ts b/packages/twenty-front-component-renderer/src/host/geometry/types/GeometryTracker.ts
index d03bdd790ee..66f68e7d114 100644
--- a/packages/twenty-front-component-renderer/src/host/geometry/types/GeometryTracker.ts
+++ b/packages/twenty-front-component-renderer/src/host/geometry/types/GeometryTracker.ts
@@ -5,6 +5,8 @@ import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot'
export type GeometryTracker = {
registerNode: (remoteElementId: string, node: Element) => void;
unregisterNode: (remoteElementId: string, node: Element) => void;
+ getRegisteredNode: (remoteElementId: string) => Element | undefined;
+ findRemoteElementIdContainingNode: (node: unknown) => string | undefined;
observe: (remoteElementIds: unknown) => void;
unobserve: (remoteElementIds: unknown) => void;
setRoot: ElementRefCallback;
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createGeometryTracker.test.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createGeometryTracker.test.ts
index 93e6d011597..049b9f48f3c 100644
--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createGeometryTracker.test.ts
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createGeometryTracker.test.ts
@@ -43,6 +43,30 @@ describe('createGeometryTracker', () => {
expect(geometryGlobals.getScheduledFrameCount()).toBe(0);
});
+ it('should find the remote element id of a node through its nearest registered ancestor', () => {
+ const tracker = createGeometryTracker();
+ const tabList = document.createElement('div');
+ const tab = document.createElement('button');
+ const tabIcon = document.createElement('span');
+ tab.append(tabIcon);
+ tabList.append(tab);
+ document.body.append(tabList);
+
+ tracker.registerNode('tab-list', tabList);
+ tracker.registerNode('tab', tab);
+
+ expect(tracker.findRemoteElementIdContainingNode(tabIcon)).toBe('tab');
+ expect(tracker.findRemoteElementIdContainingNode(tabList)).toBe('tab-list');
+ expect(
+ tracker.findRemoteElementIdContainingNode(document.body),
+ ).toBeUndefined();
+ expect(tracker.findRemoteElementIdContainingNode(null)).toBeUndefined();
+
+ tracker.unregisterNode('tab', tab);
+
+ expect(tracker.findRemoteElementIdContainingNode(tabIcon)).toBe('tab-list');
+ });
+
it('should not schedule a frame when observing before being armed', () => {
const tracker = createGeometryTracker();
armedTrackers.push(tracker);
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryTracker.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryTracker.ts
index 03d3c7c2710..18c3a322941 100644
--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryTracker.ts
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryTracker.ts
@@ -1,3 +1,4 @@
+import { findRemoteElementIdContainingNode } from '@/host/geometry/utils/findRemoteElementIdContainingNode';
import { isDefined } from 'twenty-shared/utils';
import { MAX_OBSERVED_GEOMETRY_ELEMENTS } from '@/constants/MaxObservedGeometryElements';
@@ -15,6 +16,7 @@ import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot'
export const createGeometryTracker = (): GeometryTracker => {
const registeredNodes = new Map<string, Element>();
+ const remoteElementIdByRegisteredNode = new WeakMap<object, string>();
const observedRemoteElementIds = new Set<string>();
const lastElementSnapshots = new Map<string, ElementGeometrySnapshot>();
const unregisteredObservedFrameCounts = new Map<string, number>();
@@ -149,9 +151,11 @@ export const createGeometryTracker = (): GeometryTracker => {
if (isDefined(previousNode) && previousNode !== node) {
wakeSources.stopObservingNode(previousNode);
+ remoteElementIdByRegisteredNode.delete(previousNode);
}
registeredNodes.set(remoteElementId, node);
+ remoteElementIdByRegisteredNode.set(node, remoteElementId);
unregisteredObservedFrameCounts.delete(remoteElementId);
if (observedRemoteElementIds.has(remoteElementId)) {
@@ -166,6 +170,7 @@ export const createGeometryTracker = (): GeometryTracker => {
}
registeredNodes.delete(remoteElementId);
+ remoteElementIdByRegisteredNode.delete(node);
wakeSources.stopObservingNode(node);
if (observedRemoteElementIds.has(remoteElementId)) {
@@ -265,6 +270,13 @@ export const createGeometryTracker = (): GeometryTracker => {
return {
registerNode,
unregisterNode,
+ getRegisteredNode: (remoteElementId) =>
+ registeredNodes.get(remoteElementId),
+ findRemoteElementIdContainingNode: (node) =>
+ findRemoteElementIdContainingNode({
+ node,
+ remoteElementIdByRegisteredNode,
+ }),
observe,
unobserve,
setRoot,
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/findRemoteElementIdContainingNode.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/findRemoteElementIdContainingNode.ts
new file mode 100644
index 00000000000..ab94aaa7fce
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/findRemoteElementIdContainingNode.ts
@@ -0,0 +1,28 @@
+import { isObject } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+type NodeWithParent = {
+ parentNode?: unknown;
+};
+
+export const findRemoteElementIdContainingNode = ({
+ node,
+ remoteElementIdByRegisteredNode,
+}: {
+ node: unknown;
+ remoteElementIdByRegisteredNode: WeakMap<object, string>;
+}): string | undefined => {
+ let currentNode: unknown = node;
+
+ while (isObject(currentNode)) {
+ const remoteElementId = remoteElementIdByRegisteredNode.get(currentNode);
+
+ if (isDefined(remoteElementId)) {
+ return remoteElementId;
+ }
+
+ currentNode = (currentNode as NodeWithParent).parentNode;
+ }
+
+ return undefined;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/states/workerActiveElementStore.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/states/workerActiveElementStore.ts
new file mode 100644
index 00000000000..e9e9267e5ed
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/states/workerActiveElementStore.ts
@@ -0,0 +1,3 @@
+import { createWorkerActiveElementStore } from '@/polyfills/dom/utils/createWorkerActiveElementStore';
+
+export const workerActiveElementStore = createWorkerActiveElementStore();
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/states/workerFocusTransport.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/states/workerFocusTransport.ts
new file mode 100644
index 00000000000..a7028384339
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/states/workerFocusTransport.ts
@@ -0,0 +1,3 @@
+import { createWorkerFocusTransport } from '@/polyfills/dom/utils/createWorkerFocusTransport';
+
+export const workerFocusTransport = createWorkerFocusTransport();
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerActiveElementStore.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerActiveElementStore.ts
new file mode 100644
index 00000000000..941f7b4a921
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerActiveElementStore.ts
@@ -0,0 +1,8 @@
+export type WorkerActiveElementStore = {
+ getActiveElement: () => object | null;
+ getFocusVisibleElement: () => object | null;
+ setActiveElement: (input: {
+ element: object | null;
+ isFocusVisible?: boolean;
+ }) => void;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerFocusMethodRequest.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerFocusMethodRequest.ts
new file mode 100644
index 00000000000..e74f0f46fdb
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerFocusMethodRequest.ts
@@ -0,0 +1,5 @@
+export type WorkerFocusMethodRequest = {
+ element: object;
+ methodName: 'focus' | 'blur';
+ options?: FocusOptions;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/findElementByRemoteId.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/findElementByRemoteId.test.ts
new file mode 100644
index 00000000000..e6d2cdc6fc8
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/findElementByRemoteId.test.ts
@@ -0,0 +1,52 @@
+import { remoteId } from '@remote-dom/core/elements';
+import { Window } from '@remote-dom/polyfill';
+
+import { findElementByRemoteId } from '../findElementByRemoteId';
+
+const createPolyfillDocument = (): Document =>
+ new Window().document as unknown as Document;
+
+describe('findElementByRemoteId', () => {
+ it('should find the element carrying the remote id under the root', () => {
+ const document = createPolyfillDocument();
+ const list = document.createElement('div');
+ const item = document.createElement('button');
+
+ list.append(item);
+ document.body.append(list);
+
+ expect(
+ findElementByRemoteId({
+ rootNode: document.body,
+ remoteElementId: remoteId(item),
+ }),
+ ).toBe(item);
+ });
+
+ it('should return null when no element carries the remote id', () => {
+ const document = createPolyfillDocument();
+
+ document.body.append(document.createElement('div'));
+
+ expect(
+ findElementByRemoteId({
+ rootNode: document.body,
+ remoteElementId: 'missing',
+ }),
+ ).toBeNull();
+ });
+
+ it('should ignore text nodes carrying the remote id', () => {
+ const document = createPolyfillDocument();
+ const label = document.createTextNode('Overview');
+
+ document.body.append(label);
+
+ expect(
+ findElementByRemoteId({
+ rootNode: document.body,
+ remoteElementId: remoteId(label),
+ }),
+ ).toBeNull();
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/forwardFocusMethodsToHost.test.tsx b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/forwardFocusMethodsToHost.test.tsx
new file mode 100644
index 00000000000..fb8199a3104
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/forwardFocusMethodsToHost.test.tsx
@@ -0,0 +1,199 @@
+import '@/remote/generated/remote-elements';
+
+import {
+ BatchingRemoteConnection,
+ remoteId,
+ 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 { createHtmlHostWrapper } from '@/host/elements/utils/createHtmlHostWrapper';
+import { FrontComponentHostFocusControllerContext } from '@/host/focus/contexts/FrontComponentHostFocusControllerContext';
+import { createFocusAwareRemoteConnection } from '@/host/focus/utils/createFocusAwareRemoteConnection';
+import { createHostFocusController } from '@/host/focus/utils/createHostFocusController';
+import { FrontComponentGeometryTrackerContext } from '@/host/geometry/contexts/FrontComponentGeometryTrackerContext';
+import { createGeometryTracker } from '@/host/geometry/utils/createGeometryTracker';
+
+import { createWorkerActiveElementStore } from '../createWorkerActiveElementStore';
+import { createWorkerFocusTransport } from '../createWorkerFocusTransport';
+import { installFocusAndBlurMethodsPolyfill } from '../installFocusAndBlurMethodsPolyfill';
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('forwarding focus methods to the host', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let remoteRoot: RemoteRootElement;
+
+ beforeEach(() => {
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+ remoteRoot = document.createElement('remote-root');
+ document.body.append(remoteRoot);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ remoteRoot.remove();
+ });
+
+ const renderRemoteButtons = () => {
+ const receiver = new RemoteReceiver();
+ const geometryTracker = createGeometryTracker();
+ const hostFocusController = createHostFocusController({
+ geometryTracker,
+ });
+ const connection = new BatchingRemoteConnection(
+ createFocusAwareRemoteConnection({
+ connection: receiver.connection,
+ hostFocusController,
+ }),
+ { batch: jest.fn() },
+ );
+ const activeElementStore = createWorkerActiveElementStore();
+ const focusTransport = createWorkerFocusTransport();
+ const firstItem = document.createElement(
+ 'html-button',
+ ) as HTMLButtonElement;
+ const secondItem = document.createElement(
+ 'html-button',
+ ) as HTMLButtonElement;
+ const handleSecondItemKeyDown = jest.fn();
+
+ firstItem.textContent = 'First';
+ secondItem.textContent = 'Second';
+ secondItem.addEventListener('keydown', handleSecondItemKeyDown);
+ remoteRoot.append(firstItem, secondItem);
+ remoteRoot.connect(connection);
+ focusTransport.setRootElement(remoteRoot);
+
+ for (const element of [firstItem, secondItem]) {
+ installFocusAndBlurMethodsPolyfill({
+ elementPrototype: element,
+ activeElementStore,
+ forwardFocusMethod: focusTransport.forwardFocusMethod,
+ });
+ }
+
+ act(() => {
+ root.render(
+ <FrontComponentGeometryTrackerContext.Provider value={geometryTracker}>
+ <FrontComponentHostFocusControllerContext.Provider
+ value={hostFocusController}
+ >
+ <RemoteRootRenderer
+ receiver={receiver}
+ components={
+ new Map([
+ [
+ 'html-button',
+ createRemoteComponentRenderer(
+ createHtmlHostWrapper('button'),
+ ),
+ ],
+ ])
+ }
+ />
+ </FrontComponentHostFocusControllerContext.Provider>
+ </FrontComponentGeometryTrackerContext.Provider>,
+ );
+ });
+
+ return {
+ connection,
+ activeElementStore,
+ firstItem,
+ secondItem,
+ handleSecondItemKeyDown,
+ };
+ };
+
+ it('should move host focus and route the next keyboard event to the focused item', () => {
+ const {
+ connection,
+ activeElementStore,
+ firstItem,
+ secondItem,
+ handleSecondItemKeyDown,
+ } = renderRemoteButtons();
+
+ expect(() => firstItem.focus()).not.toThrow();
+ expect(container.querySelector('button')).toBeNull();
+ act(() => connection.flush());
+
+ const hostButtons = container.querySelectorAll('button');
+ const firstHostButton = hostButtons[0];
+ const secondHostButton = hostButtons[1];
+ const focusSecondHostButton = jest.spyOn(secondHostButton, 'focus');
+
+ expect(document.activeElement).toBe(firstHostButton);
+ expect(() => connection.call(remoteId(firstItem), 'click')).toThrow(
+ 'does not implement the click() method',
+ );
+
+ act(() => secondItem.focus({ preventScroll: true }));
+ expect(document.activeElement).toBe(secondHostButton);
+ expect(activeElementStore.getActiveElement()).toBe(secondItem);
+ expect(focusSecondHostButton).toHaveBeenCalledWith({ preventScroll: true });
+
+ act(() => {
+ document.activeElement?.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }),
+ );
+ });
+ expect(handleSecondItemKeyDown).toHaveBeenCalledWith(
+ expect.objectContaining({ key: 'ArrowDown' }),
+ );
+
+ act(() => secondItem.blur());
+ expect(document.activeElement).toBe(document.body);
+ expect(activeElementStore.getActiveElement()).toBeNull();
+ });
+
+ it('should retry focus after queued properties enable a mounted host button', () => {
+ const { connection, secondItem } = renderRemoteButtons();
+
+ secondItem.disabled = true;
+ act(() => connection.flush());
+
+ const secondHostButton = container.querySelectorAll('button')[1];
+
+ expect(secondHostButton.disabled).toBe(true);
+ secondItem.disabled = false;
+ act(() => secondItem.focus());
+ expect(document.activeElement).toBe(document.body);
+
+ act(() => connection.flush());
+
+ expect(secondHostButton.disabled).toBe(false);
+ expect(document.activeElement).toBe(secondHostButton);
+ });
+
+ it('should keep focus local for elements outside the remote render root', () => {
+ const activeElementStore = createWorkerActiveElementStore();
+ const focusTransport = createWorkerFocusTransport();
+ const button = document.createElement('button');
+
+ container.append(button);
+ focusTransport.setRootElement(remoteRoot);
+ installFocusAndBlurMethodsPolyfill({
+ elementPrototype: button,
+ activeElementStore,
+ forwardFocusMethod: focusTransport.forwardFocusMethod,
+ });
+
+ expect(() => button.focus()).not.toThrow();
+ expect(activeElementStore.getActiveElement()).toBe(button);
+ expect(document.activeElement).toBe(document.body);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installFocusAndBlurMethodsPolyfill.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installFocusAndBlurMethodsPolyfill.test.ts
new file mode 100644
index 00000000000..45f5ae3171c
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installFocusAndBlurMethodsPolyfill.test.ts
@@ -0,0 +1,339 @@
+import { HOOKS, Window } from '@remote-dom/polyfill';
+import {
+ connectRemoteNode,
+ disconnectRemoteNode,
+ remoteId,
+} from '@remote-dom/core/elements';
+
+import { installSelectorMethodsPolyfill } from '@/polyfills/selectors/utils/installSelectorMethodsPolyfill';
+
+import { createWorkerActiveElementStore } from '../createWorkerActiveElementStore';
+import { createWorkerFocusTransport } from '../createWorkerFocusTransport';
+import { installActiveElementDetachmentHook } from '../installActiveElementDetachmentHook';
+import { installDocumentActiveElementPolyfill } from '../installDocumentActiveElementPolyfill';
+import { installFocusAndBlurMethodsPolyfill } from '../installFocusAndBlurMethodsPolyfill';
+
+const createPolyfillDocument = (): Document => {
+ const polyfillWindow = new Window();
+ const activeElementStore = createWorkerActiveElementStore();
+
+ installActiveElementDetachmentHook({
+ hooks: polyfillWindow[HOOKS],
+ activeElementStore,
+ });
+ installFocusAndBlurMethodsPolyfill({
+ elementPrototype: polyfillWindow.Element.prototype,
+ activeElementStore,
+ });
+ installDocumentActiveElementPolyfill({
+ documentTarget: polyfillWindow.document,
+ activeElementStore,
+ });
+
+ return polyfillWindow.document as unknown as Document;
+};
+
+describe('installFocusAndBlurMethodsPolyfill', () => {
+ it('should report the body as active before any focus call', () => {
+ const document = createPolyfillDocument();
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should make a focused element the active element', () => {
+ const document = createPolyfillDocument();
+ const button = document.createElement('button');
+
+ document.body.append(button);
+ button.focus();
+
+ expect(document.activeElement).toBe(button);
+ });
+
+ it('should accept focus options', () => {
+ const document = createPolyfillDocument();
+ const button = document.createElement('button');
+
+ document.body.append(button);
+
+ expect(() => button.focus({ preventScroll: true })).not.toThrow();
+ expect(document.activeElement).toBe(button);
+ });
+
+ it('should move the active element to the most recently focused element', () => {
+ const document = createPolyfillDocument();
+ const first = document.createElement('button');
+ const second = document.createElement('button');
+
+ document.body.append(first, second);
+ first.focus();
+ second.focus();
+
+ expect(document.activeElement).toBe(second);
+ });
+
+ it('should fall back to the body after blurring the active element', () => {
+ const document = createPolyfillDocument();
+ const button = document.createElement('button');
+
+ document.body.append(button);
+ button.focus();
+ button.blur();
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should fall back to the body once the active element is removed from the document', () => {
+ const document = createPolyfillDocument();
+ const dialog = document.createElement('div');
+ const closeButton = document.createElement('button');
+
+ dialog.append(closeButton);
+ document.body.append(dialog);
+ closeButton.focus();
+ dialog.remove();
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should not report a detached element as active', () => {
+ const document = createPolyfillDocument();
+ const button = document.createElement('button');
+
+ button.focus();
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should clear focus synchronously when a subtree is removed and reinserted', () => {
+ const document = createPolyfillDocument();
+ const dialog = document.createElement('div');
+ const button = document.createElement('button');
+ dialog.append(button);
+ document.body.append(dialog);
+ button.focus();
+ dialog.remove();
+ document.body.append(dialog);
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should keep a detached element blurred when it is reinserted', () => {
+ const document = createPolyfillDocument();
+ const button = document.createElement('button');
+ document.body.append(button);
+ button.focus();
+ button.remove();
+ expect(document.activeElement).toBe(document.body);
+ button.blur();
+ document.body.append(button);
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should cancel host focus before a focused subtree is disconnected', () => {
+ const polyfillWindow = new Window();
+ const activeElementStore = createWorkerActiveElementStore();
+ const focusTransport = createWorkerFocusTransport();
+ const connection = { mutate: jest.fn(), call: jest.fn() };
+ const document = polyfillWindow.document as unknown as Document;
+ const container = document.createElement('div');
+ const button = document.createElement('button');
+ const removeChild = jest.fn(({ node }: { node: Node }) =>
+ disconnectRemoteNode(node),
+ );
+
+ polyfillWindow[HOOKS].removeChild = (_parent, node) =>
+ removeChild({ node: node as unknown as Node });
+ installActiveElementDetachmentHook({
+ hooks: polyfillWindow[HOOKS],
+ activeElementStore,
+ onRemoveSubtree: focusTransport.blurFocusedElementWithinSubtree,
+ });
+ installFocusAndBlurMethodsPolyfill({
+ elementPrototype: polyfillWindow.Element.prototype,
+ activeElementStore,
+ forwardFocusMethod: focusTransport.forwardFocusMethod,
+ });
+ container.append(button);
+ document.body.append(container);
+ connectRemoteNode(container, connection);
+ remoteId(button);
+ focusTransport.setRootElement(container);
+ button.focus();
+ container.remove();
+
+ expect(connection.call).toHaveBeenLastCalledWith(remoteId(button), 'blur');
+ expect(connection.call.mock.invocationCallOrder[1]).toBeLessThan(
+ removeChild.mock.invocationCallOrder[0],
+ );
+ expect(activeElementStore.getActiveElement()).toBeNull();
+ });
+
+ it('should ignore a focus call on a detached element even if it is inserted later', () => {
+ const document = createPolyfillDocument();
+ const active = document.createElement('button');
+ const detached = document.createElement('button');
+ document.body.append(active);
+ active.focus();
+ detached.focus();
+ document.body.append(detached);
+
+ expect(document.activeElement).toBe(active);
+ });
+
+ it('should ignore focus on a disabled control', () => {
+ const document = createPolyfillDocument();
+ const button = document.createElement('button');
+
+ button.setAttribute('disabled', '');
+ document.body.append(button);
+ button.focus();
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should ignore focus on elements that are not focusable', () => {
+ const document = createPolyfillDocument();
+ const plainDiv = document.createElement('div');
+ const anchorWithoutHref = document.createElement('a');
+ const hiddenInput = document.createElement('input');
+
+ hiddenInput.setAttribute('type', 'hidden');
+ document.body.append(plainDiv, anchorWithoutHref, hiddenInput);
+ plainDiv.focus();
+ anchorWithoutHref.focus();
+ hiddenInput.focus();
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should focus elements made focusable by tabindex, href or contenteditable', () => {
+ const document = createPolyfillDocument();
+ const container = document.createElement('div');
+ const link = document.createElement('a');
+ const editor = document.createElement('div');
+
+ container.setAttribute('tabindex', '-1');
+ link.setAttribute('href', '/records');
+ editor.setAttribute('contenteditable', '');
+ document.body.append(container, link, editor);
+
+ container.focus();
+ expect(document.activeElement).toBe(container);
+ link.focus();
+ expect(document.activeElement).toBe(link);
+ editor.focus();
+ expect(document.activeElement).toBe(editor);
+ });
+
+ it('should focus links and media without href or controls once they have a tabindex', () => {
+ const document = createPolyfillDocument();
+ const buttonLikeLink = document.createElement('a');
+ const video = document.createElement('video');
+
+ buttonLikeLink.setAttribute('tabindex', '0');
+ video.setAttribute('tabindex', '-1');
+ document.body.append(buttonLikeLink, video);
+
+ buttonLikeLink.focus();
+ expect(document.activeElement).toBe(buttonLikeLink);
+ video.focus();
+ expect(document.activeElement).toBe(video);
+ });
+
+ it('should focus only the first summary of a details element by default', () => {
+ const document = createPolyfillDocument();
+ const details = document.createElement('details');
+ const firstSummary = document.createElement('summary');
+ const secondSummary = document.createElement('summary');
+ const orphanSummary = document.createElement('summary');
+
+ details.append(firstSummary, secondSummary);
+ document.body.append(details, orphanSummary);
+
+ secondSummary.focus();
+ orphanSummary.focus();
+ expect(document.activeElement).toBe(document.body);
+ firstSummary.focus();
+ expect(document.activeElement).toBe(firstSummary);
+ });
+
+ it('should ignore focus called on an object that is not a node', () => {
+ const document = createPolyfillDocument();
+ const focus = document.body.focus as (this: object) => void;
+
+ focus.call({});
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('should ignore blur on an element that is not active', () => {
+ const document = createPolyfillDocument();
+ const active = document.createElement('button');
+ const other = document.createElement('button');
+
+ document.body.append(active, other);
+ active.focus();
+ other.blur();
+
+ expect(document.activeElement).toBe(active);
+ });
+
+ it('should drive the focus pseudo-classes from the active element store', () => {
+ const polyfillWindow = new Window();
+ const activeElementStore = createWorkerActiveElementStore();
+
+ installActiveElementDetachmentHook({
+ hooks: polyfillWindow[HOOKS],
+ activeElementStore,
+ });
+ installFocusAndBlurMethodsPolyfill({
+ elementPrototype: polyfillWindow.Element.prototype,
+ activeElementStore,
+ });
+ installSelectorMethodsPolyfill({
+ elementPrototype: polyfillWindow.Element.prototype,
+ querySelectorTargets: [polyfillWindow.document],
+ resolveActiveElement: () => activeElementStore.getActiveElement(),
+ resolveFocusVisibleElement: () =>
+ activeElementStore.getFocusVisibleElement(),
+ });
+
+ const document = polyfillWindow.document as unknown as Document;
+ const container = document.createElement('div');
+ const button = document.createElement('button');
+
+ container.append(button);
+ document.body.append(container);
+ button.focus();
+
+ expect(button.matches(':focus')).toBe(true);
+ expect(container.matches(':focus-within')).toBe(true);
+ expect(document.querySelector(':focus')).toBe(button);
+ expect(button.matches(':focus-visible')).toBe(false);
+
+ activeElementStore.setActiveElement({
+ element: button,
+ isFocusVisible: true,
+ });
+
+ expect(button.matches(':focus-visible')).toBe(true);
+
+ button.blur();
+
+ expect(button.matches(':focus')).toBe(false);
+ expect(container.matches(':focus-within')).toBe(false);
+ expect(button.matches(':focus-visible')).toBe(false);
+
+ activeElementStore.setActiveElement({
+ element: button,
+ isFocusVisible: true,
+ });
+ container.remove();
+ document.body.append(container);
+
+ expect(button.matches(':focus-visible')).toBe(false);
+ expect(button.matches(':focus')).toBe(false);
+ });
+});
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 1ae6ec076c3..16772cd7a16 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
@@ -137,6 +137,8 @@ describe('@remote-dom/polyfill mutation hooks contract the worker MutationObserv
['Node', 'getRootNode'],
['Element', 'closest'],
['Element', 'matches'],
+ ['Element', 'focus'],
+ ['Element', 'blur'],
])(
'still ships %s without %s, which the worker polyfills install itself',
(className, methodName) => {
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerActiveElementStore.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerActiveElementStore.ts
new file mode 100644
index 00000000000..6142a5f6f16
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerActiveElementStore.ts
@@ -0,0 +1,43 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type WorkerActiveElementStore } from '@/polyfills/dom/types/WorkerActiveElementStore';
+
+type NodeWithIsConnected = {
+ isConnected?: boolean;
+};
+
+const isElementConnectedToDocument = (element: object): boolean =>
+ (element as NodeWithIsConnected).isConnected ?? false;
+
+export const createWorkerActiveElementStore = (): WorkerActiveElementStore => {
+ let activeElement: object | null = null;
+ let isFocusVisible = false;
+
+ const getActiveElement = (): object | null => {
+ if (
+ isDefined(activeElement) &&
+ !isElementConnectedToDocument(activeElement)
+ ) {
+ activeElement = null;
+ isFocusVisible = false;
+ }
+
+ return activeElement;
+ };
+
+ return {
+ getActiveElement,
+ getFocusVisibleElement: () => (isFocusVisible ? getActiveElement() : null),
+ setActiveElement: ({
+ element,
+ isFocusVisible: nextIsFocusVisible = false,
+ }) => {
+ if (isDefined(element) && !isElementConnectedToDocument(element)) {
+ return;
+ }
+
+ activeElement = element;
+ isFocusVisible = nextIsFocusVisible;
+ },
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerFocusTransport.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerFocusTransport.ts
new file mode 100644
index 00000000000..50a7cca3546
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerFocusTransport.ts
@@ -0,0 +1,41 @@
+import { callRemoteElementMethod } from '@remote-dom/core/elements';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type WorkerFocusMethodRequest } from '@/polyfills/dom/types/WorkerFocusMethodRequest';
+import { isAncestorOrSelfOfNode } from '@/polyfills/dom/utils/isAncestorOrSelfOfNode';
+import { isElementUnderRemoteRoot } from '@/polyfills/geometry/utils/isElementUnderRemoteRoot';
+
+export const createWorkerFocusTransport = () => {
+ let rootElement: object | null = null;
+ let focusedElement: object | null = null;
+
+ return {
+ setRootElement: (element: object): void => {
+ rootElement = element;
+ focusedElement = null;
+ },
+ forwardFocusMethod: ({
+ element,
+ methodName,
+ options,
+ }: WorkerFocusMethodRequest): void => {
+ if (!isElementUnderRemoteRoot(element, rootElement)) {
+ return;
+ }
+
+ focusedElement = methodName === 'focus' ? element : null;
+ callRemoteElementMethod(element as Element, methodName, options);
+ },
+ blurFocusedElementWithinSubtree: (node: object): void => {
+ if (
+ !isDefined(focusedElement) ||
+ !isAncestorOrSelfOfNode(node, focusedElement)
+ ) {
+ return;
+ }
+
+ callRemoteElementMethod(focusedElement as Element, 'blur');
+ focusedElement = null;
+ },
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/findElementByRemoteId.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/findElementByRemoteId.ts
new file mode 100644
index 00000000000..21faf6ade2f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/findElementByRemoteId.ts
@@ -0,0 +1,28 @@
+import { remoteId } from '@remote-dom/core/elements';
+
+import { NODE_TYPE_BY_NAME } from '@/polyfills/dom/constants/NodeTypeByName';
+import { type ElementLike } from '@/polyfills/dom/types/ElementLike';
+import { iterateElementSubtree } from '@/polyfills/dom/utils/iterateElementSubtree';
+
+type NodeWithNodeType = ElementLike & {
+ nodeType?: number;
+};
+
+export const findElementByRemoteId = ({
+ rootNode,
+ remoteElementId,
+}: {
+ rootNode: ElementLike;
+ remoteElementId: string;
+}): ElementLike | null => {
+ for (const node of iterateElementSubtree(rootNode)) {
+ if (
+ (node as NodeWithNodeType).nodeType === NODE_TYPE_BY_NAME.ELEMENT &&
+ remoteId(node as Node) === remoteElementId
+ ) {
+ return node;
+ }
+ }
+
+ return null;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installActiveElementDetachmentHook.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installActiveElementDetachmentHook.ts
new file mode 100644
index 00000000000..3ceaed07da5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installActiveElementDetachmentHook.ts
@@ -0,0 +1,40 @@
+import { type Hooks } from '@remote-dom/polyfill';
+import { CustomError, isDefined } from 'twenty-shared/utils';
+
+import { type WorkerActiveElementStore } from '@/polyfills/dom/types/WorkerActiveElementStore';
+import { isAncestorOrSelfOfNode } from '@/polyfills/dom/utils/isAncestorOrSelfOfNode';
+
+type InstallActiveElementDetachmentHookInput = {
+ hooks: Partial<Hooks> | null;
+ activeElementStore: WorkerActiveElementStore;
+ onRemoveSubtree?: (node: object) => void;
+};
+
+export const installActiveElementDetachmentHook = ({
+ hooks,
+ activeElementStore,
+ onRemoveSubtree,
+}: InstallActiveElementDetachmentHookInput): void => {
+ if (!isDefined(hooks)) {
+ throw new CustomError(
+ 'Worker focus tracking requires DOM mutation hooks',
+ 'FRONT_COMPONENT_DOM_MUTATION_HOOKS_UNAVAILABLE',
+ );
+ }
+
+ const previousRemoveChildHook = hooks.removeChild;
+
+ hooks.removeChild = (parent, node, index) => {
+ const activeElement = activeElementStore.getActiveElement();
+
+ if (
+ isDefined(activeElement) &&
+ isAncestorOrSelfOfNode(node, activeElement)
+ ) {
+ activeElementStore.setActiveElement({ element: null });
+ }
+
+ onRemoveSubtree?.(node);
+ previousRemoveChildHook?.(parent, node, index);
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installDocumentActiveElementPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installDocumentActiveElementPolyfill.ts
new file mode 100644
index 00000000000..6b4e52ed474
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installDocumentActiveElementPolyfill.ts
@@ -0,0 +1,21 @@
+import { type WorkerActiveElementStore } from '@/polyfills/dom/types/WorkerActiveElementStore';
+
+type DocumentWithBody = {
+ body?: object | null;
+};
+
+type InstallDocumentActiveElementPolyfillInput = {
+ documentTarget: DocumentWithBody;
+ activeElementStore: WorkerActiveElementStore;
+};
+
+export const installDocumentActiveElementPolyfill = ({
+ documentTarget,
+ activeElementStore,
+}: InstallDocumentActiveElementPolyfillInput): void => {
+ Object.defineProperty(documentTarget, 'activeElement', {
+ get: () =>
+ activeElementStore.getActiveElement() ?? documentTarget.body ?? null,
+ configurable: true,
+ });
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installFocusAndBlurMethodsPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installFocusAndBlurMethodsPolyfill.ts
new file mode 100644
index 00000000000..238ca46b18c
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installFocusAndBlurMethodsPolyfill.ts
@@ -0,0 +1,48 @@
+import { type WorkerActiveElementStore } from '@/polyfills/dom/types/WorkerActiveElementStore';
+import { type WorkerFocusMethodRequest } from '@/polyfills/dom/types/WorkerFocusMethodRequest';
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { isElementFocusable } from '@/polyfills/selectors/utils/isElementFocusable';
+import { definePolyfillMethod } from '@/polyfills/utils/definePolyfillMethod';
+
+type InstallFocusAndBlurMethodsPolyfillInput = {
+ elementPrototype: object;
+ activeElementStore: WorkerActiveElementStore;
+ forwardFocusMethod?: (request: WorkerFocusMethodRequest) => void;
+};
+
+export const installFocusAndBlurMethodsPolyfill = ({
+ elementPrototype,
+ activeElementStore,
+ forwardFocusMethod,
+}: InstallFocusAndBlurMethodsPolyfillInput): void => {
+ definePolyfillMethod({
+ target: elementPrototype,
+ methodName: 'focus',
+ method: (element: SelectorElementLike, options?: unknown): void => {
+ if (!isElementFocusable(element)) {
+ return;
+ }
+
+ activeElementStore.setActiveElement({ element });
+
+ if (activeElementStore.getActiveElement() === element) {
+ forwardFocusMethod?.({
+ element,
+ methodName: 'focus',
+ options: options as FocusOptions | undefined,
+ });
+ }
+ },
+ });
+
+ definePolyfillMethod({
+ target: elementPrototype,
+ methodName: 'blur',
+ method: (element: object): void => {
+ if (activeElementStore.getActiveElement() === element) {
+ activeElementStore.setActiveElement({ element: null });
+ forwardFocusMethod?.({ element, methodName: 'blur' });
+ }
+ },
+ });
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/StatePseudoClassMatcherByName.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/StatePseudoClassMatcherByName.ts
new file mode 100644
index 00000000000..f73ca1ce58e
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/StatePseudoClassMatcherByName.ts
@@ -0,0 +1,31 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { canElementBeDisabled } from '@/polyfills/selectors/utils/canElementBeDisabled';
+import { canElementBeRequired } from '@/polyfills/selectors/utils/canElementBeRequired';
+import { isElementChecked } from '@/polyfills/selectors/utils/isElementChecked';
+import { isElementDisabled } from '@/polyfills/selectors/utils/isElementDisabled';
+import { isElementIndeterminate } from '@/polyfills/selectors/utils/isElementIndeterminate';
+import { isElementLink } from '@/polyfills/selectors/utils/isElementLink';
+import { isElementOpen } from '@/polyfills/selectors/utils/isElementOpen';
+import { isElementPlaceholderShown } from '@/polyfills/selectors/utils/isElementPlaceholderShown';
+import { isElementReadWrite } from '@/polyfills/selectors/utils/isElementReadWrite';
+import { isElementRequired } from '@/polyfills/selectors/utils/isElementRequired';
+
+export const STATE_PSEUDO_CLASS_MATCHER_BY_NAME: Record<
+ string,
+ (element: SelectorElementLike) => boolean
+> = {
+ 'any-link': isElementLink,
+ checked: isElementChecked,
+ disabled: isElementDisabled,
+ enabled: (element) =>
+ canElementBeDisabled(element) && !isElementDisabled(element),
+ indeterminate: isElementIndeterminate,
+ link: isElementLink,
+ open: isElementOpen,
+ optional: (element) =>
+ canElementBeRequired(element) && !isElementRequired(element),
+ 'placeholder-shown': isElementPlaceholderShown,
+ 'read-only': (element) => !isElementReadWrite(element),
+ 'read-write': isElementReadWrite,
+ required: isElementRequired,
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/UnobservablePseudoClassNames.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/UnobservablePseudoClassNames.ts
index 76528210492..836e6d8ef32 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/UnobservablePseudoClassNames.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/UnobservablePseudoClassNames.ts
@@ -29,6 +29,7 @@ export const UNOBSERVABLE_PSEUDO_CLASS_NAMES = [
'target-within',
'user-invalid',
'user-valid',
+ 'valid',
'visited',
'volume-locked',
] as const;
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorElementLike.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorElementLike.ts
index 783ab243599..c97e0a8ee6b 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorElementLike.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorElementLike.ts
@@ -7,5 +7,10 @@ export type SelectorElementLike = {
childNodes?: ArrayLike<unknown>;
attributes?: Iterable<unknown>;
textContent?: unknown;
+ value?: unknown;
+ checked?: unknown;
+ disabled?: unknown;
+ selected?: unknown;
+ indeterminate?: unknown;
getAttribute?: (attributeName: string) => string | null;
};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfill.test.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfill.test.ts
index 25ea1fed545..1e206be6d11 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfill.test.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfill.test.ts
@@ -1,15 +1,18 @@
import { Window } from '@remote-dom/polyfill';
+import { type WorkerActiveElementStore } from '@/polyfills/dom/types/WorkerActiveElementStore';
+import { createWorkerActiveElementStore } from '@/polyfills/dom/utils/createWorkerActiveElementStore';
+
import { installSelectorMethodsPolyfill } from '../installSelectorMethodsPolyfill';
type SelectorFixture = {
document: Document;
- setActiveElement: (element: object | null) => void;
+ setActiveElement: WorkerActiveElementStore['setActiveElement'];
};
const createSelectorFixture = (): SelectorFixture => {
const polyfillWindow = new Window();
- let activeElement: object | null = null;
+ const activeElementStore = createWorkerActiveElementStore();
installSelectorMethodsPolyfill({
elementPrototype: polyfillWindow.Element.prototype,
@@ -18,14 +21,14 @@ const createSelectorFixture = (): SelectorFixture => {
polyfillWindow.DocumentFragment.prototype,
polyfillWindow.document,
],
- resolveActiveElement: () => activeElement,
+ resolveActiveElement: () => activeElementStore.getActiveElement(),
+ resolveFocusVisibleElement: () =>
+ activeElementStore.getFocusVisibleElement(),
});
return {
document: polyfillWindow.document as unknown as Document,
- setActiveElement: (element) => {
- activeElement = element;
- },
+ setActiveElement: activeElementStore.setActiveElement,
};
};
@@ -92,20 +95,120 @@ describe('installSelectorMethodsPolyfill', () => {
expect(firstTab.matches('button + button')).toBe(false);
});
+ it('should evaluate the disabled, enabled and checked pseudo-classes from attributes and properties', () => {
+ const { document } = createSelectorFixture();
+ const { firstTab, secondTab } = createTree(document);
+ const checkbox = document.createElement('input') as HTMLInputElement;
+ checkbox.setAttribute('type', 'checkbox');
+ checkbox.checked = true;
+ const uncheckedWithDefault = document.createElement(
+ 'input',
+ ) as HTMLInputElement;
+ uncheckedWithDefault.setAttribute('type', 'checkbox');
+ uncheckedWithDefault.setAttribute('checked', '');
+ uncheckedWithDefault.checked = false;
+ const defaultChecked = document.createElement('input');
+ defaultChecked.setAttribute('type', 'radio');
+ defaultChecked.setAttribute('checked', '');
+
+ expect(secondTab.matches(':disabled')).toBe(true);
+ expect(firstTab.matches(':disabled')).toBe(false);
+ expect(firstTab.matches(':enabled')).toBe(true);
+ expect(checkbox.matches(':checked')).toBe(true);
+ expect(uncheckedWithDefault.matches(':checked')).toBe(false);
+ expect(defaultChecked.matches(':checked')).toBe(true);
+ expect(firstTab.matches(':checked')).toBe(false);
+ });
+
it('should evaluate the focus pseudo-classes from the active element', () => {
const { document, setActiveElement } = createSelectorFixture();
const { list, firstTab, secondTab } = createTree(document);
- setActiveElement(firstTab);
+ setActiveElement({ element: firstTab, isFocusVisible: false });
expect(firstTab.matches(':focus')).toBe(true);
+ expect(firstTab.matches(':focus-visible')).toBe(false);
+ expect(document.querySelector(':focus-visible')).toBeNull();
+
+ setActiveElement({ element: firstTab, isFocusVisible: true });
+
expect(firstTab.matches(':focus-visible')).toBe(true);
+ expect(document.querySelector(':focus-visible')).toBe(firstTab);
expect(list.matches(':focus-within')).toBe(true);
expect(secondTab.matches(':focus')).toBe(false);
expect(secondTab.matches(':focus-within')).toBe(false);
- setActiveElement(secondTab);
+ setActiveElement({ element: secondTab });
expect(firstTab.matches(':focus')).toBe(false);
expect(secondTab.matches(':focus')).toBe(true);
+ expect(firstTab.matches(':focus-visible')).toBe(false);
+ expect(secondTab.matches(':focus-visible')).toBe(false);
+ });
+
+ it('should inherit fieldset disability except inside the first legend', () => {
+ const { document } = createSelectorFixture();
+ const outerFieldset = document.createElement('html-fieldset') as Element;
+ const firstLegend = document.createElement('html-legend') as Element;
+ const firstLegendInput = document.createElement('html-input') as Element;
+ const secondLegend = document.createElement('html-legend') as Element;
+ const secondLegendInput = document.createElement('html-input') as Element;
+ const nestedFieldset = document.createElement('html-fieldset') as Element;
+ const nestedLegend = document.createElement('html-legend') as Element;
+ const nestedInput = document.createElement('html-input') as Element;
+
+ outerFieldset.setAttribute('disabled', '');
+ nestedFieldset.setAttribute('disabled', '');
+ firstLegend.append(firstLegendInput);
+ secondLegend.append(secondLegendInput);
+ nestedLegend.append(nestedInput);
+ nestedFieldset.append(nestedLegend);
+ outerFieldset.append(firstLegend, secondLegend, nestedFieldset);
+
+ expect(firstLegendInput.matches(':disabled')).toBe(false);
+ expect(firstLegendInput.matches(':enabled')).toBe(true);
+ expect(secondLegendInput.matches(':disabled')).toBe(true);
+ expect(nestedInput.matches(':disabled')).toBe(true);
+ expect(firstLegend.matches(':enabled')).toBe(false);
+
+ outerFieldset.removeAttribute('disabled');
+ expect(secondLegendInput.matches(':disabled')).toBe(false);
+ expect(nestedInput.matches(':disabled')).toBe(false);
+ });
+
+ it('should respect disabled optgroups and selected option properties', () => {
+ const { document } = createSelectorFixture();
+ const group = document.createElement('html-optgroup') as Element;
+ const option = document.createElement('html-option') as HTMLOptionElement;
+ group.setAttribute('disabled', '');
+ group.append(option);
+ option.selected = true;
+
+ expect(option.matches(':disabled')).toBe(true);
+ expect(option.matches(':checked')).toBe(true);
+ option.selected = false;
+ expect(option.matches(':checked')).toBe(false);
+ });
+
+ it('should inherit disability for nested fieldsets but not options or optgroups', () => {
+ const { document } = createSelectorFixture();
+ const fieldset = document.createElement('html-fieldset') as Element;
+ const nestedFieldset = document.createElement('html-fieldset') as Element;
+ const select = document.createElement('html-select') as Element;
+ const group = document.createElement('html-optgroup') as Element;
+ const option = document.createElement('html-option') as Element;
+
+ fieldset.setAttribute('disabled', '');
+ group.append(option);
+ select.append(group);
+ fieldset.append(nestedFieldset, select);
+
+ expect(nestedFieldset.matches(':disabled')).toBe(true);
+ expect(select.matches(':disabled')).toBe(true);
+ expect(group.matches(':enabled')).toBe(true);
+ expect(option.matches(':enabled')).toBe(true);
+
+ select.setAttribute('disabled', '');
+ expect(group.matches(':disabled')).toBe(false);
+ expect(option.matches(':disabled')).toBe(false);
});
it('should anchor relative has selectors to the candidate', () => {
@@ -145,8 +248,10 @@ describe('installSelectorMethodsPolyfill', () => {
it('should evaluate not, is, where and has', () => {
const { document } = createSelectorFixture();
- const { list, firstTab } = createTree(document);
+ const { list, firstTab, secondTab } = createTree(document);
+ expect(firstTab.matches(':not(:disabled)')).toBe(true);
+ expect(secondTab.matches(':not(:disabled)')).toBe(false);
expect(firstTab.matches(':is(span, button)')).toBe(true);
expect(firstTab.matches(':where(span, .tab)')).toBe(true);
expect(list.matches(':has(span)')).toBe(true);
@@ -334,6 +439,7 @@ describe('installSelectorMethodsPolyfill', () => {
expect(Array.from(tabs)).toEqual([firstTab, secondTab]);
expect(tabs.item(0)).toBe(firstTab);
+ expect(list.querySelector(':disabled')).toBe(secondTab);
expect(list.querySelector('input')).toBeNull();
});
@@ -483,6 +589,239 @@ describe('installSelectorMethodsPolyfill', () => {
});
});
+ describe('control state pseudo-classes', () => {
+ it('should restrict :checked to checkable inputs and options', () => {
+ const { document } = createSelectorFixture();
+ const checkedDiv = document.createElement('div');
+ const checkedText = document.createElement('input');
+ const checkedRadio = document.createElement('input');
+ const selectedOption = document.createElement(
+ 'option',
+ ) as HTMLOptionElement;
+ checkedDiv.setAttribute('checked', '');
+ checkedText.setAttribute('type', 'text');
+ checkedText.setAttribute('checked', '');
+ checkedRadio.setAttribute('type', 'RADIO');
+ checkedRadio.setAttribute('checked', '');
+ selectedOption.selected = true;
+ document.body.append(
+ checkedDiv,
+ checkedText,
+ checkedRadio,
+ selectedOption,
+ );
+
+ expect(checkedDiv.matches(':checked')).toBe(false);
+ expect(checkedText.matches(':checked')).toBe(false);
+ expect(checkedRadio.matches(':checked')).toBe(true);
+ expect(selectedOption.matches(':checked')).toBe(true);
+ expect(Array.from(document.querySelectorAll(':checked'))).toEqual([
+ checkedRadio,
+ selectedOption,
+ ]);
+ });
+
+ it('should evaluate :read-only, :read-write and :placeholder-shown', () => {
+ const { document } = createSelectorFixture();
+ const { firstTab } = createTree(document);
+ const textInput = document.createElement('input') as HTMLInputElement;
+ const readOnlyInput = document.createElement('input');
+ const disabledTextarea = document.createElement('textarea');
+ const editor = document.createElement('div');
+ const nestedEditorText = document.createElement('span');
+ readOnlyInput.setAttribute('readonly', '');
+ disabledTextarea.setAttribute('disabled', '');
+ editor.setAttribute('contenteditable', 'true');
+ editor.append(nestedEditorText);
+ textInput.setAttribute('placeholder', 'Search');
+ document.body.append(textInput, readOnlyInput, disabledTextarea, editor);
+
+ expect(firstTab.matches(':read-only')).toBe(true);
+ expect(textInput.matches(':read-write')).toBe(true);
+ expect(readOnlyInput.matches(':read-only')).toBe(true);
+ expect(disabledTextarea.matches(':read-only')).toBe(true);
+ expect(nestedEditorText.matches(':read-write')).toBe(true);
+ const invalidEditor = document.createElement('div');
+ const nestedInvalidEditor = document.createElement('div');
+ invalidEditor.setAttribute('contenteditable', 'bogus');
+ nestedInvalidEditor.setAttribute('contenteditable', 'bogus');
+ editor.append(nestedInvalidEditor);
+ document.body.append(invalidEditor);
+ expect(invalidEditor.matches(':read-only')).toBe(true);
+ expect(nestedInvalidEditor.matches(':read-write')).toBe(true);
+ expect(textInput.matches(':placeholder-shown')).toBe(true);
+ textInput.value = 'acme';
+ expect(textInput.matches(':placeholder-shown')).toBe(false);
+
+ for (const inputType of ['hidden', 'checkbox']) {
+ const inputWithoutPlaceholder = document.createElement('input');
+ inputWithoutPlaceholder.setAttribute('type', inputType);
+ inputWithoutPlaceholder.setAttribute('placeholder', 'Search');
+ document.body.append(inputWithoutPlaceholder);
+
+ expect(inputWithoutPlaceholder.matches(':placeholder-shown')).toBe(
+ false,
+ );
+ }
+ });
+
+ it('should evaluate :indeterminate, :valid, :open and :defined', () => {
+ const { document } = createSelectorFixture();
+ const checkbox = document.createElement('input') as HTMLInputElement;
+ const progress = document.createElement('progress');
+ const details = document.createElement('details');
+ const plainDiv = document.createElement('div');
+ checkbox.setAttribute('type', 'checkbox');
+ checkbox.indeterminate = true;
+ details.setAttribute('open', '');
+ document.body.append(checkbox, progress, details, plainDiv);
+
+ expect(checkbox.matches(':indeterminate')).toBe(true);
+ expect(progress.matches(':indeterminate')).toBe(true);
+ expect(plainDiv.matches(':indeterminate')).toBe(false);
+ expect(checkbox.matches(':valid')).toBe(false);
+ expect(checkbox.matches(':invalid')).toBe(false);
+ expect(details.matches(':open')).toBe(true);
+ expect(plainDiv.matches(':open')).toBe(false);
+ const dialog = document.createElement('dialog');
+ dialog.setAttribute('open', '');
+ plainDiv.setAttribute('open', '');
+ document.body.append(dialog);
+ expect(dialog.matches(':open')).toBe(true);
+ expect(plainDiv.matches(':open')).toBe(false);
+ expect(plainDiv.matches(':defined')).toBe(true);
+ });
+
+ it('should match radios of a group without a checked member as indeterminate', () => {
+ const { document } = createSelectorFixture();
+ const createRadio = (name: string | null) => {
+ const radio = document.createElement('input');
+ radio.setAttribute('type', 'radio');
+
+ if (name !== null) {
+ radio.setAttribute('name', name);
+ }
+
+ return radio;
+ };
+ const firstPlan = createRadio('plan');
+ const secondPlan = createRadio('plan');
+ const namelessRadio = createRadio(null);
+ const otherForm = document.createElement('form');
+ const otherFormPlan = createRadio('plan');
+ const indeterminateText = document.createElement('input') as Element & {
+ indeterminate: boolean;
+ };
+ indeterminateText.indeterminate = true;
+ otherForm.append(otherFormPlan);
+ document.body.append(
+ firstPlan,
+ secondPlan,
+ namelessRadio,
+ otherForm,
+ indeterminateText,
+ );
+
+ expect(firstPlan.matches(':indeterminate')).toBe(true);
+ expect(namelessRadio.matches(':indeterminate')).toBe(true);
+ expect(indeterminateText.matches(':indeterminate')).toBe(false);
+
+ otherFormPlan.setAttribute('checked', '');
+ expect(firstPlan.matches(':indeterminate')).toBe(true);
+ expect(otherFormPlan.matches(':indeterminate')).toBe(false);
+
+ secondPlan.setAttribute('checked', '');
+ expect(firstPlan.matches(':indeterminate')).toBe(false);
+ expect(secondPlan.matches(':indeterminate')).toBe(false);
+ });
+
+ it('should derive the checked option from the select value or its first enabled option', () => {
+ const { document } = createSelectorFixture();
+ const createSelect = (optionValues: string[]) => {
+ const select = document.createElement('select') as unknown as Element &
+ Record<string, unknown>;
+ const options = optionValues.map((optionValue) => {
+ const option = document.createElement('option');
+
+ option.setAttribute('value', optionValue);
+
+ return option;
+ });
+
+ select.append(...options);
+ document.body.append(select);
+
+ return { select, options };
+ };
+
+ const controlledSelect = createSelect(['first', 'second']);
+ controlledSelect.select.value = 'second';
+
+ const uncontrolledSelect = createSelect(['first', 'second']);
+ uncontrolledSelect.options[0].setAttribute('disabled', '');
+
+ const multipleSelect = createSelect(['first', 'second']);
+ multipleSelect.select.setAttribute('multiple', '');
+
+ const duplicateValueSelect = createSelect(['first', 'second', 'first']);
+ duplicateValueSelect.select.value = 'first';
+
+ expect(controlledSelect.select.querySelector('option:checked')).toBe(
+ controlledSelect.options[1],
+ );
+ expect(uncontrolledSelect.select.querySelector('option:checked')).toBe(
+ uncontrolledSelect.options[1],
+ );
+ expect(multipleSelect.select.querySelector('option:checked')).toBeNull();
+ expect(
+ Array.from(
+ duplicateValueSelect.select.querySelectorAll('option:checked'),
+ ),
+ ).toEqual([duplicateValueSelect.options[0]]);
+ });
+
+ it.each(['button', 'color', 'hidden', 'image', 'range', 'reset', 'submit'])(
+ 'should exclude %s inputs from both required and optional selectors',
+ (inputType) => {
+ const { document } = createSelectorFixture();
+ const input = document.createElement('html-input') as Element;
+
+ input.setAttribute('type', inputType);
+ document.body.append(input);
+
+ expect(input.matches(':required, :optional')).toBe(false);
+ input.setAttribute('required', '');
+ expect(input.matches(':required, :optional')).toBe(false);
+ expect(document.querySelectorAll(':required, :optional')).toHaveLength(
+ 0,
+ );
+ },
+ );
+
+ it('should evaluate :required, :optional, :any-link and :link', () => {
+ const { document } = createSelectorFixture();
+ const requiredInput = document.createElement('input');
+ const optionalSelect = document.createElement('select');
+ const link = document.createElement('a');
+ const placeholderLink = document.createElement('a');
+ requiredInput.setAttribute('required', '');
+ link.setAttribute('href', '/records');
+ document.body.append(
+ requiredInput,
+ optionalSelect,
+ link,
+ placeholderLink,
+ );
+
+ expect(requiredInput.matches(':required')).toBe(true);
+ expect(requiredInput.matches(':optional')).toBe(false);
+ expect(optionalSelect.matches(':optional')).toBe(true);
+ expect(link.matches(':any-link')).toBe(true);
+ expect(link.matches(':link')).toBe(true);
+ expect(placeholderLink.matches(':any-link')).toBe(false);
+ });
+ });
+
describe(':nth-child of a selector', () => {
it('should count :nth-child and :nth-last-child among siblings matching the of selector', () => {
const { document } = createSelectorFixture();
@@ -524,8 +863,10 @@ describe('installSelectorMethodsPolyfill', () => {
const fragment = document.createDocumentFragment();
const button = document.createElement('html-button') as Element;
const span = document.createElement('span');
+ button.setAttribute('disabled', '');
fragment.append(button, span);
+ expect(fragment.querySelector(':disabled')).toBe(button);
expect(fragment.querySelector('button')).toBe(button);
expect(
Array.from(fragment.querySelectorAll('span:first-of-type')),
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteControls.test.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteControls.test.ts
new file mode 100644
index 00000000000..4dc76899212
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteControls.test.ts
@@ -0,0 +1,156 @@
+import '@/remote/generated/remote-elements';
+
+import { serializeEvent } from '@/host/events/utils/serializeEvent';
+import { installSelectorMethodsPolyfill } from '@/polyfills/selectors/utils/installSelectorMethodsPolyfill';
+import { applySerializedEventTargetProperties } from '@/remote/elements/utils/applySerializedEventTargetProperties';
+import { patchRemoteElementAttributes } from '@/remote/elements/utils/patchRemoteElementAttributes';
+
+type RemoteElementWithProperties = HTMLElement & Record<string, unknown>;
+
+const createRemoteElement = (tagName: string): RemoteElementWithProperties => {
+ const element = document.createElement(
+ tagName,
+ ) as RemoteElementWithProperties;
+
+ installSelectorMethodsPolyfill({
+ elementPrototype: element,
+ querySelectorTargets: [element],
+ resolveActiveElement: () => null,
+ resolveFocusVisibleElement: () => null,
+ });
+
+ return element;
+};
+
+const createRadio = (name: string): RemoteElementWithProperties => {
+ const radio = createRemoteElement('html-input');
+
+ radio.setAttribute('type', 'radio');
+ radio.setAttribute('name', name);
+ radio.setAttribute('checked', '');
+
+ return radio;
+};
+
+describe('installSelectorMethodsPolyfill on remote control state', () => {
+ beforeAll(() => {
+ patchRemoteElementAttributes();
+ });
+
+ it('should uncheck only radios with the same name and form owner after a host event', () => {
+ const root = createRemoteElement('html-div');
+ const form = createRemoteElement('html-form');
+ const otherForm = createRemoteElement('html-form');
+ const firstRadio = createRadio('plan');
+ const nextRadio = createRadio('plan');
+ const externalRadio = createRadio('plan');
+ const otherNameRadio = createRadio('billing');
+ const otherFormRadio = createRadio('plan');
+ const detachedRadio = createRadio('plan');
+ const checkbox = createRemoteElement('html-input');
+ const hostRadio = document.createElement('input');
+
+ form.setAttribute('id', 'plan-form');
+ externalRadio.setAttribute('form', 'plan-form');
+ checkbox.setAttribute('type', 'checkbox');
+ checkbox.setAttribute('name', 'plan');
+ checkbox.checked = true;
+ nextRadio.checked = false;
+ form.append(firstRadio, nextRadio, otherNameRadio, checkbox);
+ otherForm.append(otherFormRadio);
+ root.append(form, otherForm, externalRadio);
+ hostRadio.type = 'radio';
+ hostRadio.checked = true;
+
+ applySerializedEventTargetProperties({
+ element: nextRadio,
+ eventData: serializeEvent({ type: 'change', target: hostRadio }),
+ });
+
+ expect(Array.from(root.querySelectorAll(':checked'))).toEqual([
+ nextRadio,
+ otherNameRadio,
+ checkbox,
+ otherFormRadio,
+ ]);
+ expect(detachedRadio.matches(':checked')).toBe(true);
+ expect(firstRadio.matches('[checked]')).toBe(true);
+ expect(externalRadio.checked).toBe(false);
+ });
+
+ it('should keep unnamed radios independent after a host event', () => {
+ const root = createRemoteElement('html-div');
+ const firstRadio = createRadio('');
+ const nextRadio = createRadio('');
+
+ root.append(firstRadio, nextRadio);
+ nextRadio.checked = false;
+
+ applySerializedEventTargetProperties({
+ element: nextRadio,
+ eventData: { type: 'change', checked: true },
+ });
+
+ expect(Array.from(root.querySelectorAll(':checked'))).toEqual([
+ firstRadio,
+ nextRadio,
+ ]);
+ });
+
+ it('should preserve every selected option in a multiple select across host events', () => {
+ const select = createRemoteElement('html-select');
+ const optionGroup = createRemoteElement('html-optgroup');
+ const firstOption = createRemoteElement('html-option');
+ const duplicateOption = createRemoteElement('html-option');
+ const lastOption = createRemoteElement('html-option');
+ const hostSelect = document.createElement('select');
+ const hostOptionGroup = document.createElement('optgroup');
+ const hostFirstOption = document.createElement('option');
+ const hostDuplicateOption = document.createElement('option');
+ const hostLastOption = document.createElement('option');
+
+ select.multiple = true;
+ firstOption.value = 'duplicate';
+ duplicateOption.value = 'duplicate';
+ lastOption.value = 'last';
+ firstOption.selected = true;
+ lastOption.selected = true;
+ select.value = 'duplicate';
+ optionGroup.append(duplicateOption, lastOption);
+ select.append(firstOption, optionGroup);
+
+ expect(Array.from(select.querySelectorAll('option:checked'))).toEqual([
+ firstOption,
+ lastOption,
+ ]);
+
+ hostSelect.multiple = true;
+ hostFirstOption.value = 'duplicate';
+ hostDuplicateOption.value = 'duplicate';
+ hostLastOption.value = 'last';
+ hostOptionGroup.append(hostDuplicateOption, hostLastOption);
+ hostSelect.append(hostFirstOption, hostOptionGroup);
+ hostDuplicateOption.selected = true;
+ hostLastOption.selected = true;
+
+ applySerializedEventTargetProperties({
+ element: select,
+ eventData: serializeEvent({ type: 'change', target: hostSelect }),
+ });
+
+ expect(Array.from(select.querySelectorAll('option:checked'))).toEqual([
+ duplicateOption,
+ lastOption,
+ ]);
+
+ hostDuplicateOption.selected = false;
+ hostLastOption.selected = false;
+
+ applySerializedEventTargetProperties({
+ element: select,
+ eventData: serializeEvent({ type: 'change', target: hostSelect }),
+ });
+
+ expect(Array.from(select.querySelectorAll('option:checked'))).toEqual([]);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteElements.test.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteElements.test.ts
index f6423e09169..c8cfe878da6 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteElements.test.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteElements.test.ts
@@ -16,6 +16,7 @@ const createRemoteElement = (tagName: string): RemoteElementWithProperties => {
elementPrototype: element,
querySelectorTargets: [element],
resolveActiveElement: () => null,
+ resolveFocusVisibleElement: () => null,
});
return element;
@@ -27,6 +28,25 @@ describe('installSelectorMethodsPolyfill on remote elements', () => {
patchRemoteElementAttributes();
});
+ it('should use live control properties after an attribute initializes them', () => {
+ const button = createRemoteElement('html-button');
+ const checkbox = createRemoteElement('html-input');
+
+ button.setAttribute('disabled', '');
+ checkbox.setAttribute('type', 'checkbox');
+ checkbox.setAttribute('checked', '');
+ expect(button.matches(':disabled')).toBe(true);
+ expect(checkbox.matches(':checked')).toBe(true);
+
+ button.disabled = false;
+ checkbox.checked = false;
+ expect(button.matches(':disabled')).toBe(false);
+ expect(button.matches(':enabled')).toBe(true);
+ expect(button.matches(':not([disabled])')).toBe(true);
+ expect(checkbox.matches(':checked')).toBe(false);
+ expect(checkbox.matches('[checked]')).toBe(true);
+ });
+
it('should read declared remote properties and ignore inherited accessors', () => {
const button = createRemoteElement('html-button');
@@ -67,11 +87,32 @@ describe('installSelectorMethodsPolyfill on remote elements', () => {
it('should prefer the live property over a stale attribute', () => {
const input = createRemoteElement('html-input');
+ const details = createRemoteElement('html-details');
input.setAttribute('aria-label', 'First label');
input['aria-label'] = 'Second label';
+ input.setAttribute('readonly', '');
+ input.readOnly = false;
+ details.setAttribute('open', '');
+ details.open = false;
expect(input.matches('[aria-label="Second label"]')).toBe(true);
expect(input.matches('[aria-label="First label"]')).toBe(false);
+ expect(input.matches(':read-write')).toBe(true);
+ expect(input.matches(':read-only')).toBe(false);
+ expect(details.matches(':open')).toBe(false);
+ });
+
+ it('should report the option matching a controlled select value as checked', () => {
+ const select = createRemoteElement('html-select');
+ const firstOption = createRemoteElement('html-option');
+ const secondOption = createRemoteElement('html-option');
+
+ firstOption.value = 'first';
+ secondOption.value = 'second';
+ select.append(firstOption, secondOption);
+ select.value = 'second';
+
+ expect(select.querySelector('option:checked')).toBe(secondOption);
});
});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/buildSelectorPseudoClassMatchers.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/buildSelectorPseudoClassMatchers.ts
index f0ae484eeb3..ac7fb03f016 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/buildSelectorPseudoClassMatchers.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/buildSelectorPseudoClassMatchers.ts
@@ -1,4 +1,5 @@
import { isAncestorOrSelfOfNode } from '@/polyfills/dom/utils/isAncestorOrSelfOfNode';
+import { STATE_PSEUDO_CLASS_MATCHER_BY_NAME } from '@/polyfills/selectors/constants/StatePseudoClassMatcherByName';
import { UNOBSERVABLE_PSEUDO_CLASS_NAMES } from '@/polyfills/selectors/constants/UnobservablePseudoClassNames';
import { type CssSelectPseudoClassMatchers } from '@/polyfills/selectors/types/CssSelectPseudoClassMatchers';
import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
@@ -17,8 +18,10 @@ const isAlwaysMatching = (_element: SelectorElementLike): boolean => true;
export const buildSelectorPseudoClassMatchers = ({
resolveActiveElement,
+ resolveFocusVisibleElement,
}: {
resolveActiveElement: () => object | null;
+ resolveFocusVisibleElement: () => object | null;
}): CssSelectPseudoClassMatchers => {
const isActiveElement = (element: SelectorElementLike): boolean =>
element === resolveActiveElement();
@@ -30,11 +33,21 @@ export const buildSelectorPseudoClassMatchers = ({
isNeverMatching,
]),
),
+ // css-select's built-in aliases such as :disabled win over matcher
+ // functions, so each state pseudo-class goes through a string alias.
+ ...Object.fromEntries(
+ Object.entries(STATE_PSEUDO_CLASS_MATCHER_BY_NAME).flatMap(
+ ([pseudoClassName, matcher]) => [
+ [pseudoClassName, `:twenty-${pseudoClassName}`],
+ [`twenty-${pseudoClassName}`, matcher],
+ ],
+ ),
+ ),
state: isNeverMatchingWithArgument,
defined: isAlwaysMatching,
root: (element) => isDocumentNode(element.parentNode),
focus: isActiveElement,
- 'focus-visible': isActiveElement,
+ 'focus-visible': (element) => element === resolveFocusVisibleElement(),
'focus-within': (element) =>
isAncestorOrSelfOfNode(element, resolveActiveElement()),
};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/canElementBeDisabled.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/canElementBeDisabled.ts
new file mode 100644
index 00000000000..ccdb5bbe1af
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/canElementBeDisabled.ts
@@ -0,0 +1,15 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+
+const TAG_NAMES_THAT_CAN_BE_DISABLED = new Set([
+ 'button',
+ 'input',
+ 'select',
+ 'textarea',
+ 'fieldset',
+ 'optgroup',
+ 'option',
+]);
+
+export const canElementBeDisabled = (element: SelectorElementLike): boolean =>
+ TAG_NAMES_THAT_CAN_BE_DISABLED.has(resolveHtmlTagNameOfElement(element));
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/canElementBeRequired.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/canElementBeRequired.ts
new file mode 100644
index 00000000000..46998964bcb
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/canElementBeRequired.ts
@@ -0,0 +1,22 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+
+const TAG_NAMES_THAT_CAN_BE_REQUIRED = new Set(['input', 'select', 'textarea']);
+
+const INPUT_TYPES_WITHOUT_REQUIRED = new Set([
+ 'button',
+ 'color',
+ 'hidden',
+ 'image',
+ 'range',
+ 'reset',
+ 'submit',
+]);
+
+export const canElementBeRequired = (element: SelectorElementLike): boolean =>
+ TAG_NAMES_THAT_CAN_BE_REQUIRED.has(resolveHtmlTagNameOfElement(element)) &&
+ !(
+ resolveHtmlTagNameOfElement(element) === 'input' &&
+ INPUT_TYPES_WITHOUT_REQUIRED.has(resolveInputTypeOfElement(element))
+ );
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectOptionsOfSelect.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectOptionsOfSelect.ts
new file mode 100644
index 00000000000..c3604d687b1
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectOptionsOfSelect.ts
@@ -0,0 +1,19 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { collectChildNodes } from '@/polyfills/selectors/utils/collectChildNodes';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+
+export const collectOptionsOfSelect = (
+ select: SelectorElementLike,
+): SelectorElementLike[] =>
+ collectChildNodes(select).flatMap((childNode) => {
+ if (resolveHtmlTagNameOfElement(childNode) === 'option') {
+ return [childNode];
+ }
+
+ return resolveHtmlTagNameOfElement(childNode) === 'optgroup'
+ ? collectChildNodes(childNode).filter(
+ (optgroupChildNode) =>
+ resolveHtmlTagNameOfElement(optgroupChildNode) === 'option',
+ )
+ : [];
+ });
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/createSelectorMatcherResolver.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/createSelectorMatcherResolver.ts
index 5288600fb93..18fe4126f68 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/createSelectorMatcherResolver.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/createSelectorMatcherResolver.ts
@@ -14,11 +14,14 @@ import { resolveSelectorScopeTarget } from '@/polyfills/selectors/utils/resolveS
export const createSelectorMatcherResolver = ({
resolveActiveElement,
+ resolveFocusVisibleElement,
}: {
resolveActiveElement: () => object | null;
+ resolveFocusVisibleElement: () => object | null;
}): SelectorMatcherResolver => {
const pseudoClassMatchers = buildSelectorPseudoClassMatchers({
resolveActiveElement,
+ resolveFocusVisibleElement,
});
const unscopedMatcherBySelectorsText = new Map<string, SelectorMatcher>();
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/installSelectorMethodsPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/installSelectorMethodsPolyfill.ts
index 6006d76b209..6dfa10640ca 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/installSelectorMethodsPolyfill.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/installSelectorMethodsPolyfill.ts
@@ -12,15 +12,18 @@ type InstallSelectorMethodsPolyfillInput = {
elementPrototype: object;
querySelectorTargets: object[];
resolveActiveElement: () => object | null;
+ resolveFocusVisibleElement: () => object | null;
};
export const installSelectorMethodsPolyfill = ({
elementPrototype,
querySelectorTargets,
resolveActiveElement,
+ resolveFocusVisibleElement,
}: InstallSelectorMethodsPolyfillInput): void => {
const { resolveSelectorMatcher } = createSelectorMatcherResolver({
resolveActiveElement,
+ resolveFocusVisibleElement,
});
const createMatcherForScope = ({
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementChecked.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementChecked.ts
new file mode 100644
index 00000000000..4f7493bfc09
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementChecked.ts
@@ -0,0 +1,21 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { isOptionElementSelected } from '@/polyfills/selectors/utils/isOptionElementSelected';
+import { readBooleanControlState } from '@/polyfills/selectors/utils/readBooleanControlState';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+
+const CHECKABLE_INPUT_TYPES = new Set(['checkbox', 'radio']);
+
+export const isElementChecked = (element: SelectorElementLike): boolean => {
+ const tagName = resolveHtmlTagNameOfElement(element);
+
+ if (tagName === 'option') {
+ return isOptionElementSelected(element);
+ }
+
+ return (
+ tagName === 'input' &&
+ CHECKABLE_INPUT_TYPES.has(resolveInputTypeOfElement(element)) &&
+ readBooleanControlState({ element, propertyName: 'checked' })
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementContentEditable.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementContentEditable.ts
new file mode 100644
index 00000000000..aba32ef9b23
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementContentEditable.ts
@@ -0,0 +1,23 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { resolveInheritedAttributeValue } from '@/polyfills/selectors/utils/resolveInheritedAttributeValue';
+
+const CONTENT_EDITABLE_KEYWORDS = new Set([
+ '',
+ 'true',
+ 'false',
+ 'plaintext-only',
+]);
+
+export const isElementContentEditable = (
+ element: SelectorElementLike,
+): boolean => {
+ const contentEditableValue = resolveInheritedAttributeValue({
+ element,
+ attributeName: 'contenteditable',
+ isValueAccepted: (value) => CONTENT_EDITABLE_KEYWORDS.has(value),
+ });
+
+ return isDefined(contentEditableValue) && contentEditableValue !== 'false';
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementDisabled.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementDisabled.ts
new file mode 100644
index 00000000000..a5b2a5c9a3d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementDisabled.ts
@@ -0,0 +1,57 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { canElementBeDisabled } from '@/polyfills/selectors/utils/canElementBeDisabled';
+import { isInsideFirstLegendOfFieldset } from '@/polyfills/selectors/utils/isInsideFirstLegendOfFieldset';
+import { readBooleanControlState } from '@/polyfills/selectors/utils/readBooleanControlState';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveParentElement } from '@/polyfills/selectors/utils/resolveParentElement';
+
+const TAG_NAMES_DISABLED_BY_ANCESTOR_FIELDSET = new Set([
+ 'button',
+ 'fieldset',
+ 'input',
+ 'select',
+ 'textarea',
+]);
+
+const hasOwnDisabledState = (element: SelectorElementLike): boolean =>
+ readBooleanControlState({ element, propertyName: 'disabled' });
+export const isElementDisabled = (element: SelectorElementLike): boolean => {
+ if (!canElementBeDisabled(element)) {
+ return false;
+ }
+
+ if (hasOwnDisabledState(element)) {
+ return true;
+ }
+
+ const tagName = resolveHtmlTagNameOfElement(element);
+ let ancestor = resolveParentElement(element);
+
+ if (tagName === 'option') {
+ return (
+ isDefined(ancestor) &&
+ resolveHtmlTagNameOfElement(ancestor) === 'optgroup' &&
+ hasOwnDisabledState(ancestor)
+ );
+ }
+
+ if (!TAG_NAMES_DISABLED_BY_ANCESTOR_FIELDSET.has(tagName)) {
+ return false;
+ }
+
+ while (isDefined(ancestor)) {
+ if (
+ resolveHtmlTagNameOfElement(ancestor) === 'fieldset' &&
+ hasOwnDisabledState(ancestor) &&
+ !isInsideFirstLegendOfFieldset({ element, fieldset: ancestor })
+ ) {
+ return true;
+ }
+
+ ancestor = resolveParentElement(ancestor);
+ }
+
+ return false;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementFocusable.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementFocusable.ts
new file mode 100644
index 00000000000..383fdf87183
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementFocusable.ts
@@ -0,0 +1,29 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+import { isElementContentEditable } from '@/polyfills/selectors/utils/isElementContentEditable';
+import { isElementDisabled } from '@/polyfills/selectors/utils/isElementDisabled';
+import { isFocusableByDefault } from '@/polyfills/selectors/utils/isFocusableByDefault';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+
+export const isElementFocusable = (element: SelectorElementLike): boolean => {
+ if (isElementDisabled(element)) {
+ return false;
+ }
+
+ const tagName = resolveHtmlTagNameOfElement(element);
+
+ if (tagName === 'input') {
+ return resolveInputTypeOfElement(element) !== 'hidden';
+ }
+
+ if (tagName === 'area') {
+ return hasElementAttributeIgnoringCase(element, 'href');
+ }
+
+ return (
+ isFocusableByDefault(element) ||
+ hasElementAttributeIgnoringCase(element, 'tabindex') ||
+ isElementContentEditable(element)
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementIndeterminate.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementIndeterminate.ts
new file mode 100644
index 00000000000..095e87513bd
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementIndeterminate.ts
@@ -0,0 +1,27 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+import { isRadioButtonGroupChecked } from '@/polyfills/selectors/utils/isRadioButtonGroupChecked';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+
+export const isElementIndeterminate = (
+ element: SelectorElementLike,
+): boolean => {
+ const tagName = resolveHtmlTagNameOfElement(element);
+
+ if (tagName === 'progress') {
+ return !hasElementAttributeIgnoringCase(element, 'value');
+ }
+
+ if (tagName !== 'input') {
+ return false;
+ }
+
+ const inputType = resolveInputTypeOfElement(element);
+
+ if (inputType === 'checkbox') {
+ return element.indeterminate === true;
+ }
+
+ return inputType === 'radio' && !isRadioButtonGroupChecked(element);
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementLink.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementLink.ts
new file mode 100644
index 00000000000..8bec2b760f2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementLink.ts
@@ -0,0 +1,9 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+
+const LINK_TAG_NAMES = new Set(['a', 'area', 'link']);
+
+export const isElementLink = (element: SelectorElementLike): boolean =>
+ LINK_TAG_NAMES.has(resolveHtmlTagNameOfElement(element)) &&
+ hasElementAttributeIgnoringCase(element, 'href');
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementOpen.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementOpen.ts
new file mode 100644
index 00000000000..adc1b543018
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementOpen.ts
@@ -0,0 +1,9 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+
+const OPENABLE_TAG_NAMES = new Set(['details', 'dialog']);
+
+export const isElementOpen = (element: SelectorElementLike): boolean =>
+ OPENABLE_TAG_NAMES.has(resolveHtmlTagNameOfElement(element)) &&
+ hasElementAttributeIgnoringCase(element, 'open');
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementPlaceholderShown.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementPlaceholderShown.ts
new file mode 100644
index 00000000000..1e707cc386b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementPlaceholderShown.ts
@@ -0,0 +1,49 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { readElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/readElementAttributeIgnoringCase';
+import { readElementValue } from '@/polyfills/selectors/utils/readElementValue';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+
+const TAG_NAMES_WITH_PLACEHOLDER = new Set(['input', 'textarea']);
+
+const INPUT_TYPES_WITHOUT_PLACEHOLDER = new Set([
+ 'button',
+ 'checkbox',
+ 'color',
+ 'date',
+ 'datetime-local',
+ 'file',
+ 'hidden',
+ 'image',
+ 'month',
+ 'radio',
+ 'range',
+ 'reset',
+ 'submit',
+ 'time',
+ 'week',
+]);
+
+export const isElementPlaceholderShown = (
+ element: SelectorElementLike,
+): boolean => {
+ const tagName = resolveHtmlTagNameOfElement(element);
+
+ if (
+ !TAG_NAMES_WITH_PLACEHOLDER.has(tagName) ||
+ (tagName === 'input' &&
+ INPUT_TYPES_WITHOUT_PLACEHOLDER.has(resolveInputTypeOfElement(element)))
+ ) {
+ return false;
+ }
+
+ const placeholder = readElementAttributeIgnoringCase(element, 'placeholder');
+
+ if (!isNonEmptyString(placeholder)) {
+ return false;
+ }
+
+ return !isNonEmptyString(readElementValue(element));
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementReadWrite.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementReadWrite.ts
new file mode 100644
index 00000000000..36dbcc4e77b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementReadWrite.ts
@@ -0,0 +1,40 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+import { isElementContentEditable } from '@/polyfills/selectors/utils/isElementContentEditable';
+import { isElementDisabled } from '@/polyfills/selectors/utils/isElementDisabled';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+
+const NON_EDITABLE_INPUT_TYPES = new Set([
+ 'button',
+ 'checkbox',
+ 'color',
+ 'file',
+ 'hidden',
+ 'image',
+ 'radio',
+ 'range',
+ 'reset',
+ 'submit',
+]);
+
+const isEditableFormControl = (element: SelectorElementLike): boolean =>
+ !hasElementAttributeIgnoringCase(element, 'readonly') &&
+ !isElementDisabled(element);
+
+export const isElementReadWrite = (element: SelectorElementLike): boolean => {
+ const tagName = resolveHtmlTagNameOfElement(element);
+
+ if (tagName === 'textarea') {
+ return isEditableFormControl(element);
+ }
+
+ if (tagName === 'input') {
+ return (
+ !NON_EDITABLE_INPUT_TYPES.has(resolveInputTypeOfElement(element)) &&
+ isEditableFormControl(element)
+ );
+ }
+
+ return isElementContentEditable(element);
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementRequired.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementRequired.ts
new file mode 100644
index 00000000000..f8e9eb81f54
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isElementRequired.ts
@@ -0,0 +1,7 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { canElementBeRequired } from '@/polyfills/selectors/utils/canElementBeRequired';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+
+export const isElementRequired = (element: SelectorElementLike): boolean =>
+ canElementBeRequired(element) &&
+ hasElementAttributeIgnoringCase(element, 'required');
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isFocusableByDefault.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isFocusableByDefault.ts
new file mode 100644
index 00000000000..9751f76d9dd
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isFocusableByDefault.ts
@@ -0,0 +1,32 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+import { isSummaryOfItsDetails } from '@/polyfills/selectors/utils/isSummaryOfItsDetails';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+const TAG_NAMES_FOCUSABLE_WITH_CONTROLS = new Set(['audio', 'video']);
+const ALWAYS_FOCUSABLE_TAG_NAMES = new Set([
+ 'button',
+ 'iframe',
+ 'select',
+ 'textarea',
+]);
+
+export const isFocusableByDefault = (element: SelectorElementLike): boolean => {
+ const tagName = resolveHtmlTagNameOfElement(element);
+
+ if (ALWAYS_FOCUSABLE_TAG_NAMES.has(tagName)) {
+ return true;
+ }
+
+ if (tagName === 'a') {
+ return hasElementAttributeIgnoringCase(element, 'href');
+ }
+
+ if (tagName === 'summary') {
+ return isSummaryOfItsDetails(element);
+ }
+
+ return (
+ TAG_NAMES_FOCUSABLE_WITH_CONTROLS.has(tagName) &&
+ hasElementAttributeIgnoringCase(element, 'controls')
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isInsideFirstLegendOfFieldset.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isInsideFirstLegendOfFieldset.ts
new file mode 100644
index 00000000000..704e2470ca5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isInsideFirstLegendOfFieldset.ts
@@ -0,0 +1,27 @@
+import { isAncestorOrSelfOfNode } from '@/polyfills/dom/utils/isAncestorOrSelfOfNode';
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { isSelectorElementNode } from '@/polyfills/selectors/utils/isSelectorElementNode';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+
+export const isInsideFirstLegendOfFieldset = ({
+ element,
+ fieldset,
+}: {
+ element: SelectorElementLike;
+ fieldset: SelectorElementLike;
+}): boolean => {
+ const children = fieldset.childNodes ?? [];
+
+ for (let index = 0; index < children.length; index += 1) {
+ const child = children[index];
+
+ if (
+ isSelectorElementNode(child) &&
+ resolveHtmlTagNameOfElement(child) === 'legend'
+ ) {
+ return isAncestorOrSelfOfNode(child, element);
+ }
+ }
+
+ return false;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isOptionElementSelected.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isOptionElementSelected.ts
new file mode 100644
index 00000000000..99821145e9a
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isOptionElementSelected.ts
@@ -0,0 +1,40 @@
+import { isArray, isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { collectOptionsOfSelect } from '@/polyfills/selectors/utils/collectOptionsOfSelect';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+import { isOptionSelectedByDefault } from '@/polyfills/selectors/utils/isOptionSelectedByDefault';
+import { readBooleanControlState } from '@/polyfills/selectors/utils/readBooleanControlState';
+import { resolveOptionValue } from '@/polyfills/selectors/utils/resolveOptionValue';
+import { resolveOwnerSelectElement } from '@/polyfills/selectors/utils/resolveOwnerSelectElement';
+
+export const isOptionElementSelected = (
+ option: SelectorElementLike,
+): boolean => {
+ const select = resolveOwnerSelectElement(option);
+ const selectValue = select?.value;
+
+ if (
+ isDefined(select) &&
+ isString(selectValue) &&
+ !hasElementAttributeIgnoringCase(select, 'multiple')
+ ) {
+ return (
+ collectOptionsOfSelect(select).find(
+ (candidateOption) =>
+ resolveOptionValue(candidateOption) === selectValue,
+ ) === option
+ );
+ }
+
+ if (isArray(selectValue)) {
+ return selectValue.includes(resolveOptionValue(option));
+ }
+
+ if (readBooleanControlState({ element: option, propertyName: 'selected' })) {
+ return true;
+ }
+
+ return isDefined(select) && isOptionSelectedByDefault({ option, select });
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isOptionSelectedByDefault.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isOptionSelectedByDefault.ts
new file mode 100644
index 00000000000..7fe461564e2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isOptionSelectedByDefault.ts
@@ -0,0 +1,35 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { collectOptionsOfSelect } from '@/polyfills/selectors/utils/collectOptionsOfSelect';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+import { isElementDisabled } from '@/polyfills/selectors/utils/isElementDisabled';
+import { readBooleanControlState } from '@/polyfills/selectors/utils/readBooleanControlState';
+
+export const isOptionSelectedByDefault = ({
+ option,
+ select,
+}: {
+ option: SelectorElementLike;
+ select: SelectorElementLike;
+}): boolean => {
+ if (hasElementAttributeIgnoringCase(select, 'multiple')) {
+ return false;
+ }
+
+ const options = collectOptionsOfSelect(select);
+
+ if (
+ options.some((candidateOption) =>
+ readBooleanControlState({
+ element: candidateOption,
+ propertyName: 'selected',
+ }),
+ )
+ ) {
+ return false;
+ }
+
+ return (
+ options.find((candidateOption) => !isElementDisabled(candidateOption)) ===
+ option
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isRadioButtonGroupChecked.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isRadioButtonGroupChecked.ts
new file mode 100644
index 00000000000..744f0e90553
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isRadioButtonGroupChecked.ts
@@ -0,0 +1,15 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { isElementChecked } from '@/polyfills/selectors/utils/isElementChecked';
+import { iterateRadioButtonGroup } from '@/polyfills/selectors/utils/iterateRadioButtonGroup';
+
+export const isRadioButtonGroupChecked = (
+ radio: SelectorElementLike,
+): boolean => {
+ for (const groupMember of iterateRadioButtonGroup(radio)) {
+ if (isElementChecked(groupMember)) {
+ return true;
+ }
+ }
+
+ return false;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isSummaryOfItsDetails.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isSummaryOfItsDetails.ts
new file mode 100644
index 00000000000..c55a0173361
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isSummaryOfItsDetails.ts
@@ -0,0 +1,27 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { collectChildNodes } from '@/polyfills/selectors/utils/collectChildNodes';
+import { isSelectorElementNode } from '@/polyfills/selectors/utils/isSelectorElementNode';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveParentElement } from '@/polyfills/selectors/utils/resolveParentElement';
+import { isDefined } from 'twenty-shared/utils';
+
+export const isSummaryOfItsDetails = (
+ element: SelectorElementLike,
+): boolean => {
+ const parentElement = resolveParentElement(element);
+
+ if (
+ !isDefined(parentElement) ||
+ resolveHtmlTagNameOfElement(parentElement) !== 'details'
+ ) {
+ return false;
+ }
+
+ const firstSummaryElement = collectChildNodes(parentElement).find(
+ (childNode) =>
+ isSelectorElementNode(childNode) &&
+ resolveHtmlTagNameOfElement(childNode) === 'summary',
+ );
+
+ return firstSummaryElement === element;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/iterateRadioButtonGroup.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/iterateRadioButtonGroup.ts
new file mode 100644
index 00000000000..34234819e0a
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/iterateRadioButtonGroup.ts
@@ -0,0 +1,39 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { iterateMatchingDescendants } from '@/polyfills/selectors/utils/iterateMatchingDescendants';
+import { readElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/readElementAttributeIgnoringCase';
+import { resolveFormOwnerElement } from '@/polyfills/selectors/utils/resolveFormOwnerElement';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveInputTypeOfElement } from '@/polyfills/selectors/utils/resolveInputTypeOfElement';
+import { resolveNodeTreeRoot } from '@/polyfills/selectors/utils/resolveNodeTreeRoot';
+
+const isRadioInput = (element: SelectorElementLike): boolean =>
+ resolveHtmlTagNameOfElement(element) === 'input' &&
+ resolveInputTypeOfElement(element) === 'radio';
+
+export function* iterateRadioButtonGroup(
+ radio: SelectorElementLike,
+): Generator<SelectorElementLike> {
+ if (!isRadioInput(radio)) {
+ return;
+ }
+
+ const groupName = readElementAttributeIgnoringCase(radio, 'name');
+
+ if (!isNonEmptyString(groupName)) {
+ yield radio;
+ return;
+ }
+
+ const treeRoot = resolveNodeTreeRoot(radio);
+ const formOwner = resolveFormOwnerElement({ element: radio, treeRoot });
+
+ yield* iterateMatchingDescendants({
+ nodes: [treeRoot],
+ isElementMatching: (candidate) =>
+ isRadioInput(candidate) &&
+ readElementAttributeIgnoringCase(candidate, 'name') === groupName &&
+ resolveFormOwnerElement({ element: candidate, treeRoot }) === formOwner,
+ });
+}
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/readBooleanControlState.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/readBooleanControlState.ts
new file mode 100644
index 00000000000..bc0a2aab6f6
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/readBooleanControlState.ts
@@ -0,0 +1,18 @@
+import { isBoolean } from '@sniptt/guards';
+
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';
+
+export const readBooleanControlState = ({
+ element,
+ propertyName,
+}: {
+ element: SelectorElementLike;
+ propertyName: 'checked' | 'disabled' | 'selected';
+}): boolean => {
+ const propertyValue = element[propertyName];
+
+ return isBoolean(propertyValue)
+ ? propertyValue
+ : hasElementAttributeIgnoringCase(element, propertyName);
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/readElementValue.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/readElementValue.ts
new file mode 100644
index 00000000000..ec5b9fe5c8d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/readElementValue.ts
@@ -0,0 +1,9 @@
+import { isString } from '@sniptt/guards';
+
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { readElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/readElementAttributeIgnoringCase';
+
+export const readElementValue = (element: SelectorElementLike): string | null =>
+ isString(element.value)
+ ? element.value
+ : readElementAttributeIgnoringCase(element, 'value');
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveFormOwnerElement.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveFormOwnerElement.ts
new file mode 100644
index 00000000000..fcdb8910252
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveFormOwnerElement.ts
@@ -0,0 +1,37 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { findFirstMatchingDescendant } from '@/polyfills/selectors/utils/findFirstMatchingDescendant';
+import { readElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/readElementAttributeIgnoringCase';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveParentElement } from '@/polyfills/selectors/utils/resolveParentElement';
+
+const isFormElement = (element: SelectorElementLike): boolean =>
+ resolveHtmlTagNameOfElement(element) === 'form';
+
+export const resolveFormOwnerElement = ({
+ element,
+ treeRoot,
+}: {
+ element: SelectorElementLike;
+ treeRoot: SelectorElementLike;
+}): SelectorElementLike | null => {
+ const formId = readElementAttributeIgnoringCase(element, 'form');
+
+ if (isDefined(formId)) {
+ return findFirstMatchingDescendant({
+ nodes: [treeRoot],
+ isElementMatching: (candidate) =>
+ isFormElement(candidate) &&
+ readElementAttributeIgnoringCase(candidate, 'id') === formId,
+ });
+ }
+
+ let ancestorElement = resolveParentElement(element);
+
+ while (isDefined(ancestorElement) && !isFormElement(ancestorElement)) {
+ ancestorElement = resolveParentElement(ancestorElement);
+ }
+
+ return ancestorElement;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveInheritedAttributeValue.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveInheritedAttributeValue.ts
new file mode 100644
index 00000000000..4b16c03911d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveInheritedAttributeValue.ts
@@ -0,0 +1,32 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { readElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/readElementAttributeIgnoringCase';
+import { resolveParentElement } from '@/polyfills/selectors/utils/resolveParentElement';
+
+export const resolveInheritedAttributeValue = ({
+ element,
+ attributeName,
+ isValueAccepted = () => true,
+}: {
+ element: SelectorElementLike;
+ attributeName: string;
+ isValueAccepted?: (value: string) => boolean;
+}): string | null => {
+ let currentElement: SelectorElementLike | null = element;
+
+ while (isDefined(currentElement)) {
+ const value = readElementAttributeIgnoringCase(
+ currentElement,
+ attributeName,
+ )?.toLowerCase();
+
+ if (isDefined(value) && isValueAccepted(value)) {
+ return value;
+ }
+
+ currentElement = resolveParentElement(currentElement);
+ }
+
+ return null;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveInputTypeOfElement.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveInputTypeOfElement.ts
new file mode 100644
index 00000000000..803886beb7f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveInputTypeOfElement.ts
@@ -0,0 +1,10 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { readElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/readElementAttributeIgnoringCase';
+
+const DEFAULT_INPUT_TYPE = 'text';
+
+export const resolveInputTypeOfElement = (
+ element: SelectorElementLike,
+): string =>
+ readElementAttributeIgnoringCase(element, 'type')?.toLowerCase() ??
+ DEFAULT_INPUT_TYPE;
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveNodeTreeRoot.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveNodeTreeRoot.ts
new file mode 100644
index 00000000000..ede1089f525
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveNodeTreeRoot.ts
@@ -0,0 +1,7 @@
+import { collectAncestorChainFromRootToNode } from '@/polyfills/dom/utils/collectAncestorChainFromRootToNode';
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+
+export const resolveNodeTreeRoot = (
+ node: SelectorElementLike,
+): SelectorElementLike =>
+ (collectAncestorChainFromRootToNode(node)[0] ?? node) as SelectorElementLike;
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveOptionValue.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveOptionValue.ts
new file mode 100644
index 00000000000..aeeb29ad974
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveOptionValue.ts
@@ -0,0 +1,11 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { readElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/readElementAttributeIgnoringCase';
+import { isString } from '@sniptt/guards';
+
+const OPTION_TEXT_WHITESPACE_PATTERN = /\s+/g;
+
+export const resolveOptionValue = (option: SelectorElementLike): string =>
+ readElementAttributeIgnoringCase(option, 'value') ??
+ (isString(option.textContent)
+ ? option.textContent.replace(OPTION_TEXT_WHITESPACE_PATTERN, ' ').trim()
+ : '');
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveOwnerSelectElement.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveOwnerSelectElement.ts
new file mode 100644
index 00000000000..4f3590ac542
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveOwnerSelectElement.ts
@@ -0,0 +1,31 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';
+import { resolveParentElement } from '@/polyfills/selectors/utils/resolveParentElement';
+import { isDefined } from 'twenty-shared/utils';
+
+export const resolveOwnerSelectElement = (
+ option: SelectorElementLike,
+): SelectorElementLike | null => {
+ const parentElement = resolveParentElement(option);
+
+ if (
+ isDefined(parentElement) &&
+ resolveHtmlTagNameOfElement(parentElement) === 'select'
+ ) {
+ return parentElement;
+ }
+
+ if (
+ !isDefined(parentElement) ||
+ resolveHtmlTagNameOfElement(parentElement) !== 'optgroup'
+ ) {
+ return null;
+ }
+
+ const optgroupParentElement = resolveParentElement(parentElement);
+
+ return isDefined(optgroupParentElement) &&
+ resolveHtmlTagNameOfElement(optgroupParentElement) === 'select'
+ ? optgroupParentElement
+ : null;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveParentElement.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveParentElement.ts
new file mode 100644
index 00000000000..b16f07b3aeb
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveParentElement.ts
@@ -0,0 +1,7 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { isSelectorElementNode } from '@/polyfills/selectors/utils/isSelectorElementNode';
+
+export const resolveParentElement = (
+ element: SelectorElementLike,
+): SelectorElementLike | null =>
+ isSelectorElementNode(element.parentNode) ? element.parentNode : null;
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/applySelectedOptionIndexes.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/applySelectedOptionIndexes.ts
new file mode 100644
index 00000000000..d0f2bb14666
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/applySelectedOptionIndexes.ts
@@ -0,0 +1,18 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { collectOptionsOfSelect } from '@/polyfills/selectors/utils/collectOptionsOfSelect';
+
+export const applySelectedOptionIndexes = ({
+ element,
+ selectedOptionIndexes,
+}: {
+ element: SelectorElementLike;
+ selectedOptionIndexes: number[];
+}): void => {
+ const selectedOptionIndexSet = new Set(selectedOptionIndexes);
+
+ for (const [optionIndex, option] of collectOptionsOfSelect(
+ element,
+ ).entries()) {
+ option.selected = selectedOptionIndexSet.has(optionIndex);
+ }
+};
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 1cc6ea51805..76306c37d88 100644
--- a/packages/twenty-front-component-renderer/src/remote/elements/utils/applySerializedEventTargetProperties.ts
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/applySerializedEventTargetProperties.ts
@@ -1,9 +1,16 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { applySelectedOptionIndexes } from '@/remote/elements/utils/applySelectedOptionIndexes';
+import { uncheckOtherRadioButtons } from '@/remote/elements/utils/uncheckOtherRadioButtons';
import { type SerializedEventData } from '@/types/SerializedEventData';
-export const applySerializedEventTargetProperties = (
- element: Record<string, unknown>,
- eventData: SerializedEventData,
-): void => {
+export const applySerializedEventTargetProperties = ({
+ element,
+ eventData,
+}: {
+ element: Record<string, unknown>;
+ eventData: SerializedEventData;
+}): void => {
if ('value' in eventData) {
element.value = eventData.value;
}
@@ -12,6 +19,17 @@ export const applySerializedEventTargetProperties = (
element.checked = eventData.checked;
}
+ if (eventData.checked) {
+ uncheckOtherRadioButtons(element);
+ }
+
+ if (isDefined(eventData.selectedOptionIndexes)) {
+ applySelectedOptionIndexes({
+ element,
+ selectedOptionIndexes: eventData.selectedOptionIndexes,
+ });
+ }
+
if ('files' in eventData) {
element.files = eventData.files;
}
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/uncheckOtherRadioButtons.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/uncheckOtherRadioButtons.ts
new file mode 100644
index 00000000000..7464a1345ba
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/uncheckOtherRadioButtons.ts
@@ -0,0 +1,10 @@
+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';
+import { iterateRadioButtonGroup } from '@/polyfills/selectors/utils/iterateRadioButtonGroup';
+
+export const uncheckOtherRadioButtons = (radio: SelectorElementLike): void => {
+ for (const groupMember of iterateRadioButtonGroup(radio)) {
+ if (groupMember !== radio) {
+ groupMember.checked = false;
+ }
+ }
+};
diff --git a/packages/twenty-front-component-renderer/src/remote/generated/remote-elements.ts b/packages/twenty-front-component-renderer/src/remote/generated/remote-elements.ts
index 91532db9abb..672f09e805b 100644
--- a/packages/twenty-front-component-renderer/src/remote/generated/remote-elements.ts
+++ b/packages/twenty-front-component-renderer/src/remote/generated/remote-elements.ts
@@ -120,10 +120,10 @@ const createSerializedEventConfig = (
eventType: string,
): RemoteElementEventListenerDefinition => ({
dispatchEvent(this: Element, eventData: SerializedEventData) {
- applySerializedEventTargetProperties(
- this as unknown as Record<string, unknown>,
+ applySerializedEventTargetProperties({
+ element: this as unknown as Record<string, unknown>,
eventData,
- );
+ });
const event = new CustomEvent(eventType, {
detail: eventData,
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 0179d0171f3..a90f90169c3 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
@@ -10,15 +10,22 @@ import { isDefined } from 'twenty-shared/utils';
import { frontComponentHostCommunicationApi } from '@/remote/worker/thread/states/frontComponentHostCommunicationApi';
import { HTML_TAG_TO_CUSTOM_ELEMENT_TAG } from '@/constants/HtmlTagToCustomElementTag';
import { installClipboardPolyfill } from '@/polyfills/clipboard/utils/installClipboardPolyfill';
+import { workerActiveElementStore } from '@/polyfills/dom/states/workerActiveElementStore';
+import { workerFocusTransport } from '@/polyfills/dom/states/workerFocusTransport';
+import { installActiveElementDetachmentHook } from '@/polyfills/dom/utils/installActiveElementDetachmentHook';
import { installClassAttributeAccessors } from '@/polyfills/dom/utils/installClassAttributeAccessors';
import { installCompareDocumentPositionPolyfill } from '@/polyfills/dom/utils/installCompareDocumentPositionPolyfill';
+import { installDocumentActiveElementPolyfill } from '@/polyfills/dom/utils/installDocumentActiveElementPolyfill';
+import { findElementByRemoteId } from '@/polyfills/dom/utils/findElementByRemoteId';
import { installDocumentGetElementById } from '@/polyfills/dom/utils/installDocumentGetElementById';
+import { installFocusAndBlurMethodsPolyfill } from '@/polyfills/dom/utils/installFocusAndBlurMethodsPolyfill';
import { installGetComputedStyle } from '@/polyfills/dom/utils/installGetComputedStyle';
import { installGetElementsByClassName } from '@/polyfills/dom/utils/installGetElementsByClassName';
import { installGetRootNodePolyfill } from '@/polyfills/dom/utils/installGetRootNodePolyfill';
import { installLocalStyleOnBaseElements } from '@/polyfills/dom/utils/installLocalStyleOnBaseElements';
import { installMutationObserver } from '@/polyfills/dom/utils/installMutationObserver';
import { installNodeContainsPolyfill } from '@/polyfills/dom/utils/installNodeContainsPolyfill';
+import { resolvePolyfillHooks } from '@/polyfills/dom/utils/resolvePolyfillHooks';
import { installSelectorMethodsPolyfill } from '@/polyfills/selectors/utils/installSelectorMethodsPolyfill';
import { workerGeometryStore } from '@/polyfills/geometry/states/workerGeometryStore';
import { installElementGeometryPolyfill } from '@/polyfills/geometry/utils/installElementGeometryPolyfill';
@@ -28,6 +35,7 @@ import { workerMediaBridge } from '@/polyfills/media/states/workerMediaBridge';
import { installMediaCapturePolyfills } from '@/polyfills/media/utils/installMediaCapturePolyfills';
import { installMatchMediaPolyfill } from '@/polyfills/media-query/utils/installMatchMediaPolyfill';
import { frontComponentStorageBridges } from '@/polyfills/storage/states/frontComponentStorageBridges';
+import { resolveGlobalScopeInstallTargets } from '@/polyfills/utils/resolveGlobalScopeInstallTargets';
import { toGlobalScopeRecord } from '@/polyfills/utils/toGlobalScopeRecord';
import { installStorageBridge } from '@/polyfills/storage/utils/installStorageBridge';
import { installWindowAliasesPolyfill } from '@/polyfills/window-aliases/utils/installWindowAliasesPolyfill';
@@ -73,7 +81,25 @@ installSelectorMethodsPolyfill({
DocumentFragment.prototype,
document,
],
- resolveActiveElement: () => null,
+ resolveActiveElement: () => workerActiveElementStore.getActiveElement(),
+ resolveFocusVisibleElement: () =>
+ workerActiveElementStore.getFocusVisibleElement(),
+});
+installFocusAndBlurMethodsPolyfill({
+ elementPrototype: Element.prototype,
+ activeElementStore: workerActiveElementStore,
+ forwardFocusMethod: workerFocusTransport.forwardFocusMethod,
+});
+installDocumentActiveElementPolyfill({
+ documentTarget: document,
+ activeElementStore: workerActiveElementStore,
+});
+installActiveElementDetachmentHook({
+ hooks: resolvePolyfillHooks(
+ resolveGlobalScopeInstallTargets(toGlobalScopeRecord(globalThis)),
+ ),
+ activeElementStore: workerActiveElementStore,
+ onRemoveSubtree: workerFocusTransport.blurFocusedElementWithinSubtree,
});
installGetComputedStyle(toGlobalScopeRecord(globalThis));
@@ -169,6 +195,14 @@ const workerExports: WorkerExports = {
pushGeometryUpdates: async (batch) => {
workerGeometryStore.applyGeometryBatch(batch);
},
+ pushFocusUpdate: async ({ remoteElementId, isFocusVisible }) => {
+ workerActiveElementStore.setActiveElement({
+ element: isDefined(remoteElementId)
+ ? findElementByRemoteId({ rootNode: document.body, remoteElementId })
+ : null,
+ isFocusVisible,
+ });
+ },
pushMediaSessionEvents: async (batch) => {
workerMediaBridge.dispatchEvents(batch);
},
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 e2d03c43a7c..7e73413b619 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 { workerFocusTransport } from '@/polyfills/dom/states/workerFocusTransport';
import { installStyleBridge } from '@/polyfills/style/utils/installStyleBridge';
export const attachRemoteRenderRootToWorkerDocument = (
@@ -18,6 +19,7 @@ export const attachRemoteRenderRootToWorkerDocument = (
remoteRoot.append(renderContainer);
document.body.append(remoteRoot);
workerGeometryStore.setRootElement(remoteRoot);
+ workerFocusTransport.setRootElement(remoteRoot);
installStyleBridge(remoteRoot);
return renderContainer;
diff --git a/packages/twenty-front-component-renderer/src/testing/createGeometryTrackerStub.ts b/packages/twenty-front-component-renderer/src/testing/createGeometryTrackerStub.ts
index 7cefdb3ae69..d4d5096d950 100644
--- a/packages/twenty-front-component-renderer/src/testing/createGeometryTrackerStub.ts
+++ b/packages/twenty-front-component-renderer/src/testing/createGeometryTrackerStub.ts
@@ -4,6 +4,8 @@ import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot'
export const createGeometryTrackerStub = (): GeometryTracker => ({
registerNode: jest.fn(),
unregisterNode: jest.fn(),
+ getRegisteredNode: jest.fn(),
+ findRemoteElementIdContainingNode: jest.fn(),
observe: jest.fn(),
unobserve: jest.fn(),
setRoot: jest.fn(),
diff --git a/packages/twenty-front-component-renderer/src/types/FocusUpdate.ts b/packages/twenty-front-component-renderer/src/types/FocusUpdate.ts
new file mode 100644
index 00000000000..8b53840c624
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/FocusUpdate.ts
@@ -0,0 +1,4 @@
+export type FocusUpdate = {
+ remoteElementId: string | null;
+ isFocusVisible: boolean;
+};
diff --git a/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts b/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts
index 6a20ce19556..43df3fa6cc7 100644
--- a/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts
+++ b/packages/twenty-front-component-renderer/src/types/SerializedEventData.ts
@@ -38,6 +38,7 @@ export type SerializedEventData = {
clipboardText?: string;
value?: string;
checked?: boolean;
+ selectedOptionIndexes?: number[];
scrollTop?: number;
scrollLeft?: number;
deltaX?: number;
diff --git a/packages/twenty-front-component-renderer/src/types/WorkerExports.ts b/packages/twenty-front-component-renderer/src/types/WorkerExports.ts
index 8d1e61c2819..8bca5c20915 100644
--- a/packages/twenty-front-component-renderer/src/types/WorkerExports.ts
+++ b/packages/twenty-front-component-renderer/src/types/WorkerExports.ts
@@ -3,6 +3,7 @@ import {
type CommandConfirmationModalResult,
type FrontComponentExecutionContext,
} from 'twenty-sdk/front-component';
+import { type FocusUpdate } from '@/types/FocusUpdate';
import { type GeometryUpdateBatch } from '@/types/GeometryUpdateBatch';
import { type HostToWorkerRenderContext } from '@/types/HostToWorkerRenderContext';
import { type MediaSessionEventBatch } from '@/types/MediaSession';
@@ -18,5 +19,6 @@ export type WorkerExports = {
result: CommandConfirmationModalResult,
) => Promise<void>;
pushGeometryUpdates: (batch: GeometryUpdateBatch) => Promise<void>;
+ pushFocusUpdate: (update: FocusUpdate) => Promise<void>;
pushMediaSessionEvents: (batch: MediaSessionEventBatch) => Promise<void>;
};