Skip to content

The open alternative to Salesforce, designed for AI.

Support matchMedia in front components (#24160)

Raphaël Bosi7cbdfec6f346
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 74c02bd7b6a..a4ad8dc9122 100644
--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
@@ -906,7 +906,8 @@ Elements can measure themselves: the host mirrors geometry into the sandbox, so
| API | What happens |
|-----|--------------|
| `getBoundingClientRect()`, `offsetWidth`, `clientWidth`, `scrollWidth`, `offsetTop`, ... | Work, from the mirror; assigning `scrollTop` / `scrollLeft` is a no-op |
-| `getClientRects()`, `window.matchMedia()` | Throws |
+| `getClientRects()` | Throws |
+| `window.matchMedia()` | Works for a fixed set of features, with `change` events (see below) |
| `window.innerWidth`, `innerHeight`, `devicePixelRatio`, `scrollX`, `scrollY` | Work, reporting the **browser viewport**; your widget's own size is `document.body.clientWidth` / `clientHeight` |
| `window.getComputedStyle()` | Returns the element's inline styles only, never the host-computed cascade |
| `ResizeObserver`, `IntersectionObserver` | `ReferenceError` (`typeof` guards do work) |
@@ -914,6 +915,12 @@ Elements can measure themselves: the host mirrors geometry into the sandbox, so
Positioning from `getBoundingClientRect` now works, but anything watching size changes through `ResizeObserver` (recharts `ResponsiveContainer`, Floating UI's `autoUpdate`) still does not. Prefer CSS for layout anyway: your stylesheet reaches the real page, so flexbox, grid, `aspect-ratio`, `clamp()` and `@container` behave normally, with no frame lag.
+`matchMedia()` evaluates `width`, `height`, `orientation`, `-webkit-device-pixel-ratio`, `resolution`, `hover`, `pointer` and `prefers-color-scheme`, in the `min-`/`max-` form, the Level 4 range form (`(width >= 600px)`, `(400px <= width <= 800px)`) and the valueless form (`(width)`). Widths, heights and `orientation` describe **your widget's box**, not the browser viewport, so they follow `document.body.clientWidth` rather than `window.innerWidth`, and `em` and `rem` count as 16px. `hover` and `pointer` describe the primary input of the user's device. Any other condition counts as unknown, the way browsers treat unknown features: the comma-separated member it appears in evaluates to `false`, even under `not`, unless the rest of that member already decides the result, as in `not print and (prefers-reduced-motion: reduce)`. That covers unknown features and the syntax this parser does not implement inside a condition, such as nested groups like `((min-width: 600px))`, `not` inside a group and `calc()` values. An `or` between conditions makes its member `false`. The `MediaQueryList` and `MediaQueryListEvent` constructors are not exposed either, so `instanceof` checks against them throw a `ReferenceError`.
+
+Because that stylesheet reaches the real page, a `@media (min-width: ...)` rule is evaluated by the host against the browser viewport, while `matchMedia('(min-width: ...)')` answers for your widget's box. To make CSS follow the same box your JavaScript sees, declare your own `container-type` on a wrapper and query that: an `@container` rule without one resolves against the nearest host container, not your widget. The same split applies to color scheme, where a stylesheet `@media (prefers-color-scheme: dark)` follows the browser and OS preference while `matchMedia('(prefers-color-scheme: dark)')` follows the theme selected in Twenty, so style from `useTheme()` tokens when the two must agree.
+
+The height you are handed is your own box as well, and depending on where the host mounts you that box can be sized by your own content. Branching layout on `min-height`, `max-height` or `orientation` can then feed back into itself and oscillate. Prefer width-based queries, or `@container` with `container-type: inline-size`, for layout decisions.
+
<Note>
`requestAnimationFrame` works, with or without the `window.` prefix. Only Chrome runs a real animation frame inside a worker; Firefox and Safari get a 16 ms timer, so use it to defer a re-read past a write, not to drive an animation.
</Note>
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
index 2b49566b61e..74ffd2e5311 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
@@ -7,6 +7,7 @@ import { pickerListItemsTest } from '@/__stories__/twenty-ui-gallery/utils/picke
import { iconButtonElevatedTest } from '@/__stories__/twenty-ui-gallery/utils/iconButtonElevatedTest';
import { buttonControlsTest } from '@/__stories__/twenty-ui-gallery/utils/buttonControlsTest';
import { responsiveHooksTest } from '@/__stories__/twenty-ui-gallery/utils/responsiveHooksTest';
+import { RESPONSIVE_HOOKS_WIDGET_SIZING } from '@/__stories__/twenty-ui-gallery/constants/RESPONSIVE_HOOKS_WIDGET_SIZING';
import { dialogTest } from '@/__stories__/twenty-ui-gallery/utils/dialogTest';
import { dropdownSandboxFailureTest } from '@/__stories__/twenty-ui-gallery/utils/dropdownSandboxFailureTest';
import { selectPreactTest } from '@/__stories__/twenty-ui-gallery/utils/selectPreactTest';
@@ -449,16 +450,29 @@ export const ButtonControlsPreact: Story = createGalleryStory({
play: buttonControlsTest,
});
+const RESPONSIVE_HOOKS_DECORATORS: Story['decorators'] = [
+ (Story) => (
+ <div
+ data-testid={RESPONSIVE_HOOKS_WIDGET_SIZING.containerTestId}
+ style={{ width: RESPONSIVE_HOOKS_WIDGET_SIZING.desktopWidth }}
+ >
+ <Story />
+ </div>
+ ),
+];
+
export const ResponsiveHooksReact: Story = createGalleryStory({
frontComponentBundleName: 'twenty-ui-responsive-hooks',
runtime: 'react',
play: responsiveHooksTest,
+ decorators: RESPONSIVE_HOOKS_DECORATORS,
});
export const ResponsiveHooksPreact: Story = createGalleryStory({
frontComponentBundleName: 'twenty-ui-responsive-hooks',
runtime: 'preact',
play: responsiveHooksTest,
+ decorators: RESPONSIVE_HOOKS_DECORATORS,
});
export const AvatarControlsReact: Story = createGalleryStory({
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 adb06e37614..c1e0f3064e1 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx
@@ -1,9 +1,12 @@
import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useState } from 'react';
import { expect, userEvent, waitFor, within } from 'storybook/test';
import {
errorHandler,
FRONT_COMPONENT_STORY_DEFAULT_ARGS,
+ FRONT_COMPONENT_STORY_DEFAULT_EXECUTION_CONTEXT,
+ hostApiMocks,
resetFrontComponentStoryMocks,
} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
import { expectJsonDataAttribute } from '@/__stories__/shared/test-utils/matchers/expectJsonDataAttribute';
@@ -101,22 +104,156 @@ const classListTest: Story['play'] = async ({ canvasElement }) => {
expect(errorHandler).not.toHaveBeenCalled();
};
+const createMatchMediaTest =
+ (expectedColorScheme: 'light' | 'dark'): Story['play'] =>
+ async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await canvas.findByTestId(
+ 'match-media-component',
+ {},
+ { timeout: MOUNT_TIMEOUT },
+ );
+
+ await waitFor(
+ () => {
+ expect(
+ canvas.getByTestId('match-media-color-scheme'),
+ ).toHaveTextContent(`color scheme: ${expectedColorScheme}`);
+ expect(
+ canvas.getByTestId('match-media-own-width-value'),
+ ).not.toHaveTextContent('own width: 0');
+ },
+ { timeout: MOUNT_TIMEOUT },
+ );
+
+ expect(canvas.getByTestId('match-media-own-width')).toHaveTextContent(
+ 'own width matches: true',
+ );
+ expect(
+ canvas.getByTestId('match-media-wider-than-own-width'),
+ ).toHaveTextContent('wider than own width matches: false');
+ expect(canvas.getByTestId('match-media-unknown-query')).toHaveTextContent(
+ 'unknown query matches: false',
+ );
+ expect(
+ canvas.getByTestId('match-media-empty-query-in-list'),
+ ).toHaveTextContent('empty query in list matches: false');
+ expect(canvas.getByTestId('match-media-orientation')).toHaveTextContent(
+ 'orientation matches: true',
+ );
+ expect(
+ canvas.getByTestId('match-media-color-scheme-change-count'),
+ ).toHaveTextContent('color scheme changes: 0');
+ expect(
+ canvas.getByTestId('match-media-wide-width-change-count'),
+ ).toHaveTextContent('wide width changes: 0');
+ expect(
+ canvas.getByTestId('match-media-portrait-orientation-change-count'),
+ ).toHaveTextContent('portrait orientation changes: 0');
+
+ const container = canvas.getByTestId('match-media-container');
+
+ for (const {
+ width,
+ height,
+ wideWidthChangeCount,
+ portraitOrientationChangeCount,
+ } of [
+ {
+ width: 700,
+ height: 300,
+ wideWidthChangeCount: 1,
+ portraitOrientationChangeCount: 1,
+ },
+ {
+ width: 700,
+ height: 900,
+ wideWidthChangeCount: 1,
+ portraitOrientationChangeCount: 2,
+ },
+ {
+ width: 400,
+ height: 600,
+ wideWidthChangeCount: 2,
+ portraitOrientationChangeCount: 2,
+ },
+ ]) {
+ container.style.width = `${width}px`;
+ container.style.height = `${height}px`;
+
+ await waitFor(
+ () => {
+ expect(
+ canvas.getByTestId('match-media-own-width-value'),
+ ).toHaveTextContent(`own width: ${width}`);
+ expect(
+ canvas.getByTestId('match-media-own-height-value'),
+ ).toHaveTextContent(`own height: ${height}`);
+ expect(canvas.getByTestId('match-media-own-width')).toHaveTextContent(
+ 'own width matches: true',
+ );
+ expect(
+ canvas.getByTestId('match-media-wider-than-own-width'),
+ ).toHaveTextContent('wider than own width matches: false');
+ expect(
+ canvas.getByTestId('match-media-orientation'),
+ ).toHaveTextContent('orientation matches: true');
+ expect(
+ canvas.getByTestId('match-media-wide-width-change-count'),
+ ).toHaveTextContent(`wide width changes: ${wideWidthChangeCount}`);
+ expect(
+ canvas.getByTestId('match-media-portrait-orientation-change-count'),
+ ).toHaveTextContent(
+ `portrait orientation changes: ${portraitOrientationChangeCount}`,
+ );
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
+ }
+
+ expect(
+ canvas.getByTestId('match-media-color-scheme-change-count'),
+ ).toHaveTextContent('color scheme changes: 0');
+
+ expect(errorHandler).not.toHaveBeenCalled();
+ };
+
+const MATCH_MEDIA_DECORATORS: Story['decorators'] = [
+ (Story) => (
+ <div
+ data-testid="match-media-container"
+ style={{ width: 400, height: 600 }}
+ >
+ <Story />
+ </div>
+ ),
+];
+
+type CreateStoryInput = {
+ name: string;
+ play: Story['play'];
+ decorators?: Story['decorators'];
+ runtime?: 'preact';
+ args?: Partial<Story['args']>;
+};
+
const createStory = ({
name,
play,
+ decorators,
runtime,
-}: {
- name: string;
- play: Story['play'];
- runtime?: 'preact';
-}): Story => ({
+ args,
+}: CreateStoryInput): Story => ({
args: {
componentUrl: getBuiltStoryComponentPathForRender(
`${name}.front-component`,
runtime,
),
+ ...args,
},
play,
+ decorators,
});
export const MutationObserverReact: Story = createStory({
@@ -137,3 +274,104 @@ export const ClassListPreact: Story = createStory({
play: classListTest,
runtime: 'preact',
});
+export const MatchMediaReact: Story = createStory({
+ name: 'match-media',
+ play: createMatchMediaTest('light'),
+ decorators: MATCH_MEDIA_DECORATORS,
+});
+export const MatchMediaPreact: Story = createStory({
+ name: 'match-media',
+ play: createMatchMediaTest('light'),
+ decorators: MATCH_MEDIA_DECORATORS,
+ runtime: 'preact',
+});
+export const MatchMediaDarkColorScheme: Story = createStory({
+ name: 'match-media',
+ play: createMatchMediaTest('dark'),
+ decorators: MATCH_MEDIA_DECORATORS,
+ args: {
+ colorScheme: 'dark',
+ executionContext: {
+ ...FRONT_COMPONENT_STORY_DEFAULT_EXECUTION_CONTEXT,
+ colorScheme: 'dark',
+ },
+ },
+});
+
+const MatchMediaColorSchemeToggle = () => {
+ const [colorScheme, setColorScheme] = useState<'light' | 'dark'>('light');
+
+ return (
+ <>
+ <button
+ type="button"
+ data-testid="match-media-toggle-color-scheme"
+ onClick={() =>
+ setColorScheme((currentColorScheme) =>
+ currentColorScheme === 'light' ? 'dark' : 'light',
+ )
+ }
+ >
+ Toggle color scheme
+ </button>
+ <FrontComponentRenderer
+ componentUrl={getBuiltStoryComponentPathForRender(
+ 'match-media.front-component',
+ )}
+ applicationAccessToken={
+ FRONT_COMPONENT_STORY_DEFAULT_ARGS.applicationAccessToken
+ }
+ executionContext={{
+ ...FRONT_COMPONENT_STORY_DEFAULT_EXECUTION_CONTEXT,
+ colorScheme,
+ }}
+ frontComponentHostCommunicationApi={hostApiMocks}
+ onError={errorHandler}
+ colorScheme={colorScheme}
+ />
+ </>
+ );
+};
+
+export const MatchMediaColorSchemeChange: Story = {
+ render: () => <MatchMediaColorSchemeToggle />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await canvas.findByTestId(
+ 'match-media-component',
+ {},
+ { timeout: MOUNT_TIMEOUT },
+ );
+
+ await waitFor(
+ () => {
+ expect(
+ canvas.getByTestId('match-media-color-scheme'),
+ ).toHaveTextContent('color scheme: light');
+ },
+ { timeout: MOUNT_TIMEOUT },
+ );
+ expect(
+ canvas.getByTestId('match-media-color-scheme-change-count'),
+ ).toHaveTextContent('color scheme changes: 0');
+
+ await userEvent.click(
+ canvas.getByTestId('match-media-toggle-color-scheme'),
+ );
+
+ await waitFor(
+ () => {
+ expect(
+ canvas.getByTestId('match-media-color-scheme'),
+ ).toHaveTextContent('color scheme: dark');
+ expect(
+ canvas.getByTestId('match-media-color-scheme-change-count'),
+ ).toHaveTextContent('color scheme changes: 1');
+ },
+ { timeout: MOUNT_TIMEOUT },
+ );
+
+ expect(errorHandler).not.toHaveBeenCalled();
+ },
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/createFrontComponentStoryMeta.ts b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/createFrontComponentStoryMeta.ts
index e00ce5523d5..18fe7421562 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/createFrontComponentStoryMeta.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/createFrontComponentStoryMeta.ts
@@ -1,5 +1,6 @@
import { type Meta } from '@storybook/react-vite';
import { fn } from 'storybook/test';
+import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
import { type FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';
@@ -24,19 +25,22 @@ export const hostApiMocks = {
storageClear: fn().mockResolvedValue(undefined),
};
-export const FRONT_COMPONENT_STORY_DEFAULT_ARGS: NonNullable<
- Meta<typeof FrontComponentRenderer>['args']
-> = {
- onError: errorHandler,
- applicationAccessToken: 'fake-token',
- executionContext: {
+export const FRONT_COMPONENT_STORY_DEFAULT_EXECUTION_CONTEXT: FrontComponentExecutionContext =
+ {
frontComponentId: 'unset',
userId: null,
recordId: null,
selectedRecordIds: [],
timelineActivityId: null,
colorScheme: 'light',
- },
+ };
+
+export const FRONT_COMPONENT_STORY_DEFAULT_ARGS: NonNullable<
+ Meta<typeof FrontComponentRenderer>['args']
+> = {
+ onError: errorHandler,
+ applicationAccessToken: 'fake-token',
+ executionContext: FRONT_COMPONENT_STORY_DEFAULT_EXECUTION_CONTEXT,
colorScheme: 'light',
frontComponentHostCommunicationApi: hostApiMocks,
};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/showcase/match-media.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/showcase/match-media.front-component.tsx
new file mode 100644
index 00000000000..88d2e37817c
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/showcase/match-media.front-component.tsx
@@ -0,0 +1,121 @@
+import { defineFrontComponent } from 'twenty-sdk/define';
+import { useEffect, useState } from 'react';
+
+const DARK_COLOR_SCHEME_QUERY = '(prefers-color-scheme: dark)';
+const WIDE_WIDTH_QUERY = '(min-width: 600px)';
+const PORTRAIT_ORIENTATION_QUERY = '(orientation: portrait)';
+const MEASUREMENT_INTERVAL_MS = 50;
+
+const readOwnBoxSize = () => ({
+ width: document.body.clientWidth,
+ height: document.body.clientHeight,
+});
+
+const useMediaQueryChangeCount = (mediaQuery: string) => {
+ const [changeCount, setChangeCount] = useState(0);
+
+ useEffect(() => {
+ const mediaQueryList = window.matchMedia(mediaQuery);
+ const handleChange = () => {
+ setChangeCount((count) => count + 1);
+ };
+
+ mediaQueryList.addEventListener('change', handleChange);
+
+ return () => {
+ mediaQueryList.removeEventListener('change', handleChange);
+ };
+ }, [mediaQuery]);
+
+ return changeCount;
+};
+
+const MatchMediaComponent = () => {
+ const colorSchemeChangeCount = useMediaQueryChangeCount(
+ DARK_COLOR_SCHEME_QUERY,
+ );
+ const wideWidthChangeCount = useMediaQueryChangeCount(WIDE_WIDTH_QUERY);
+ const portraitOrientationChangeCount = useMediaQueryChangeCount(
+ PORTRAIT_ORIENTATION_QUERY,
+ );
+ const [ownBoxSize, setOwnBoxSize] = useState(readOwnBoxSize);
+
+ useEffect(() => {
+ const intervalId = setInterval(() => {
+ const nextBoxSize = readOwnBoxSize();
+
+ setOwnBoxSize((currentBoxSize) =>
+ currentBoxSize.width === nextBoxSize.width &&
+ currentBoxSize.height === nextBoxSize.height
+ ? currentBoxSize
+ : nextBoxSize,
+ );
+ }, MEASUREMENT_INTERVAL_MS);
+
+ return () => clearInterval(intervalId);
+ }, []);
+
+ const { width: ownWidth, height: ownHeight } = ownBoxSize;
+
+ const ownWidthMatches = String(
+ window.matchMedia(`(min-width: ${ownWidth}px)`).matches,
+ );
+ const widerThanOwnWidthMatches = String(
+ window.matchMedia(`(min-width: ${ownWidth + 1}px)`).matches,
+ );
+ const unknownQueryMatches = String(
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches,
+ );
+ const emptyQueryInListMatches = String(
+ window.matchMedia(`(min-width: ${ownWidth + 1}px),`).matches,
+ );
+ const colorScheme = window.matchMedia(DARK_COLOR_SCHEME_QUERY).matches
+ ? 'dark'
+ : 'light';
+ const expectedOrientation = ownHeight >= ownWidth ? 'portrait' : 'landscape';
+ const orientationMatches = String(
+ window.matchMedia(`(orientation: ${expectedOrientation})`).matches,
+ );
+
+ return (
+ <div
+ data-testid="match-media-component"
+ style={{ fontFamily: 'system-ui, sans-serif', padding: 16 }}
+ >
+ <p data-testid="match-media-own-width-value">own width: {ownWidth}</p>
+ <p data-testid="match-media-own-height-value">own height: {ownHeight}</p>
+ <p data-testid="match-media-own-width">
+ own width matches: {ownWidthMatches}
+ </p>
+ <p data-testid="match-media-wider-than-own-width">
+ wider than own width matches: {widerThanOwnWidthMatches}
+ </p>
+ <p data-testid="match-media-unknown-query">
+ unknown query matches: {unknownQueryMatches}
+ </p>
+ <p data-testid="match-media-empty-query-in-list">
+ empty query in list matches: {emptyQueryInListMatches}
+ </p>
+ <p data-testid="match-media-orientation">
+ orientation matches: {orientationMatches}
+ </p>
+ <p data-testid="match-media-color-scheme">color scheme: {colorScheme}</p>
+ <p data-testid="match-media-color-scheme-change-count">
+ color scheme changes: {colorSchemeChangeCount}
+ </p>
+ <p data-testid="match-media-wide-width-change-count">
+ wide width changes: {wideWidthChangeCount}
+ </p>
+ <p data-testid="match-media-portrait-orientation-change-count">
+ portrait orientation changes: {portraitOrientationChangeCount}
+ </p>
+ </div>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: 'fc-match-media-0000-0000-0000-000000000001',
+ name: 'match-media-component',
+ description: 'Front component evaluating media queries through matchMedia',
+ component: MatchMediaComponent,
+});
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 0ceca2e9a63..0be89f4b80c 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
@@ -58,7 +58,7 @@ No stories are skipped or marked as expected-to-fail by the runner.
| Switch, Checkbox, Radio, CardPicker, SegmentedControl | Activation attempts to construct an unavailable `PointerEvent`. `CardPickerReact` never gets that far: React drops the click handler Base UI adds through `React.cloneElement`, so only the group's focus handling fails on the missing `nativeEvent` for `composedPath`. |
| Slider | Thumbs stay hidden because the sandbox has no `ResizeObserver` to re-measure after the first geometry batch. |
| 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. |
+| Responsive hooks | The sandbox `window.matchMedia` answers for the widget's own box, so `useIsMobile` follows the widget width rather than the browser viewport: a widget 768px wide or narrower gets the mobile layout, and Button drops its hotkey hint, on any screen. `useIsTouchDevice` follows the primary input of the host device, so it is `false` under the desktop Chromium that runs these stories. The fixture asserts both at a 1024px and a 400px widget width. |
The worker DOM now provides `Node.contains`, `compareDocumentPosition`,
`getRootNode`, `Element.matches`, `closest`, `querySelector` backed by
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/RESPONSIVE_HOOKS_WIDGET_SIZING.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/RESPONSIVE_HOOKS_WIDGET_SIZING.ts
new file mode 100644
index 00000000000..5da33e4cad9
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/RESPONSIVE_HOOKS_WIDGET_SIZING.ts
@@ -0,0 +1,5 @@
+export const RESPONSIVE_HOOKS_WIDGET_SIZING = {
+ containerTestId: 'responsive-hooks-widget',
+ desktopWidth: 1024,
+ mobileWidth: 400,
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-responsive-hooks.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-responsive-hooks.front-component.tsx
index 608161ca7c2..2241c678868 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-responsive-hooks.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-responsive-hooks.front-component.tsx
@@ -28,6 +28,6 @@ const ResponsiveHooks = () => {
export default defineFrontComponent({
universalIdentifier: 'f1cdb7cb-79db-421c-bfb6-9f7c20f03ad1',
name: 'twenty-ui-responsive-hooks',
- description: 'Responsive hooks without a sandbox media-query bridge',
+ description: 'Responsive hooks evaluated against the widget box',
component: ResponsiveHooks,
});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/createGalleryStory.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/createGalleryStory.ts
index b80a418d753..ed76acad2aa 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/createGalleryStory.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/createGalleryStory.ts
@@ -6,12 +6,14 @@ type CreateGalleryStoryOptions = {
frontComponentBundleName: string;
runtime: 'react' | 'preact';
play: TwentyUiGalleryPlayFunction;
+ decorators?: TwentyUiGalleryStory['decorators'];
};
export const createGalleryStory = ({
frontComponentBundleName,
runtime,
play,
+ decorators,
}: CreateGalleryStoryOptions): TwentyUiGalleryStory => ({
args: {
componentUrl: getBuiltStoryComponentPathForRender(
@@ -20,4 +22,5 @@ export const createGalleryStory = ({
),
},
play,
+ decorators,
});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/responsiveHooksTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/responsiveHooksTest.ts
index 693cfd5636d..52a813a20e3 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/responsiveHooksTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/responsiveHooksTest.ts
@@ -1,5 +1,6 @@
import { expect, userEvent, waitFor, within } from 'storybook/test';
+import { RESPONSIVE_HOOKS_WIDGET_SIZING } from '@/__stories__/twenty-ui-gallery/constants/RESPONSIVE_HOOKS_WIDGET_SIZING';
import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
export const responsiveHooksTest: TwentyUiGalleryPlayFunction = async ({
@@ -16,5 +17,19 @@ export const responsiveHooksTest: TwentyUiGalleryPlayFunction = async ({
await userEvent.click(save);
await userEvent.click(canvas.getByRole('button', { name: 'Pointer action' }));
await waitFor(() => expect(canvas.getByText('Activations: 2')).toBeVisible());
+
+ canvas.getByTestId(
+ RESPONSIVE_HOOKS_WIDGET_SIZING.containerTestId,
+ ).style.width = `${RESPONSIVE_HOOKS_WIDGET_SIZING.mobileWidth}px`;
+
+ await expect(
+ await canvas.findByText('Mobile layout: true', {}, { timeout: 10000 }),
+ ).toBeVisible();
+ await expect(canvas.getByText('Touch input: false')).toBeVisible();
+ await expect(
+ within(canvas.getByRole('button', { name: 'Save record' })).queryByText(
+ 'S',
+ ),
+ ).not.toBeInTheDocument();
await expect(args.onError).not.toHaveBeenCalled();
};
diff --git a/packages/twenty-front-component-renderer/src/constants/DefaultInputMediaFeatures.ts b/packages/twenty-front-component-renderer/src/constants/DefaultInputMediaFeatures.ts
new file mode 100644
index 00000000000..f850bf73946
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/constants/DefaultInputMediaFeatures.ts
@@ -0,0 +1,6 @@
+import { type InputMediaFeatures } from '@/types/InputMediaFeatures';
+
+export const DEFAULT_INPUT_MEDIA_FEATURES: InputMediaFeatures = {
+ hover: 'none',
+ pointer: 'none',
+};
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 c61163b8bf2..781838695a7 100644
--- a/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx
+++ b/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx
@@ -69,6 +69,7 @@ export const FrontComponentRenderer = ({
const [isExecutionContextInitialized, setIsExecutionContextInitialized] =
useState(false);
const [geometryTracker] = useState(() => createGeometryTracker());
+ const [initialExecutionContext] = useState(executionContext);
const isReady = isDefined(receiver) && isExecutionContextInitialized;
@@ -84,6 +85,7 @@ export const FrontComponentRenderer = ({
sharedDependenciesUrl={sharedDependenciesUrl}
applicationVariables={applicationVariables}
storageNamespace={storageNamespace}
+ initialExecutionContext={initialExecutionContext}
geometryTracker={geometryTracker}
mediaSessionHost={mediaSessionHost}
setReceiver={setReceiver}
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 5bc0c33d0dd..5a064bd48c7 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
@@ -14,6 +14,8 @@ import { buildFrontComponentStorageSnapshots } from '@/host/storage/utils/buildF
import { FRONT_COMPONENT_SANDBOX_DOCUMENT } from '@/remote/sandbox/generated/frontComponentSandboxDocument';
import { createFrontComponentSandboxIframe } from '@/remote/sandbox/utils/createFrontComponentSandboxIframe';
import { createFrontComponentSandboxMessageHandler } from '@/remote/sandbox/utils/createFrontComponentSandboxMessageHandler';
+import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
+
import { type FrontComponentThread } from '@/types/FrontComponentThread';
import { type SdkClientUrls } from '@/types/SdkClientUrls';
import { buildAuthorizationHeadersFromAccessToken } from '@/host/component-source/utils/buildAuthorizationHeadersFromAccessToken';
@@ -29,6 +31,7 @@ type FrontComponentWorkerEffectProps = {
sharedDependenciesUrl?: string;
applicationVariables?: Record<string, string>;
storageNamespace?: string;
+ initialExecutionContext: FrontComponentExecutionContext;
geometryTracker: GeometryTracker;
mediaSessionHost?: FrontComponentMediaSessionHost;
setReceiver: React.Dispatch<React.SetStateAction<RemoteReceiver | null>>;
@@ -45,6 +48,7 @@ export const FrontComponentWorkerEffect = ({
sharedDependenciesUrl,
applicationVariables,
storageNamespace,
+ initialExecutionContext,
geometryTracker,
mediaSessionHost,
setReceiver,
@@ -147,6 +151,7 @@ export const FrontComponentWorkerEffect = ({
hostFetchOrigins: hostFetchPolicy.allowedOrigins,
applicationVariables,
initialViewportGeometry: geometryTracker.getViewportGeometry(),
+ initialExecutionContext,
storageSnapshots,
mediaRecorderCapabilities:
mediaSessionHost?.getRecorderCapabilities(),
@@ -180,6 +185,7 @@ export const FrontComponentWorkerEffect = ({
sharedDependenciesUrl,
applicationVariables,
storageNamespace,
+ initialExecutionContext,
geometryTracker,
mediaSessionHost,
setError,
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/constants/InputMediaFeatureQueries.ts b/packages/twenty-front-component-renderer/src/host/geometry/constants/InputMediaFeatureQueries.ts
new file mode 100644
index 00000000000..e67005d797f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/geometry/constants/InputMediaFeatureQueries.ts
@@ -0,0 +1,5 @@
+export const INPUT_MEDIA_FEATURE_QUERIES = {
+ hover: '(hover: hover)',
+ finePointer: '(pointer: fine)',
+ coarsePointer: '(pointer: coarse)',
+};
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/types/MediaEnvironmentChangeObserver.ts b/packages/twenty-front-component-renderer/src/host/geometry/types/MediaEnvironmentChangeObserver.ts
new file mode 100644
index 00000000000..4b6a21deef0
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/geometry/types/MediaEnvironmentChangeObserver.ts
@@ -0,0 +1,4 @@
+export type MediaEnvironmentChangeObserver = {
+ observe: () => void;
+ disconnect: () => void;
+};
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createDevicePixelRatioChangeObserver.test.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createDevicePixelRatioChangeObserver.test.ts
new file mode 100644
index 00000000000..bc25b550082
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createDevicePixelRatioChangeObserver.test.ts
@@ -0,0 +1,73 @@
+import { stubWindowMatchMedia } from '@/testing/stubWindowMatchMedia';
+import { createDevicePixelRatioChangeObserver } from '../createDevicePixelRatioChangeObserver';
+
+const setDevicePixelRatio = (devicePixelRatio: number) => {
+ Object.defineProperty(window, 'devicePixelRatio', {
+ value: devicePixelRatio,
+ configurable: true,
+ });
+};
+
+const flipResolution = (mediaQueryList: EventTarget) => {
+ mediaQueryList.dispatchEvent(new Event('change'));
+};
+
+describe('createDevicePixelRatioChangeObserver', () => {
+ afterEach(() => {
+ delete (window as { matchMedia?: unknown }).matchMedia;
+ delete (window as { devicePixelRatio?: unknown }).devicePixelRatio;
+ });
+
+ it('should watch a resolution query for the current device pixel ratio', () => {
+ const { matchMedia } = stubWindowMatchMedia();
+ setDevicePixelRatio(2);
+
+ createDevicePixelRatioChangeObserver(jest.fn()).observe();
+
+ expect(matchMedia).toHaveBeenCalledWith('(resolution: 2dppx)');
+ });
+
+ it('should notify once per change and re-arm for the new ratio', () => {
+ const { matchMedia, createdMediaQueryLists } = stubWindowMatchMedia();
+ const onDevicePixelRatioChange = jest.fn();
+ setDevicePixelRatio(2);
+
+ createDevicePixelRatioChangeObserver(onDevicePixelRatioChange).observe();
+
+ const [firstResolutionQueryList] = createdMediaQueryLists;
+
+ setDevicePixelRatio(1);
+ flipResolution(firstResolutionQueryList);
+
+ expect(onDevicePixelRatioChange).toHaveBeenCalledTimes(1);
+ expect(matchMedia).toHaveBeenLastCalledWith('(resolution: 1dppx)');
+
+ flipResolution(firstResolutionQueryList);
+
+ expect(onDevicePixelRatioChange).toHaveBeenCalledTimes(1);
+
+ flipResolution(createdMediaQueryLists[1]);
+
+ expect(onDevicePixelRatioChange).toHaveBeenCalledTimes(2);
+ });
+
+ it('should stop notifying once disconnected', () => {
+ const { createdMediaQueryLists } = stubWindowMatchMedia();
+ const onDevicePixelRatioChange = jest.fn();
+ const devicePixelRatioChangeObserver = createDevicePixelRatioChangeObserver(
+ onDevicePixelRatioChange,
+ );
+
+ devicePixelRatioChangeObserver.observe();
+ devicePixelRatioChangeObserver.disconnect();
+ flipResolution(createdMediaQueryLists[0]);
+
+ expect(onDevicePixelRatioChange).not.toHaveBeenCalled();
+ });
+
+ it('should do nothing where matchMedia is unavailable', () => {
+ expect(() =>
+ createDevicePixelRatioChangeObserver(jest.fn()).observe(),
+ ).not.toThrow();
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createInputMediaFeatureChangeObserver.test.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createInputMediaFeatureChangeObserver.test.ts
new file mode 100644
index 00000000000..e6b4fec8ab1
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createInputMediaFeatureChangeObserver.test.ts
@@ -0,0 +1,50 @@
+import { stubWindowMatchMedia } from '@/testing/stubWindowMatchMedia';
+import { createInputMediaFeatureChangeObserver } from '../createInputMediaFeatureChangeObserver';
+
+const dispatchChangeOnEveryMediaQueryList = (
+ mediaQueryLists: EventTarget[],
+) => {
+ for (const mediaQueryList of mediaQueryLists) {
+ mediaQueryList.dispatchEvent(new Event('change'));
+ }
+};
+
+describe('createInputMediaFeatureChangeObserver', () => {
+ afterEach(() => {
+ delete (window as { matchMedia?: unknown }).matchMedia;
+ });
+
+ it('should notify when a hover or pointer query changes', () => {
+ const { matchMedia, createdMediaQueryLists } = stubWindowMatchMedia();
+ const onInputMediaFeatureChange = jest.fn();
+
+ createInputMediaFeatureChangeObserver(onInputMediaFeatureChange).observe();
+ dispatchChangeOnEveryMediaQueryList(createdMediaQueryLists);
+
+ expect(matchMedia.mock.calls.map(([media]) => media)).toEqual([
+ '(hover: hover)',
+ '(pointer: fine)',
+ '(pointer: coarse)',
+ ]);
+ expect(onInputMediaFeatureChange).toHaveBeenCalledTimes(3);
+ });
+
+ it('should stop notifying once disconnected', () => {
+ const { createdMediaQueryLists } = stubWindowMatchMedia();
+ const onInputMediaFeatureChange = jest.fn();
+ const inputMediaFeatureChangeObserver =
+ createInputMediaFeatureChangeObserver(onInputMediaFeatureChange);
+
+ inputMediaFeatureChangeObserver.observe();
+ inputMediaFeatureChangeObserver.disconnect();
+ dispatchChangeOnEveryMediaQueryList(createdMediaQueryLists);
+
+ expect(onInputMediaFeatureChange).not.toHaveBeenCalled();
+ });
+
+ it('should do nothing where matchMedia is unavailable', () => {
+ expect(() =>
+ createInputMediaFeatureChangeObserver(jest.fn()).observe(),
+ ).not.toThrow();
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/measureViewportGeometry.test.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/measureViewportGeometry.test.ts
index 92da860e137..07b4f515c15 100644
--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/measureViewportGeometry.test.ts
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/measureViewportGeometry.test.ts
@@ -1,6 +1,20 @@
+import { stubWindowMatchMedia } from '@/testing/stubWindowMatchMedia';
import { measureViewportGeometry } from '../measureViewportGeometry';
describe('measureViewportGeometry', () => {
+ afterEach(() => {
+ delete (window as { matchMedia?: unknown }).matchMedia;
+ });
+
+ it('should read the primary input media features', () => {
+ stubWindowMatchMedia(['(pointer: coarse)']);
+
+ const viewport = measureViewportGeometry(null);
+
+ expect(viewport.hover).toBe('none');
+ expect(viewport.pointer).toBe('coarse');
+ });
+
it('should read the window fields', () => {
const viewport = measureViewportGeometry(null);
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/readInputMediaFeatures.test.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/readInputMediaFeatures.test.ts
new file mode 100644
index 00000000000..6373049ab89
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/readInputMediaFeatures.test.ts
@@ -0,0 +1,33 @@
+import { stubWindowMatchMedia } from '@/testing/stubWindowMatchMedia';
+import { readInputMediaFeatures } from '../readInputMediaFeatures';
+
+describe('readInputMediaFeatures', () => {
+ afterEach(() => {
+ delete (window as { matchMedia?: unknown }).matchMedia;
+ });
+
+ it('should report no hover and no pointer where matchMedia is unavailable', () => {
+ expect(readInputMediaFeatures()).toEqual({
+ hover: 'none',
+ pointer: 'none',
+ });
+ });
+
+ it('should report a mouse as a fine pointer that hovers', () => {
+ stubWindowMatchMedia(['(hover: hover)', '(pointer: fine)']);
+
+ expect(readInputMediaFeatures()).toEqual({
+ hover: 'hover',
+ pointer: 'fine',
+ });
+ });
+
+ it('should report a touch screen as a coarse pointer that cannot hover', () => {
+ stubWindowMatchMedia(['(pointer: coarse)']);
+
+ expect(readInputMediaFeatures()).toEqual({
+ hover: 'none',
+ pointer: 'coarse',
+ });
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/createDevicePixelRatioChangeObserver.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/createDevicePixelRatioChangeObserver.ts
new file mode 100644
index 00000000000..a5b40decae3
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/createDevicePixelRatioChangeObserver.ts
@@ -0,0 +1,39 @@
+import { isFunction } from '@sniptt/guards';
+
+import { type MediaEnvironmentChangeObserver } from '@/host/geometry/types/MediaEnvironmentChangeObserver';
+
+export const createDevicePixelRatioChangeObserver = (
+ onDevicePixelRatioChange: () => void,
+): MediaEnvironmentChangeObserver => {
+ let resolutionListenerAbortController: AbortController | null = null;
+
+ const disconnect = (): void => {
+ resolutionListenerAbortController?.abort();
+ resolutionListenerAbortController = null;
+ };
+
+ const observe = (): void => {
+ disconnect();
+
+ if (!isFunction(window.matchMedia)) {
+ return;
+ }
+
+ const abortController = new AbortController();
+
+ resolutionListenerAbortController = abortController;
+
+ window
+ .matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`)
+ .addEventListener(
+ 'change',
+ () => {
+ observe();
+ onDevicePixelRatioChange();
+ },
+ { signal: abortController.signal },
+ );
+ };
+
+ return { observe, disconnect };
+};
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryWakeSources.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryWakeSources.ts
index 337431c805a..bae71db31a8 100644
--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryWakeSources.ts
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryWakeSources.ts
@@ -1,6 +1,8 @@
import { isDefined } from 'twenty-shared/utils';
import { type GeometryWakeSources } from '@/host/geometry/types/GeometryWakeSources';
+import { createDevicePixelRatioChangeObserver } from '@/host/geometry/utils/createDevicePixelRatioChangeObserver';
+import { createInputMediaFeatureChangeObserver } from '@/host/geometry/utils/createInputMediaFeatureChangeObserver';
const ANIMATION_EVENT_TYPES = [
'transitionrun',
@@ -22,6 +24,10 @@ export const createGeometryWakeSources = (
onWake: () => void,
): GeometryWakeSources => {
const resizeObservedNodes = new Set<Element>();
+ const devicePixelRatioChangeObserver =
+ createDevicePixelRatioChangeObserver(onWake);
+ const inputMediaFeatureChangeObserver =
+ createInputMediaFeatureChangeObserver(onWake);
let rootContainer: Element | null = null;
let resizeObserver: ResizeObserver | null = null;
@@ -128,6 +134,8 @@ export const createGeometryWakeSources = (
window.addEventListener('resize', onWake);
observeDocumentStyleMutations();
+ devicePixelRatioChangeObserver.observe();
+ inputMediaFeatureChangeObserver.observe();
if (isDefined(rootContainer)) {
resolveResizeObserver()?.observe(rootContainer);
@@ -182,6 +190,8 @@ export const createGeometryWakeSources = (
window.removeEventListener('resize', onWake);
documentStyleObserver?.disconnect();
documentStyleObserver = null;
+ devicePixelRatioChangeObserver.disconnect();
+ inputMediaFeatureChangeObserver.disconnect();
}
resizeObserver?.disconnect();
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/createInputMediaFeatureChangeObserver.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/createInputMediaFeatureChangeObserver.ts
new file mode 100644
index 00000000000..c01650a71f3
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/createInputMediaFeatureChangeObserver.ts
@@ -0,0 +1,39 @@
+import { isFunction } from '@sniptt/guards';
+
+import { INPUT_MEDIA_FEATURE_QUERIES } from '@/host/geometry/constants/InputMediaFeatureQueries';
+import { type MediaEnvironmentChangeObserver } from '@/host/geometry/types/MediaEnvironmentChangeObserver';
+
+export const createInputMediaFeatureChangeObserver = (
+ onInputMediaFeatureChange: () => void,
+): MediaEnvironmentChangeObserver => {
+ let changeListenerAbortController: AbortController | null = null;
+
+ const disconnect = (): void => {
+ changeListenerAbortController?.abort();
+ changeListenerAbortController = null;
+ };
+
+ const observe = (): void => {
+ disconnect();
+
+ if (!isFunction(window.matchMedia)) {
+ return;
+ }
+
+ const abortController = new AbortController();
+
+ changeListenerAbortController = abortController;
+
+ for (const inputMediaFeatureQuery of Object.values(
+ INPUT_MEDIA_FEATURE_QUERIES,
+ )) {
+ window
+ .matchMedia(inputMediaFeatureQuery)
+ .addEventListener('change', onInputMediaFeatureChange, {
+ signal: abortController.signal,
+ });
+ }
+ };
+
+ return { observe, disconnect };
+};
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/measureViewportGeometry.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/measureViewportGeometry.ts
index 742e724782d..9ce0261850c 100644
--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/measureViewportGeometry.ts
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/measureViewportGeometry.ts
@@ -1,5 +1,6 @@
import { isDefined } from 'twenty-shared/utils';
+import { readInputMediaFeatures } from '@/host/geometry/utils/readInputMediaFeatures';
import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot';
export const measureViewportGeometry = (
@@ -21,5 +22,6 @@ export const measureViewportGeometry = (
rootContainerHeight: rootContainerRect?.height ?? 0,
rootContainerClientWidth: rootContainer?.clientWidth ?? 0,
rootContainerClientHeight: rootContainer?.clientHeight ?? 0,
+ ...readInputMediaFeatures(),
};
};
diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/readInputMediaFeatures.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/readInputMediaFeatures.ts
new file mode 100644
index 00000000000..4cb386c5e39
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/readInputMediaFeatures.ts
@@ -0,0 +1,29 @@
+import { isFunction } from '@sniptt/guards';
+
+import { DEFAULT_INPUT_MEDIA_FEATURES } from '@/constants/DefaultInputMediaFeatures';
+import { INPUT_MEDIA_FEATURE_QUERIES } from '@/host/geometry/constants/InputMediaFeatureQueries';
+import { type InputMediaFeatures } from '@/types/InputMediaFeatures';
+import { type PointerMediaFeatureValue } from '@/types/PointerMediaFeatureValue';
+
+const readPointerMediaFeature = (): PointerMediaFeatureValue => {
+ if (window.matchMedia(INPUT_MEDIA_FEATURE_QUERIES.finePointer).matches) {
+ return 'fine';
+ }
+
+ return window.matchMedia(INPUT_MEDIA_FEATURE_QUERIES.coarsePointer).matches
+ ? 'coarse'
+ : 'none';
+};
+
+export const readInputMediaFeatures = (): InputMediaFeatures => {
+ if (!isFunction(window.matchMedia)) {
+ return DEFAULT_INPUT_MEDIA_FEATURES;
+ }
+
+ return {
+ hover: window.matchMedia(INPUT_MEDIA_FEATURE_QUERIES.hover).matches
+ ? 'hover'
+ : 'none',
+ pointer: readPointerMediaFeature(),
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/types/WorkerGeometryStore.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/types/WorkerGeometryStore.ts
index 4176c9ab777..3ba148d8621 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/geometry/types/WorkerGeometryStore.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/types/WorkerGeometryStore.ts
@@ -8,5 +8,6 @@ export type WorkerGeometryStore = {
connectTransport: (transport: GeometryObservationTransport) => void;
applyGeometryBatch: (batch: GeometryUpdateBatch) => void;
getViewportSnapshot: () => ViewportGeometrySnapshot | null;
+ subscribeToGeometryUpdates: (listener: () => void) => () => void;
resolveElementSnapshot: (element: object) => ElementGeometrySnapshot | null;
};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/createWorkerGeometryStore.test.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/createWorkerGeometryStore.test.ts
index d7e33edb31f..c7f397951f3 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/createWorkerGeometryStore.test.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/createWorkerGeometryStore.test.ts
@@ -166,6 +166,35 @@ describe('createWorkerGeometryStore', () => {
expect(store.getViewportSnapshot()?.innerWidth).toBe(1200);
});
+ it('should notify geometry subscribers after each applied batch', () => {
+ const { store } = createRootedStore();
+ const geometryUpdateListener = jest.fn(() => store.getViewportSnapshot());
+
+ store.subscribeToGeometryUpdates(geometryUpdateListener);
+
+ store.applyGeometryBatch({ elements: { '0': createSnapshot(5) } });
+ expect(geometryUpdateListener).toHaveBeenCalledTimes(1);
+
+ store.applyGeometryBatch({ viewport: createViewport(800) });
+ expect(geometryUpdateListener).toHaveBeenCalledTimes(2);
+ expect(geometryUpdateListener).toHaveLastReturnedWith(createViewport(800));
+ });
+
+ it('should stop notifying an unsubscribed geometry listener', () => {
+ const { store } = createRootedStore();
+ const geometryUpdateListener = jest.fn();
+
+ const unsubscribe = store.subscribeToGeometryUpdates(
+ geometryUpdateListener,
+ );
+
+ store.applyGeometryBatch({ viewport: createViewport(800) });
+ unsubscribe();
+ store.applyGeometryBatch({ viewport: createViewport(1200) });
+
+ expect(geometryUpdateListener).toHaveBeenCalledTimes(1);
+ });
+
it('should stop enrolling once the observation limit is reached', async () => {
const { store, rootElement } = createRootedStore();
const observeElementGeometry = jest.fn().mockResolvedValue(undefined);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createWorkerGeometryStore.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createWorkerGeometryStore.ts
index 0b41d3c68eb..8cdfde6245a 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createWorkerGeometryStore.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createWorkerGeometryStore.ts
@@ -16,6 +16,7 @@ export const createWorkerGeometryStore = (): WorkerGeometryStore => {
const enrolledRemoteElementIds = new WeakMap<object, string>();
const observedRemoteElementIds = new Set<string>();
const pendingObservationIds = new Set<string>();
+ const geometryUpdateListeners = new Set<() => void>();
let rootElement: object | null = null;
let transport: GeometryObservationTransport | null = null;
@@ -134,6 +135,10 @@ export const createWorkerGeometryStore = (): WorkerGeometryStore => {
.catch(warnAboutTransportFailure);
}
}
+
+ for (const geometryUpdateListener of [...geometryUpdateListeners]) {
+ geometryUpdateListener();
+ }
};
return {
@@ -146,6 +151,13 @@ export const createWorkerGeometryStore = (): WorkerGeometryStore => {
},
applyGeometryBatch,
getViewportSnapshot: () => viewportSnapshot,
+ subscribeToGeometryUpdates: (listener: () => void) => {
+ geometryUpdateListeners.add(listener);
+
+ return () => {
+ geometryUpdateListeners.delete(listener);
+ };
+ },
resolveElementSnapshot,
};
};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/CssClosingDelimitersByOpeningDelimiter.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/CssClosingDelimitersByOpeningDelimiter.ts
new file mode 100644
index 00000000000..a6432db1a10
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/CssClosingDelimitersByOpeningDelimiter.ts
@@ -0,0 +1,5 @@
+export const CSS_CLOSING_DELIMITERS_BY_OPENING_DELIMITER = new Map([
+ ['(', ')'],
+ ['[', ']'],
+ ['{', '}'],
+]);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/CssEscapeCharacter.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/CssEscapeCharacter.ts
new file mode 100644
index 00000000000..87955444a84
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/CssEscapeCharacter.ts
@@ -0,0 +1 @@
+export const CSS_ESCAPE_CHARACTER = '\\';
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MatchingMediaTypes.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MatchingMediaTypes.ts
new file mode 100644
index 00000000000..422370b5a18
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MatchingMediaTypes.ts
@@ -0,0 +1 @@
+export const MATCHING_MEDIA_TYPES = new Set(['all', 'screen']);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryKeywordFeatures.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryKeywordFeatures.ts
new file mode 100644
index 00000000000..8245fb8f005
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryKeywordFeatures.ts
@@ -0,0 +1,38 @@
+import { type MediaQueryKeywordFeature } from '@/polyfills/media-query/types/MediaQueryKeywordFeature';
+
+export const MEDIA_QUERY_KEYWORD_FEATURES = new Map<
+ string,
+ MediaQueryKeywordFeature
+>([
+ [
+ 'prefers-color-scheme',
+ {
+ values: new Set(['light', 'dark']),
+ readValue: (environment) => environment.colorScheme,
+ },
+ ],
+ [
+ 'orientation',
+ {
+ values: new Set(['portrait', 'landscape']),
+ readValue: (environment) =>
+ environment.componentHeight >= environment.componentWidth
+ ? 'portrait'
+ : 'landscape',
+ },
+ ],
+ [
+ 'hover',
+ {
+ values: new Set(['none', 'hover']),
+ readValue: (environment) => environment.hover,
+ },
+ ],
+ [
+ 'pointer',
+ {
+ values: new Set(['none', 'coarse', 'fine']),
+ readValue: (environment) => environment.pointer,
+ },
+ ],
+]);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryLengthUnitToPixels.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryLengthUnitToPixels.ts
new file mode 100644
index 00000000000..ae0e51b021b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryLengthUnitToPixels.ts
@@ -0,0 +1,11 @@
+export const MEDIA_QUERY_LENGTH_UNIT_TO_PIXELS = new Map<string, number>([
+ ['px', 1],
+ ['em', 16],
+ ['rem', 16],
+ ['in', 96],
+ ['cm', 96 / 2.54],
+ ['mm', 96 / 25.4],
+ ['q', 96 / 101.6],
+ ['pt', 96 / 72],
+ ['pc', 16],
+]);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryNumericFeatures.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryNumericFeatures.ts
new file mode 100644
index 00000000000..c22b9604809
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryNumericFeatures.ts
@@ -0,0 +1,32 @@
+import { type MediaQueryNumericFeature } from '@/polyfills/media-query/types/MediaQueryNumericFeature';
+import { parseMediaQueryDevicePixelRatioValue } from '@/polyfills/media-query/utils/parseMediaQueryDevicePixelRatioValue';
+import { parseMediaQueryLengthToPixels } from '@/polyfills/media-query/utils/parseMediaQueryLengthToPixels';
+import { parseMediaQueryResolutionToDevicePixelRatio } from '@/polyfills/media-query/utils/parseMediaQueryResolutionToDevicePixelRatio';
+
+export const MEDIA_QUERY_NUMERIC_FEATURES = new Map<
+ string,
+ MediaQueryNumericFeature
+>([
+ [
+ 'width',
+ { source: 'componentWidth', parseValue: parseMediaQueryLengthToPixels },
+ ],
+ [
+ 'height',
+ { source: 'componentHeight', parseValue: parseMediaQueryLengthToPixels },
+ ],
+ [
+ 'device-pixel-ratio',
+ {
+ source: 'devicePixelRatio',
+ parseValue: parseMediaQueryDevicePixelRatioValue,
+ },
+ ],
+ [
+ 'resolution',
+ {
+ source: 'devicePixelRatio',
+ parseValue: parseMediaQueryResolutionToDevicePixelRatio,
+ },
+ ],
+]);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryReservedKeywords.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryReservedKeywords.ts
new file mode 100644
index 00000000000..b7435dbefe5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryReservedKeywords.ts
@@ -0,0 +1,7 @@
+export const MEDIA_QUERY_RESERVED_KEYWORDS = new Set([
+ 'not',
+ 'only',
+ 'and',
+ 'or',
+ 'layer',
+]);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryResolutionUnitToDevicePixelRatio.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryResolutionUnitToDevicePixelRatio.ts
new file mode 100644
index 00000000000..3dbb72525c3
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/constants/MediaQueryResolutionUnitToDevicePixelRatio.ts
@@ -0,0 +1,9 @@
+export const MEDIA_QUERY_RESOLUTION_UNIT_TO_DEVICE_PIXEL_RATIO = new Map<
+ string,
+ number
+>([
+ ['dppx', 1],
+ ['x', 1],
+ ['dpi', 1 / 96],
+ ['dpcm', 2.54 / 96],
+]);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/states/mediaQueryEnvironmentSource.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/states/mediaQueryEnvironmentSource.ts
new file mode 100644
index 00000000000..c8efdcdbb46
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/states/mediaQueryEnvironmentSource.ts
@@ -0,0 +1,11 @@
+import { workerGeometryStore } from '@/polyfills/geometry/states/workerGeometryStore';
+import { createMediaQueryEnvironmentSource } from '@/polyfills/media-query/utils/createMediaQueryEnvironmentSource';
+import { getFrontComponentColorScheme } from '@/remote/worker/environment/utils/getFrontComponentColorScheme';
+import { subscribeToFrontComponentExecutionContextUpdates } from '@/remote/worker/environment/utils/subscribeToFrontComponentExecutionContextUpdates';
+
+export const mediaQueryEnvironmentSource = createMediaQueryEnvironmentSource({
+ geometryStore: workerGeometryStore,
+ getColorScheme: getFrontComponentColorScheme,
+ subscribeToColorSchemeUpdates:
+ subscribeToFrontComponentExecutionContextUpdates,
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/CssTextSegment.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/CssTextSegment.ts
new file mode 100644
index 00000000000..ba7aeacfecd
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/CssTextSegment.ts
@@ -0,0 +1,5 @@
+export type CssTextSegment = {
+ text: string;
+ endIndex: number;
+ isPlainCharacter: boolean;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryComparisonOperator.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryComparisonOperator.ts
new file mode 100644
index 00000000000..16ed5e62fd6
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryComparisonOperator.ts
@@ -0,0 +1 @@
+export type MediaQueryComparisonOperator = '<' | '<=' | '>' | '>=' | '=';
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryEnvironment.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryEnvironment.ts
new file mode 100644
index 00000000000..83064732827
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryEnvironment.ts
@@ -0,0 +1,8 @@
+import { type InputMediaFeatures } from '@/types/InputMediaFeatures';
+
+export type MediaQueryEnvironment = InputMediaFeatures & {
+ componentWidth: number;
+ componentHeight: number;
+ devicePixelRatio: number;
+ colorScheme: 'light' | 'dark';
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryEnvironmentSource.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryEnvironmentSource.ts
new file mode 100644
index 00000000000..486cfb73c45
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryEnvironmentSource.ts
@@ -0,0 +1,6 @@
+import { type MediaQueryEnvironment } from '@/polyfills/media-query/types/MediaQueryEnvironment';
+
+export type MediaQueryEnvironmentSource = {
+ readEnvironment: () => MediaQueryEnvironment;
+ subscribeToEnvironmentUpdates: (listener: () => void) => () => void;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryKeywordFeature.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryKeywordFeature.ts
new file mode 100644
index 00000000000..e6009b44107
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryKeywordFeature.ts
@@ -0,0 +1,6 @@
+import { type MediaQueryEnvironment } from '@/polyfills/media-query/types/MediaQueryEnvironment';
+
+export type MediaQueryKeywordFeature = {
+ values: Set<string>;
+ readValue: (environment: MediaQueryEnvironment) => string;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryNumericFeature.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryNumericFeature.ts
new file mode 100644
index 00000000000..847c4518f4e
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryNumericFeature.ts
@@ -0,0 +1,6 @@
+import { type MediaQueryNumericSource } from '@/polyfills/media-query/types/MediaQueryNumericSource';
+
+export type MediaQueryNumericFeature = {
+ source: MediaQueryNumericSource;
+ parseValue: (featureValue: string) => number | null;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryNumericSource.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryNumericSource.ts
new file mode 100644
index 00000000000..87abbfd6c00
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryNumericSource.ts
@@ -0,0 +1,4 @@
+export type MediaQueryNumericSource =
+ | 'componentWidth'
+ | 'componentHeight'
+ | 'devicePixelRatio';
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryRangeParts.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryRangeParts.ts
new file mode 100644
index 00000000000..b0e856a7ca6
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/MediaQueryRangeParts.ts
@@ -0,0 +1,4 @@
+export type MediaQueryRangeParts = {
+ operands: string[];
+ operators: string[];
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQuery.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQuery.ts
new file mode 100644
index 00000000000..f0440ca93fc
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQuery.ts
@@ -0,0 +1,7 @@
+import { type ParsedMediaQueryCondition } from '@/polyfills/media-query/types/ParsedMediaQueryCondition';
+
+export type ParsedMediaQuery = {
+ isNegated: boolean;
+ matchesMediaType: boolean;
+ conditions: ParsedMediaQueryCondition[];
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryCondition.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryCondition.ts
new file mode 100644
index 00000000000..e81de037003
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryCondition.ts
@@ -0,0 +1,23 @@
+import { type MediaQueryComparisonOperator } from '@/polyfills/media-query/types/MediaQueryComparisonOperator';
+import { type MediaQueryNumericSource } from '@/polyfills/media-query/types/MediaQueryNumericSource';
+
+export type ParsedMediaQueryCondition =
+ | {
+ kind: 'numeric';
+ source: MediaQueryNumericSource;
+ operator: MediaQueryComparisonOperator;
+ value: number;
+ }
+ | {
+ kind: 'non-zero';
+ source: MediaQueryNumericSource;
+ }
+ | {
+ kind: 'keyword';
+ featureName: string;
+ value: string;
+ }
+ | {
+ kind: 'not-none';
+ featureName: string;
+ };
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryConditionParts.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryConditionParts.ts
new file mode 100644
index 00000000000..e06c3b5e618
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryConditionParts.ts
@@ -0,0 +1,6 @@
+import { type ParsedMediaQueryCondition } from '@/polyfills/media-query/types/ParsedMediaQueryCondition';
+
+export type ParsedMediaQueryConditionParts = {
+ knownConditions: ParsedMediaQueryCondition[];
+ hasUnknownCondition: boolean;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryModifier.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryModifier.ts
new file mode 100644
index 00000000000..023de8ff279
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryModifier.ts
@@ -0,0 +1,4 @@
+export type ParsedMediaQueryModifier = {
+ modifier: 'not' | 'only' | null;
+ remainingFirstPart: string;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryNumericFeatureName.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryNumericFeatureName.ts
new file mode 100644
index 00000000000..ad9e33a952d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/ParsedMediaQueryNumericFeatureName.ts
@@ -0,0 +1,7 @@
+import { type MediaQueryComparisonOperator } from '@/polyfills/media-query/types/MediaQueryComparisonOperator';
+import { type MediaQueryNumericFeature } from '@/polyfills/media-query/types/MediaQueryNumericFeature';
+
+export type ParsedMediaQueryNumericFeatureName = {
+ operator: MediaQueryComparisonOperator;
+ feature: MediaQueryNumericFeature;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/WorkerMediaQueryList.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/WorkerMediaQueryList.ts
new file mode 100644
index 00000000000..dfa3b01741f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/WorkerMediaQueryList.ts
@@ -0,0 +1,9 @@
+import { type WorkerMediaQueryListener } from '@/polyfills/media-query/types/WorkerMediaQueryListener';
+
+export type WorkerMediaQueryList = EventTarget & {
+ readonly matches: boolean;
+ readonly media: string;
+ onchange: WorkerMediaQueryListener | null;
+ addListener: (listener: WorkerMediaQueryListener) => void;
+ removeListener: (listener: WorkerMediaQueryListener) => void;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/WorkerMediaQueryListEvent.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/WorkerMediaQueryListEvent.ts
new file mode 100644
index 00000000000..77592ad33ea
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/WorkerMediaQueryListEvent.ts
@@ -0,0 +1,4 @@
+export type WorkerMediaQueryListEvent = Event & {
+ media: string;
+ matches: boolean;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/types/WorkerMediaQueryListener.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/WorkerMediaQueryListener.ts
new file mode 100644
index 00000000000..27f16672a6f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/types/WorkerMediaQueryListener.ts
@@ -0,0 +1,5 @@
+import { type WorkerMediaQueryListEvent } from '@/polyfills/media-query/types/WorkerMediaQueryListEvent';
+
+export type WorkerMediaQueryListener = (
+ event: WorkerMediaQueryListEvent,
+) => void;
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/createMediaQueryEnvironmentSource.test.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/createMediaQueryEnvironmentSource.test.ts
new file mode 100644
index 00000000000..dc738280361
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/createMediaQueryEnvironmentSource.test.ts
@@ -0,0 +1,184 @@
+import { createMediaQueryEnvironmentFixture } from '@/testing/createMediaQueryEnvironmentFixture';
+import { createSubscriptionStub } from '@/testing/createSubscriptionStub';
+import { createWorkerGeometryStoreStub } from '@/testing/createWorkerGeometryStoreStub';
+import { createViewportGeometrySnapshotFixture } from '@/testing/createViewportGeometrySnapshotFixture';
+import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot';
+import { createMediaQueryEnvironmentSource } from '../createMediaQueryEnvironmentSource';
+
+const setupEnvironmentSource = () => {
+ let viewportSnapshot: ViewportGeometrySnapshot | null = null;
+ let colorScheme: 'light' | 'dark' = 'light';
+
+ const geometrySubscription = createSubscriptionStub();
+ const colorSchemeSubscription = createSubscriptionStub();
+
+ const geometryStore = createWorkerGeometryStoreStub({
+ getViewportSnapshot: jest.fn(() => viewportSnapshot),
+ subscribeToGeometryUpdates: geometrySubscription.subscribe,
+ });
+
+ const environmentSource = createMediaQueryEnvironmentSource({
+ geometryStore,
+ getColorScheme: () => colorScheme,
+ subscribeToColorSchemeUpdates: colorSchemeSubscription.subscribe,
+ });
+
+ const pushViewportSnapshot = (
+ overrides: Partial<ViewportGeometrySnapshot>,
+ ) => {
+ viewportSnapshot = createViewportGeometrySnapshotFixture({
+ ...viewportSnapshot,
+ ...overrides,
+ });
+
+ geometrySubscription.notify();
+ };
+
+ const notifyColorSchemeSource = colorSchemeSubscription.notify;
+
+ const setColorScheme = (nextColorScheme: 'light' | 'dark') => {
+ colorScheme = nextColorScheme;
+ notifyColorSchemeSource();
+ };
+
+ return {
+ environmentSource,
+ pushViewportSnapshot,
+ setColorScheme,
+ notifyColorSchemeSource,
+ };
+};
+
+describe('createMediaQueryEnvironmentSource', () => {
+ it('should read zeroed defaults before the first viewport snapshot', () => {
+ const { environmentSource } = setupEnvironmentSource();
+
+ expect(environmentSource.readEnvironment()).toEqual(
+ createMediaQueryEnvironmentFixture(),
+ );
+ });
+
+ it('should measure the component box rather than the host browser window', () => {
+ const { environmentSource, pushViewportSnapshot } =
+ setupEnvironmentSource();
+
+ pushViewportSnapshot({
+ innerWidth: 1440,
+ innerHeight: 900,
+ rootContainerClientWidth: 350,
+ rootContainerClientHeight: 600,
+ });
+
+ expect(environmentSource.readEnvironment()).toEqual(
+ createMediaQueryEnvironmentFixture({
+ componentWidth: 350,
+ componentHeight: 600,
+ }),
+ );
+ });
+
+ it('should notify on a component size change with the environment already updated', () => {
+ const { environmentSource, pushViewportSnapshot } =
+ setupEnvironmentSource();
+ const environmentUpdateListener = jest.fn(() =>
+ environmentSource.readEnvironment(),
+ );
+
+ environmentSource.subscribeToEnvironmentUpdates(environmentUpdateListener);
+
+ pushViewportSnapshot({ rootContainerClientWidth: 1024 });
+
+ expect(environmentUpdateListener).toHaveBeenCalledTimes(1);
+ expect(environmentUpdateListener).toHaveReturnedWith(
+ createMediaQueryEnvironmentFixture({ componentWidth: 1024 }),
+ );
+ });
+
+ it('should read hover and pointer from the host viewport snapshot', () => {
+ const { environmentSource, pushViewportSnapshot } =
+ setupEnvironmentSource();
+ const environmentUpdateListener = jest.fn();
+
+ environmentSource.subscribeToEnvironmentUpdates(environmentUpdateListener);
+
+ pushViewportSnapshot({ hover: 'none', pointer: 'coarse' });
+
+ expect(environmentSource.readEnvironment()).toEqual(
+ createMediaQueryEnvironmentFixture({ hover: 'none', pointer: 'coarse' }),
+ );
+ expect(environmentUpdateListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not notify on scroll-only viewport updates', () => {
+ const { environmentSource, pushViewportSnapshot } =
+ setupEnvironmentSource();
+ const environmentUpdateListener = jest.fn();
+
+ environmentSource.subscribeToEnvironmentUpdates(environmentUpdateListener);
+
+ pushViewportSnapshot({ rootContainerClientWidth: 1024 });
+ pushViewportSnapshot({ scrollY: 200 });
+ pushViewportSnapshot({ scrollY: 400, rootContainerY: 50 });
+
+ expect(environmentUpdateListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not notify on color scheme source updates that keep the scheme', () => {
+ const { environmentSource, notifyColorSchemeSource } =
+ setupEnvironmentSource();
+ const environmentUpdateListener = jest.fn();
+
+ environmentSource.subscribeToEnvironmentUpdates(environmentUpdateListener);
+
+ notifyColorSchemeSource();
+ notifyColorSchemeSource();
+
+ expect(environmentUpdateListener).not.toHaveBeenCalled();
+ });
+
+ it('should notify once per color scheme change', () => {
+ const { environmentSource, setColorScheme } = setupEnvironmentSource();
+ const environmentUpdateListener = jest.fn();
+
+ environmentSource.subscribeToEnvironmentUpdates(environmentUpdateListener);
+
+ setColorScheme('dark');
+ expect(environmentUpdateListener).toHaveBeenCalledTimes(1);
+
+ setColorScheme('dark');
+ expect(environmentUpdateListener).toHaveBeenCalledTimes(1);
+
+ setColorScheme('light');
+ expect(environmentUpdateListener).toHaveBeenCalledTimes(2);
+ });
+
+ it('should notify when the environment reverts to a value cached while unobserved', () => {
+ const { environmentSource, pushViewportSnapshot } =
+ setupEnvironmentSource();
+ const environmentUpdateListener = jest.fn();
+
+ pushViewportSnapshot({ rootContainerClientWidth: 1024 });
+
+ environmentSource.subscribeToEnvironmentUpdates(environmentUpdateListener);
+
+ pushViewportSnapshot({ rootContainerClientWidth: 0 });
+
+ expect(environmentUpdateListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('should stop notifying after unsubscribe', () => {
+ const { environmentSource, pushViewportSnapshot } =
+ setupEnvironmentSource();
+ const environmentUpdateListener = jest.fn();
+
+ const unsubscribe = environmentSource.subscribeToEnvironmentUpdates(
+ environmentUpdateListener,
+ );
+
+ pushViewportSnapshot({ rootContainerClientWidth: 1024 });
+ unsubscribe();
+ pushViewportSnapshot({ rootContainerClientWidth: 1200 });
+
+ expect(environmentUpdateListener).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/createWorkerMediaQueryList.test.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/createWorkerMediaQueryList.test.ts
new file mode 100644
index 00000000000..a493ddb0238
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/createWorkerMediaQueryList.test.ts
@@ -0,0 +1,453 @@
+import { Window } from '@remote-dom/polyfill';
+
+import { type createWorkerMediaQueryList as CreateWorkerMediaQueryList } from '@/polyfills/media-query/utils/createWorkerMediaQueryList';
+import { createSubscriptionStub } from '@/testing/createSubscriptionStub';
+
+const polyfillWindow = new Window();
+
+let createWorkerMediaQueryList: typeof CreateWorkerMediaQueryList;
+
+beforeAll(async () => {
+ Object.defineProperty(globalThis, 'EventTarget', {
+ value: polyfillWindow.EventTarget,
+ writable: true,
+ configurable: true,
+ });
+ Object.defineProperty(globalThis, 'Event', {
+ value: polyfillWindow.Event,
+ writable: true,
+ configurable: true,
+ });
+
+ ({ createWorkerMediaQueryList } =
+ await import('@/polyfills/media-query/utils/createWorkerMediaQueryList'));
+});
+
+const setupMediaQueryList = () => {
+ let matches = false;
+ const reportListenerError = jest.fn();
+ const environmentSubscription = createSubscriptionStub();
+
+ const mediaQueryList = createWorkerMediaQueryList({
+ media: '(min-width: 600px)',
+ evaluateMatches: () => matches,
+ subscribeToEnvironmentUpdates: environmentSubscription.subscribe,
+ reportListenerError,
+ });
+
+ const setMatches = (nextMatches: boolean) => {
+ matches = nextMatches;
+ environmentSubscription.notify();
+ };
+
+ return {
+ mediaQueryList,
+ setMatches,
+ subscribeToEnvironmentUpdates: environmentSubscription.subscribe,
+ unsubscribe: environmentSubscription.unsubscribe,
+ reportListenerError,
+ };
+};
+
+describe('createWorkerMediaQueryList', () => {
+ it('should extend the EventTarget the worker ships with', () => {
+ const { mediaQueryList } = setupMediaQueryList();
+
+ expect(mediaQueryList).toBeInstanceOf(polyfillWindow.EventTarget);
+ });
+
+ it('should expose live matches without any listener attached', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+
+ expect(mediaQueryList.matches).toBe(false);
+
+ setMatches(true);
+
+ expect(mediaQueryList.matches).toBe(true);
+ });
+
+ it('should not subscribe to environment updates until a listener is attached', () => {
+ const { mediaQueryList, subscribeToEnvironmentUpdates } =
+ setupMediaQueryList();
+
+ expect(subscribeToEnvironmentUpdates).not.toHaveBeenCalled();
+
+ mediaQueryList.addEventListener('change', jest.fn());
+
+ expect(subscribeToEnvironmentUpdates).toHaveBeenCalledTimes(1);
+ });
+
+ it('should unsubscribe from environment updates when the last listener is removed', () => {
+ const { mediaQueryList, unsubscribe } = setupMediaQueryList();
+ const firstListener = jest.fn();
+ const secondListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', firstListener);
+ mediaQueryList.addListener(secondListener);
+
+ mediaQueryList.removeEventListener('change', firstListener);
+ expect(unsubscribe).not.toHaveBeenCalled();
+
+ mediaQueryList.removeListener(secondListener);
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+
+ it('should ignore events other than change and non-function listeners', () => {
+ const { mediaQueryList, subscribeToEnvironmentUpdates, setMatches } =
+ setupMediaQueryList();
+
+ mediaQueryList.addEventListener('resize', jest.fn());
+ expect(subscribeToEnvironmentUpdates).not.toHaveBeenCalled();
+
+ expect(() => {
+ mediaQueryList.addListener(
+ null as unknown as Parameters<typeof mediaQueryList.addListener>[0],
+ );
+ setMatches(true);
+ }).not.toThrow();
+ });
+
+ it('should dispatch events carrying media and matches', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const changeListener = jest.fn();
+
+ mediaQueryList.addListener(changeListener);
+
+ setMatches(true);
+ expect(changeListener).toHaveBeenCalledTimes(1);
+ expect(changeListener.mock.calls[0][0]).toBeInstanceOf(
+ polyfillWindow.Event,
+ );
+ expect(changeListener.mock.calls[0][0]).toMatchObject({
+ type: 'change',
+ media: '(min-width: 600px)',
+ matches: true,
+ });
+
+ mediaQueryList.removeListener(changeListener);
+
+ setMatches(false);
+ expect(changeListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('should expose media as a read-only accessor', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const changeListener = jest.fn();
+
+ mediaQueryList.addListener(changeListener);
+
+ expect(Reflect.set(mediaQueryList, 'media', '(max-width: 1px)')).toBe(
+ false,
+ );
+ expect(mediaQueryList.media).toBe('(min-width: 600px)');
+ expect(Object.keys(mediaQueryList)).toEqual([]);
+
+ setMatches(true);
+
+ expect(changeListener.mock.calls[0][0]).toMatchObject({
+ media: '(min-width: 600px)',
+ });
+ });
+
+ it('should invoke and clear the onchange handler', () => {
+ const { mediaQueryList, setMatches, unsubscribe } = setupMediaQueryList();
+ const onchangeHandler = jest.fn();
+
+ mediaQueryList.onchange = onchangeHandler;
+
+ setMatches(true);
+ expect(onchangeHandler).toHaveBeenCalledTimes(1);
+
+ mediaQueryList.onchange = null;
+
+ setMatches(false);
+ expect(onchangeHandler).toHaveBeenCalledTimes(1);
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+
+ it('should invoke the onchange handler in its registration position', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const invocationOrder: string[] = [];
+
+ mediaQueryList.addEventListener('change', () =>
+ invocationOrder.push('first'),
+ );
+ mediaQueryList.onchange = () => invocationOrder.push('onchange');
+ mediaQueryList.addEventListener('change', () =>
+ invocationOrder.push('last'),
+ );
+
+ setMatches(true);
+
+ expect(invocationOrder).toEqual(['first', 'onchange', 'last']);
+ });
+
+ it('should keep the onchange position when the handler is reassigned', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const invocationOrder: string[] = [];
+
+ mediaQueryList.addEventListener('change', () =>
+ invocationOrder.push('first'),
+ );
+ mediaQueryList.onchange = () => invocationOrder.push('initial');
+ mediaQueryList.addEventListener('change', () =>
+ invocationOrder.push('last'),
+ );
+ mediaQueryList.onchange = () => invocationOrder.push('reassigned');
+
+ setMatches(true);
+
+ expect(invocationOrder).toEqual(['first', 'reassigned', 'last']);
+ });
+
+ it('should invoke a function that is both the onchange handler and a listener twice', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const changeListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', changeListener);
+ mediaQueryList.onchange = changeListener;
+
+ setMatches(true);
+
+ expect(changeListener).toHaveBeenCalledTimes(2);
+ });
+
+ it('should keep an explicit listener when onchange is cleared', () => {
+ const { mediaQueryList, setMatches, unsubscribe } = setupMediaQueryList();
+ const changeListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', changeListener);
+ mediaQueryList.onchange = changeListener;
+ mediaQueryList.onchange = null;
+
+ setMatches(true);
+
+ expect(changeListener).toHaveBeenCalledTimes(1);
+ expect(unsubscribe).not.toHaveBeenCalled();
+ });
+
+ it('should keep the onchange handler when the same function is removed as a listener', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const changeListener = jest.fn();
+
+ mediaQueryList.onchange = changeListener;
+ mediaQueryList.removeListener(changeListener);
+
+ setMatches(true);
+
+ expect(changeListener).toHaveBeenCalledTimes(1);
+ expect(mediaQueryList.onchange).toBe(changeListener);
+ });
+
+ it('should invoke a once listener a single time and release the subscription', () => {
+ const { mediaQueryList, setMatches, unsubscribe } = setupMediaQueryList();
+ const changeListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', changeListener, { once: true });
+
+ setMatches(true);
+ setMatches(false);
+
+ expect(changeListener).toHaveBeenCalledTimes(1);
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+
+ it('should invoke a listener registered plainly and with once exactly once per change', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const changeListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', changeListener);
+ mediaQueryList.addEventListener('change', changeListener, { once: true });
+
+ setMatches(true);
+ expect(changeListener).toHaveBeenCalledTimes(1);
+
+ setMatches(false);
+ expect(changeListener).toHaveBeenCalledTimes(2);
+ });
+
+ it('should keep a re-added listener alive after its once registration was removed', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const changeListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', changeListener, { once: true });
+ mediaQueryList.removeEventListener('change', changeListener);
+ mediaQueryList.addEventListener('change', changeListener);
+
+ setMatches(true);
+ setMatches(false);
+ setMatches(true);
+
+ expect(changeListener).toHaveBeenCalledTimes(3);
+ });
+
+ it('should keep firing a once listener that re-registers itself', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const MAXIMUM_INVOCATIONS = 10;
+ const changeListener = jest.fn(() => {
+ if (changeListener.mock.calls.length >= MAXIMUM_INVOCATIONS) {
+ return;
+ }
+
+ mediaQueryList.addEventListener('change', changeListener, { once: true });
+ });
+
+ mediaQueryList.addEventListener('change', changeListener, { once: true });
+
+ setMatches(true);
+ setMatches(false);
+ setMatches(true);
+
+ expect(changeListener).toHaveBeenCalledTimes(3);
+ });
+
+ it('should detach a listener when its abort signal fires', () => {
+ const { mediaQueryList, setMatches, unsubscribe } = setupMediaQueryList();
+ const abortController = new AbortController();
+ const changeListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', changeListener, {
+ signal: abortController.signal,
+ });
+
+ abortController.abort();
+ setMatches(true);
+
+ expect(changeListener).not.toHaveBeenCalled();
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+
+ it('should ignore a listener whose signal is already aborted', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const abortController = new AbortController();
+ const abortedListener = jest.fn();
+ const liveListener = jest.fn();
+
+ abortController.abort();
+ mediaQueryList.addEventListener('change', abortedListener, {
+ signal: abortController.signal,
+ });
+ mediaQueryList.addEventListener('change', liveListener);
+
+ setMatches(true);
+
+ expect(abortedListener).not.toHaveBeenCalled();
+ expect(liveListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('should keep a re-added listener alive after its previous abort signal fires', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const abortController = new AbortController();
+ const changeListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', changeListener, {
+ signal: abortController.signal,
+ });
+ mediaQueryList.removeEventListener('change', changeListener);
+ mediaQueryList.addEventListener('change', changeListener);
+ abortController.abort();
+
+ setMatches(true);
+
+ expect(changeListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('should accept null listener options', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const changeListener = jest.fn();
+
+ expect(() => {
+ mediaQueryList.addEventListener(
+ 'change',
+ changeListener,
+ null as unknown as AddEventListenerOptions,
+ );
+ }).not.toThrow();
+
+ setMatches(true);
+
+ expect(changeListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('should notify listeners passed as an object with handleEvent', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const handleEvent = jest.fn();
+
+ mediaQueryList.addEventListener('change', { handleEvent });
+
+ setMatches(true);
+
+ expect(handleEvent).toHaveBeenCalledTimes(1);
+ });
+
+ it('should report a throwing listener and keep notifying the remaining ones', () => {
+ const { mediaQueryList, setMatches, reportListenerError } =
+ setupMediaQueryList();
+ const listenerFailure = new Error('listener failure');
+ const throwingListener = jest.fn(() => {
+ throw listenerFailure;
+ });
+ const secondListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', throwingListener);
+ mediaQueryList.addEventListener('change', secondListener);
+
+ expect(() => setMatches(true)).not.toThrow();
+ expect(reportListenerError).toHaveBeenCalledWith(listenerFailure);
+ expect(secondListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not invoke a listener removed by an earlier listener during dispatch', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+
+ const secondListener = jest.fn();
+ const firstListener = jest.fn(() => {
+ mediaQueryList.removeEventListener('change', secondListener);
+ });
+
+ mediaQueryList.addEventListener('change', firstListener);
+ mediaQueryList.addEventListener('change', secondListener);
+
+ setMatches(true);
+
+ expect(firstListener).toHaveBeenCalledTimes(1);
+ expect(secondListener).not.toHaveBeenCalled();
+ });
+
+ it('should not invoke a listener added during dispatch until the next change', () => {
+ const { mediaQueryList, setMatches } = setupMediaQueryList();
+ const lateListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', () => {
+ mediaQueryList.addEventListener('change', lateListener);
+ });
+
+ setMatches(true);
+ expect(lateListener).not.toHaveBeenCalled();
+
+ setMatches(false);
+ expect(lateListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('should stop at a listener that stops immediate propagation and still remove it when once', () => {
+ const { mediaQueryList, setMatches, unsubscribe } = setupMediaQueryList();
+ const stoppingListener = jest.fn((event: Event) => {
+ event.stopImmediatePropagation();
+ });
+ const laterListener = jest.fn();
+
+ mediaQueryList.addEventListener('change', stoppingListener, { once: true });
+ mediaQueryList.addEventListener('change', laterListener);
+
+ setMatches(true);
+ expect(stoppingListener).toHaveBeenCalledTimes(1);
+ expect(laterListener).not.toHaveBeenCalled();
+
+ setMatches(false);
+ expect(stoppingListener).toHaveBeenCalledTimes(1);
+ expect(laterListener).toHaveBeenCalledTimes(1);
+
+ mediaQueryList.removeEventListener('change', laterListener);
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/installMatchMediaPolyfill.test.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/installMatchMediaPolyfill.test.ts
new file mode 100644
index 00000000000..a775f17ca50
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/installMatchMediaPolyfill.test.ts
@@ -0,0 +1,330 @@
+import { type MediaQueryEnvironment } from '@/polyfills/media-query/types/MediaQueryEnvironment';
+import { type WorkerMediaQueryList } from '@/polyfills/media-query/types/WorkerMediaQueryList';
+import { createMediaQueryEnvironmentFixture } from '@/testing/createMediaQueryEnvironmentFixture';
+import { createSubscriptionStub } from '@/testing/createSubscriptionStub';
+import { installMatchMediaPolyfill } from '../installMatchMediaPolyfill';
+
+type MatchMediaFunction = (query: unknown) => WorkerMediaQueryList;
+
+const setupMatchMedia = () => {
+ let environment = createMediaQueryEnvironmentFixture();
+
+ const environmentSubscription = createSubscriptionStub();
+
+ const globalScope: Record<string, unknown> = {};
+
+ installMatchMediaPolyfill({
+ globalScope,
+ environmentSource: {
+ readEnvironment: () => environment,
+ subscribeToEnvironmentUpdates: environmentSubscription.subscribe,
+ },
+ });
+
+ const setEnvironment = (overrides: Partial<MediaQueryEnvironment>) => {
+ environment = { ...environment, ...overrides };
+
+ environmentSubscription.notify();
+ };
+
+ return {
+ matchMedia: globalScope.matchMedia as MatchMediaFunction,
+ globalScope,
+ setEnvironment,
+ };
+};
+
+describe('installMatchMediaPolyfill', () => {
+ it('should evaluate min-width and max-width against the environment', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 1024 });
+
+ expect(matchMedia('(min-width: 800px)').matches).toBe(true);
+ expect(matchMedia('(min-width: 1024px)').matches).toBe(true);
+ expect(matchMedia('(min-width: 1200px)').matches).toBe(false);
+ expect(matchMedia('(max-width: 1024px)').matches).toBe(true);
+ expect(matchMedia('(max-width: 1000px)').matches).toBe(false);
+ });
+
+ it('should evaluate combined and comma-separated queries', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 1024 });
+
+ expect(
+ matchMedia('screen and (min-width: 800px) and (max-width: 1200px)')
+ .matches,
+ ).toBe(true);
+ expect(matchMedia('(min-width: 2000px), (max-width: 1100px)').matches).toBe(
+ true,
+ );
+ expect(matchMedia('print').matches).toBe(false);
+ expect(matchMedia('not print').matches).toBe(true);
+ });
+
+ it('should evaluate device pixel ratio queries against the environment', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ devicePixelRatio: 2 });
+
+ expect(matchMedia('(-webkit-min-device-pixel-ratio: 2)').matches).toBe(
+ true,
+ );
+ expect(matchMedia('(min-resolution: 192dpi)').matches).toBe(true);
+ expect(matchMedia('(min-resolution: 3dppx)').matches).toBe(false);
+ expect(matchMedia('(min-device-pixel-ratio: 2)').matches).toBe(false);
+ });
+
+ it.each([
+ '(width: max(10px, screen, 20px))',
+ '(width: max(min(10px, 20px), screen, 30px))',
+ '(unknown: "), screen, (")',
+ '(unknown: "\\\r\n), screen, (")',
+ '(unknown: /* ), screen, ( */ value)',
+ '(unknown: [), screen, (])',
+ '(unknown: {), screen, (})',
+ '(width: max(10px, screen, 20px)',
+ ])('should not treat nested commas as query separators in %s', (query) => {
+ const { matchMedia } = setupMatchMedia();
+
+ expect(matchMedia(query).matches).toBe(false);
+ });
+
+ it('should preserve independent queries around an unsupported expression', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 1024 });
+
+ expect(
+ matchMedia('(width: max(10px, screen, 20px)), (min-width: 800px)')
+ .matches,
+ ).toBe(true);
+ expect(
+ matchMedia('(min-width: 800px), (width: max(10px, screen, 20px))')
+ .matches,
+ ).toBe(true);
+ expect(
+ matchMedia('(width: max(10px, screen, 20px)), (min-width: 1200px)')
+ .matches,
+ ).toBe(false);
+ expect(matchMedia('(unknown: "unterminated\n), all').matches).toBe(true);
+ });
+
+ it('should evaluate range syntax against the environment', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 700, componentHeight: 300 });
+
+ expect(matchMedia('(width >= 600px)').matches).toBe(true);
+ expect(matchMedia('(400px <= width <= 800px)').matches).toBe(true);
+ expect(matchMedia('(width < 700px)').matches).toBe(false);
+ expect(matchMedia('(width = 700px)').matches).toBe(true);
+ expect(matchMedia('(height > 300px)').matches).toBe(false);
+ });
+
+ it('should report zero component sizes before the first environment update', () => {
+ const { matchMedia } = setupMatchMedia();
+
+ expect(matchMedia('(min-width: 1px)').matches).toBe(false);
+ expect(matchMedia('(max-width: 100px)').matches).toBe(true);
+ expect(matchMedia('(width)').matches).toBe(false);
+ });
+
+ it('should return false for unknown or unparseable queries without throwing', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 1024 });
+
+ expect(matchMedia('(prefers-reduced-motion: reduce)').matches).toBe(false);
+ expect(matchMedia('(min-width >= 600px)').matches).toBe(false);
+ expect(matchMedia('garbage').matches).toBe(false);
+ expect(matchMedia('not garbage').matches).toBe(true);
+ expect(matchMedia(undefined).matches).toBe(false);
+ expect(matchMedia('(constructor: 1)').matches).toBe(false);
+ expect(matchMedia('garbage').media).toBe('garbage');
+ });
+
+ it('should match the empty query like the all media type', () => {
+ const { matchMedia } = setupMatchMedia();
+
+ expect(matchMedia('').matches).toBe(true);
+ expect(matchMedia(' ').matches).toBe(true);
+ expect(matchMedia('all').matches).toBe(true);
+ });
+
+ it('should treat an empty query inside a list as never matching', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 320 });
+
+ expect(matchMedia('(min-width: 2000px),').matches).toBe(false);
+ expect(
+ matchMedia('(min-width: 2000px), , (min-width: 3000px)').matches,
+ ).toBe(false);
+ expect(matchMedia('(min-width: 2000px), (min-width: 100px)').matches).toBe(
+ true,
+ );
+ });
+
+ it('should evaluate orientation from the component box', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 1024, componentHeight: 400 });
+
+ expect(matchMedia('(orientation: landscape)').matches).toBe(true);
+ expect(matchMedia('(orientation: portrait)').matches).toBe(false);
+
+ setEnvironment({ componentWidth: 400, componentHeight: 1024 });
+
+ expect(matchMedia('(orientation: portrait)').matches).toBe(true);
+ expect(matchMedia('(orientation: landscape)').matches).toBe(false);
+ });
+
+ it('should evaluate prefers-color-scheme from the environment', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+
+ expect(matchMedia('(prefers-color-scheme: light)').matches).toBe(true);
+ expect(matchMedia('(prefers-color-scheme: dark)').matches).toBe(false);
+
+ setEnvironment({ colorScheme: 'dark' });
+
+ expect(matchMedia('(prefers-color-scheme: dark)').matches).toBe(true);
+ });
+
+ it('should dispatch a change event when the color scheme flips', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ const changeListener = jest.fn();
+
+ const mediaQueryList = matchMedia('(prefers-color-scheme: dark)');
+ mediaQueryList.addEventListener('change', changeListener);
+
+ setEnvironment({ colorScheme: 'dark' });
+
+ expect(changeListener).toHaveBeenCalledTimes(1);
+ expect(changeListener).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'change',
+ media: '(prefers-color-scheme: dark)',
+ matches: true,
+ }),
+ );
+ });
+
+ it('should notify a change listener exactly once per flip', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 1024 });
+
+ const changeListener = jest.fn();
+ const mediaQueryList = matchMedia('(min-width: 1000px)');
+ mediaQueryList.addEventListener('change', changeListener);
+
+ setEnvironment({ componentWidth: 800 });
+ setEnvironment({ componentWidth: 700 });
+
+ expect(changeListener).toHaveBeenCalledTimes(1);
+ expect(changeListener).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ type: 'change',
+ media: '(min-width: 1000px)',
+ matches: false,
+ }),
+ );
+
+ setEnvironment({ componentWidth: 1200 });
+
+ expect(changeListener).toHaveBeenCalledTimes(2);
+ expect(changeListener).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ type: 'change',
+ media: '(min-width: 1000px)',
+ matches: true,
+ }),
+ );
+ });
+
+ it('should install matchMedia on both the global scope and a distinct window', () => {
+ const polyfillWindow: Record<string, unknown> = {};
+ const globalScope: Record<string, unknown> = { window: polyfillWindow };
+
+ installMatchMediaPolyfill({
+ globalScope,
+ environmentSource: {
+ readEnvironment: () => createMediaQueryEnvironmentFixture(),
+ subscribeToEnvironmentUpdates: () => () => {},
+ },
+ });
+
+ expect(typeof globalScope.matchMedia).toBe('function');
+ expect(globalScope.matchMedia).toBe(polyfillWindow.matchMedia);
+ });
+
+ it('should ignore CSS comments the way browsers do', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 1024 });
+
+ expect(matchMedia('(min-width: 600px) /* tablet */').matches).toBe(true);
+ expect(matchMedia('/* tablet */ (min-width: 600px)').matches).toBe(true);
+ expect(matchMedia('(min-width: /* tablet */ 600px)').matches).toBe(true);
+ expect(
+ matchMedia('screen /* tablet */ and (min-width: 600px)').matches,
+ ).toBe(true);
+ expect(matchMedia('screen/**/and/**/(min-width: 600px)').matches).toBe(
+ true,
+ );
+ expect(matchMedia('/* */').matches).toBe(true);
+ expect(matchMedia('/* */, (min-width: 2000px)').matches).toBe(false);
+ expect(matchMedia('(unknown: "/*"), (min-width: 800px)').matches).toBe(
+ true,
+ );
+ });
+
+ it('should let the rest of a negated query decide around an unknown condition', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 1024 });
+
+ expect(
+ matchMedia('not print and (prefers-reduced-motion: reduce)').matches,
+ ).toBe(true);
+ expect(matchMedia('not print and (min-width: calc(1px))').matches).toBe(
+ true,
+ );
+ expect(
+ matchMedia('not all and (prefers-reduced-motion: reduce)').matches,
+ ).toBe(false);
+ expect(
+ matchMedia(
+ 'not all and (prefers-reduced-motion: reduce) and (min-width: 2000px)',
+ ).matches,
+ ).toBe(true);
+ expect(matchMedia('not (prefers-reduced-motion: reduce)').matches).toBe(
+ false,
+ );
+ expect(
+ matchMedia('print and (prefers-reduced-motion: reduce)').matches,
+ ).toBe(false);
+ });
+
+ it('should evaluate hover and pointer from the host input', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ hover: 'none', pointer: 'coarse' });
+
+ expect(matchMedia('(hover: none) and (pointer: coarse)').matches).toBe(
+ true,
+ );
+ expect(matchMedia('(pointer: fine)').matches).toBe(false);
+ expect(matchMedia('(hover)').matches).toBe(false);
+ expect(matchMedia('(pointer)').matches).toBe(true);
+
+ setEnvironment({ hover: 'hover', pointer: 'fine' });
+
+ expect(matchMedia('(hover: none) and (pointer: coarse)').matches).toBe(
+ false,
+ );
+ expect(matchMedia('(hover: hover) and (pointer: fine)').matches).toBe(true);
+ expect(matchMedia('(any-pointer: coarse)').matches).toBe(false);
+ });
+
+ it('should evaluate absolute length units', () => {
+ const { matchMedia, setEnvironment } = setupMatchMedia();
+ setEnvironment({ componentWidth: 1000 });
+
+ expect(matchMedia('(min-width: 480pt)').matches).toBe(true);
+ expect(matchMedia('(max-width: 10in)').matches).toBe(false);
+ expect(matchMedia('(max-width: 11in)').matches).toBe(true);
+ expect(matchMedia('(max-width: 25cm)').matches).toBe(false);
+ expect(matchMedia('(width >= 480pt)').matches).toBe(true);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/parseMediaQuery.test.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/parseMediaQuery.test.ts
new file mode 100644
index 00000000000..d7929982c1a
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/parseMediaQuery.test.ts
@@ -0,0 +1,495 @@
+import { parseMediaQuery } from '../parseMediaQuery';
+
+describe('parseMediaQuery', () => {
+ it('should reject an empty query, which only a whole query list may be', () => {
+ expect(parseMediaQuery('')).toBeNull();
+ expect(parseMediaQuery(' ')).toBeNull();
+ });
+
+ it('should parse a min-width condition in pixels', () => {
+ expect(parseMediaQuery('(min-width: 600px)')).toEqual({
+ isNegated: false,
+ matchesMediaType: true,
+ conditions: [
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ ],
+ });
+ });
+
+ it('should convert em and rem lengths to pixels', () => {
+ expect(parseMediaQuery('(max-width: 40em)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '<=',
+ value: 640,
+ },
+ ]);
+ expect(parseMediaQuery('(min-height: 10rem)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentHeight',
+ operator: '>=',
+ value: 160,
+ },
+ ]);
+ });
+
+ it('should parse a media type combined with conditions', () => {
+ expect(
+ parseMediaQuery('screen and (min-width: 600px) and (max-width: 900px)'),
+ ).toEqual({
+ isNegated: false,
+ matchesMediaType: true,
+ conditions: [
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '<=',
+ value: 900,
+ },
+ ],
+ });
+ });
+
+ it('should parse not and only prefixes', () => {
+ expect(parseMediaQuery('not print')).toEqual({
+ isNegated: true,
+ matchesMediaType: false,
+ conditions: [],
+ });
+ expect(parseMediaQuery('only screen and (min-width: 0px)')?.isNegated).toBe(
+ false,
+ );
+ });
+
+ it('should parse device pixel ratio and resolution features', () => {
+ expect(
+ parseMediaQuery('(-webkit-min-device-pixel-ratio: 2)')?.conditions,
+ ).toEqual([
+ {
+ kind: 'numeric',
+ source: 'devicePixelRatio',
+ operator: '>=',
+ value: 2,
+ },
+ ]);
+ expect(parseMediaQuery('(min-resolution: 192dpi)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'devicePixelRatio',
+ operator: '>=',
+ value: 2,
+ },
+ ]);
+ expect(parseMediaQuery('(max-resolution: 1.5dppx)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'devicePixelRatio',
+ operator: '<=',
+ value: 1.5,
+ },
+ ]);
+ });
+
+ it('should parse hover and pointer values', () => {
+ expect(parseMediaQuery('(hover: hover)')?.conditions).toEqual([
+ { kind: 'keyword', featureName: 'hover', value: 'hover' },
+ ]);
+ expect(parseMediaQuery('(pointer: coarse)')?.conditions).toEqual([
+ { kind: 'keyword', featureName: 'pointer', value: 'coarse' },
+ ]);
+ expect(parseMediaQuery('(pointer: sideways)')).toBeNull();
+ expect(parseMediaQuery('(any-pointer: coarse)')).toBeNull();
+ });
+
+ it('should parse orientation values', () => {
+ expect(parseMediaQuery('(orientation: portrait)')?.conditions).toEqual([
+ { kind: 'keyword', featureName: 'orientation', value: 'portrait' },
+ ]);
+ expect(parseMediaQuery('(orientation: landscape)')?.conditions).toEqual([
+ { kind: 'keyword', featureName: 'orientation', value: 'landscape' },
+ ]);
+ expect(parseMediaQuery('(orientation: sideways)')).toBeNull();
+ });
+
+ it('should parse prefers-color-scheme values', () => {
+ expect(parseMediaQuery('(prefers-color-scheme: dark)')?.conditions).toEqual(
+ [{ kind: 'keyword', featureName: 'prefers-color-scheme', value: 'dark' }],
+ );
+ });
+
+ it('should reject unknown features, malformed queries, and unitless lengths', () => {
+ expect(parseMediaQuery('(min-width: 600)')).toBeNull();
+ expect(parseMediaQuery('(min-width >= 600px)')).toBeNull();
+ expect(parseMediaQuery('(min-width: 600vw)')).toBeNull();
+ expect(parseMediaQuery('(constructor: 1)')).toBeNull();
+ expect(parseMediaQuery('(__proto__: 1)')).toBeNull();
+ expect(parseMediaQuery('(min-width: 600constructor)')).toBeNull();
+ expect(parseMediaQuery('(resolution: 2constructor)')).toBeNull();
+ expect(parseMediaQuery('not')).toBeNull();
+ expect(parseMediaQuery('(prefers-color-scheme: solarized)')).toBeNull();
+ expect(parseMediaQuery('(prefers-color-scheme: no-preference)')).toBeNull();
+ expect(parseMediaQuery('(min-width: 600px) and screen')).toBeNull();
+ });
+
+ it('should reject only when it is not followed by a media type', () => {
+ expect(parseMediaQuery('only (min-width: 600px)')).toBeNull();
+ });
+
+ it('should accept not when it is not followed by a media type', () => {
+ expect(parseMediaQuery('not (min-width: 600px)')).toEqual({
+ isNegated: true,
+ matchesMediaType: true,
+ conditions: [
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ ],
+ });
+ });
+
+ it('should reject not applied to a condition followed by and clauses', () => {
+ expect(
+ parseMediaQuery('not (min-width: 600px) and (max-width: 900px)'),
+ ).toBeNull();
+ expect(parseMediaQuery('not screen and (min-width: 600px)')).toEqual({
+ isNegated: true,
+ matchesMediaType: true,
+ conditions: [
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ ],
+ });
+ });
+
+ it('should reject webkit-prefixed features other than device pixel ratio', () => {
+ expect(parseMediaQuery('(-webkit-min-width: 600px)')).toBeNull();
+ });
+
+ it('should parse values with a leading decimal point', () => {
+ expect(parseMediaQuery('(min-width: .5em)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 8,
+ },
+ ]);
+ });
+
+ it('should accept a zero length without a unit', () => {
+ expect(parseMediaQuery('(min-width: 0)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 0,
+ },
+ ]);
+ });
+
+ it('should accept CSS whitespace inside conditions and after modifiers', () => {
+ expect(parseMediaQuery('(min-width:\n600px)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ ]);
+ expect(parseMediaQuery('not\tprint')).toEqual({
+ isNegated: true,
+ matchesMediaType: false,
+ conditions: [],
+ });
+ expect(
+ parseMediaQuery('only\nscreen and (min-width: 0)')?.matchesMediaType,
+ ).toBe(true);
+ expect(
+ parseMediaQuery('(min-width: 600px)and (max-width: 900px)')?.conditions,
+ ).toHaveLength(2);
+ });
+
+ it('should reject whitespace that CSS does not recognize', () => {
+ expect(parseMediaQuery('screen and\u00a0(min-width: 1px)')).toBeNull();
+ expect(
+ parseMediaQuery('(min-width: 600px)and(max-width: 900px)'),
+ ).toBeNull();
+ expect(parseMediaQuery('not(min-width: 1px)')).toBeNull();
+ });
+
+ it('should treat an unknown media type as valid but never matching', () => {
+ expect(parseMediaQuery('garbage')).toEqual({
+ isNegated: false,
+ matchesMediaType: false,
+ conditions: [],
+ });
+ expect(parseMediaQuery('not tablet')).toEqual({
+ isNegated: true,
+ matchesMediaType: false,
+ conditions: [],
+ });
+ expect(parseMediaQuery('12px')).toBeNull();
+ expect(parseMediaQuery('not and')).toBeNull();
+ expect(parseMediaQuery('not not')).toBeNull();
+ });
+
+ it('should parse range syntax with the feature on either side', () => {
+ expect(parseMediaQuery('(width >= 600px)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ ]);
+ expect(parseMediaQuery('(600px <= width)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ ]);
+ expect(parseMediaQuery('(width = 600px)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '=',
+ value: 600,
+ },
+ ]);
+ expect(parseMediaQuery('(400px <= width <= 800px)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 400,
+ },
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '<=',
+ value: 800,
+ },
+ ]);
+ expect(parseMediaQuery('(800px >= height > 400px)')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentHeight',
+ operator: '<=',
+ value: 800,
+ },
+ {
+ kind: 'numeric',
+ source: 'componentHeight',
+ operator: '>',
+ value: 400,
+ },
+ ]);
+ });
+
+ it('should reject malformed range syntax', () => {
+ expect(parseMediaQuery('(400px <= width >= 800px)')).toBeNull();
+ expect(parseMediaQuery('(width >= 400px <= 800px)')).toBeNull();
+ expect(parseMediaQuery('(400px = width <= 800px)')).toBeNull();
+ expect(parseMediaQuery('(orientation >= portrait)')).toBeNull();
+ expect(parseMediaQuery('(width >= 600)')).toBeNull();
+ expect(parseMediaQuery('(-webkit-min-device-pixel-ratio >= 2)')).toBeNull();
+ expect(parseMediaQuery('(400px <= width = 800px)')).toBeNull();
+ expect(parseMediaQuery('(400px <= width <= 800px <= 900px)')).toBeNull();
+ });
+
+ it('should reject a long unparseable condition without catastrophic backtracking', () => {
+ const LINE_SEPARATOR = '\u2028';
+ const OPERATOR_RUN_LENGTH = 6400;
+
+ expect(
+ parseMediaQuery(`(${'<'.repeat(OPERATOR_RUN_LENGTH)}${LINE_SEPARATOR})`),
+ ).toBeNull();
+ });
+
+ it('should parse features in boolean context', () => {
+ expect(parseMediaQuery('(width)')?.conditions).toEqual([
+ { kind: 'non-zero', source: 'componentWidth' },
+ ]);
+ expect(parseMediaQuery('(orientation)')?.conditions).toEqual([
+ { kind: 'not-none', featureName: 'orientation' },
+ ]);
+ expect(parseMediaQuery('(prefers-color-scheme)')?.conditions).toEqual([
+ { kind: 'not-none', featureName: 'prefers-color-scheme' },
+ ]);
+ expect(parseMediaQuery('(hover)')?.conditions).toEqual([
+ { kind: 'not-none', featureName: 'hover' },
+ ]);
+ expect(parseMediaQuery('(-webkit-device-pixel-ratio)')?.conditions).toEqual(
+ [{ kind: 'non-zero', source: 'devicePixelRatio' }],
+ );
+ expect(parseMediaQuery('(min-width)')).toBeNull();
+ expect(parseMediaQuery('(prefers-reduced-motion)')).toBeNull();
+ });
+
+ it('should reject non-CSS whitespace anywhere in a condition', () => {
+ expect(parseMediaQuery('(\u00a0width >= 600px)')).toBeNull();
+ expect(parseMediaQuery('(min-width:\u00a0600px)')).toBeNull();
+ expect(parseMediaQuery('(min-width: 600px\u00a0)')).toBeNull();
+ expect(parseMediaQuery('\u00a0screen')).toBeNull();
+ });
+
+ it('should let the rest of a negated query decide when a condition is unknown', () => {
+ expect(
+ parseMediaQuery('not print and (prefers-reduced-motion: reduce)'),
+ ).toEqual({
+ isNegated: true,
+ matchesMediaType: false,
+ conditions: [],
+ });
+ expect(
+ parseMediaQuery(
+ 'not all and (prefers-reduced-motion: reduce) and (min-width: 600px)',
+ ),
+ ).toEqual({
+ isNegated: true,
+ matchesMediaType: true,
+ conditions: [
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ ],
+ });
+ expect(parseMediaQuery('not (prefers-reduced-motion: reduce)')).toEqual({
+ isNegated: true,
+ matchesMediaType: true,
+ conditions: [],
+ });
+ expect(
+ parseMediaQuery('not print and ((min-width: 1px) and (max-width: 2px))'),
+ ).toEqual({
+ isNegated: true,
+ matchesMediaType: false,
+ conditions: [],
+ });
+ });
+
+ it('should reject malformed conditions even when negated', () => {
+ expect(parseMediaQuery('not print and garbage')).toBeNull();
+ expect(parseMediaQuery('not print and (hover)(pointer)')).toBeNull();
+ });
+
+ it('should close blocks left open at the end of the query', () => {
+ expect(parseMediaQuery('(min-width: 600px')?.conditions).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ ]);
+ expect(parseMediaQuery('not print and ((hover)')).toEqual({
+ isNegated: true,
+ matchesMediaType: false,
+ conditions: [],
+ });
+ });
+
+ it('should treat a negative resolution as an unknown condition', () => {
+ expect(parseMediaQuery('(min-resolution: -1dppx)')).toBeNull();
+ expect(parseMediaQuery('not print and (min-resolution: -1dppx)')).toEqual({
+ isNegated: true,
+ matchesMediaType: false,
+ conditions: [],
+ });
+ expect(
+ parseMediaQuery('(-webkit-min-device-pixel-ratio: -1)')?.conditions,
+ ).toEqual([
+ {
+ kind: 'numeric',
+ source: 'devicePixelRatio',
+ operator: '>=',
+ value: -1,
+ },
+ ]);
+ });
+
+ it('should convert absolute length units and accept signed numbers', () => {
+ const readFirstConditionValue = (mediaQuery: string) => {
+ const [firstCondition] = parseMediaQuery(mediaQuery)?.conditions ?? [];
+
+ return firstCondition?.kind === 'numeric' ? firstCondition.value : null;
+ };
+
+ expect(readFirstConditionValue('(max-width: 10in)')).toBeCloseTo(960);
+ expect(readFirstConditionValue('(min-width: 480pt)')).toBeCloseTo(640);
+ expect(readFirstConditionValue('(min-width: 40pc)')).toBeCloseTo(640);
+ expect(readFirstConditionValue('(max-width: 2.54cm)')).toBeCloseTo(96);
+ expect(readFirstConditionValue('(max-width: 25.4mm)')).toBeCloseTo(96);
+ expect(readFirstConditionValue('(max-width: 101.6Q)')).toBeCloseTo(96);
+ expect(readFirstConditionValue('(min-width: +600px)')).toBe(600);
+ expect(readFirstConditionValue('(min-width: -1px)')).toBe(-1);
+ expect(readFirstConditionValue('(min-resolution: +2dppx)')).toBe(2);
+ });
+
+ it('should require the webkit prefix on device pixel ratio features', () => {
+ expect(parseMediaQuery('(device-pixel-ratio: 2)')).toBeNull();
+ expect(parseMediaQuery('(min-device-pixel-ratio: 2)')).toBeNull();
+ expect(parseMediaQuery('(max-device-pixel-ratio: 2)')).toBeNull();
+ expect(parseMediaQuery('(device-pixel-ratio)')).toBeNull();
+ expect(parseMediaQuery('(device-pixel-ratio >= 2)')).toBeNull();
+ expect(
+ parseMediaQuery('(-webkit-device-pixel-ratio >= 2)')?.conditions,
+ ).toEqual([
+ {
+ kind: 'numeric',
+ source: 'devicePixelRatio',
+ operator: '>=',
+ value: 2,
+ },
+ ]);
+ });
+
+ it('should fold only ASCII letters to lowercase', () => {
+ expect(parseMediaQuery('(PREFERS-COLOR-SCHEME: DARK)')?.conditions).toEqual(
+ [{ kind: 'keyword', featureName: 'prefers-color-scheme', value: 'dark' }],
+ );
+ expect(parseMediaQuery('(prefers-color-scheme: dar\u212A)')).toBeNull();
+ });
+
+ it('should parse long whitespace runs in linear time', () => {
+ const WHITESPACE_RUN_LENGTH = 100000;
+ const whitespaceRun = ' '.repeat(WHITESPACE_RUN_LENGTH);
+
+ expect(
+ parseMediaQuery(`(min-width:${whitespaceRun}600px)`)?.conditions,
+ ).toEqual([
+ {
+ kind: 'numeric',
+ source: 'componentWidth',
+ operator: '>=',
+ value: 600,
+ },
+ ]);
+ expect(parseMediaQuery(`(min-width: 1px)${whitespaceRun}x`)).toBeNull();
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/splitCssAtTopLevel.test.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/splitCssAtTopLevel.test.ts
new file mode 100644
index 00000000000..e5545446699
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/__tests__/splitCssAtTopLevel.test.ts
@@ -0,0 +1,56 @@
+import { splitCssAtTopLevel } from '../splitCssAtTopLevel';
+
+describe('splitCssAtTopLevel', () => {
+ it('should split only on separators outside of blocks', () => {
+ expect(
+ splitCssAtTopLevel({
+ cssText: 'a, (b, c), [d, e], {f, g}, h',
+ separator: ',',
+ }),
+ ).toEqual(['a', ' (b, c)', ' [d, e]', ' {f, g}', ' h']);
+ });
+
+ it('should ignore separators inside strings, including strings ended by a newline', () => {
+ expect(
+ splitCssAtTopLevel({ cssText: '"a, b", c', separator: ',' }),
+ ).toEqual(['"a, b"', ' c']);
+ expect(splitCssAtTopLevel({ cssText: '"a\n, b', separator: ',' })).toEqual([
+ '"a\n',
+ ' b',
+ ]);
+ });
+
+ it('should replace each comment with a space and ignore separators inside it', () => {
+ expect(
+ splitCssAtTopLevel({ cssText: 'a/* , */b, c', separator: ',' }),
+ ).toEqual(['a b', ' c']);
+ expect(
+ splitCssAtTopLevel({ cssText: 'a /* b, c', separator: ',' }),
+ ).toEqual(['a ']);
+ expect(splitCssAtTopLevel({ cssText: '"/*", a', separator: ',' })).toEqual([
+ '"/*"',
+ ' a',
+ ]);
+ });
+
+ it('should close blocks left open at the end of the text', () => {
+ expect(
+ splitCssAtTopLevel({ cssText: 'a, (b, [c', separator: ',' }),
+ ).toEqual(['a', ' (b, [c])']);
+ });
+
+ it('should keep escaped separators', () => {
+ expect(
+ splitCssAtTopLevel({ cssText: 'a\\, b, c', separator: ',' }),
+ ).toEqual(['a\\, b', ' c']);
+ });
+
+ it('should split on a multi-character separator at the top level only', () => {
+ expect(
+ splitCssAtTopLevel({
+ cssText: '(a) and ((b) and (c)) and d',
+ separator: ' and ',
+ }),
+ ).toEqual(['(a)', '((b) and (c))', 'd']);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createMediaQueryEnvironmentSource.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createMediaQueryEnvironmentSource.ts
new file mode 100644
index 00000000000..da6956e0749
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createMediaQueryEnvironmentSource.ts
@@ -0,0 +1,64 @@
+import { fastDeepEqual } from 'twenty-shared/utils';
+
+import { DEFAULT_INPUT_MEDIA_FEATURES } from '@/constants/DefaultInputMediaFeatures';
+import { type WorkerGeometryStore } from '@/polyfills/geometry/types/WorkerGeometryStore';
+import { type MediaQueryEnvironment } from '@/polyfills/media-query/types/MediaQueryEnvironment';
+import { type MediaQueryEnvironmentSource } from '@/polyfills/media-query/types/MediaQueryEnvironmentSource';
+
+type CreateMediaQueryEnvironmentSourceInput = {
+ geometryStore: WorkerGeometryStore;
+ getColorScheme: () => MediaQueryEnvironment['colorScheme'];
+ subscribeToColorSchemeUpdates: (listener: () => void) => () => void;
+};
+
+export const createMediaQueryEnvironmentSource = ({
+ geometryStore,
+ getColorScheme,
+ subscribeToColorSchemeUpdates,
+}: CreateMediaQueryEnvironmentSourceInput): MediaQueryEnvironmentSource => {
+ const environmentUpdateListeners = new Set<() => void>();
+
+ const readUpstreamEnvironment = (): MediaQueryEnvironment => {
+ const viewportSnapshot = geometryStore.getViewportSnapshot();
+
+ return {
+ componentWidth: viewportSnapshot?.rootContainerClientWidth ?? 0,
+ componentHeight: viewportSnapshot?.rootContainerClientHeight ?? 0,
+ devicePixelRatio: viewportSnapshot?.devicePixelRatio ?? 1,
+ hover: viewportSnapshot?.hover ?? DEFAULT_INPUT_MEDIA_FEATURES.hover,
+ pointer:
+ viewportSnapshot?.pointer ?? DEFAULT_INPUT_MEDIA_FEATURES.pointer,
+ colorScheme: getColorScheme(),
+ };
+ };
+
+ let environment = readUpstreamEnvironment();
+
+ const handleUpstreamUpdate = () => {
+ const nextEnvironment = readUpstreamEnvironment();
+
+ if (fastDeepEqual(nextEnvironment, environment)) {
+ return;
+ }
+
+ environment = nextEnvironment;
+
+ for (const environmentUpdateListener of [...environmentUpdateListeners]) {
+ environmentUpdateListener();
+ }
+ };
+
+ geometryStore.subscribeToGeometryUpdates(handleUpstreamUpdate);
+ subscribeToColorSchemeUpdates(handleUpstreamUpdate);
+
+ return {
+ readEnvironment: () => environment,
+ subscribeToEnvironmentUpdates: (listener) => {
+ environmentUpdateListeners.add(listener);
+
+ return () => {
+ environmentUpdateListeners.delete(listener);
+ };
+ },
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createMediaQueryNumericCondition.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createMediaQueryNumericCondition.ts
new file mode 100644
index 00000000000..d460960d3f4
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createMediaQueryNumericCondition.ts
@@ -0,0 +1,25 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type MediaQueryComparisonOperator } from '@/polyfills/media-query/types/MediaQueryComparisonOperator';
+import { type MediaQueryNumericFeature } from '@/polyfills/media-query/types/MediaQueryNumericFeature';
+import { type ParsedMediaQueryCondition } from '@/polyfills/media-query/types/ParsedMediaQueryCondition';
+
+type CreateMediaQueryNumericConditionInput = {
+ feature: MediaQueryNumericFeature;
+ operator: MediaQueryComparisonOperator;
+ valueString: string;
+};
+
+export const createMediaQueryNumericCondition = ({
+ feature,
+ operator,
+ valueString,
+}: CreateMediaQueryNumericConditionInput): ParsedMediaQueryCondition | null => {
+ const value = feature.parseValue(valueString);
+
+ if (!isDefined(value)) {
+ return null;
+ }
+
+ return { kind: 'numeric', source: feature.source, operator, value };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createWorkerMediaQueryList.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createWorkerMediaQueryList.ts
new file mode 100644
index 00000000000..19cba753184
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createWorkerMediaQueryList.ts
@@ -0,0 +1,247 @@
+import { isFunction } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { type WorkerMediaQueryList } from '@/polyfills/media-query/types/WorkerMediaQueryList';
+import { type WorkerMediaQueryListEvent } from '@/polyfills/media-query/types/WorkerMediaQueryListEvent';
+import { type WorkerMediaQueryListener } from '@/polyfills/media-query/types/WorkerMediaQueryListener';
+import { createWorkerMediaQueryListEvent } from '@/polyfills/media-query/utils/createWorkerMediaQueryListEvent';
+import { resolveAddEventListenerOptions } from '@/polyfills/utils/resolveAddEventListenerOptions';
+
+const CHANGE_EVENT_TYPE = 'change';
+
+type CreateWorkerMediaQueryListInput = {
+ media: string;
+ evaluateMatches: () => boolean;
+ subscribeToEnvironmentUpdates: (listener: () => void) => () => void;
+ reportListenerError: (error: unknown) => void;
+};
+
+type ChangeListenerRegistration = {
+ listener: EventListenerOrEventListenerObject;
+ once: boolean;
+ removeAbortListener: (() => void) | null;
+};
+
+class WorkerMediaQueryListImplementation extends EventTarget {
+ #media: string;
+ #evaluateMatches: () => boolean;
+ #subscribeToEnvironmentUpdates: (listener: () => void) => () => void;
+ #reportListenerError: (error: unknown) => void;
+
+ #changeListenerRegistrations: ChangeListenerRegistration[] = [];
+ #onchangeHandler: WorkerMediaQueryListener | null = null;
+ #invokeOnchangeHandler: EventListener = (event) => {
+ this.#onchangeHandler?.call(this, event as WorkerMediaQueryListEvent);
+ };
+ #lastNotifiedMatches: boolean | null = null;
+ #unsubscribeFromEnvironmentUpdates: (() => void) | null = null;
+
+ constructor({
+ media,
+ evaluateMatches,
+ subscribeToEnvironmentUpdates,
+ reportListenerError,
+ }: CreateWorkerMediaQueryListInput) {
+ super();
+
+ this.#media = media;
+ this.#evaluateMatches = evaluateMatches;
+ this.#subscribeToEnvironmentUpdates = subscribeToEnvironmentUpdates;
+ this.#reportListenerError = reportListenerError;
+
+ super.addEventListener(CHANGE_EVENT_TYPE, (event) => {
+ this.#invokeChangeListeners(event);
+ });
+ }
+
+ get media(): string {
+ return this.#media;
+ }
+
+ get matches(): boolean {
+ return this.#evaluateMatches();
+ }
+
+ get onchange(): WorkerMediaQueryListener | null {
+ return this.#onchangeHandler;
+ }
+
+ set onchange(handler: WorkerMediaQueryListener | null) {
+ this.#onchangeHandler = isFunction(handler) ? handler : null;
+
+ if (isDefined(this.#onchangeHandler)) {
+ this.addEventListener(CHANGE_EVENT_TYPE, this.#invokeOnchangeHandler);
+ return;
+ }
+
+ this.removeEventListener(CHANGE_EVENT_TYPE, this.#invokeOnchangeHandler);
+ }
+
+ override addEventListener(
+ type: string,
+ listener: EventListenerOrEventListenerObject | null,
+ options?: AddEventListenerOptions | boolean | null,
+ ): void {
+ if (type !== CHANGE_EVENT_TYPE || !isDefined(listener)) {
+ super.addEventListener(type, listener, options ?? undefined);
+ return;
+ }
+
+ const { once, signal } = resolveAddEventListenerOptions(options);
+
+ if (
+ signal?.aborted === true ||
+ isDefined(this.#findChangeListenerRegistration(listener))
+ ) {
+ return;
+ }
+
+ const registration: ChangeListenerRegistration = {
+ listener,
+ once: once === true,
+ removeAbortListener: null,
+ };
+
+ if (isDefined(signal)) {
+ const handleAbort = () => {
+ this.#removeChangeListenerRegistration(registration);
+ };
+
+ signal.addEventListener('abort', handleAbort, { once: true });
+ registration.removeAbortListener = () => {
+ signal.removeEventListener('abort', handleAbort);
+ };
+ }
+
+ this.#changeListenerRegistrations.push(registration);
+ this.#ensureEnvironmentSubscription();
+ }
+
+ override removeEventListener(
+ type: string,
+ listener: EventListenerOrEventListenerObject | null,
+ options?: EventListenerOptions | boolean | null,
+ ): void {
+ if (type !== CHANGE_EVENT_TYPE || !isDefined(listener)) {
+ super.removeEventListener(type, listener, options ?? undefined);
+ return;
+ }
+
+ const registration = this.#findChangeListenerRegistration(listener);
+
+ if (isDefined(registration)) {
+ this.#removeChangeListenerRegistration(registration);
+ }
+ }
+
+ addListener(listener: WorkerMediaQueryListener): void {
+ this.addEventListener(CHANGE_EVENT_TYPE, listener as EventListener);
+ }
+
+ removeListener(listener: WorkerMediaQueryListener): void {
+ this.removeEventListener(CHANGE_EVENT_TYPE, listener as EventListener);
+ }
+
+ #findChangeListenerRegistration(
+ listener: EventListenerOrEventListenerObject,
+ ): ChangeListenerRegistration | undefined {
+ return this.#changeListenerRegistrations.find(
+ (registration) => registration.listener === listener,
+ );
+ }
+
+ #removeChangeListenerRegistration(
+ registration: ChangeListenerRegistration,
+ ): void {
+ const registrationIndex =
+ this.#changeListenerRegistrations.indexOf(registration);
+ const isRegistered = registrationIndex !== -1;
+
+ if (!isRegistered) {
+ return;
+ }
+
+ this.#changeListenerRegistrations.splice(registrationIndex, 1);
+ registration.removeAbortListener?.();
+ this.#releaseEnvironmentSubscriptionIfUnused();
+ }
+
+ #invokeChangeListeners(event: Event): void {
+ for (const registration of [...this.#changeListenerRegistrations]) {
+ if (!this.#changeListenerRegistrations.includes(registration)) {
+ continue;
+ }
+
+ if (registration.once) {
+ this.#removeChangeListenerRegistration(registration);
+ }
+
+ this.#invokeChangeListener(registration.listener, event);
+
+ if (event.cancelBubble) {
+ return;
+ }
+ }
+ }
+
+ #invokeChangeListener(
+ listener: EventListenerOrEventListenerObject,
+ event: Event,
+ ): void {
+ try {
+ if (isFunction(listener)) {
+ listener.call(this, event);
+ return;
+ }
+
+ listener.handleEvent(event);
+ } catch (error) {
+ this.#reportListenerError(error);
+ }
+ }
+
+ #ensureEnvironmentSubscription(): void {
+ if (isDefined(this.#unsubscribeFromEnvironmentUpdates)) {
+ return;
+ }
+
+ this.#lastNotifiedMatches = this.matches;
+ this.#unsubscribeFromEnvironmentUpdates =
+ this.#subscribeToEnvironmentUpdates(() => {
+ this.#handleEnvironmentUpdate();
+ });
+ }
+
+ #releaseEnvironmentSubscriptionIfUnused(): void {
+ if (
+ isNonEmptyArray(this.#changeListenerRegistrations) ||
+ !isDefined(this.#unsubscribeFromEnvironmentUpdates)
+ ) {
+ return;
+ }
+
+ this.#unsubscribeFromEnvironmentUpdates();
+ this.#unsubscribeFromEnvironmentUpdates = null;
+ }
+
+ #handleEnvironmentUpdate(): void {
+ const nextMatches = this.#evaluateMatches();
+
+ if (nextMatches === this.#lastNotifiedMatches) {
+ return;
+ }
+
+ this.#lastNotifiedMatches = nextMatches;
+
+ this.dispatchEvent(
+ createWorkerMediaQueryListEvent({
+ media: this.#media,
+ matches: nextMatches,
+ }),
+ );
+ }
+}
+
+export const createWorkerMediaQueryList = (
+ input: CreateWorkerMediaQueryListInput,
+): WorkerMediaQueryList => new WorkerMediaQueryListImplementation(input);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createWorkerMediaQueryListEvent.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createWorkerMediaQueryListEvent.ts
new file mode 100644
index 00000000000..2b99dadfc14
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/createWorkerMediaQueryListEvent.ts
@@ -0,0 +1,13 @@
+import { type WorkerMediaQueryListEvent } from '@/polyfills/media-query/types/WorkerMediaQueryListEvent';
+import { createEventWithReadonlyProperties } from '@/polyfills/utils/createEventWithReadonlyProperties';
+
+type CreateWorkerMediaQueryListEventInput = {
+ media: string;
+ matches: boolean;
+};
+
+export const createWorkerMediaQueryListEvent = ({
+ media,
+ matches,
+}: CreateWorkerMediaQueryListEventInput): WorkerMediaQueryListEvent =>
+ createEventWithReadonlyProperties('change', { media, matches });
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/evaluateParsedMediaQuery.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/evaluateParsedMediaQuery.ts
new file mode 100644
index 00000000000..73f925f70b6
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/evaluateParsedMediaQuery.ts
@@ -0,0 +1,23 @@
+import { type MediaQueryEnvironment } from '@/polyfills/media-query/types/MediaQueryEnvironment';
+import { type ParsedMediaQuery } from '@/polyfills/media-query/types/ParsedMediaQuery';
+import { evaluateParsedMediaQueryCondition } from '@/polyfills/media-query/utils/evaluateParsedMediaQueryCondition';
+
+type EvaluateParsedMediaQueryInput = {
+ parsedMediaQuery: ParsedMediaQuery;
+ environment: MediaQueryEnvironment;
+};
+
+export const evaluateParsedMediaQuery = ({
+ parsedMediaQuery,
+ environment,
+}: EvaluateParsedMediaQueryInput): boolean => {
+ const matchesWithoutNegation =
+ parsedMediaQuery.matchesMediaType &&
+ parsedMediaQuery.conditions.every((condition) =>
+ evaluateParsedMediaQueryCondition({ condition, environment }),
+ );
+
+ return parsedMediaQuery.isNegated
+ ? !matchesWithoutNegation
+ : matchesWithoutNegation;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/evaluateParsedMediaQueryCondition.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/evaluateParsedMediaQueryCondition.ts
new file mode 100644
index 00000000000..f4ff03ff923
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/evaluateParsedMediaQueryCondition.ts
@@ -0,0 +1,55 @@
+import { MEDIA_QUERY_KEYWORD_FEATURES } from '@/polyfills/media-query/constants/MediaQueryKeywordFeatures';
+import { type MediaQueryComparisonOperator } from '@/polyfills/media-query/types/MediaQueryComparisonOperator';
+import { type MediaQueryEnvironment } from '@/polyfills/media-query/types/MediaQueryEnvironment';
+import { type ParsedMediaQueryCondition } from '@/polyfills/media-query/types/ParsedMediaQueryCondition';
+
+const COMPARE_BY_OPERATOR: Record<
+ MediaQueryComparisonOperator,
+ (environmentValue: number, conditionValue: number) => boolean
+> = {
+ '<': (environmentValue, conditionValue) => environmentValue < conditionValue,
+ '<=': (environmentValue, conditionValue) =>
+ environmentValue <= conditionValue,
+ '>': (environmentValue, conditionValue) => environmentValue > conditionValue,
+ '>=': (environmentValue, conditionValue) =>
+ environmentValue >= conditionValue,
+ '=': (environmentValue, conditionValue) =>
+ environmentValue === conditionValue,
+};
+
+const NONE_KEYWORD_VALUE = 'none';
+
+type EvaluateParsedMediaQueryConditionInput = {
+ condition: ParsedMediaQueryCondition;
+ environment: MediaQueryEnvironment;
+};
+
+export const evaluateParsedMediaQueryCondition = ({
+ condition,
+ environment,
+}: EvaluateParsedMediaQueryConditionInput): boolean => {
+ if (condition.kind === 'non-zero') {
+ return environment[condition.source] !== 0;
+ }
+
+ if (condition.kind === 'not-none') {
+ return (
+ MEDIA_QUERY_KEYWORD_FEATURES.get(condition.featureName)?.readValue(
+ environment,
+ ) !== NONE_KEYWORD_VALUE
+ );
+ }
+
+ if (condition.kind === 'keyword') {
+ return (
+ MEDIA_QUERY_KEYWORD_FEATURES.get(condition.featureName)?.readValue(
+ environment,
+ ) === condition.value
+ );
+ }
+
+ return COMPARE_BY_OPERATOR[condition.operator](
+ environment[condition.source],
+ condition.value,
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/findCssCommentEndIndex.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/findCssCommentEndIndex.ts
new file mode 100644
index 00000000000..116adc0bc2d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/findCssCommentEndIndex.ts
@@ -0,0 +1,23 @@
+const COMMENT_START = '/*';
+
+const COMMENT_END = '*/';
+
+type FindCssCommentEndIndexInput = {
+ cssText: string;
+ commentStartIndex: number;
+};
+
+export const findCssCommentEndIndex = ({
+ cssText,
+ commentStartIndex,
+}: FindCssCommentEndIndexInput): number => {
+ const commentEndMarkerIndex = cssText.indexOf(
+ COMMENT_END,
+ commentStartIndex + COMMENT_START.length,
+ );
+ const isUnterminatedComment = commentEndMarkerIndex === -1;
+
+ return isUnterminatedComment
+ ? cssText.length
+ : commentEndMarkerIndex + COMMENT_END.length;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/findCssEscapeEndIndex.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/findCssEscapeEndIndex.ts
new file mode 100644
index 00000000000..8a438208ee3
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/findCssEscapeEndIndex.ts
@@ -0,0 +1,24 @@
+const CARRIAGE_RETURN_LINE_FEED = '\r\n';
+
+const SINGLE_ESCAPED_CHARACTER_LENGTH = 1;
+
+type FindCssEscapeEndIndexInput = {
+ cssText: string;
+ escapeStartIndex: number;
+};
+
+export const findCssEscapeEndIndex = ({
+ cssText,
+ escapeStartIndex,
+}: FindCssEscapeEndIndexInput): number => {
+ const escapedCharacterIndex = escapeStartIndex + 1;
+ const escapesCarriageReturnLineFeed = cssText.startsWith(
+ CARRIAGE_RETURN_LINE_FEED,
+ escapedCharacterIndex,
+ );
+ const escapedTextLength = escapesCarriageReturnLineFeed
+ ? CARRIAGE_RETURN_LINE_FEED.length
+ : SINGLE_ESCAPED_CHARACTER_LENGTH;
+
+ return Math.min(escapedCharacterIndex + escapedTextLength, cssText.length);
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/findCssStringEndIndex.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/findCssStringEndIndex.ts
new file mode 100644
index 00000000000..b669dfd4be2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/findCssStringEndIndex.ts
@@ -0,0 +1,41 @@
+import { CSS_ESCAPE_CHARACTER } from '@/polyfills/media-query/constants/CssEscapeCharacter';
+import { findCssEscapeEndIndex } from '@/polyfills/media-query/utils/findCssEscapeEndIndex';
+
+const CSS_NEWLINE_CHARACTERS = new Set(['\n', '\r', '\f']);
+
+type FindCssStringEndIndexInput = {
+ cssText: string;
+ stringStartIndex: number;
+};
+
+export const findCssStringEndIndex = ({
+ cssText,
+ stringStartIndex,
+}: FindCssStringEndIndexInput): number => {
+ const quoteCharacter = cssText[stringStartIndex];
+
+ let characterIndex = stringStartIndex + 1;
+
+ while (characterIndex < cssText.length) {
+ const character = cssText[characterIndex];
+
+ if (character === CSS_ESCAPE_CHARACTER) {
+ characterIndex = findCssEscapeEndIndex({
+ cssText,
+ escapeStartIndex: characterIndex,
+ });
+ continue;
+ }
+
+ const isStringTerminator =
+ character === quoteCharacter || CSS_NEWLINE_CHARACTERS.has(character);
+
+ if (isStringTerminator) {
+ return characterIndex + 1;
+ }
+
+ characterIndex += 1;
+ }
+
+ return cssText.length;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/getNextExpectedCssClosingDelimiters.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/getNextExpectedCssClosingDelimiters.ts
new file mode 100644
index 00000000000..8a6d11eb65c
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/getNextExpectedCssClosingDelimiters.ts
@@ -0,0 +1,28 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { CSS_CLOSING_DELIMITERS_BY_OPENING_DELIMITER } from '@/polyfills/media-query/constants/CssClosingDelimitersByOpeningDelimiter';
+
+type GetNextExpectedCssClosingDelimitersInput = {
+ expectedClosingDelimiters: string[];
+ character: string;
+};
+
+export const getNextExpectedCssClosingDelimiters = ({
+ expectedClosingDelimiters,
+ character,
+}: GetNextExpectedCssClosingDelimitersInput): string[] => {
+ const openedBlockClosingDelimiter =
+ CSS_CLOSING_DELIMITERS_BY_OPENING_DELIMITER.get(character);
+
+ if (isDefined(openedBlockClosingDelimiter)) {
+ return [...expectedClosingDelimiters, openedBlockClosingDelimiter];
+ }
+
+ const innermostExpectedClosingDelimiter =
+ expectedClosingDelimiters[expectedClosingDelimiters.length - 1];
+ const closesInnermostBlock = character === innermostExpectedClosingDelimiter;
+
+ return closesInnermostBlock
+ ? expectedClosingDelimiters.slice(0, -1)
+ : expectedClosingDelimiters;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/installMatchMediaPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/installMatchMediaPolyfill.ts
new file mode 100644
index 00000000000..3d9ddfafdd5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/installMatchMediaPolyfill.ts
@@ -0,0 +1,47 @@
+import { type MediaQueryEnvironmentSource } from '@/polyfills/media-query/types/MediaQueryEnvironmentSource';
+import { type WorkerMediaQueryList } from '@/polyfills/media-query/types/WorkerMediaQueryList';
+import { createWorkerMediaQueryList } from '@/polyfills/media-query/utils/createWorkerMediaQueryList';
+import { evaluateParsedMediaQuery } from '@/polyfills/media-query/utils/evaluateParsedMediaQuery';
+import { parseMediaQueryList } from '@/polyfills/media-query/utils/parseMediaQueryList';
+import { reportErrorToPolyfillWindow } from '@/polyfills/utils/reportErrorToPolyfillWindow';
+import { resolveGlobalScopeInstallTargets } from '@/polyfills/utils/resolveGlobalScopeInstallTargets';
+import { resolvePolyfillWindow } from '@/polyfills/utils/resolvePolyfillWindow';
+
+type InstallMatchMediaPolyfillInput = {
+ globalScope: Record<string, unknown>;
+ environmentSource: MediaQueryEnvironmentSource;
+};
+
+export const installMatchMediaPolyfill = ({
+ globalScope,
+ environmentSource,
+}: InstallMatchMediaPolyfillInput): void => {
+ const polyfillWindow = resolvePolyfillWindow(globalScope);
+
+ const reportListenerError = (error: unknown): void => {
+ reportErrorToPolyfillWindow({ polyfillWindow, error });
+ };
+
+ const matchMedia = (mediaQuery: unknown): WorkerMediaQueryList => {
+ const media = String(mediaQuery);
+ const parsedMediaQueryList = parseMediaQueryList(media);
+
+ return createWorkerMediaQueryList({
+ media,
+ evaluateMatches: () => {
+ const environment = environmentSource.readEnvironment();
+
+ return parsedMediaQueryList.some((parsedMediaQuery) =>
+ evaluateParsedMediaQuery({ parsedMediaQuery, environment }),
+ );
+ },
+ subscribeToEnvironmentUpdates:
+ environmentSource.subscribeToEnvironmentUpdates,
+ reportListenerError,
+ });
+ };
+
+ for (const installTarget of resolveGlobalScopeInstallTargets(globalScope)) {
+ installTarget.matchMedia = matchMedia;
+ }
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/isMediaQueryRangeOperator.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/isMediaQueryRangeOperator.ts
new file mode 100644
index 00000000000..6f3f0680e18
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/isMediaQueryRangeOperator.ts
@@ -0,0 +1,14 @@
+import { type MediaQueryComparisonOperator } from '@/polyfills/media-query/types/MediaQueryComparisonOperator';
+
+const MEDIA_QUERY_RANGE_OPERATORS = new Set<string>([
+ '<',
+ '<=',
+ '>',
+ '>=',
+ '=',
+]);
+
+export const isMediaQueryRangeOperator = (
+ value: string,
+): value is MediaQueryComparisonOperator =>
+ MEDIA_QUERY_RANGE_OPERATORS.has(value);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/isMediaQueryTypeIdentifier.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/isMediaQueryTypeIdentifier.ts
new file mode 100644
index 00000000000..e692eb70864
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/isMediaQueryTypeIdentifier.ts
@@ -0,0 +1,7 @@
+import { MEDIA_QUERY_RESERVED_KEYWORDS } from '@/polyfills/media-query/constants/MediaQueryReservedKeywords';
+
+const MEDIA_TYPE_IDENTIFIER_PATTERN = /^-?[a-z_][a-z0-9_-]*$/;
+
+export const isMediaQueryTypeIdentifier = (queryPart: string): boolean =>
+ MEDIA_TYPE_IDENTIFIER_PATTERN.test(queryPart) &&
+ !MEDIA_QUERY_RESERVED_KEYWORDS.has(queryPart);
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/isParenthesizedCssBlock.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/isParenthesizedCssBlock.ts
new file mode 100644
index 00000000000..55bf9ab376f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/isParenthesizedCssBlock.ts
@@ -0,0 +1,41 @@
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
+import { getNextExpectedCssClosingDelimiters } from '@/polyfills/media-query/utils/getNextExpectedCssClosingDelimiters';
+import { readCssTextSegment } from '@/polyfills/media-query/utils/readCssTextSegment';
+
+const OPENING_PARENTHESIS = '(';
+
+export const isParenthesizedCssBlock = (cssText: string): boolean => {
+ if (!cssText.startsWith(OPENING_PARENTHESIS)) {
+ return false;
+ }
+
+ let expectedClosingDelimiters: string[] = [];
+ let characterIndex = 0;
+
+ while (characterIndex < cssText.length) {
+ const segment = readCssTextSegment({
+ cssText,
+ startIndex: characterIndex,
+ });
+
+ characterIndex = segment.endIndex;
+
+ if (!segment.isPlainCharacter) {
+ continue;
+ }
+
+ expectedClosingDelimiters = getNextExpectedCssClosingDelimiters({
+ expectedClosingDelimiters,
+ character: segment.text,
+ });
+
+ const isOpeningBlockClosed = !isNonEmptyArray(expectedClosingDelimiters);
+
+ if (isOpeningBlockClosed) {
+ return characterIndex === cssText.length;
+ }
+ }
+
+ return false;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/lowercaseAsciiLetters.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/lowercaseAsciiLetters.ts
new file mode 100644
index 00000000000..f652e4f1463
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/lowercaseAsciiLetters.ts
@@ -0,0 +1,6 @@
+const ASCII_UPPERCASE_LETTER_PATTERN = /[A-Z]/g;
+
+export const lowercaseAsciiLetters = (value: string): string =>
+ value.replace(ASCII_UPPERCASE_LETTER_PATTERN, (uppercaseLetter) =>
+ uppercaseLetter.toLowerCase(),
+ );
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/normalizeMediaQueryString.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/normalizeMediaQueryString.ts
new file mode 100644
index 00000000000..bcdc57d4fe4
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/normalizeMediaQueryString.ts
@@ -0,0 +1,25 @@
+import { ASCII_WHITESPACE_REGEX } from '@/polyfills/dom/constants/AsciiWhitespaceRegex';
+import { lowercaseAsciiLetters } from '@/polyfills/media-query/utils/lowercaseAsciiLetters';
+import { trimCssWhitespace } from '@/polyfills/media-query/utils/trimCssWhitespace';
+
+const CSS_WHITESPACE_RUN_PATTERN = new RegExp(
+ ASCII_WHITESPACE_REGEX.source,
+ 'g',
+);
+
+const SINGLE_SPACE = ' ';
+
+const CLOSING_PARENTHESIS_FOLLOWED_BY_AND_PATTERN = /\) ?and /g;
+
+const CLOSING_PARENTHESIS_AND_SEPARATOR = ') and ';
+
+export const normalizeMediaQueryString = (mediaQueryString: string): string =>
+ lowercaseAsciiLetters(
+ trimCssWhitespace(mediaQueryString).replace(
+ CSS_WHITESPACE_RUN_PATTERN,
+ SINGLE_SPACE,
+ ),
+ ).replace(
+ CLOSING_PARENTHESIS_FOLLOWED_BY_AND_PATTERN,
+ CLOSING_PARENTHESIS_AND_SEPARATOR,
+ );
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQuery.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQuery.ts
new file mode 100644
index 00000000000..6331cdc7b39
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQuery.ts
@@ -0,0 +1,73 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { MATCHING_MEDIA_TYPES } from '@/polyfills/media-query/constants/MatchingMediaTypes';
+import { type ParsedMediaQuery } from '@/polyfills/media-query/types/ParsedMediaQuery';
+import { isMediaQueryTypeIdentifier } from '@/polyfills/media-query/utils/isMediaQueryTypeIdentifier';
+import { normalizeMediaQueryString } from '@/polyfills/media-query/utils/normalizeMediaQueryString';
+import { parseMediaQueryConditionParts } from '@/polyfills/media-query/utils/parseMediaQueryConditionParts';
+import { parseMediaQueryModifier } from '@/polyfills/media-query/utils/parseMediaQueryModifier';
+import { splitCssAtTopLevel } from '@/polyfills/media-query/utils/splitCssAtTopLevel';
+
+const MEDIA_QUERY_PART_SEPARATOR = ' and ';
+
+const CONDITION_OPENING_PARENTHESIS = '(';
+
+export const parseMediaQuery = (
+ mediaQueryString: string,
+): ParsedMediaQuery | null => {
+ const normalizedQuery = normalizeMediaQueryString(mediaQueryString);
+
+ if (!isNonEmptyString(normalizedQuery)) {
+ return null;
+ }
+
+ const [firstQueryPart, ...followingQueryParts] = splitCssAtTopLevel({
+ cssText: normalizedQuery,
+ separator: MEDIA_QUERY_PART_SEPARATOR,
+ });
+
+ const { modifier, remainingFirstPart } =
+ parseMediaQueryModifier(firstQueryPart);
+
+ const isNegated = modifier === 'not';
+ const startsWithCondition = remainingFirstPart.startsWith(
+ CONDITION_OPENING_PARENTHESIS,
+ );
+ const isOnlyWithoutMediaType = modifier === 'only' && startsWithCondition;
+ const isNegatedConditionFollowedByAnd =
+ isNegated && startsWithCondition && isNonEmptyArray(followingQueryParts);
+ const isInvalidMediaType =
+ !startsWithCondition && !isMediaQueryTypeIdentifier(remainingFirstPart);
+
+ if (
+ isOnlyWithoutMediaType ||
+ isNegatedConditionFollowedByAnd ||
+ isInvalidMediaType
+ ) {
+ return null;
+ }
+
+ const parsedConditionParts = parseMediaQueryConditionParts(
+ startsWithCondition
+ ? [remainingFirstPart, ...followingQueryParts]
+ : followingQueryParts,
+ );
+
+ if (!isDefined(parsedConditionParts)) {
+ return null;
+ }
+
+ const canNeverMatch = parsedConditionParts.hasUnknownCondition && !isNegated;
+
+ if (canNeverMatch) {
+ return null;
+ }
+
+ return {
+ isNegated,
+ matchesMediaType:
+ startsWithCondition || MATCHING_MEDIA_TYPES.has(remainingFirstPart),
+ conditions: parsedConditionParts.knownConditions,
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryBareNumericFeature.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryBareNumericFeature.ts
new file mode 100644
index 00000000000..ca924b734c9
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryBareNumericFeature.ts
@@ -0,0 +1,16 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type MediaQueryNumericFeature } from '@/polyfills/media-query/types/MediaQueryNumericFeature';
+import { parseMediaQueryNumericFeatureName } from '@/polyfills/media-query/utils/parseMediaQueryNumericFeatureName';
+
+export const parseMediaQueryBareNumericFeature = (
+ featureName: string,
+): MediaQueryNumericFeature | null => {
+ const numericFeatureName = parseMediaQueryNumericFeatureName(featureName);
+
+ if (!isDefined(numericFeatureName) || numericFeatureName.operator !== '=') {
+ return null;
+ }
+
+ return numericFeatureName.feature;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryBooleanCondition.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryBooleanCondition.ts
new file mode 100644
index 00000000000..844e3873e59
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryBooleanCondition.ts
@@ -0,0 +1,21 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { MEDIA_QUERY_KEYWORD_FEATURES } from '@/polyfills/media-query/constants/MediaQueryKeywordFeatures';
+import { type ParsedMediaQueryCondition } from '@/polyfills/media-query/types/ParsedMediaQueryCondition';
+import { parseMediaQueryBareNumericFeature } from '@/polyfills/media-query/utils/parseMediaQueryBareNumericFeature';
+
+export const parseMediaQueryBooleanCondition = (
+ featureName: string,
+): ParsedMediaQueryCondition[] | null => {
+ if (MEDIA_QUERY_KEYWORD_FEATURES.has(featureName)) {
+ return [{ kind: 'not-none', featureName }];
+ }
+
+ const feature = parseMediaQueryBareNumericFeature(featureName);
+
+ if (!isDefined(feature)) {
+ return null;
+ }
+
+ return [{ kind: 'non-zero', source: feature.source }];
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryCondition.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryCondition.ts
new file mode 100644
index 00000000000..f7d1c558989
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryCondition.ts
@@ -0,0 +1,50 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ParsedMediaQueryCondition } from '@/polyfills/media-query/types/ParsedMediaQueryCondition';
+import { parseMediaQueryBooleanCondition } from '@/polyfills/media-query/utils/parseMediaQueryBooleanCondition';
+import { parseMediaQueryPlainCondition } from '@/polyfills/media-query/utils/parseMediaQueryPlainCondition';
+import { parseMediaQueryRangeCondition } from '@/polyfills/media-query/utils/parseMediaQueryRangeCondition';
+import { trimCssWhitespace } from '@/polyfills/media-query/utils/trimCssWhitespace';
+
+const CONDITION_WRAPPING_PARENTHESES_PATTERN = /^\(([\s\S]*)\)$/;
+
+export const parseMediaQueryCondition = (
+ conditionString: string,
+): ParsedMediaQueryCondition[] | null => {
+ const conditionMatch = conditionString.match(
+ CONDITION_WRAPPING_PARENTHESES_PATTERN,
+ );
+
+ if (!isDefined(conditionMatch)) {
+ return null;
+ }
+
+ const [, wrappedConditionContent] = conditionMatch;
+ const conditionContent = trimCssWhitespace(wrappedConditionContent);
+ const colonIndex = conditionContent.indexOf(':');
+ const hasFeatureNameValueSeparator = colonIndex !== -1;
+
+ if (!hasFeatureNameValueSeparator) {
+ return (
+ parseMediaQueryBooleanCondition(conditionContent) ??
+ parseMediaQueryRangeCondition(conditionContent)
+ );
+ }
+
+ const featureName = trimCssWhitespace(conditionContent.slice(0, colonIndex));
+ const featureValue = trimCssWhitespace(
+ conditionContent.slice(colonIndex + 1),
+ );
+
+ if (!isNonEmptyString(featureName) || !isNonEmptyString(featureValue)) {
+ return null;
+ }
+
+ const plainCondition = parseMediaQueryPlainCondition({
+ featureName,
+ featureValue,
+ });
+
+ return isDefined(plainCondition) ? [plainCondition] : null;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryConditionParts.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryConditionParts.ts
new file mode 100644
index 00000000000..b42407e1e30
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryConditionParts.ts
@@ -0,0 +1,31 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ParsedMediaQueryCondition } from '@/polyfills/media-query/types/ParsedMediaQueryCondition';
+import { type ParsedMediaQueryConditionParts } from '@/polyfills/media-query/types/ParsedMediaQueryConditionParts';
+import { isParenthesizedCssBlock } from '@/polyfills/media-query/utils/isParenthesizedCssBlock';
+import { parseMediaQueryCondition } from '@/polyfills/media-query/utils/parseMediaQueryCondition';
+
+export const parseMediaQueryConditionParts = (
+ conditionParts: string[],
+): ParsedMediaQueryConditionParts | null => {
+ const knownConditions: ParsedMediaQueryCondition[] = [];
+
+ let hasUnknownCondition = false;
+
+ for (const conditionPart of conditionParts) {
+ if (!isParenthesizedCssBlock(conditionPart)) {
+ return null;
+ }
+
+ const parsedConditions = parseMediaQueryCondition(conditionPart);
+
+ if (!isDefined(parsedConditions)) {
+ hasUnknownCondition = true;
+ continue;
+ }
+
+ knownConditions.push(...parsedConditions);
+ }
+
+ return { knownConditions, hasUnknownCondition };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryDevicePixelRatioValue.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryDevicePixelRatioValue.ts
new file mode 100644
index 00000000000..f9ffc1bf0ed
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryDevicePixelRatioValue.ts
@@ -0,0 +1,16 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { parseMediaQueryNumericValueParts } from '@/polyfills/media-query/utils/parseMediaQueryNumericValueParts';
+
+export const parseMediaQueryDevicePixelRatioValue = (
+ featureValue: string,
+): number | null => {
+ const valueParts = parseMediaQueryNumericValueParts(featureValue);
+
+ if (!isDefined(valueParts) || isNonEmptyString(valueParts.unit)) {
+ return null;
+ }
+
+ return valueParts.numericValue;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryLengthToPixels.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryLengthToPixels.ts
new file mode 100644
index 00000000000..6efac53f4fc
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryLengthToPixels.ts
@@ -0,0 +1,31 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { MEDIA_QUERY_LENGTH_UNIT_TO_PIXELS } from '@/polyfills/media-query/constants/MediaQueryLengthUnitToPixels';
+import { parseMediaQueryNumericValueParts } from '@/polyfills/media-query/utils/parseMediaQueryNumericValueParts';
+
+export const parseMediaQueryLengthToPixels = (
+ lengthString: string,
+): number | null => {
+ const lengthParts = parseMediaQueryNumericValueParts(lengthString);
+
+ if (!isDefined(lengthParts)) {
+ return null;
+ }
+
+ const { numericValue, unit } = lengthParts;
+
+ if (!isNonEmptyString(unit)) {
+ const isZeroLength = numericValue === 0;
+
+ return isZeroLength ? 0 : null;
+ }
+
+ const pixelsPerUnit = MEDIA_QUERY_LENGTH_UNIT_TO_PIXELS.get(unit);
+
+ if (!isDefined(pixelsPerUnit)) {
+ return null;
+ }
+
+ return numericValue * pixelsPerUnit;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryList.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryList.ts
new file mode 100644
index 00000000000..14cea7ede3c
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryList.ts
@@ -0,0 +1,34 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { type ParsedMediaQuery } from '@/polyfills/media-query/types/ParsedMediaQuery';
+import { parseMediaQuery } from '@/polyfills/media-query/utils/parseMediaQuery';
+import { splitCssAtTopLevel } from '@/polyfills/media-query/utils/splitCssAtTopLevel';
+import { trimCssWhitespace } from '@/polyfills/media-query/utils/trimCssWhitespace';
+
+const MEDIA_QUERY_LIST_SEPARATOR = ',';
+
+const MATCH_ALL_MEDIA_QUERY = 'all';
+
+export const parseMediaQueryList = (
+ mediaQueryListString: string,
+): ParsedMediaQuery[] => {
+ const [firstMediaQueryString, ...otherMediaQueryStrings] = splitCssAtTopLevel(
+ {
+ cssText: mediaQueryListString,
+ separator: MEDIA_QUERY_LIST_SEPARATOR,
+ },
+ );
+
+ const isEmptyMediaQueryList =
+ !isNonEmptyArray(otherMediaQueryStrings) &&
+ !isNonEmptyString(trimCssWhitespace(firstMediaQueryString));
+
+ const mediaQueryStrings = isEmptyMediaQueryList
+ ? [MATCH_ALL_MEDIA_QUERY]
+ : [firstMediaQueryString, ...otherMediaQueryStrings];
+
+ return mediaQueryStrings
+ .map((mediaQueryString) => parseMediaQuery(mediaQueryString))
+ .filter(isDefined);
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryModifier.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryModifier.ts
new file mode 100644
index 00000000000..f46dc55ac8a
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryModifier.ts
@@ -0,0 +1,27 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { ASCII_WHITESPACE_REGEX } from '@/polyfills/dom/constants/AsciiWhitespaceRegex';
+import { type ParsedMediaQueryModifier } from '@/polyfills/media-query/types/ParsedMediaQueryModifier';
+
+const MODIFIER_PATTERN = new RegExp(
+ `^(not|only)${ASCII_WHITESPACE_REGEX.source}`,
+);
+
+export const parseMediaQueryModifier = (
+ firstQueryPart: string,
+): ParsedMediaQueryModifier => {
+ const modifierMatch = firstQueryPart.match(MODIFIER_PATTERN);
+
+ if (!isDefined(modifierMatch)) {
+ return { modifier: null, remainingFirstPart: firstQueryPart };
+ }
+
+ const [modifierWithTrailingWhitespace, modifierKeyword] = modifierMatch;
+
+ return {
+ modifier: modifierKeyword === 'not' ? 'not' : 'only',
+ remainingFirstPart: firstQueryPart.slice(
+ modifierWithTrailingWhitespace.length,
+ ),
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryNumericFeatureName.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryNumericFeatureName.ts
new file mode 100644
index 00000000000..f589382b57f
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryNumericFeatureName.ts
@@ -0,0 +1,61 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { MEDIA_QUERY_NUMERIC_FEATURES } from '@/polyfills/media-query/constants/MediaQueryNumericFeatures';
+import { type MediaQueryComparisonOperator } from '@/polyfills/media-query/types/MediaQueryComparisonOperator';
+import { type ParsedMediaQueryNumericFeatureName } from '@/polyfills/media-query/types/ParsedMediaQueryNumericFeatureName';
+
+const WEBKIT_FEATURE_PREFIX = '-webkit-';
+
+const WEBKIT_PREFIXED_BASE_FEATURE_NAME = 'device-pixel-ratio';
+
+const MINIMUM_FEATURE_PREFIX = 'min-';
+
+const MAXIMUM_FEATURE_PREFIX = 'max-';
+
+const parseComparisonPrefix = (
+ featureName: string,
+): { operator: MediaQueryComparisonOperator; baseFeatureName: string } => {
+ if (featureName.startsWith(MINIMUM_FEATURE_PREFIX)) {
+ return {
+ operator: '>=',
+ baseFeatureName: featureName.slice(MINIMUM_FEATURE_PREFIX.length),
+ };
+ }
+
+ if (featureName.startsWith(MAXIMUM_FEATURE_PREFIX)) {
+ return {
+ operator: '<=',
+ baseFeatureName: featureName.slice(MAXIMUM_FEATURE_PREFIX.length),
+ };
+ }
+
+ return { operator: '=', baseFeatureName: featureName };
+};
+
+export const parseMediaQueryNumericFeatureName = (
+ featureName: string,
+): ParsedMediaQueryNumericFeatureName | null => {
+ const isWebkitPrefixed = featureName.startsWith(WEBKIT_FEATURE_PREFIX);
+ const unprefixedFeatureName = isWebkitPrefixed
+ ? featureName.slice(WEBKIT_FEATURE_PREFIX.length)
+ : featureName;
+
+ const { operator, baseFeatureName } = parseComparisonPrefix(
+ unprefixedFeatureName,
+ );
+
+ const isWebkitPrefixRequired =
+ baseFeatureName === WEBKIT_PREFIXED_BASE_FEATURE_NAME;
+
+ if (isWebkitPrefixed !== isWebkitPrefixRequired) {
+ return null;
+ }
+
+ const feature = MEDIA_QUERY_NUMERIC_FEATURES.get(baseFeatureName);
+
+ if (!isDefined(feature)) {
+ return null;
+ }
+
+ return { operator, feature };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryNumericValueParts.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryNumericValueParts.ts
new file mode 100644
index 00000000000..9b36bae03e4
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryNumericValueParts.ts
@@ -0,0 +1,18 @@
+import { isDefined } from 'twenty-shared/utils';
+
+const MEDIA_QUERY_NUMERIC_VALUE_PATTERN =
+ /^([+-]?(?:\d+(?:\.\d+)?|\.\d+))([a-z]*)$/;
+
+export const parseMediaQueryNumericValueParts = (
+ valueString: string,
+): { numericValue: number; unit: string } | null => {
+ const valueMatch = valueString.match(MEDIA_QUERY_NUMERIC_VALUE_PATTERN);
+
+ if (!isDefined(valueMatch)) {
+ return null;
+ }
+
+ const [, numericValuePart, unit] = valueMatch;
+
+ return { numericValue: Number(numericValuePart), unit };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryPlainCondition.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryPlainCondition.ts
new file mode 100644
index 00000000000..42fb16dad38
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryPlainCondition.ts
@@ -0,0 +1,36 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { MEDIA_QUERY_KEYWORD_FEATURES } from '@/polyfills/media-query/constants/MediaQueryKeywordFeatures';
+import { type ParsedMediaQueryCondition } from '@/polyfills/media-query/types/ParsedMediaQueryCondition';
+import { createMediaQueryNumericCondition } from '@/polyfills/media-query/utils/createMediaQueryNumericCondition';
+import { parseMediaQueryNumericFeatureName } from '@/polyfills/media-query/utils/parseMediaQueryNumericFeatureName';
+
+type ParseMediaQueryPlainConditionInput = {
+ featureName: string;
+ featureValue: string;
+};
+
+export const parseMediaQueryPlainCondition = ({
+ featureName,
+ featureValue,
+}: ParseMediaQueryPlainConditionInput): ParsedMediaQueryCondition | null => {
+ const keywordFeature = MEDIA_QUERY_KEYWORD_FEATURES.get(featureName);
+
+ if (isDefined(keywordFeature)) {
+ return keywordFeature.values.has(featureValue)
+ ? { kind: 'keyword', featureName, value: featureValue }
+ : null;
+ }
+
+ const numericFeatureName = parseMediaQueryNumericFeatureName(featureName);
+
+ if (!isDefined(numericFeatureName)) {
+ return null;
+ }
+
+ return createMediaQueryNumericCondition({
+ feature: numericFeatureName.feature,
+ operator: numericFeatureName.operator,
+ valueString: featureValue,
+ });
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryRangeCondition.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryRangeCondition.ts
new file mode 100644
index 00000000000..b7223f829c6
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryRangeCondition.ts
@@ -0,0 +1,93 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type MediaQueryComparisonOperator } from '@/polyfills/media-query/types/MediaQueryComparisonOperator';
+import { type ParsedMediaQueryCondition } from '@/polyfills/media-query/types/ParsedMediaQueryCondition';
+import { createMediaQueryNumericCondition } from '@/polyfills/media-query/utils/createMediaQueryNumericCondition';
+import { isMediaQueryRangeOperator } from '@/polyfills/media-query/utils/isMediaQueryRangeOperator';
+import { parseMediaQueryBareNumericFeature } from '@/polyfills/media-query/utils/parseMediaQueryBareNumericFeature';
+import { parseMediaQueryRangeParts } from '@/polyfills/media-query/utils/parseMediaQueryRangeParts';
+
+const FLIPPED_COMPARISON_OPERATORS: Record<
+ MediaQueryComparisonOperator,
+ MediaQueryComparisonOperator
+> = {
+ '<': '>',
+ '<=': '>=',
+ '>': '<',
+ '>=': '<=',
+ '=': '=',
+};
+
+const isLessThanOperator = (operator: MediaQueryComparisonOperator): boolean =>
+ operator === '<' || operator === '<=';
+
+export const parseMediaQueryRangeCondition = (
+ conditionContent: string,
+): ParsedMediaQueryCondition[] | null => {
+ const rangeParts = parseMediaQueryRangeParts(conditionContent);
+
+ if (!isDefined(rangeParts)) {
+ return null;
+ }
+
+ const [leftOperand, middleOperand, rightOperand] = rangeParts.operands;
+ const [firstOperator, secondOperator] = rangeParts.operators;
+
+ if (!isMediaQueryRangeOperator(firstOperator)) {
+ return null;
+ }
+
+ const leftFeature = parseMediaQueryBareNumericFeature(leftOperand);
+ const hasSecondOperator = isDefined(secondOperator);
+
+ if (isDefined(leftFeature) && hasSecondOperator) {
+ return null;
+ }
+
+ if (isDefined(leftFeature)) {
+ const condition = createMediaQueryNumericCondition({
+ feature: leftFeature,
+ operator: firstOperator,
+ valueString: middleOperand,
+ });
+
+ return isDefined(condition) ? [condition] : null;
+ }
+
+ const middleFeature = parseMediaQueryBareNumericFeature(middleOperand);
+
+ if (!isDefined(middleFeature)) {
+ return null;
+ }
+
+ const firstCondition = createMediaQueryNumericCondition({
+ feature: middleFeature,
+ operator: FLIPPED_COMPARISON_OPERATORS[firstOperator],
+ valueString: leftOperand,
+ });
+
+ if (!isDefined(firstCondition)) {
+ return null;
+ }
+
+ if (!hasSecondOperator) {
+ return [firstCondition];
+ }
+
+ if (
+ firstOperator === '=' ||
+ !isMediaQueryRangeOperator(secondOperator) ||
+ secondOperator === '=' ||
+ isLessThanOperator(firstOperator) !== isLessThanOperator(secondOperator)
+ ) {
+ return null;
+ }
+
+ const secondCondition = createMediaQueryNumericCondition({
+ feature: middleFeature,
+ operator: secondOperator,
+ valueString: rightOperand,
+ });
+
+ return isDefined(secondCondition) ? [firstCondition, secondCondition] : null;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryRangeParts.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryRangeParts.ts
new file mode 100644
index 00000000000..e3fc29f2c1b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryRangeParts.ts
@@ -0,0 +1,40 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type MediaQueryRangeParts } from '@/polyfills/media-query/types/MediaQueryRangeParts';
+import { trimCssWhitespace } from '@/polyfills/media-query/utils/trimCssWhitespace';
+
+const RANGE_OPERATOR_SPLIT_PATTERN = /(<=|>=|<|>|=)/;
+
+const ONE_OPERATOR_PART_COUNT = 3;
+
+const TWO_OPERATOR_PART_COUNT = 5;
+
+const isOperandPartIndex = (partIndex: number): boolean => partIndex % 2 === 0;
+
+export const parseMediaQueryRangeParts = (
+ conditionContent: string,
+): MediaQueryRangeParts | null => {
+ const splitParts = conditionContent.split(RANGE_OPERATOR_SPLIT_PATTERN);
+ const hasOneOrTwoOperators =
+ splitParts.length === ONE_OPERATOR_PART_COUNT ||
+ splitParts.length === TWO_OPERATOR_PART_COUNT;
+
+ if (!hasOneOrTwoOperators) {
+ return null;
+ }
+
+ const operands = splitParts
+ .filter((_, partIndex) => isOperandPartIndex(partIndex))
+ .map(trimCssWhitespace);
+
+ if (!operands.every(isNonEmptyString)) {
+ return null;
+ }
+
+ return {
+ operands,
+ operators: splitParts.filter(
+ (_, partIndex) => !isOperandPartIndex(partIndex),
+ ),
+ };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryResolutionToDevicePixelRatio.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryResolutionToDevicePixelRatio.ts
new file mode 100644
index 00000000000..244d0dd15f0
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/parseMediaQueryResolutionToDevicePixelRatio.ts
@@ -0,0 +1,29 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { MEDIA_QUERY_RESOLUTION_UNIT_TO_DEVICE_PIXEL_RATIO } from '@/polyfills/media-query/constants/MediaQueryResolutionUnitToDevicePixelRatio';
+import { parseMediaQueryNumericValueParts } from '@/polyfills/media-query/utils/parseMediaQueryNumericValueParts';
+
+export const parseMediaQueryResolutionToDevicePixelRatio = (
+ resolutionString: string,
+): number | null => {
+ const resolutionParts = parseMediaQueryNumericValueParts(resolutionString);
+
+ if (!isDefined(resolutionParts)) {
+ return null;
+ }
+
+ const isNegativeResolution = resolutionParts.numericValue < 0;
+
+ if (isNegativeResolution) {
+ return null;
+ }
+
+ const devicePixelRatioPerUnit =
+ MEDIA_QUERY_RESOLUTION_UNIT_TO_DEVICE_PIXEL_RATIO.get(resolutionParts.unit);
+
+ if (!isDefined(devicePixelRatioPerUnit)) {
+ return null;
+ }
+
+ return resolutionParts.numericValue * devicePixelRatioPerUnit;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/readCssTextSegment.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/readCssTextSegment.ts
new file mode 100644
index 00000000000..3c693ea4400
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/readCssTextSegment.ts
@@ -0,0 +1,62 @@
+import { CSS_ESCAPE_CHARACTER } from '@/polyfills/media-query/constants/CssEscapeCharacter';
+import { type CssTextSegment } from '@/polyfills/media-query/types/CssTextSegment';
+import { findCssCommentEndIndex } from '@/polyfills/media-query/utils/findCssCommentEndIndex';
+import { findCssEscapeEndIndex } from '@/polyfills/media-query/utils/findCssEscapeEndIndex';
+import { findCssStringEndIndex } from '@/polyfills/media-query/utils/findCssStringEndIndex';
+
+const COMMENT_START = '/*';
+
+const COMMENT_REPLACEMENT = ' ';
+
+const CSS_QUOTE_CHARACTERS = new Set(['"', "'"]);
+
+type ReadCssTextSegmentInput = {
+ cssText: string;
+ startIndex: number;
+};
+
+export const readCssTextSegment = ({
+ cssText,
+ startIndex,
+}: ReadCssTextSegmentInput): CssTextSegment => {
+ const character = cssText[startIndex];
+
+ if (cssText.startsWith(COMMENT_START, startIndex)) {
+ return {
+ text: COMMENT_REPLACEMENT,
+ endIndex: findCssCommentEndIndex({
+ cssText,
+ commentStartIndex: startIndex,
+ }),
+ isPlainCharacter: false,
+ };
+ }
+
+ if (character === CSS_ESCAPE_CHARACTER) {
+ const escapeEndIndex = findCssEscapeEndIndex({
+ cssText,
+ escapeStartIndex: startIndex,
+ });
+
+ return {
+ text: cssText.slice(startIndex, escapeEndIndex),
+ endIndex: escapeEndIndex,
+ isPlainCharacter: false,
+ };
+ }
+
+ if (CSS_QUOTE_CHARACTERS.has(character)) {
+ const stringEndIndex = findCssStringEndIndex({
+ cssText,
+ stringStartIndex: startIndex,
+ });
+
+ return {
+ text: cssText.slice(startIndex, stringEndIndex),
+ endIndex: stringEndIndex,
+ isPlainCharacter: false,
+ };
+ }
+
+ return { text: character, endIndex: startIndex + 1, isPlainCharacter: true };
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/splitCssAtTopLevel.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/splitCssAtTopLevel.ts
new file mode 100644
index 00000000000..56d89c0dfcc
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/splitCssAtTopLevel.ts
@@ -0,0 +1,56 @@
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
+import { getNextExpectedCssClosingDelimiters } from '@/polyfills/media-query/utils/getNextExpectedCssClosingDelimiters';
+import { readCssTextSegment } from '@/polyfills/media-query/utils/readCssTextSegment';
+
+type SplitCssAtTopLevelInput = {
+ cssText: string;
+ separator: string;
+};
+
+export const splitCssAtTopLevel = ({
+ cssText,
+ separator,
+}: SplitCssAtTopLevelInput): string[] => {
+ const parts: string[] = [];
+
+ let currentPart = '';
+ let expectedClosingDelimiters: string[] = [];
+ let characterIndex = 0;
+
+ while (characterIndex < cssText.length) {
+ const isAtTopLevel = !isNonEmptyArray(expectedClosingDelimiters);
+ const isSeparatorAtTopLevel =
+ isAtTopLevel && cssText.startsWith(separator, characterIndex);
+
+ if (isSeparatorAtTopLevel) {
+ parts.push(currentPart);
+ currentPart = '';
+ characterIndex += separator.length;
+ continue;
+ }
+
+ const segment = readCssTextSegment({
+ cssText,
+ startIndex: characterIndex,
+ });
+
+ currentPart += segment.text;
+ characterIndex = segment.endIndex;
+
+ if (segment.isPlainCharacter) {
+ expectedClosingDelimiters = getNextExpectedCssClosingDelimiters({
+ expectedClosingDelimiters,
+ character: segment.text,
+ });
+ }
+ }
+
+ const closingDelimitersOfUnterminatedBlocks = [...expectedClosingDelimiters]
+ .reverse()
+ .join('');
+
+ parts.push(`${currentPart}${closingDelimitersOfUnterminatedBlocks}`);
+
+ return parts;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/trimCssWhitespace.ts b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/trimCssWhitespace.ts
new file mode 100644
index 00000000000..1302c5a705d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/media-query/utils/trimCssWhitespace.ts
@@ -0,0 +1,22 @@
+import { ASCII_WHITESPACE_REGEX } from '@/polyfills/dom/constants/AsciiWhitespaceRegex';
+
+export const trimCssWhitespace = (value: string): string => {
+ let startIndex = 0;
+ let endIndex = value.length;
+
+ while (
+ startIndex < endIndex &&
+ ASCII_WHITESPACE_REGEX.test(value[startIndex])
+ ) {
+ startIndex += 1;
+ }
+
+ while (
+ endIndex > startIndex &&
+ ASCII_WHITESPACE_REGEX.test(value[endIndex - 1])
+ ) {
+ endIndex -= 1;
+ }
+
+ return value.slice(startIndex, endIndex);
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/createEventWithReadonlyProperties.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/createEventWithReadonlyProperties.ts
new file mode 100644
index 00000000000..d8e65500c60
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/createEventWithReadonlyProperties.ts
@@ -0,0 +1,14 @@
+export const createEventWithReadonlyProperties = <
+ TProperties extends Record<string, unknown>,
+>(
+ type: string,
+ properties: TProperties,
+): Event & TProperties => {
+ const event = new Event(type);
+
+ for (const [propertyName, propertyValue] of Object.entries(properties)) {
+ Object.defineProperty(event, propertyName, { value: propertyValue });
+ }
+
+ return event as Event & TProperties;
+};
diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/resolveAddEventListenerOptions.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/resolveAddEventListenerOptions.ts
new file mode 100644
index 00000000000..0d37553be90
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/resolveAddEventListenerOptions.ts
@@ -0,0 +1,6 @@
+import { isObject } from '@sniptt/guards';
+
+export const resolveAddEventListenerOptions = (
+ options?: AddEventListenerOptions | boolean | null,
+): AddEventListenerOptions =>
+ isObject(options) ? options : { capture: options === true };
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/__tests__/seedFrontComponentExecutionContext.test.ts b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/__tests__/seedFrontComponentExecutionContext.test.ts
new file mode 100644
index 00000000000..09462526fd1
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/__tests__/seedFrontComponentExecutionContext.test.ts
@@ -0,0 +1,43 @@
+import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
+
+import { FRONT_COMPONENT_CONTEXT_KEY } from 'twenty-sdk/front-component-renderer';
+
+import { getFrontComponentExecutionContext } from '@/remote/worker/environment/utils/getFrontComponentExecutionContext';
+import { seedFrontComponentExecutionContext } from '@/remote/worker/environment/utils/seedFrontComponentExecutionContext';
+import { setFrontComponentExecutionContext } from '@/remote/worker/environment/utils/setFrontComponentExecutionContext';
+
+const createExecutionContext = (
+ overrides: Partial<FrontComponentExecutionContext> = {},
+): FrontComponentExecutionContext => ({
+ frontComponentId: 'front-component-id',
+ userId: null,
+ recordId: null,
+ selectedRecordIds: [],
+ timelineActivityId: null,
+ colorScheme: 'light',
+ ...overrides,
+});
+
+describe('seedFrontComponentExecutionContext', () => {
+ beforeEach(() => {
+ delete (globalThis as Record<string, unknown>)[FRONT_COMPONENT_CONTEXT_KEY];
+ });
+
+ it('should set the context when the worker has none yet', () => {
+ const context = createExecutionContext();
+
+ seedFrontComponentExecutionContext(context);
+
+ expect(getFrontComponentExecutionContext()).toBe(context);
+ });
+
+ it('should keep a context the host already pushed through updateContext', () => {
+ const pushedContext = createExecutionContext({ colorScheme: 'dark' });
+ const staleMountContext = createExecutionContext({ colorScheme: 'light' });
+
+ setFrontComponentExecutionContext(pushedContext);
+ seedFrontComponentExecutionContext(staleMountContext);
+
+ expect(getFrontComponentExecutionContext()).toBe(pushedContext);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/getFrontComponentColorScheme.ts b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/getFrontComponentColorScheme.ts
new file mode 100644
index 00000000000..a55e7e17f87
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/getFrontComponentColorScheme.ts
@@ -0,0 +1,10 @@
+import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
+
+import { getFrontComponentExecutionContext } from '@/remote/worker/environment/utils/getFrontComponentExecutionContext';
+
+const DEFAULT_COLOR_SCHEME: FrontComponentExecutionContext['colorScheme'] =
+ 'light';
+
+export const getFrontComponentColorScheme =
+ (): FrontComponentExecutionContext['colorScheme'] =>
+ getFrontComponentExecutionContext()?.colorScheme ?? DEFAULT_COLOR_SCHEME;
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/getFrontComponentExecutionContext.ts b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/getFrontComponentExecutionContext.ts
new file mode 100644
index 00000000000..42706148d8c
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/getFrontComponentExecutionContext.ts
@@ -0,0 +1,12 @@
+import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
+
+import { FRONT_COMPONENT_CONTEXT_KEY } from 'twenty-sdk/front-component-renderer';
+
+import { toGlobalScopeRecord } from '@/polyfills/utils/toGlobalScopeRecord';
+
+export const getFrontComponentExecutionContext = ():
+ | FrontComponentExecutionContext
+ | undefined =>
+ toGlobalScopeRecord(globalThis)[FRONT_COMPONENT_CONTEXT_KEY] as
+ | FrontComponentExecutionContext
+ | undefined;
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/getFrontComponentExecutionContextListeners.ts b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/getFrontComponentExecutionContextListeners.ts
new file mode 100644
index 00000000000..c9da922fe97
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/getFrontComponentExecutionContextListeners.ts
@@ -0,0 +1,17 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { FRONT_COMPONENT_LISTENERS_KEY } from 'twenty-sdk/front-component-renderer';
+
+import { toGlobalScopeRecord } from '@/polyfills/utils/toGlobalScopeRecord';
+
+export const getFrontComponentExecutionContextListeners = (): Set<
+ () => void
+> => {
+ const globalScope = toGlobalScopeRecord(globalThis);
+
+ if (!isDefined(globalScope[FRONT_COMPONENT_LISTENERS_KEY])) {
+ globalScope[FRONT_COMPONENT_LISTENERS_KEY] = new Set<() => void>();
+ }
+
+ return globalScope[FRONT_COMPONENT_LISTENERS_KEY] as Set<() => void>;
+};
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/seedFrontComponentExecutionContext.ts b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/seedFrontComponentExecutionContext.ts
new file mode 100644
index 00000000000..9febe188595
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/seedFrontComponentExecutionContext.ts
@@ -0,0 +1,16 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
+
+import { getFrontComponentExecutionContext } from '@/remote/worker/environment/utils/getFrontComponentExecutionContext';
+import { setFrontComponentExecutionContext } from '@/remote/worker/environment/utils/setFrontComponentExecutionContext';
+
+export const seedFrontComponentExecutionContext = (
+ context: FrontComponentExecutionContext,
+): void => {
+ if (isDefined(getFrontComponentExecutionContext())) {
+ return;
+ }
+
+ setFrontComponentExecutionContext(context);
+};
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/setFrontComponentExecutionContext.ts b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/setFrontComponentExecutionContext.ts
index b0cbc1125a9..bde8a0c3a04 100644
--- a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/setFrontComponentExecutionContext.ts
+++ b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/setFrontComponentExecutionContext.ts
@@ -1,42 +1,28 @@
import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
-import {
- FRONT_COMPONENT_CONTEXT_KEY,
- FRONT_COMPONENT_LISTENERS_KEY,
-} from 'twenty-sdk/front-component-renderer';
+import { FRONT_COMPONENT_CONTEXT_KEY } from 'twenty-sdk/front-component-renderer';
import { isDefined } from 'twenty-shared/utils';
+import { toGlobalScopeRecord } from '@/polyfills/utils/toGlobalScopeRecord';
+import { getFrontComponentExecutionContext } from '@/remote/worker/environment/utils/getFrontComponentExecutionContext';
+import { getFrontComponentExecutionContextListeners } from '@/remote/worker/environment/utils/getFrontComponentExecutionContextListeners';
import { reuseUnchangedExecutionContextValues } from '@/remote/worker/environment/utils/reuseUnchangedExecutionContextValues';
-type Listener = () => void;
-
-const getListeners = (): Set<Listener> => {
- if (!(globalThis as Record<string, unknown>)[FRONT_COMPONENT_LISTENERS_KEY]) {
- (globalThis as Record<string, unknown>)[FRONT_COMPONENT_LISTENERS_KEY] =
- new Set<Listener>();
- }
-
- return (globalThis as Record<string, unknown>)[
- FRONT_COMPONENT_LISTENERS_KEY
- ] as Set<Listener>;
-};
-
export const setFrontComponentExecutionContext = (
context: FrontComponentExecutionContext,
): void => {
- const previousContext = (globalThis as Record<string, unknown>)[
- FRONT_COMPONENT_CONTEXT_KEY
- ] as FrontComponentExecutionContext | undefined;
-
- (globalThis as Record<string, unknown>)[FRONT_COMPONENT_CONTEXT_KEY] =
- isDefined(previousContext)
- ? reuseUnchangedExecutionContextValues({
- previousExecutionContext: previousContext,
- nextExecutionContext: context,
- })
- : context;
-
- for (const listener of getListeners()) {
+ const previousContext = getFrontComponentExecutionContext();
+
+ toGlobalScopeRecord(globalThis)[FRONT_COMPONENT_CONTEXT_KEY] = isDefined(
+ previousContext,
+ )
+ ? reuseUnchangedExecutionContextValues({
+ previousExecutionContext: previousContext,
+ nextExecutionContext: context,
+ })
+ : context;
+
+ for (const listener of getFrontComponentExecutionContextListeners()) {
listener();
}
};
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/subscribeToFrontComponentExecutionContextUpdates.ts b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/subscribeToFrontComponentExecutionContextUpdates.ts
new file mode 100644
index 00000000000..d35235adbe0
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/subscribeToFrontComponentExecutionContextUpdates.ts
@@ -0,0 +1,14 @@
+import { getFrontComponentExecutionContextListeners } from '@/remote/worker/environment/utils/getFrontComponentExecutionContextListeners';
+
+export const subscribeToFrontComponentExecutionContextUpdates = (
+ listener: () => void,
+): (() => void) => {
+ const executionContextListeners =
+ getFrontComponentExecutionContextListeners();
+
+ executionContextListeners.add(listener);
+
+ return () => {
+ executionContextListeners.delete(listener);
+ };
+};
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 d51148553a8..0179d0171f3 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
@@ -23,8 +23,10 @@ import { installSelectorMethodsPolyfill } from '@/polyfills/selectors/utils/inst
import { workerGeometryStore } from '@/polyfills/geometry/states/workerGeometryStore';
import { installElementGeometryPolyfill } from '@/polyfills/geometry/utils/installElementGeometryPolyfill';
import { installWindowGeometryPolyfill } from '@/polyfills/geometry/utils/installWindowGeometryPolyfill';
+import { mediaQueryEnvironmentSource } from '@/polyfills/media-query/states/mediaQueryEnvironmentSource';
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 { toGlobalScopeRecord } from '@/polyfills/utils/toGlobalScopeRecord';
import { installStorageBridge } from '@/polyfills/storage/utils/installStorageBridge';
@@ -95,6 +97,11 @@ installWindowAliasesPolyfill({
globalScope: toGlobalScopeRecord(globalThis),
});
+installMatchMediaPolyfill({
+ globalScope: toGlobalScopeRecord(globalThis),
+ environmentSource: mediaQueryEnvironmentSource,
+});
+
installStorageBridge({
globalScope: toGlobalScopeRecord(globalThis),
storageBridges: frontComponentStorageBridges,
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/__tests__/renderFrontComponent.test.ts b/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/__tests__/renderFrontComponent.test.ts
index 6f21166ecaf..20010f677af 100644
--- a/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/__tests__/renderFrontComponent.test.ts
+++ b/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/__tests__/renderFrontComponent.test.ts
@@ -1,19 +1,108 @@
import { type RemoteConnection } from '@remote-dom/core/elements';
+import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
+
+import { FRONT_COMPONENT_CONTEXT_KEY } from 'twenty-sdk/front-component-renderer';
+
+import { getFrontComponentExecutionContext } from '@/remote/worker/environment/utils/getFrontComponentExecutionContext';
+import { setFrontComponentExecutionContext } from '@/remote/worker/environment/utils/setFrontComponentExecutionContext';
+import { loadFrontComponentModule } from '@/remote/worker/module-loading/utils/loadFrontComponentModule';
import { renderFrontComponent } from '../renderFrontComponent';
+jest.mock(
+ '@/remote/worker/rendering/utils/attachRemoteRenderRootToWorkerDocument',
+ () => ({
+ attachRemoteRenderRootToWorkerDocument: jest.fn(() => ({})),
+ }),
+);
+
+jest.mock('@/remote/worker/fetch-proxy/utils/installHostFetchProxy', () => ({
+ installHostFetchProxy: jest.fn(),
+}));
+
+jest.mock(
+ '@/remote/worker/module-loading/utils/loadFrontComponentModule',
+ () => ({
+ loadFrontComponentModule: jest.fn(),
+ }),
+);
+
+const COMPONENT_RENDER_CONTEXT = {
+ componentUrl: 'https://api.twenty.test/rest/front-components/id',
+ componentSource: 'export default () => {};',
+};
+
+const createExecutionContext = (
+ overrides: Partial<FrontComponentExecutionContext> = {},
+): FrontComponentExecutionContext => ({
+ frontComponentId: 'front-component-id',
+ userId: null,
+ recordId: null,
+ selectedRecordIds: [],
+ timelineActivityId: null,
+ colorScheme: 'light',
+ ...overrides,
+});
+
+const readExecutionContextWhenModuleLoads = async (
+ initialExecutionContext: FrontComponentExecutionContext,
+) => {
+ let executionContextWhenModuleLoads:
+ | FrontComponentExecutionContext
+ | undefined;
+
+ jest.mocked(loadFrontComponentModule).mockImplementation(async () => {
+ executionContextWhenModuleLoads = getFrontComponentExecutionContext();
+
+ return { default: jest.fn() };
+ });
+
+ await renderFrontComponent({
+ connection: {} as RemoteConnection,
+ renderContext: { ...COMPONENT_RENDER_CONTEXT, initialExecutionContext },
+ hostFetch: jest.fn(),
+ });
+
+ return executionContextWhenModuleLoads;
+};
+
describe('renderFrontComponent', () => {
+ beforeEach(() => {
+ delete (globalThis as Record<string, unknown>)[FRONT_COMPONENT_CONTEXT_KEY];
+ });
+
it('should fail closed when the host fetch bridge is unavailable', async () => {
await expect(
renderFrontComponent({
connection: {} as RemoteConnection,
- renderContext: {
- componentUrl: 'https://api.twenty.test/rest/front-components/id',
- componentSource: 'export default () => {};',
- },
+ renderContext: COMPONENT_RENDER_CONTEXT,
hostFetch: null,
}),
).rejects.toMatchObject({
code: 'FRONT_COMPONENT_HOST_FETCH_UNAVAILABLE',
});
});
+
+ it('should seed the initial execution context before the component module loads', async () => {
+ const initialExecutionContext = createExecutionContext({
+ colorScheme: 'dark',
+ });
+
+ expect(
+ await readExecutionContextWhenModuleLoads(initialExecutionContext),
+ ).toBe(initialExecutionContext);
+ });
+
+ it('should keep a context the host pushed before render when the module loads', async () => {
+ const pushedExecutionContext = createExecutionContext({
+ colorScheme: 'dark',
+ });
+
+ setFrontComponentExecutionContext(pushedExecutionContext);
+
+ expect(
+ await readExecutionContextWhenModuleLoads(
+ createExecutionContext({ colorScheme: 'light' }),
+ ),
+ ).toBe(pushedExecutionContext);
+ });
});
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/renderFrontComponent.ts b/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/renderFrontComponent.ts
index af2e4bd68fc..5f7f8e7f0e3 100644
--- a/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/renderFrontComponent.ts
+++ b/packages/twenty-front-component-renderer/src/remote/worker/rendering/utils/renderFrontComponent.ts
@@ -7,6 +7,7 @@ import { frontComponentStorageBridges } from '@/polyfills/storage/states/frontCo
import { attachRemoteRenderRootToWorkerDocument } from '@/remote/worker/rendering/utils/attachRemoteRenderRootToWorkerDocument';
import { installHostFetchProxy } from '@/remote/worker/fetch-proxy/utils/installHostFetchProxy';
import { loadFrontComponentModule } from '@/remote/worker/module-loading/utils/loadFrontComponentModule';
+import { seedFrontComponentExecutionContext } from '@/remote/worker/environment/utils/seedFrontComponentExecutionContext';
import { setWorkerEnvironmentVariablesFromRenderContext } from '@/remote/worker/environment/utils/setWorkerEnvironmentVariablesFromRenderContext';
import { type HostFetchFunction } from '@/types/HostFetchFunction';
import { type HostToWorkerRenderContext } from '@/types/HostToWorkerRenderContext';
@@ -41,6 +42,10 @@ export const renderFrontComponent = async ({
});
}
+ if (isDefined(renderContext.initialExecutionContext)) {
+ seedFrontComponentExecutionContext(renderContext.initialExecutionContext);
+ }
+
if (isDefined(renderContext.mediaRecorderCapabilities)) {
workerMediaBridge.seedRecorderCapabilities(
renderContext.mediaRecorderCapabilities,
diff --git a/packages/twenty-front-component-renderer/src/testing/createMediaQueryEnvironmentFixture.ts b/packages/twenty-front-component-renderer/src/testing/createMediaQueryEnvironmentFixture.ts
new file mode 100644
index 00000000000..cd3b0a7460e
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/testing/createMediaQueryEnvironmentFixture.ts
@@ -0,0 +1,13 @@
+import { DEFAULT_INPUT_MEDIA_FEATURES } from '@/constants/DefaultInputMediaFeatures';
+import { type MediaQueryEnvironment } from '@/polyfills/media-query/types/MediaQueryEnvironment';
+
+export const createMediaQueryEnvironmentFixture = (
+ overrides: Partial<MediaQueryEnvironment> = {},
+): MediaQueryEnvironment => ({
+ componentWidth: 0,
+ componentHeight: 0,
+ devicePixelRatio: 1,
+ colorScheme: 'light',
+ ...DEFAULT_INPUT_MEDIA_FEATURES,
+ ...overrides,
+});
diff --git a/packages/twenty-front-component-renderer/src/testing/createSubscriptionStub.ts b/packages/twenty-front-component-renderer/src/testing/createSubscriptionStub.ts
new file mode 100644
index 00000000000..6f15b393413
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/testing/createSubscriptionStub.ts
@@ -0,0 +1,21 @@
+export const createSubscriptionStub = () => {
+ const listeners = new Set<() => void>();
+ const unsubscribe = jest.fn();
+
+ const subscribe = jest.fn((listener: () => void) => {
+ listeners.add(listener);
+
+ return () => {
+ listeners.delete(listener);
+ unsubscribe();
+ };
+ });
+
+ const notify = () => {
+ for (const listener of [...listeners]) {
+ listener();
+ }
+ };
+
+ return { subscribe, unsubscribe, notify };
+};
diff --git a/packages/twenty-front-component-renderer/src/testing/createViewportGeometrySnapshotFixture.ts b/packages/twenty-front-component-renderer/src/testing/createViewportGeometrySnapshotFixture.ts
index ad3d1368ea3..c4f55fa379b 100644
--- a/packages/twenty-front-component-renderer/src/testing/createViewportGeometrySnapshotFixture.ts
+++ b/packages/twenty-front-component-renderer/src/testing/createViewportGeometrySnapshotFixture.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_INPUT_MEDIA_FEATURES } from '@/constants/DefaultInputMediaFeatures';
import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot';
export const createViewportGeometrySnapshotFixture = (
@@ -14,5 +15,6 @@ export const createViewportGeometrySnapshotFixture = (
rootContainerHeight: 0,
rootContainerClientWidth: 0,
rootContainerClientHeight: 0,
+ ...DEFAULT_INPUT_MEDIA_FEATURES,
...overrides,
});
diff --git a/packages/twenty-front-component-renderer/src/testing/createWorkerGeometryStoreStub.ts b/packages/twenty-front-component-renderer/src/testing/createWorkerGeometryStoreStub.ts
index ce6dc3fc7f4..c8138e48a86 100644
--- a/packages/twenty-front-component-renderer/src/testing/createWorkerGeometryStoreStub.ts
+++ b/packages/twenty-front-component-renderer/src/testing/createWorkerGeometryStoreStub.ts
@@ -7,6 +7,7 @@ export const createWorkerGeometryStoreStub = (
connectTransport: jest.fn(),
applyGeometryBatch: jest.fn(),
getViewportSnapshot: jest.fn(() => null),
+ subscribeToGeometryUpdates: jest.fn(() => () => {}),
resolveElementSnapshot: jest.fn(() => null),
...overrides,
});
diff --git a/packages/twenty-front-component-renderer/src/testing/stubWindowMatchMedia.ts b/packages/twenty-front-component-renderer/src/testing/stubWindowMatchMedia.ts
new file mode 100644
index 00000000000..1f20aeea1e5
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/testing/stubWindowMatchMedia.ts
@@ -0,0 +1,22 @@
+export const stubWindowMatchMedia = (matchingQueries: string[] = []) => {
+ const createdMediaQueryLists: EventTarget[] = [];
+
+ const matchMedia = jest.fn((media: string) => {
+ const mediaQueryList = Object.assign(new EventTarget(), {
+ media,
+ matches: matchingQueries.includes(media),
+ });
+
+ createdMediaQueryLists.push(mediaQueryList);
+
+ return mediaQueryList;
+ });
+
+ Object.defineProperty(window, 'matchMedia', {
+ value: matchMedia,
+ configurable: true,
+ writable: true,
+ });
+
+ return { matchMedia, createdMediaQueryLists };
+};
diff --git a/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts b/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts
index 384bc5917b1..4090be15b3c 100644
--- a/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts
+++ b/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts
@@ -1,3 +1,5 @@
+import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
+
import { type FrontComponentStorageSnapshots } from '@/types/FrontComponentStorageSnapshots';
import { type MediaRecorderCapabilities } from '@/types/MediaSession';
import { type SdkClientSources } from '@/types/SdkClientSources';
@@ -14,6 +16,7 @@ export type HostToWorkerRenderContext = {
hostFetchOrigins?: string[];
applicationVariables?: Record<string, string>;
initialViewportGeometry?: ViewportGeometrySnapshot;
+ initialExecutionContext?: FrontComponentExecutionContext;
storageSnapshots?: FrontComponentStorageSnapshots;
// MediaRecorder.isTypeSupported is synchronous, so the worker polyfill
// answers from this snapshot instead of a round trip to the host.
diff --git a/packages/twenty-front-component-renderer/src/types/HoverMediaFeatureValue.ts b/packages/twenty-front-component-renderer/src/types/HoverMediaFeatureValue.ts
new file mode 100644
index 00000000000..6e49173967d
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/HoverMediaFeatureValue.ts
@@ -0,0 +1 @@
+export type HoverMediaFeatureValue = 'none' | 'hover';
diff --git a/packages/twenty-front-component-renderer/src/types/InputMediaFeatures.ts b/packages/twenty-front-component-renderer/src/types/InputMediaFeatures.ts
new file mode 100644
index 00000000000..32732a551d1
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/InputMediaFeatures.ts
@@ -0,0 +1,7 @@
+import { type HoverMediaFeatureValue } from '@/types/HoverMediaFeatureValue';
+import { type PointerMediaFeatureValue } from '@/types/PointerMediaFeatureValue';
+
+export type InputMediaFeatures = {
+ hover: HoverMediaFeatureValue;
+ pointer: PointerMediaFeatureValue;
+};
diff --git a/packages/twenty-front-component-renderer/src/types/PointerMediaFeatureValue.ts b/packages/twenty-front-component-renderer/src/types/PointerMediaFeatureValue.ts
new file mode 100644
index 00000000000..73f730d2b43
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/types/PointerMediaFeatureValue.ts
@@ -0,0 +1 @@
+export type PointerMediaFeatureValue = 'none' | 'coarse' | 'fine';
diff --git a/packages/twenty-front-component-renderer/src/types/ViewportGeometrySnapshot.ts b/packages/twenty-front-component-renderer/src/types/ViewportGeometrySnapshot.ts
index 38af73fe37d..369d450ad1a 100644
--- a/packages/twenty-front-component-renderer/src/types/ViewportGeometrySnapshot.ts
+++ b/packages/twenty-front-component-renderer/src/types/ViewportGeometrySnapshot.ts
@@ -1,4 +1,6 @@
-export type ViewportGeometrySnapshot = {
+import { type InputMediaFeatures } from '@/types/InputMediaFeatures';
+
+export type ViewportGeometrySnapshot = InputMediaFeatures & {
innerWidth: number;
innerHeight: number;
devicePixelRatio: number;
diff --git a/packages/twenty-ui/README.md b/packages/twenty-ui/README.md
index bf7156251bb..cd3e2f9e6f5 100644
--- a/packages/twenty-ui/README.md
+++ b/packages/twenty-ui/README.md
@@ -92,7 +92,7 @@ See the [theming guide](https://docs.twenty.com/ui/theming) for scoped overrides
Import responsive hooks and media-query constants from `twenty-ui/utilities`, `MOBILE_VIEWPORT` from `twenty-ui/theme`, and story overrides from `twenty-ui/testing`.
- `useIsMobile` matches `MOBILE_MEDIA_QUERY` (up to and including `MOBILE_VIEWPORT`). `useIsTouchDevice` matches `TOUCH_DEVICE_MEDIA_QUERY` and is independent of width: branch interaction behavior on it, and layout on `useIsMobile`.
-- `useMediaQuery(query)` subscribes to native `matchMedia` changes and shares one `MediaQueryList` per query. It returns `false` during server rendering and the first hydration render, and wherever `window.matchMedia` is unavailable, including the front component sandbox.
+- `useMediaQuery(query)` subscribes to native `matchMedia` changes and shares one `MediaQueryList` per query. It returns `false` during server rendering and the first hydration render, and wherever `window.matchMedia` is unavailable. In a front component, `matchMedia` answers for the widget's own box, so `useIsMobile` follows the widget width rather than the browser viewport, while `useIsTouchDevice` follows the primary input of the user's device.
- To force a result in a story, return `overrideMediaQueryMatches({ [MOBILE_MEDIA_QUERY]: true })` from `beforeEach`; the returned cleanup restores the native `matchMedia`.
## Development