The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Polyfill matches, closest and querySelector in the front component worker (#26516)
Raphaël Bosibe4bdc1b894b
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdxindex e5c457a2193..0d43d80d975 100644--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx@@ -930,7 +930,7 @@ 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()` and `getElementById()` work; `getElementsByClassName()` works too, but returns a static collection, not a live `HTMLCollection` |+| `document.createTreeWalker()` | Throws | `querySelector()` / `querySelectorAll()`, `matches()`, `closest()` (including pseudo-classes such as `:not()`) and `getElementById()` work; `getElementsByClassName()` works too, but returns a static collection, not a live `HTMLCollection` || `document.activeElement` | Always `undefined` | Track focus with `onFocus` / `onBlur` || `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/jest.config.mjs b/packages/twenty-front-component-renderer/jest.config.mjsindex 42dc18dd87d..444a70be812 100644--- a/packages/twenty-front-component-renderer/jest.config.mjs+++ b/packages/twenty-front-component-renderer/jest.config.mjs@@ -14,7 +14,9 @@ const jestConfig = {preset: '../../jest.preset.js',testEnvironment: 'jsdom',setupFiles: ['<rootDir>/jest.setup.mjs'],- transformIgnorePatterns: ['node_modules/(?!@quilted/)'],+ transformIgnorePatterns: [+ 'node_modules/(?!(@quilted|boolbase|css-select|css-what|dom-serializer|domelementtype|domhandler|domutils|entities|nth-check)/)',+ ],transform: {'^.+\\.(mjs|[tj]sx?)$': ['@swc/jest',diff --git a/packages/twenty-front-component-renderer/package.json b/packages/twenty-front-component-renderer/package.jsonindex dd6a01d4cfd..7b38b43d163 100644--- a/packages/twenty-front-component-renderer/package.json+++ b/packages/twenty-front-component-renderer/package.json@@ -24,6 +24,8 @@"@remote-dom/core": "^1.10.1","@remote-dom/react": "^1.2.2","@sniptt/guards": "^0.2.0",+ "css-select": "^7.0.0",+ "css-what": "^8.0.0","react": "^19.2.0","react-dom": "^19.2.0","react-error-boundary": "^4.0.11",diff --git a/packages/twenty-front-component-renderer/scripts/front-component-sandbox/build-sandbox-document.ts b/packages/twenty-front-component-renderer/scripts/front-component-sandbox/build-sandbox-document.tsindex 583211fd62c..b7dc3ca75c7 100644--- a/packages/twenty-front-component-renderer/scripts/front-component-sandbox/build-sandbox-document.ts+++ b/packages/twenty-front-component-renderer/scripts/front-component-sandbox/build-sandbox-document.ts@@ -4,6 +4,8 @@ import { fileURLToPath } from 'node:url';import { build, type Rollup } from 'vite';+import { createDomutilsStubPlugin } from '../worker/createDomutilsStubPlugin';+const dirname = path.dirname(fileURLToPath(import.meta.url));const projectRoot = path.resolve(dirname, '../..');@@ -34,6 +36,9 @@ const buildSandboxDocument = async (): Promise<void> => {'@/': path.resolve(projectRoot, 'src') + '/',},},+ worker: {+ plugins: () => [createDomutilsStubPlugin()],+ },define: {'process.env.NODE_ENV': JSON.stringify('production'),},diff --git a/packages/twenty-front-component-renderer/scripts/worker/createDomutilsStubPlugin.ts b/packages/twenty-front-component-renderer/scripts/worker/createDomutilsStubPlugin.tsnew file mode 100644index 00000000000..b703d7f3c6d--- /dev/null+++ b/packages/twenty-front-component-renderer/scripts/worker/createDomutilsStubPlugin.ts@@ -0,0 +1,17 @@+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { type Plugin } from 'vite';++const DOMUTILS_STUB_PATH = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../src/polyfills/selectors/stubs/domutilsAdapterStub.ts',+);++// css-select imports domutils only as its default adapter; the worker always+// supplies its own, so the dependency would otherwise ship as dead weight.+export const createDomutilsStubPlugin = (): Plugin => ({+ name: 'twenty-domutils-stub',+ enforce: 'pre',+ resolveId: (source) => (source === 'domutils' ? DOMUTILS_STUB_PATH : null),+});diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsxindex 96f54b65828..379df68a2b1 100644--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx@@ -49,7 +49,10 @@ import {tabsReactTest,} from '@/__stories__/twenty-ui-gallery/utils/sandboxFailureTests';import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';-import { createTooltipSandboxFailureTest } from '@/__stories__/twenty-ui-gallery/utils/createTooltipSandboxFailureTest';+import {+ tooltipEscapeDismissalTest,+ tooltipEscapeIgnoredTest,+} from '@/__stories__/twenty-ui-gallery/utils/tooltipTests';const meta: Meta<typeof FrontComponentRenderer> = {title: 'FrontComponent/Twenty UI Gallery',@@ -285,13 +288,13 @@ export const PopoverPreact: Story = createGalleryStory({export const TooltipReact: Story = createGalleryStory({frontComponentBundleName: 'twenty-ui-tooltip',runtime: 'react',- play: createTooltipSandboxFailureTest('react'),+ play: tooltipEscapeIgnoredTest,});export const TooltipPreact: Story = createGalleryStory({frontComponentBundleName: 'twenty-ui-tooltip',runtime: 'preact',- play: createTooltipSandboxFailureTest('preact'),+ play: tooltipEscapeDismissalTest,});export const MenuReact: Story = createGalleryStory({diff --git a/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/timeouts.ts b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/timeouts.tsindex a1a45f82127..4fee1fb74de 100644--- a/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/timeouts.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/timeouts.ts@@ -3,3 +3,4 @@ export const INTERACTION_TIMEOUT = 5000;export const HOST_API_TIMEOUT = 10000;export const TYPING_TIMEOUT = 10000;export const TYPING_DELAY = 30;+export const SANDBOX_ROUND_TRIP_SETTLE_DELAY = 1000;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.mdindex 71c227e819d..244595181bb 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@@ -47,30 +47,26 @@ No stories are skipped or marked as expected-to-fail by the runner.| --- | --- || Field controls | Forwarded events lack the native event used for `composedPath`. React serializes boolean `aria-invalid` as an empty string; Textarea's cloned render element loses its change handler in React. The value report checks the state received by the component after typing. || Tabs | React cannot mount without `compareDocumentPosition`; Preact activation fails on the missing native event for `composedPath`. |-| Radio, RadioGroup | Unselected radios need `Element.matches(':disabled')`; React also orders radio groups with `compareDocumentPosition`. |-| SegmentedControl | Ordering its radios needs `compareDocumentPosition`, so React cannot mount it. In the Preact input gallery the `Radio` failure skips that ordering at mount, so the control fails on first focus instead. Selecting would also need `PointerEvent` and native radio activation. |+| RadioGroup | Ordering its radios needs `compareDocumentPosition`, which the sandbox DOM does not implement. |+| SegmentedControl | Ordering its radios needs `compareDocumentPosition`, so React cannot mount it. In the Preact input gallery it mounts and fails on first focus instead. Selecting would also need `PointerEvent` and native radio activation. || Popover, AlertDialog | Opening fails while reading unavailable viewport width data. || Menu, Select | Opening fails on viewport data and/or missing `nativeEvent.pointerType`. || Switch | Activation attempts to construct an unavailable `PointerEvent`. |-| Tooltip | `TooltipReact` opens on hover but remains open after Escape because the SDK does not forward handlers added by `React.cloneElement`. `TooltipPreact` throws on hover because the sandbox lacks `Element.closest`. |+| Tooltip | `TooltipReact` opens on hover but remains open after Escape because React drops the handlers Base UI adds through `React.cloneElement`. || Responsive hooks | The sandbox has no `window.matchMedia`, so `useIsMobile` and `useIsTouchDevice` return `false` whatever the host viewport or input. The fixture asserts that fallback and must assert host-derived values once a media-query bridge lands. |-The tooltip stories assert these known failures and must be updated to assert-successful interactions when compatibility is fixed. The surfaces gallery checks-that the migrated tooltip mounts in both runtimes. Full tooltip interaction-coverage remains in twenty-ui's own stories.+The worker DOM now provides `Element.matches`, `closest`, and `querySelector`+backed by `css-select`, which matches the sandbox's custom element tags by+their HTML tag names. `TooltipPreact` therefore covers hover opening and Escape+dismissal. Pointer leave still needs the `Node.contains` fix and document-level+`mousemove` delivery for the safe polygon, and the compound tooltip's title and+description are not covered yet.-SDK event handling and sandbox DOM fixes are deferred from the tooltip migration.-Further gaps found while investigating include forwarded events without-`nativeEvent` and a `Node.contains` ancestor traversal bug that can hang pointer-leave handling. After fixing those gaps, cover Escape dismissal, pointer leave,-and the compound tooltip's title and description in both renderer runtimes.--Once those gaps are fixed, extend the stories to verify selection, disabled-items, keyboard navigation, and overlay content, dismissal, and focus restoration.-The fixtures already include the controlled state, compound parts, and callback-output for those checks. Passing display, ListItem, and Toast stories verify-rendering/CSS or interaction behavior directly.+Once the remaining gaps are fixed, extend the stories to verify selection,+disabled items, keyboard navigation, and overlay content, dismissal, and focus+restoration. The fixtures already include the controlled state, compound parts,+and callback output for those checks. Passing display, ListItem, and Toast+stories verify rendering/CSS or interaction behavior directly.## Rundiff --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.tsindex 1acf690dd07..f7124eac03d 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@@ -9,8 +9,6 @@ export const SANDBOX_ERROR_PATTERNS = {"Uncaught TypeError: Cannot read properties of undefined (reading 'defaultPrevented')",POINTER_TYPE:"Uncaught TypeError: Cannot read properties of undefined (reading 'pointerType')",- ELEMENT_MATCHES: /^(?:Uncaught TypeError: )?\w+\.matches is not a function$/,- ELEMENT_CLOSEST: /^(?:Uncaught TypeError: )?\w+\.closest is not a function$/,ELEMENT_CONTAINS:/^(?:Uncaught TypeError: )?\w+\.contains is not a function$/,HOST_EVENT_LISTENER: 'Uncaught TypeError: listener is not a function',diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/createTooltipSandboxFailureTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/createTooltipSandboxFailureTest.tsdeleted file mode 100644index 80569e5f71e..00000000000--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/createTooltipSandboxFailureTest.ts+++ /dev/null@@ -1,56 +0,0 @@-import { expect, userEvent, waitFor, within } from 'storybook/test';--import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';-import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';-import { INTERACTION_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';-import { SANDBOX_ERROR_PATTERNS } from '@/__stories__/twenty-ui-gallery/constants/SANDBOX_ERROR_PATTERNS';-import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';-import { expectSandboxErrors } from '@/__stories__/twenty-ui-gallery/utils/expectSandboxErrors';--export const createTooltipSandboxFailureTest =- (runtime: 'react' | 'preact'): TwentyUiGalleryPlayFunction =>- async ({ canvasElement }) => {- const user = userEvent.setup();- const canvas = within(canvasElement);- const page = within(canvasElement.ownerDocument.body);- await expectFrontComponentMounted(canvas);- await waitFor(() => {- expect(canvas.getByRole('status')).toHaveAttribute('aria-busy', 'false');- });-- const exportButton = canvas.getByRole('button', { name: 'Export records' });- await user.hover(exportButton);-- if (runtime === 'preact') {- await expectSandboxErrors({- requiredErrors: [SANDBOX_ERROR_PATTERNS.ELEMENT_CLOSEST],- });- return;- }-- await waitFor(() => {- expect(errorHandler).not.toHaveBeenCalled();- expect(canvas.getByRole('status')).toHaveTextContent('Export help: open');- expect(- page.getByText('Download visible records as a CSV file'),- ).toBeVisible();- });-- await user.tab();- expect(exportButton).toHaveFocus();- await user.keyboard('{Escape}');- await expect(- waitFor(- () =>- expect(canvas.getByRole('status')).toHaveTextContent(- 'Export help: closed',- ),- { timeout: INTERACTION_TIMEOUT },- ),- ).rejects.toThrow();- expect(errorHandler).not.toHaveBeenCalled();- expect(canvas.getByRole('status')).toHaveTextContent('Export help: open');- expect(- page.getByText('Download visible records as a CSV file'),- ).toBeVisible();- };diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputPreactTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputPreactTest.tsindex 9becb5bdb76..220e84af83a 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputPreactTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputPreactTest.ts@@ -7,7 +7,7 @@ import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallerimport { createGalleryRenderTest } from '@/__stories__/twenty-ui-gallery/utils/createGalleryRenderTest';export const inputPreactTest: TwentyUiGalleryPlayFunction = async (context) => {- await createGalleryRenderTest({ expectedFailedComponents: ['Radio'] })(+ await createGalleryRenderTest({ expectedFailedComponents: ['RadioGroup'] })(context,);@@ -27,7 +27,7 @@ export const inputPreactTest: TwentyUiGalleryPlayFunction = async (context) => {expect(status).toHaveAttribute('data-failed-names',- 'Radio, SegmentedControl',+ 'RadioGroup, SegmentedControl',);expect(status).toHaveAttribute('data-failed-messages',diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputReactTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputReactTest.tsindex 94faac0a9fa..56e7f895dff 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputReactTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputReactTest.ts@@ -6,7 +6,7 @@ import { createGalleryRenderTest } from '@/__stories__/twenty-ui-gallery/utils/cexport const inputReactTest: TwentyUiGalleryPlayFunction = async (context) => {await createGalleryRenderTest({- expectedFailedComponents: ['Radio', 'RadioGroup', 'SegmentedControl'],+ expectedFailedComponents: ['RadioGroup', 'SegmentedControl'],})(context);expect(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.tsindex cd92bbfc453..dbabb252bbf 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@@ -34,7 +34,6 @@ export const selectTest = createSandboxFailureTest({SANDBOX_ERROR_PATTERNS.VIEWPORT_WIDTH,SANDBOX_ERROR_PATTERNS.COMPOSED_PATH,SANDBOX_ERROR_PATTERNS.DOCUMENT_POSITION,- SANDBOX_ERROR_PATTERNS.ELEMENT_MATCHES,],});diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipTests.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipTests.tsnew file mode 100644index 00000000000..de73381b3bd--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipTests.ts@@ -0,0 +1,60 @@+import { expect, userEvent, waitFor, within } from 'storybook/test';++import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';+import { SANDBOX_ROUND_TRIP_SETTLE_DELAY } from '@/__stories__/shared/test-utils/timeouts';+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';++const TOOLTIP_CONTENT = 'Download visible records as a CSV file';++const openTooltipThenPressEscape = async (canvasElement: HTMLElement) => {+ const user = userEvent.setup();+ const canvas = within(canvasElement);+ const page = within(canvasElement.ownerDocument.body);+ await expectFrontComponentMounted(canvas);+ await waitFor(() => {+ expect(canvas.getByRole('status')).toHaveAttribute('aria-busy', 'false');+ });++ const exportButton = canvas.getByRole('button', { name: 'Export records' });+ await user.hover(exportButton);++ await waitFor(() => {+ expect(errorHandler).not.toHaveBeenCalled();+ expect(canvas.getByRole('status')).toHaveTextContent('Export help: open');+ expect(page.getByText(TOOLTIP_CONTENT)).toBeVisible();+ });++ await user.tab();+ expect(exportButton).toHaveFocus();+ await user.keyboard('{Escape}');++ return { canvas, page };+};++export const tooltipEscapeDismissalTest: TwentyUiGalleryPlayFunction = async ({+ canvasElement,+}) => {+ const { canvas, page } = await openTooltipThenPressEscape(canvasElement);++ await waitFor(() =>+ expect(canvas.getByRole('status')).toHaveTextContent('Export help: closed'),+ );+ expect(page.queryByText(TOOLTIP_CONTENT)).not.toBeInTheDocument();+ expect(errorHandler).not.toHaveBeenCalled();+};++// React drops the handlers Base UI adds through cloneElement, so the Escape+// key never reaches the sandbox and the tooltip stays open.+export const tooltipEscapeIgnoredTest: TwentyUiGalleryPlayFunction = async ({+ canvasElement,+}) => {+ const { canvas, page } = await openTooltipThenPressEscape(canvasElement);++ await new Promise((resolve) =>+ setTimeout(resolve, SANDBOX_ROUND_TRIP_SETTLE_DELAY),+ );+ expect(errorHandler).not.toHaveBeenCalled();+ expect(canvas.getByRole('status')).toHaveTextContent('Export help: open');+ expect(page.getByText(TOOLTIP_CONTENT)).toBeVisible();+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeTypeByName.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeTypeByName.tsnew file mode 100644index 00000000000..e995868f8f6--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/NodeTypeByName.ts@@ -0,0 +1,5 @@+export const NODE_TYPE_BY_NAME = {+ ELEMENT: 1,+ COMMENT: 8,+ DOCUMENT: 9,+} as const;diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/NodeLike.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/NodeLike.tsnew file mode 100644index 00000000000..55e75948bf5--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/NodeLike.ts@@ -0,0 +1,3 @@+export type NodeLike = {+ parentNode?: unknown;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerNodeList.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerNodeList.tsindex 58114cf8903..e64a0e8c320 100644--- a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerNodeList.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerNodeList.ts@@ -1,3 +1,3 @@-export type WorkerNodeList = Node[] & {- item: (index: number) => Node | null;+export type WorkerNodeList<TNode = Node> = TNode[] & {+ item: (index: number) => TNode | null;};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/isAncestorOrSelfOfNode.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/isAncestorOrSelfOfNode.test.tsnew file mode 100644index 00000000000..6ad0230565b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/isAncestorOrSelfOfNode.test.ts@@ -0,0 +1,35 @@+import { isAncestorOrSelfOfNode } from '../isAncestorOrSelfOfNode';++type FakeNode = {+ parentNode: FakeNode | null;+};++const createNode = (parentNode: FakeNode | null = null): FakeNode => ({+ parentNode,+});++describe('isAncestorOrSelfOfNode', () => {+ it('should return true for the node itself', () => {+ const node = createNode();++ expect(isAncestorOrSelfOfNode(node, node)).toBe(true);+ });++ it('should return true for an indirect ancestor', () => {+ const ancestor = createNode();+ const descendant = createNode(createNode(ancestor));++ expect(isAncestorOrSelfOfNode(ancestor, descendant)).toBe(true);+ });++ it('should return false for a descendant, a sibling subtree and non-nodes', () => {+ const root = createNode();+ const child = createNode(root);+ const sibling = createNode(root);++ expect(isAncestorOrSelfOfNode(child, root)).toBe(false);+ expect(isAncestorOrSelfOfNode(child, createNode(sibling))).toBe(false);+ expect(isAncestorOrSelfOfNode(root, null)).toBe(false);+ expect(isAncestorOrSelfOfNode(root, 'text')).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.tsindex f4cad2071db..4aa65aca30b 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@@ -132,6 +132,34 @@ describe('@remote-dom/polyfill mutation hooks contract the worker MutationObservexpect(callsNamed('setText')[0].args[1]).toBe('second');});+ it.each([+ ['Element', 'closest'],+ ['Element', 'matches'],+ ])(+ 'still ships %s without %s, which the worker polyfills install itself',+ (className, methodName) => {+ const polyfillWindow = new Window() as unknown as Record<+ string,+ { prototype: Record<string, unknown> }+ >;++ expect(polyfillWindow[className].prototype).not.toHaveProperty(+ methodName,+ );+ },+ );++ it('still throws on pseudo-class selectors, which the worker selector engine replaces', () => {+ const polyfillWindow = new Window();+ const { document } = polyfillWindow;++ document.body.append(document.createElement('button'));++ expect(() => document.body.querySelectorAll(':disabled')).toThrow(+ 'not implemented',+ );+ });+it('exposes childNodes as a list whose item returns undefined out of range', () => {const { document } = createHookRecorder();diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerNodeList.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerNodeList.tsindex a7475ecda77..0ec95f2b77d 100644--- a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerNodeList.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerNodeList.ts@@ -1,13 +1,15 @@import { type WorkerNodeList } from '@/polyfills/dom/types/WorkerNodeList';-class NodeListImplementation extends Array<Node> {- item(index: number): Node | null {+class NodeListImplementation<TNode> extends Array<TNode> {+ item(index: number): TNode | null {return this[index] ?? null;}}-export const createWorkerNodeList = (nodes: Node[]): WorkerNodeList => {- const nodeList = new NodeListImplementation();+export const createWorkerNodeList = <TNode = Node>(+ nodes: TNode[],+): WorkerNodeList<TNode> => {+ const nodeList = new NodeListImplementation<TNode>();for (const node of nodes) {nodeList.push(node);diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isAncestorOrSelfOfNode.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isAncestorOrSelfOfNode.tsnew file mode 100644index 00000000000..2f4ff634bbf--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isAncestorOrSelfOfNode.ts@@ -0,0 +1,20 @@+import { isObject } from '@sniptt/guards';++import { type NodeLike } from '@/polyfills/dom/types/NodeLike';++export const isAncestorOrSelfOfNode = (+ candidateAncestor: object,+ node: unknown,+): boolean => {+ let currentNode: unknown = node;++ while (isObject(currentNode)) {+ if (currentNode === candidateAncestor) {+ return true;+ }++ currentNode = (currentNode as NodeLike).parentNode;+ }++ return false;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/HtmlTagNameByRemoteElementTagName.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/HtmlTagNameByRemoteElementTagName.tsnew file mode 100644index 00000000000..a92ff9f75d1--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/HtmlTagNameByRemoteElementTagName.ts@@ -0,0 +1,8 @@+import { HTML_TAG_TO_CUSTOM_ELEMENT_TAG } from '@/constants/HtmlTagToCustomElementTag';++export const HTML_TAG_NAME_BY_REMOTE_ELEMENT_TAG_NAME = new Map(+ Object.entries(HTML_TAG_TO_CUSTOM_ELEMENT_TAG).map(([htmlTag, remoteTag]) => [+ remoteTag,+ htmlTag.toLowerCase(),+ ]),+);diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/ScopePseudoClassPattern.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/ScopePseudoClassPattern.tsnew file mode 100644index 00000000000..f6c852b1a27--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/ScopePseudoClassPattern.ts@@ -0,0 +1 @@+export const SCOPE_PSEUDO_CLASS_PATTERN = /:scope/i;diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/SelectorMatcherCacheSize.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/SelectorMatcherCacheSize.tsnew file mode 100644index 00000000000..d07bd125a72--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/SelectorMatcherCacheSize.ts@@ -0,0 +1 @@+export const SELECTOR_MATCHER_CACHE_SIZE = 256;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.tsnew file mode 100644index 00000000000..76528210492--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/UnobservablePseudoClassNames.ts@@ -0,0 +1,34 @@+export const UNOBSERVABLE_PSEUDO_CLASS_NAMES = [+ '-webkit-autofill',+ 'active',+ 'active-view-transition',+ 'autofill',+ 'blank',+ 'buffering',+ 'current',+ 'default',+ 'fullscreen',+ 'future',+ 'has-slotted',+ 'host',+ 'hover',+ 'in-range',+ 'invalid',+ 'local-link',+ 'modal',+ 'muted',+ 'out-of-range',+ 'past',+ 'paused',+ 'picture-in-picture',+ 'playing',+ 'popover-open',+ 'seeking',+ 'stalled',+ 'target',+ 'target-within',+ 'user-invalid',+ 'user-valid',+ 'visited',+ 'volume-locked',+] as const;diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/WorkerDomCssSelectAdapter.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/WorkerDomCssSelectAdapter.tsnew file mode 100644index 00000000000..c5b25f251b3--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/constants/WorkerDomCssSelectAdapter.ts@@ -0,0 +1,25 @@+import { type CssSelectAdapter } from '@/polyfills/selectors/types/CssSelectAdapter';+import { collectChildNodes } from '@/polyfills/selectors/utils/collectChildNodes';+import { collectSiblingNodes } from '@/polyfills/selectors/utils/collectSiblingNodes';+import { hasElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/hasElementAttributeIgnoringCase';+import { isSelectorElementNode } from '@/polyfills/selectors/utils/isSelectorElementNode';+import { readElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/readElementAttributeIgnoringCase';+import { removeNestedNodes } from '@/polyfills/selectors/utils/removeNestedNodes';+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';+import { resolveNodeText } from '@/polyfills/selectors/utils/resolveNodeText';+import { resolveParentNode } from '@/polyfills/selectors/utils/resolveParentNode';+import { resolvePreviousSiblingElement } from '@/polyfills/selectors/utils/resolvePreviousSiblingElement';++export const WORKER_DOM_CSS_SELECT_ADAPTER: CssSelectAdapter = {+ isTag: isSelectorElementNode,+ getName: resolveHtmlTagNameOfElement,+ getAttributeValue: (element, attributeName) =>+ readElementAttributeIgnoringCase(element, attributeName) ?? undefined,+ hasAttrib: hasElementAttributeIgnoringCase,+ getChildren: collectChildNodes,+ getParent: resolveParentNode,+ getSiblings: collectSiblingNodes,+ prevElementSibling: resolvePreviousSiblingElement,+ getText: resolveNodeText,+ removeSubsets: removeNestedNodes,+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/stubs/domutilsAdapterStub.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/stubs/domutilsAdapterStub.tsnew file mode 100644index 00000000000..7f4f06da44f--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/stubs/domutilsAdapterStub.ts@@ -0,0 +1,3 @@+// Empty on purpose: createDomutilsStubPlugin resolves domutils to this module,+// since css-select only needs it as a default adapter and the worker passes its own.+export {};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/types/CssSelectAdapter.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/CssSelectAdapter.tsnew file mode 100644index 00000000000..85ed82b5226--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/CssSelectAdapter.ts@@ -0,0 +1,7 @@+import { type Options } from 'css-select';++import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export type CssSelectAdapter = NonNullable<+ Options<SelectorElementLike, SelectorElementLike>['adapter']+>;diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/types/CssSelectPseudoClassMatchers.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/CssSelectPseudoClassMatchers.tsnew file mode 100644index 00000000000..af7b9820c3d--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/CssSelectPseudoClassMatchers.ts@@ -0,0 +1,7 @@+import { type Options } from 'css-select';++import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export type CssSelectPseudoClassMatchers = NonNullable<+ Options<SelectorElementLike, SelectorElementLike>['pseudos']+>;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.tsnew file mode 100644index 00000000000..783ab243599--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorElementLike.ts@@ -0,0 +1,11 @@+export type SelectorElementLike = {+ nodeType?: number;+ localName?: string;+ parentNode?: unknown;+ previousElementSibling?: unknown;+ nextElementSibling?: unknown;+ childNodes?: ArrayLike<unknown>;+ attributes?: Iterable<unknown>;+ textContent?: unknown;+ getAttribute?: (attributeName: string) => string | null;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorMatcher.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorMatcher.tsnew file mode 100644index 00000000000..de57c910f2b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorMatcher.ts@@ -0,0 +1,3 @@+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export type SelectorMatcher = (element: SelectorElementLike) => boolean;diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorMatcherResolver.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorMatcherResolver.tsnew file mode 100644index 00000000000..eca401a3319--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/types/SelectorMatcherResolver.ts@@ -0,0 +1,9 @@+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { type SelectorMatcher } from '@/polyfills/selectors/types/SelectorMatcher';++export type SelectorMatcherResolver = {+ resolveSelectorMatcher: (input: {+ selectorsText: string;+ scopeElement: SelectorElementLike;+ }) => SelectorMatcher;+};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.tsnew file mode 100644index 00000000000..25ea1fed545--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfill.test.ts@@ -0,0 +1,535 @@+import { Window } from '@remote-dom/polyfill';++import { installSelectorMethodsPolyfill } from '../installSelectorMethodsPolyfill';++type SelectorFixture = {+ document: Document;+ setActiveElement: (element: object | null) => void;+};++const createSelectorFixture = (): SelectorFixture => {+ const polyfillWindow = new Window();+ let activeElement: object | null = null;++ installSelectorMethodsPolyfill({+ elementPrototype: polyfillWindow.Element.prototype,+ querySelectorTargets: [+ polyfillWindow.Element.prototype,+ polyfillWindow.DocumentFragment.prototype,+ polyfillWindow.document,+ ],+ resolveActiveElement: () => activeElement,+ });++ return {+ document: polyfillWindow.document as unknown as Document,+ setActiveElement: (element) => {+ activeElement = element;+ },+ };+};++const createTree = (document: Document) => {+ const list = document.createElement('div');+ list.setAttribute('role', 'tablist');+ const firstTab = document.createElement('button');+ firstTab.setAttribute('role', 'tab');+ firstTab.setAttribute('class', 'tab active');+ firstTab.setAttribute('id', 'overview');+ const secondTab = document.createElement('button');+ secondTab.setAttribute('role', 'tab');+ secondTab.setAttribute('class', 'tab');+ secondTab.setAttribute('disabled', '');+ const label = document.createElement('span');+ label.setAttribute('data-tooltip-trigger', 'true');+ secondTab.append(label);+ list.append(firstTab, secondTab);+ document.body.append(list);++ return { list, firstTab, secondTab, label };+};++describe('installSelectorMethodsPolyfill', () => {+ describe('matches', () => {+ it('should match type, id, class and attribute selectors', () => {+ const { document } = createSelectorFixture();+ const { firstTab } = createTree(document);++ expect(firstTab.matches('button')).toBe(true);+ expect(firstTab.matches('#overview')).toBe(true);+ expect(firstTab.matches('.active')).toBe(true);+ expect(firstTab.matches('.tab.active')).toBe(true);+ expect(firstTab.matches('[role="tab"]')).toBe(true);+ expect(firstTab.matches('[class~=active]')).toBe(true);+ expect(firstTab.matches('[id^=over][id$=view][id*=erv]')).toBe(true);+ expect(firstTab.matches('[role="TAB" i]')).toBe(true);+ expect(firstTab.matches('[role="TAB"]')).toBe(false);+ expect(firstTab.matches('span')).toBe(false);+ expect(firstTab.matches('.inactive')).toBe(false);+ });++ it('should match a type selector against the sandbox custom element tag', () => {+ const { document } = createSelectorFixture();+ const button = document.createElement('html-button') as Element;+ const textarea = document.createElement('html-textarea') as Element;++ expect(button.matches('button')).toBe(true);+ expect(button.matches('html-button')).toBe(false);+ expect(button.matches('button,a[href],[role="button"]')).toBe(true);+ expect(textarea.matches('input,textarea,[contenteditable]')).toBe(true);+ expect(button.matches('textarea')).toBe(false);+ });++ it('should match combinators against ancestors and siblings', () => {+ const { document } = createSelectorFixture();+ const { firstTab, secondTab, label } = createTree(document);++ expect(secondTab.matches('[role="tablist"] > [role="tab"]')).toBe(true);+ expect(label.matches('[role="tablist"] span')).toBe(true);+ expect(label.matches('[role="tablist"] > span')).toBe(false);+ expect(secondTab.matches('#overview + button')).toBe(true);+ expect(secondTab.matches('#overview ~ button')).toBe(true);+ expect(firstTab.matches('button + button')).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);++ expect(firstTab.matches(':focus')).toBe(true);+ expect(firstTab.matches(':focus-visible')).toBe(true);+ expect(list.matches(':focus-within')).toBe(true);+ expect(secondTab.matches(':focus')).toBe(false);+ expect(secondTab.matches(':focus-within')).toBe(false);+ setActiveElement(secondTab);+ expect(firstTab.matches(':focus')).toBe(false);+ expect(secondTab.matches(':focus')).toBe(true);+ });++ it('should anchor relative has selectors to the candidate', () => {+ const { document } = createSelectorFixture();+ const outer = document.createElement('div');+ const candidate = document.createElement('section');+ const sibling = document.createElement('p');+ const descendant = document.createElement('span');+ outer.setAttribute('class', 'outer');+ candidate.append(descendant);+ outer.append(candidate, sibling);++ expect(candidate.matches(':has(> span)')).toBe(true);+ expect(candidate.matches(':has(+ p)')).toBe(true);+ expect(candidate.matches(':has(~ p)')).toBe(true);+ expect(candidate.matches(':has(.outer span)')).toBe(false);+ descendant.remove();+ expect(candidate.matches(':has(> span)')).toBe(false);+ });++ it('should evaluate structural pseudo-classes', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab, secondTab, label } = createTree(document);++ expect(firstTab.matches(':first-child')).toBe(true);+ expect(secondTab.matches(':last-child')).toBe(true);+ expect(label.matches(':only-child')).toBe(true);+ expect(firstTab.matches(':first-of-type')).toBe(true);+ expect(secondTab.matches(':first-of-type')).toBe(false);+ expect(secondTab.matches(':last-of-type')).toBe(true);+ expect(label.matches(':only-of-type')).toBe(true);+ expect(label.matches(':empty')).toBe(true);+ expect(list.matches(':empty')).toBe(false);+ expect(document.documentElement.matches(':root')).toBe(true);+ expect(list.matches(':root')).toBe(false);+ });++ it('should evaluate not, is, where and has', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab } = createTree(document);++ expect(firstTab.matches(':is(span, button)')).toBe(true);+ expect(firstTab.matches(':where(span, .tab)')).toBe(true);+ expect(list.matches(':has(span)')).toBe(true);+ expect(list.matches(':has(input)')).toBe(false);+ });++ describe.each(['is', 'where'])(':%s forgiving selector lists', (pseudo) => {+ it('should keep valid branches when another branch is unsupported', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab, secondTab, label } = createTree(document);+ const selector = `:${pseudo}(button, :unknown-pseudo)`;++ expect(firstTab.matches(selector)).toBe(true);+ expect(label.matches(selector)).toBe(false);+ expect(label.closest(selector)).toBe(secondTab);+ expect(list.querySelector(selector)).toBe(firstTab);+ expect(Array.from(list.querySelectorAll(selector))).toEqual([+ firstTab,+ secondTab,+ ]);+ });++ it('should match nothing when every branch is unsupported', () => {+ const { document } = createSelectorFixture();+ const { firstTab } = createTree(document);++ expect(firstTab.matches(`:${pseudo}(:unknown-pseudo, ::before)`)).toBe(+ false,+ );+ expect(firstTab.matches(`:not(:${pseudo}(:unknown-pseudo))`)).toBe(+ true,+ );+ });++ it('should discard a whole invalid branch including nested selectors', () => {+ const { document } = createSelectorFixture();+ const { firstTab, label } = createTree(document);+ const selector = `:${pseudo}(span, :not(:unknown-pseudo))`;++ expect(firstTab.matches(selector)).toBe(false);+ expect(label.matches(selector)).toBe(true);+ expect(+ firstTab.matches(`:${pseudo}(span, :not(:where(:unknown-pseudo)))`),+ ).toBe(true);+ });++ it('should retain scope and relative has semantics in valid branches', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab, secondTab } = createTree(document);++ expect(+ Array.from(+ list.querySelectorAll(+ `:${pseudo}(:scope > button, :unknown-pseudo)`,+ ),+ ),+ ).toEqual([firstTab, secondTab]);+ expect(+ list.querySelector(`:${pseudo}(:has(> span), :unknown-pseudo)`),+ ).toBe(secondTab);+ expect(+ list.querySelector(`button:has(> :${pseudo}(span, :unknown-pseudo))`),+ ).toBe(secondTab);+ });+ });++ it('should evaluate form state pseudo-classes from attributes', () => {+ const { document } = createSelectorFixture();+ const { firstTab, secondTab } = createTree(document);++ expect(secondTab.matches(':disabled')).toBe(true);+ expect(firstTab.matches(':disabled')).toBe(false);+ expect(firstTab.matches(':enabled')).toBe(true);+ });++ it('should treat interaction pseudo-classes that the sandbox cannot observe as unmatched', () => {+ const { document } = createSelectorFixture();+ const { firstTab } = createTree(document);++ expect(firstTab.matches(':hover')).toBe(false);+ expect(firstTab.matches(':active')).toBe(false);+ });++ it('should treat pseudo-classes the sandbox cannot observe as unmatched', () => {+ const { document } = createSelectorFixture();+ const { firstTab } = createTree(document);++ expect(firstTab.matches(':popover-open')).toBe(false);+ expect(firstTab.matches(':modal')).toBe(false);+ expect(firstTab.matches(':host')).toBe(false);+ expect(firstTab.matches(':state(pressed)')).toBe(false);+ expect(firstTab.matches(':-webkit-autofill')).toBe(false);+ expect(firstTab.matches(':not(:popover-open)')).toBe(true);+ });++ it('should throw a SyntaxError DOMException for an invalid selector', () => {+ const { document } = createSelectorFixture();+ const { firstTab } = createTree(document);++ expect(() => firstTab.matches(':unknown-pseudo')).toThrow(+ expect.objectContaining({ name: 'SyntaxError' }),+ );+ });+ });++ describe('closest', () => {+ it('should return the element itself when it matches', () => {+ const { document } = createSelectorFixture();+ const { firstTab } = createTree(document);++ expect(firstTab.closest('[role="tab"]')).toBe(firstTab);+ });++ it('should walk up to the nearest matching ancestor', () => {+ const { document } = createSelectorFixture();+ const { list, label } = createTree(document);++ expect(label.closest('[role="tablist"]')).toBe(list);+ });++ it('should return null when no ancestor matches', () => {+ const { document } = createSelectorFixture();+ const { label } = createTree(document);++ expect(label.closest('[hidden], [inert]')).toBeNull();+ });+ });++ describe('querySelector and querySelectorAll', () => {+ it('should decode CSS escapes in identifiers and attribute strings', () => {+ const { document } = createSelectorFixture();+ const target = document.createElement('html-button') as Element;+ target.setAttribute('id', '123');+ target.setAttribute('class', 'sm:flex');+ target.setAttribute('data-label', 'ABC');+ document.body.append(target);++ expect(document.querySelector(String.raw`#\31 23`)).toBe(target);+ expect(document.querySelector(String.raw`.sm\:flex`)).toBe(target);+ expect(document.querySelector(String.raw`[data-label="\41 BC"]`)).toBe(+ target,+ );+ });++ it.each([+ 'div,',+ '> div',+ '[',+ ':unknown-pseudo',+ 'button, :unknown-pseudo',+ ':not(button, :unknown-pseudo)',+ ':has(button, :unknown-pseudo)',+ ':is(button, :unknown-pseudo):unknown-pseudo',+ ':not(',+ ':disabled(x)',+ ':defined(tab)',+ ':focus(x)',+ ':state',+ 'button::before',+ ])(+ 'should reject invalid selector %p through the DOM interface',+ (selector) => {+ const { document } = createSelectorFixture();++ expect(() => document.querySelector(selector)).toThrow(+ expect.objectContaining({ name: 'SyntaxError' }),+ );+ },+ );++ it('should resolve document scope and support structural selector arguments', () => {+ const { document } = createSelectorFixture();+ const { list, secondTab } = createTree(document);++ expect(document.querySelector(':scope')).toBe(document.documentElement);+ expect(list.querySelector('button:nth-child(2)')).toBe(secondTab);+ expect(list.querySelector('body button:nth-child(2)')).toBe(secondTab);+ });++ it('should query descendants in document order from an element', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab, secondTab } = createTree(document);++ const tabs = list.querySelectorAll('[role="tab"]');++ expect(Array.from(tabs)).toEqual([firstTab, secondTab]);+ expect(tabs.item(0)).toBe(firstTab);+ expect(list.querySelector('input')).toBeNull();+ });++ it('should query from the document', () => {+ const { document } = createSelectorFixture();+ const { list, label } = createTree(document);++ expect(document.querySelector('[role="tablist"]')).toBe(list);+ expect(document.querySelectorAll('span')).toHaveLength(1);+ expect(document.querySelector('span')).toBe(label);+ });++ it('should not match the scope element itself', () => {+ const { document } = createSelectorFixture();+ const { list } = createTree(document);++ expect(list.querySelectorAll('[role="tablist"]')).toHaveLength(0);+ });++ it('should resolve :scope to the query root', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab, secondTab } = createTree(document);++ expect(Array.from(list.querySelectorAll(':scope > button'))).toEqual([+ firstTab,+ secondTab,+ ]);+ });++ it('should support the tabbable candidate selector', () => {+ const { document } = createSelectorFixture();+ const details = document.createElement('details');+ const summary = document.createElement('summary');+ const input = document.createElement('html-input') as Element;+ details.append(summary);+ document.body.append(details, input);++ const candidates = document.querySelectorAll(+ 'input,select,textarea,a[href],button,[tabindex],audio[controls],video[controls],[contenteditable]:not([contenteditable="false"]),details>summary:first-of-type,details',+ );++ expect(Array.from(candidates)).toEqual([details, summary, input]);+ });+ });++ describe('sub-selectors outside the scope subtree', () => {+ it('should match ancestors through :is, :where and :not', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab, secondTab, label } = createTree(document);+ const container = document.createElement('div');+ container.setAttribute('class', 'foo');+ document.body.append(container);+ container.append(list);++ expect(firstTab.closest(':is(.foo)')).toBe(container);+ expect(label.closest(':where([role="tablist"])')).toBe(list);+ expect(label.closest('button:not([disabled])')).toBeNull();+ expect(secondTab.matches(':not([role="tablist"]) > button')).toBe(false);+ expect(secondTab.matches(':is([role="tablist"]) > button')).toBe(true);+ expect(label.matches(':is(.foo) span')).toBe(true);+ expect(Array.from(list.querySelectorAll(':is(body) button'))).toEqual([+ firstTab,+ secondTab,+ ]);+ });++ it('should not treat a tabindex="-1" popup ancestor as interactive', () => {+ const { document } = createSelectorFixture();+ const popup = document.createElement('div');+ const content = document.createElement('div');+ const text = document.createElement('span');+ popup.setAttribute('tabindex', '-1');+ popup.append(content);+ content.append(text);+ document.body.append(popup);++ expect(+ text.closest(+ 'button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),input:not([type=\'hidden\']):not([disabled]),textarea:not([disabled]),[contenteditable]:not([contenteditable=\'false\'])',+ ),+ ).toBeNull();+ });++ it('should keep relative :has arguments anchored to the candidate', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab, secondTab, label } = createTree(document);++ expect(Array.from(list.querySelectorAll(':has(> span)'))).toEqual([+ secondTab,+ ]);+ expect(label.closest(':has(> span)')).toBe(secondTab);+ expect(+ Array.from(document.querySelectorAll('button:has(+ button)')),+ ).toEqual([firstTab]);+ });++ it('should exclude the scoping root from document-scoped :scope queries', () => {+ const { document } = createSelectorFixture();++ const descendants = Array.from(document.querySelectorAll(':scope *'));++ expect(descendants).not.toContain(document.documentElement);+ expect(descendants).toContain(document.body);+ });++ it('should resolve :scope per call when the same selector is reused', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab, secondTab } = createTree(document);++ expect(Array.from(list.querySelectorAll(':scope > button'))).toEqual([+ firstTab,+ secondTab,+ ]);+ expect(Array.from(firstTab.querySelectorAll(':scope > button'))).toEqual(+ [],+ );+ expect(firstTab.matches(':scope')).toBe(true);+ expect(secondTab.matches(':scope')).toBe(true);+ expect(firstTab.matches(':not(:scope)')).toBe(false);+ });+ });++ describe('attribute selectors', () => {+ it('should match attribute names case-insensitively', () => {+ const { document } = createSelectorFixture();+ const { firstTab } = createTree(document);+ firstTab.setAttribute('data-testId', 'abc');+ firstTab.setAttribute('contentEditable', '');++ expect(firstTab.matches('[data-testId="abc"]')).toBe(true);+ expect(firstTab.matches('[data-testid="abc"]')).toBe(true);+ expect(document.querySelector('[data-testid]')).toBe(firstTab);+ expect(+ firstTab.matches('[contenteditable]:not([contenteditable="false"])'),+ ).toBe(true);+ });++ it('should not treat inherited element accessors as attributes', () => {+ const { document } = createSelectorFixture();+ const { firstTab } = createTree(document);++ expect(firstTab.matches('[slot]')).toBe(false);+ expect(firstTab.matches(':not([slot])')).toBe(true);+ expect(document.querySelectorAll('[slot]')).toHaveLength(0);+ firstTab.setAttribute('slot', 'actions');+ expect(firstTab.matches('[slot="actions"]')).toBe(true);+ });+ });++ describe(':nth-child of a selector', () => {+ it('should count :nth-child and :nth-last-child among siblings matching the of selector', () => {+ const { document } = createSelectorFixture();+ const { list, firstTab, secondTab } = createTree(document);+ const thirdTab = document.createElement('button');+ thirdTab.setAttribute('class', 'tab');+ list.append(thirdTab);++ expect(secondTab.matches(':nth-child(2 of .tab)')).toBe(true);+ expect(thirdTab.matches(':nth-child(odd of .tab)')).toBe(true);+ expect(firstTab.matches(':nth-last-child(3 of .tab)')).toBe(true);+ expect(firstTab.matches(':nth-child(2 of .tab)')).toBe(false);+ expect(() =>+ firstTab.matches(':nth-child(2 of :unknown-pseudo)'),+ ).toThrow(expect.objectContaining({ name: 'SyntaxError' }));+ });+ });++ describe(':root', () => {+ it('should match only the document element', () => {+ const { document } = createSelectorFixture();+ const detached = document.createElement('div');+ const detachedChild = document.createElement('span');+ const fragment = document.createDocumentFragment();+ const fragmentChild = document.createElement('div');+ detached.append(detachedChild);+ fragment.append(fragmentChild);++ expect(document.documentElement.matches(':root')).toBe(true);+ expect(detached.matches(':root')).toBe(false);+ expect(detachedChild.closest(':root')).toBeNull();+ expect(fragmentChild.matches(':root')).toBe(false);+ });+ });++ describe('DocumentFragment', () => {+ it('should query fragments with the worker selector engine', () => {+ const { document } = createSelectorFixture();+ const fragment = document.createDocumentFragment();+ const button = document.createElement('html-button') as Element;+ const span = document.createElement('span');+ fragment.append(button, span);++ expect(fragment.querySelector('button')).toBe(button);+ expect(+ Array.from(fragment.querySelectorAll('span:first-of-type')),+ ).toEqual([span]);+ });+ });+});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.tsnew file mode 100644index 00000000000..f0ae484eeb3--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/buildSelectorPseudoClassMatchers.ts@@ -0,0 +1,41 @@+import { isAncestorOrSelfOfNode } from '@/polyfills/dom/utils/isAncestorOrSelfOfNode';+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';+import { isDocumentNode } from '@/polyfills/selectors/utils/isDocumentNode';++// css-select reads whether a pseudo-class takes an argument from the matcher's+// arity, so these unused parameters are required.+const isNeverMatching = (_element: SelectorElementLike): boolean => false;++const isNeverMatchingWithArgument = (+ _element: SelectorElementLike,+ _argument?: string | null,+): boolean => false;++const isAlwaysMatching = (_element: SelectorElementLike): boolean => true;++export const buildSelectorPseudoClassMatchers = ({+ resolveActiveElement,+}: {+ resolveActiveElement: () => object | null;+}): CssSelectPseudoClassMatchers => {+ const isActiveElement = (element: SelectorElementLike): boolean =>+ element === resolveActiveElement();++ return {+ ...Object.fromEntries(+ UNOBSERVABLE_PSEUDO_CLASS_NAMES.map((pseudoClassName) => [+ pseudoClassName,+ isNeverMatching,+ ]),+ ),+ state: isNeverMatchingWithArgument,+ defined: isAlwaysMatching,+ root: (element) => isDocumentNode(element.parentNode),+ focus: isActiveElement,+ 'focus-visible': isActiveElement,+ 'focus-within': (element) =>+ isAncestorOrSelfOfNode(element, resolveActiveElement()),+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectChildNodes.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectChildNodes.tsnew file mode 100644index 00000000000..61fcef71d8e--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectChildNodes.ts@@ -0,0 +1,20 @@+import { isObject } from '@sniptt/guards';++import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export const collectChildNodes = (+ node: SelectorElementLike,+): SelectorElementLike[] => {+ const childNodes = node.childNodes ?? [];+ const children: SelectorElementLike[] = [];++ for (let index = 0; index < childNodes.length; index += 1) {+ const child = childNodes[index];++ if (isObject(child)) {+ children.push(child as SelectorElementLike);+ }+ }++ return children;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectMatchingDescendants.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectMatchingDescendants.tsnew file mode 100644index 00000000000..a295d3a5f82--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectMatchingDescendants.ts@@ -0,0 +1,12 @@+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { iterateMatchingDescendants } from '@/polyfills/selectors/utils/iterateMatchingDescendants';++export const collectMatchingDescendants = ({+ nodes,+ isElementMatching,+}: {+ nodes: SelectorElementLike[];+ isElementMatching: (element: SelectorElementLike) => boolean;+}): SelectorElementLike[] => [+ ...iterateMatchingDescendants({ nodes, isElementMatching }),+];diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectSiblingNodes.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectSiblingNodes.tsnew file mode 100644index 00000000000..15ad24af055--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/collectSiblingNodes.ts@@ -0,0 +1,13 @@+import { isDefined } from 'twenty-shared/utils';++import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { collectChildNodes } from '@/polyfills/selectors/utils/collectChildNodes';+import { resolveParentNode } from '@/polyfills/selectors/utils/resolveParentNode';++export const collectSiblingNodes = (+ node: SelectorElementLike,+): SelectorElementLike[] => {+ const parentNode = resolveParentNode(node);++ return isDefined(parentNode) ? collectChildNodes(parentNode) : [node];+};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.tsnew file mode 100644index 00000000000..5288600fb93--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/createSelectorMatcherResolver.ts@@ -0,0 +1,87 @@+import { compile } from 'css-select';+import { isDefined } from 'twenty-shared/utils';++import { SCOPE_PSEUDO_CLASS_PATTERN } from '@/polyfills/selectors/constants/ScopePseudoClassPattern';+import { SELECTOR_MATCHER_CACHE_SIZE } from '@/polyfills/selectors/constants/SelectorMatcherCacheSize';+import { WORKER_DOM_CSS_SELECT_ADAPTER } from '@/polyfills/selectors/constants/WorkerDomCssSelectAdapter';+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { type SelectorMatcher } from '@/polyfills/selectors/types/SelectorMatcher';+import { type SelectorMatcherResolver } from '@/polyfills/selectors/types/SelectorMatcherResolver';+import { buildSelectorPseudoClassMatchers } from '@/polyfills/selectors/utils/buildSelectorPseudoClassMatchers';+import { createSelectorSyntaxError } from '@/polyfills/selectors/utils/createSelectorSyntaxError';+import { parseSelectorsWithForgivingLists } from '@/polyfills/selectors/utils/parseSelectorsWithForgivingLists';+import { resolveSelectorScopeTarget } from '@/polyfills/selectors/utils/resolveSelectorScopeTarget';++export const createSelectorMatcherResolver = ({+ resolveActiveElement,+}: {+ resolveActiveElement: () => object | null;+}): SelectorMatcherResolver => {+ const pseudoClassMatchers = buildSelectorPseudoClassMatchers({+ resolveActiveElement,+ });+ const unscopedMatcherBySelectorsText = new Map<string, SelectorMatcher>();++ const compileSelectorsText = ({+ selectorsText,+ scopeTarget,+ }: {+ selectorsText: string;+ scopeTarget?: SelectorElementLike;+ }): SelectorMatcher => {+ try {+ return compile(+ parseSelectorsWithForgivingLists({+ selectorsText,+ pseudoClassMatchers,+ }),+ {+ adapter: WORKER_DOM_CSS_SELECT_ADAPTER,+ pseudos: pseudoClassMatchers,+ relativeSelector: false,+ // Compiled matchers are reused across DOM mutations.+ cacheResults: false,+ },+ scopeTarget,+ );+ } catch {+ throw createSelectorSyntaxError(selectorsText);+ }+ };++ const resolveUnscopedMatcher = (selectorsText: string): SelectorMatcher => {+ const cachedMatcher = unscopedMatcherBySelectorsText.get(selectorsText);++ if (isDefined(cachedMatcher)) {+ return cachedMatcher;+ }++ const matcher = compileSelectorsText({ selectorsText });++ if (unscopedMatcherBySelectorsText.size >= SELECTOR_MATCHER_CACHE_SIZE) {+ const oldestSelectorsText = unscopedMatcherBySelectorsText+ .keys()+ .next().value;++ if (isDefined(oldestSelectorsText)) {+ unscopedMatcherBySelectorsText.delete(oldestSelectorsText);+ }+ }++ unscopedMatcherBySelectorsText.set(selectorsText, matcher);++ return matcher;+ };++ return {+ // css-select binds :scope to the element given at compile time, so+ // selectors using it are compiled for each call instead of cached.+ resolveSelectorMatcher: ({ selectorsText, scopeElement }) =>+ SCOPE_PSEUDO_CLASS_PATTERN.test(selectorsText)+ ? compileSelectorsText({+ selectorsText,+ scopeTarget: resolveSelectorScopeTarget(scopeElement),+ })+ : resolveUnscopedMatcher(selectorsText),+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/createSelectorSyntaxError.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/createSelectorSyntaxError.tsnew file mode 100644index 00000000000..549482d54ac--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/createSelectorSyntaxError.ts@@ -0,0 +1,7 @@+import { createDomException } from '@/polyfills/utils/createDomException';++export const createSelectorSyntaxError = (selectorsText: string): Error =>+ createDomException(+ `'${selectorsText}' is not a valid selector.`,+ 'SyntaxError',+ );diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/findFirstMatchingDescendant.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/findFirstMatchingDescendant.tsnew file mode 100644index 00000000000..bc455839ac2--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/findFirstMatchingDescendant.ts@@ -0,0 +1,11 @@+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { iterateMatchingDescendants } from '@/polyfills/selectors/utils/iterateMatchingDescendants';++export const findFirstMatchingDescendant = ({+ nodes,+ isElementMatching,+}: {+ nodes: SelectorElementLike[];+ isElementMatching: (element: SelectorElementLike) => boolean;+}): SelectorElementLike | null =>+ iterateMatchingDescendants({ nodes, isElementMatching }).next().value ?? null;diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/hasElementAttributeIgnoringCase.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/hasElementAttributeIgnoringCase.tsnew file mode 100644index 00000000000..3963e66d6ba--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/hasElementAttributeIgnoringCase.ts@@ -0,0 +1,10 @@+import { isDefined } from 'twenty-shared/utils';++import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { readElementAttributeIgnoringCase } from '@/polyfills/selectors/utils/readElementAttributeIgnoringCase';++export const hasElementAttributeIgnoringCase = (+ element: SelectorElementLike,+ attributeName: string,+): boolean =>+ isDefined(readElementAttributeIgnoringCase(element, attributeName));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.tsnew file mode 100644index 00000000000..6006d76b209--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/installSelectorMethodsPolyfill.ts@@ -0,0 +1,116 @@+import { type WorkerNodeList } from '@/polyfills/dom/types/WorkerNodeList';+import { createWorkerNodeList } from '@/polyfills/dom/utils/createWorkerNodeList';+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { collectChildNodes } from '@/polyfills/selectors/utils/collectChildNodes';+import { collectMatchingDescendants } from '@/polyfills/selectors/utils/collectMatchingDescendants';+import { createSelectorMatcherResolver } from '@/polyfills/selectors/utils/createSelectorMatcherResolver';+import { findFirstMatchingDescendant } from '@/polyfills/selectors/utils/findFirstMatchingDescendant';+import { isSelectorElementNode } from '@/polyfills/selectors/utils/isSelectorElementNode';+import { definePolyfillMethod } from '@/polyfills/utils/definePolyfillMethod';++type InstallSelectorMethodsPolyfillInput = {+ elementPrototype: object;+ querySelectorTargets: object[];+ resolveActiveElement: () => object | null;+};++export const installSelectorMethodsPolyfill = ({+ elementPrototype,+ querySelectorTargets,+ resolveActiveElement,+}: InstallSelectorMethodsPolyfillInput): void => {+ const { resolveSelectorMatcher } = createSelectorMatcherResolver({+ resolveActiveElement,+ });++ const createMatcherForScope = ({+ selectorsText,+ scopeElement,+ }: {+ selectorsText: unknown;+ scopeElement: SelectorElementLike;+ }) =>+ resolveSelectorMatcher({+ selectorsText: String(selectorsText),+ scopeElement,+ });++ const matches = (+ element: SelectorElementLike,+ selectorsText: unknown,+ ): boolean =>+ createMatcherForScope({ selectorsText, scopeElement: element })(element);++ const closest = (+ element: SelectorElementLike,+ selectorsText: unknown,+ ): SelectorElementLike | null => {+ const isElementMatchingSelectors = createMatcherForScope({+ selectorsText,+ scopeElement: element,+ });+ let currentNode: unknown = element;++ while (isSelectorElementNode(currentNode)) {+ if (isElementMatchingSelectors(currentNode)) {+ return currentNode;+ }++ currentNode = currentNode.parentNode;+ }++ return null;+ };++ const querySelectorAll = (+ scopeElement: SelectorElementLike,+ selectorsText: unknown,+ ): WorkerNodeList<SelectorElementLike> =>+ createWorkerNodeList(+ collectMatchingDescendants({+ nodes: collectChildNodes(scopeElement),+ isElementMatching: createMatcherForScope({+ selectorsText,+ scopeElement,+ }),+ }),+ );++ const querySelector = (+ scopeElement: SelectorElementLike,+ selectorsText: unknown,+ ): SelectorElementLike | null =>+ findFirstMatchingDescendant({+ nodes: collectChildNodes(scopeElement),+ isElementMatching: createMatcherForScope({ selectorsText, scopeElement }),+ });++ definePolyfillMethod({+ target: elementPrototype,+ methodName: 'matches',+ method: matches,+ });+ definePolyfillMethod({+ target: elementPrototype,+ methodName: 'webkitMatchesSelector',+ method: matches,+ });+ definePolyfillMethod({+ target: elementPrototype,+ methodName: 'closest',+ method: closest,+ });++ for (const target of querySelectorTargets) {+ definePolyfillMethod({+ target,+ methodName: 'querySelectorAll',+ method: querySelectorAll,+ });+ definePolyfillMethod({+ target,+ methodName: 'querySelector',+ method: querySelector,+ });+ }+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isDocumentNode.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isDocumentNode.tsnew file mode 100644index 00000000000..4a1f9c5a4bc--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isDocumentNode.ts@@ -0,0 +1,8 @@+import { isObject } from '@sniptt/guards';++import { NODE_TYPE_BY_NAME } from '@/polyfills/dom/constants/NodeTypeByName';+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export const isDocumentNode = (node: unknown): node is SelectorElementLike =>+ isObject(node) &&+ (node as SelectorElementLike).nodeType === NODE_TYPE_BY_NAME.DOCUMENT;diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isSelectorElementNode.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isSelectorElementNode.tsnew file mode 100644index 00000000000..f5b7cee14ad--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/isSelectorElementNode.ts@@ -0,0 +1,10 @@+import { isObject } from '@sniptt/guards';++import { NODE_TYPE_BY_NAME } from '@/polyfills/dom/constants/NodeTypeByName';+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export const isSelectorElementNode = (+ node: unknown,+): node is SelectorElementLike =>+ isObject(node) &&+ (node as SelectorElementLike).nodeType === NODE_TYPE_BY_NAME.ELEMENT;diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/iterateMatchingDescendants.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/iterateMatchingDescendants.tsnew file mode 100644index 00000000000..3a040656d01--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/iterateMatchingDescendants.ts@@ -0,0 +1,19 @@+import { iterateElementSubtree } from '@/polyfills/dom/utils/iterateElementSubtree';+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { isSelectorElementNode } from '@/polyfills/selectors/utils/isSelectorElementNode';++export function* iterateMatchingDescendants({+ nodes,+ isElementMatching,+}: {+ nodes: SelectorElementLike[];+ isElementMatching: (element: SelectorElementLike) => boolean;+}): Generator<SelectorElementLike> {+ for (const node of nodes) {+ for (const descendant of iterateElementSubtree(node)) {+ if (isSelectorElementNode(descendant) && isElementMatching(descendant)) {+ yield descendant;+ }+ }+ }+}diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/normalizeRemoteTagNameToHtmlTagName.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/normalizeRemoteTagNameToHtmlTagName.tsnew file mode 100644index 00000000000..dbfcfa886d4--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/normalizeRemoteTagNameToHtmlTagName.ts@@ -0,0 +1,5 @@+import { HTML_TAG_NAME_BY_REMOTE_ELEMENT_TAG_NAME } from '@/polyfills/selectors/constants/HtmlTagNameByRemoteElementTagName';++export const normalizeRemoteTagNameToHtmlTagName = (tagName: string): string =>+ HTML_TAG_NAME_BY_REMOTE_ELEMENT_TAG_NAME.get(tagName.toLowerCase()) ??+ tagName.toLowerCase();diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/parseSelectorsWithForgivingLists.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/parseSelectorsWithForgivingLists.tsnew file mode 100644index 00000000000..2571f947892--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/parseSelectorsWithForgivingLists.ts@@ -0,0 +1,50 @@+import { isArray } from '@sniptt/guards';+import { compile } from 'css-select';+import { parse, type Selector, SelectorType } from 'css-what';++import { WORKER_DOM_CSS_SELECT_ADAPTER } from '@/polyfills/selectors/constants/WorkerDomCssSelectAdapter';+import { type CssSelectPseudoClassMatchers } from '@/polyfills/selectors/types/CssSelectPseudoClassMatchers';++export const parseSelectorsWithForgivingLists = ({+ selectorsText,+ pseudoClassMatchers,+}: {+ selectorsText: string;+ pseudoClassMatchers: CssSelectPseudoClassMatchers;+}): Selector[][] => {+ const isSupportedBranch = (branch: Selector[]): boolean => {+ try {+ compile(structuredClone([branch]), {+ adapter: WORKER_DOM_CSS_SELECT_ADAPTER,+ pseudos: pseudoClassMatchers,+ relativeSelector: false,+ cacheResults: false,+ });++ return true;+ } catch {+ return false;+ }+ };++ const normalizeSelectorLists = (selectorList: Selector[][]): Selector[][] => {+ for (const branch of selectorList) {+ for (const selector of branch) {+ if (selector.type !== SelectorType.Pseudo || !isArray(selector.data)) {+ continue;+ }++ const nestedSelectorList = normalizeSelectorLists(selector.data);+ const isForgiving = selector.name === 'is' || selector.name === 'where';++ selector.data = isForgiving+ ? nestedSelectorList.filter(isSupportedBranch)+ : nestedSelectorList;+ }+ }++ return selectorList;+ };++ return normalizeSelectorLists(parse(selectorsText));+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/readElementAttributeIgnoringCase.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/readElementAttributeIgnoringCase.tsnew file mode 100644index 00000000000..852bf070785--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/readElementAttributeIgnoringCase.ts@@ -0,0 +1,48 @@+import { isFunction, isObject, isString } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++type AttributeLike = {+ name?: unknown;+};++const resolveStoredAttributeName = (attribute: unknown): string | null => {+ if (!isObject(attribute)) {+ return null;+ }++ const { name } = attribute as AttributeLike;++ return isString(name) ? name : null;+};++export const readElementAttributeIgnoringCase = (+ element: SelectorElementLike,+ attributeName: string,+): string | null => {+ if (!isFunction(element.getAttribute)) {+ return null;+ }++ const exactAttributeValue = element.getAttribute(attributeName);++ if (isDefined(exactAttributeValue)) {+ return exactAttributeValue;+ }++ const lowerCasedAttributeName = attributeName.toLowerCase();++ for (const attribute of element.attributes ?? []) {+ const storedAttributeName = resolveStoredAttributeName(attribute);++ if (+ isDefined(storedAttributeName) &&+ storedAttributeName.toLowerCase() === lowerCasedAttributeName+ ) {+ return element.getAttribute(storedAttributeName);+ }+ }++ return null;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/removeNestedNodes.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/removeNestedNodes.tsnew file mode 100644index 00000000000..dd5068d3c2a--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/removeNestedNodes.ts@@ -0,0 +1,16 @@+import { isAncestorOrSelfOfNode } from '@/polyfills/dom/utils/isAncestorOrSelfOfNode';+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export const removeNestedNodes = (+ nodes: SelectorElementLike[],+): SelectorElementLike[] => {+ const uniqueNodes = [...new Set(nodes)];++ return uniqueNodes.filter(+ (node) =>+ !uniqueNodes.some(+ (otherNode) =>+ otherNode !== node && isAncestorOrSelfOfNode(otherNode, node),+ ),+ );+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveHtmlTagNameOfElement.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveHtmlTagNameOfElement.tsnew file mode 100644index 00000000000..ea3f7a5fa21--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveHtmlTagNameOfElement.ts@@ -0,0 +1,6 @@+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { normalizeRemoteTagNameToHtmlTagName } from '@/polyfills/selectors/utils/normalizeRemoteTagNameToHtmlTagName';++export const resolveHtmlTagNameOfElement = (+ element: SelectorElementLike,+): string => normalizeRemoteTagNameToHtmlTagName(element.localName ?? '');diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveNodeText.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveNodeText.tsnew file mode 100644index 00000000000..eeca1610dc2--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveNodeText.ts@@ -0,0 +1,9 @@+import { isString } from '@sniptt/guards';++import { NODE_TYPE_BY_NAME } from '@/polyfills/dom/constants/NodeTypeByName';+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export const resolveNodeText = (node: SelectorElementLike): string =>+ node.nodeType !== NODE_TYPE_BY_NAME.COMMENT && isString(node.textContent)+ ? node.textContent+ : '';diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveParentNode.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveParentNode.tsnew file mode 100644index 00000000000..d1a597454ea--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveParentNode.ts@@ -0,0 +1,8 @@+import { isObject } from '@sniptt/guards';++import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export const resolveParentNode = (+ node: SelectorElementLike,+): SelectorElementLike | null =>+ isObject(node.parentNode) ? (node.parentNode as SelectorElementLike) : null;diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolvePreviousSiblingElement.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolvePreviousSiblingElement.tsnew file mode 100644index 00000000000..e2c126283ac--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolvePreviousSiblingElement.ts@@ -0,0 +1,9 @@+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { isSelectorElementNode } from '@/polyfills/selectors/utils/isSelectorElementNode';++export const resolvePreviousSiblingElement = (+ element: SelectorElementLike,+): SelectorElementLike | null =>+ isSelectorElementNode(element.previousElementSibling)+ ? element.previousElementSibling+ : null;diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveSelectorScopeTarget.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveSelectorScopeTarget.tsnew file mode 100644index 00000000000..559039315bb--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/resolveSelectorScopeTarget.ts@@ -0,0 +1,11 @@+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { collectChildNodes } from '@/polyfills/selectors/utils/collectChildNodes';+import { isDocumentNode } from '@/polyfills/selectors/utils/isDocumentNode';+import { isSelectorElementNode } from '@/polyfills/selectors/utils/isSelectorElementNode';++export const resolveSelectorScopeTarget = (+ scopeElement: SelectorElementLike,+): SelectorElementLike | undefined =>+ isDocumentNode(scopeElement)+ ? collectChildNodes(scopeElement).find(isSelectorElementNode)+ : scopeElement;diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/definePolyfillMethod.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/definePolyfillMethod.tsnew file mode 100644index 00000000000..7d0eacb9516--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/definePolyfillMethod.ts@@ -0,0 +1,22 @@+type PolyfillMethodImplementation<TReceiver extends object> = (+ receiver: TReceiver,+ ...methodArguments: unknown[]+) => unknown;++export const definePolyfillMethod = <TReceiver extends object>({+ target,+ methodName,+ method,+}: {+ target: object;+ methodName: string;+ method: PolyfillMethodImplementation<TReceiver>;+}): void => {+ Object.defineProperty(target, methodName, {+ value(this: TReceiver, ...methodArguments: unknown[]) {+ return method(this, ...methodArguments);+ },+ configurable: true,+ writable: true,+ });+};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.tsindex 7b79e989661..63ca1f416e1 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@@ -16,6 +16,7 @@ import { installGetComputedStyle } from '@/polyfills/dom/utils/installGetComputeimport { installGetElementsByClassName } from '@/polyfills/dom/utils/installGetElementsByClassName';import { installLocalStyleOnBaseElements } from '@/polyfills/dom/utils/installLocalStyleOnBaseElements';import { installMutationObserver } from '@/polyfills/dom/utils/installMutationObserver';+import { installSelectorMethodsPolyfill } from '@/polyfills/selectors/utils/installSelectorMethodsPolyfill';import { workerGeometryStore } from '@/polyfills/geometry/states/workerGeometryStore';import { installElementGeometryPolyfill } from '@/polyfills/geometry/utils/installElementGeometryPolyfill';import { installWindowGeometryPolyfill } from '@/polyfills/geometry/utils/installWindowGeometryPolyfill';@@ -52,6 +53,16 @@ installClassAttributeAccessors({});installLocalStyleOnBaseElements(Element.prototype);+installSelectorMethodsPolyfill({+ elementPrototype: Element.prototype,+ querySelectorTargets: [+ Element.prototype,+ DocumentFragment.prototype,+ document,+ ],+ resolveActiveElement: () => null,+});+installGetComputedStyle(toGlobalScopeRecord(globalThis));installMutationObserver({diff --git a/packages/twenty-front-component-renderer/vite.config.ts b/packages/twenty-front-component-renderer/vite.config.tsindex 4f3662f40e3..8cb887cec5a 100644--- a/packages/twenty-front-component-renderer/vite.config.ts+++ b/packages/twenty-front-component-renderer/vite.config.ts@@ -3,6 +3,7 @@ import { type PackageJson } from 'type-fest';import { defineConfig } from 'vite';import packageJson from './package.json';+import { createDomutilsStubPlugin } from './scripts/worker/createDomutilsStubPlugin';export default defineConfig(() => {return {@@ -23,6 +24,7 @@ export default defineConfig(() => {},},plugins: () => [+ createDomutilsStubPlugin(),{name: 'define-process-env',transform: (code: string) =>diff --git a/yarn.lock b/yarn.lockindex 123bb051198..1ec5d1e19ff 100644--- a/yarn.lock+++ b/yarn.lock@@ -26340,6 +26340,13 @@ __metadata:languageName: nodelinkType: hard+"boolbase@npm:^2.0.0":+ version: 2.0.0+ resolution: "boolbase@npm:2.0.0"+ checksum: 10c0/08b2e79d3368fc7592cf3edb0a070a7288ece00ee2c5378f63c11dbf98c3a35386b65c368bd584a9e689c450070d2dae154df7ac42e9e8f64c6853507abcb8c4+ languageName: node+ linkType: hard+"boolean@npm:^3.0.1":version: 3.2.0resolution: "boolean@npm:3.2.0"@@ -28347,6 +28354,19 @@ __metadata:languageName: nodelinkType: hard+"css-select@npm:^7.0.0":+ version: 7.0.0+ resolution: "css-select@npm:7.0.0"+ dependencies:+ boolbase: "npm:^2.0.0"+ css-what: "npm:^8.0.0"+ domhandler: "npm:^6.0.1"+ domutils: "npm:^4.0.2"+ nth-check: "npm:^3.0.1"+ checksum: 10c0/cf485fc635d05d1a5443984cc1c1ff079ba221fe53a7bdd7aca31813d4d5c818ce441e2fbb0043f36d7caa94eb409c22c9defd5900502a985698ede2e4e9dfa4+ languageName: node+ linkType: hard+"css-to-react-native@npm:3.2.0":version: 3.2.0resolution: "css-to-react-native@npm:3.2.0"@@ -28395,6 +28415,13 @@ __metadata:languageName: nodelinkType: hard+"css-what@npm:^8.0.0":+ version: 8.0.0+ resolution: "css-what@npm:8.0.0"+ checksum: 10c0/11053f3da58abda961bf3ddc9de28a1d84e2e072a7a6873e68bfce7d0796b55800a41e31c0857b632b71d1a3fc42d0dd1d8e96237e52f43d7cfd90510040bdd4+ languageName: node+ linkType: hard+"css.escape@npm:^1.5.1":version: 1.5.1resolution: "css.escape@npm:1.5.1"@@ -29650,7 +29677,7 @@ __metadata:languageName: nodelinkType: hard-"domhandler@npm:^6.0.0":+"domhandler@npm:^6.0.0, domhandler@npm:^6.0.1":version: 6.0.1resolution: "domhandler@npm:6.0.1"dependencies:@@ -41134,6 +41161,15 @@ __metadata:languageName: nodelinkType: hard+"nth-check@npm:^3.0.1":+ version: 3.0.1+ resolution: "nth-check@npm:3.0.1"+ dependencies:+ boolbase: "npm:^2.0.0"+ checksum: 10c0/392479224b596b8fb1a2f6378d2a3401aa26577c3f7619b07409fc7d95dbfbe224458920a4ab5ce75c43b468fc7e0f60424fda950aec8159353687eb5c508f9a+ languageName: node+ linkType: hard+"nullthrows@npm:^1.0.0":version: 1.1.1resolution: "nullthrows@npm:1.1.1"@@ -50333,6 +50369,8 @@ __metadata:"@types/react-dom": "npm:^19.2.0""@typescript/native-preview": "npm:^7.0.0-dev.20260116.1""@vitest/browser-playwright": "npm:^4.1.0"+ css-select: "npm:^7.0.0"+ css-what: "npm:^8.0.0"monaco-editor: "npm:0.52.2"playwright: "npm:^1.60.0"prettier: "npm:^3.1.1"