The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Fix front component layout measurements (#27807)
Raphaël Bosiced3f25e4fe6
diff --git a/.github/workflows/ci-front-component-renderer.yaml b/.github/workflows/ci-front-component-renderer.yamlindex cf4606df517..8b5cdf0d6f1 100644--- a/.github/workflows/ci-front-component-renderer.yaml+++ b/.github/workflows/ci-front-component-renderer.yaml@@ -101,6 +101,7 @@ jobs:timeout 30 bash -c 'until curl -sf http://localhost:6008 > /dev/null 2>&1; do sleep 1; done'npx nx storybook:test:no-coverage twenty-front-component-renderernpx nx run twenty-front-component-renderer:storybook:test:file-selection+ npx nx run twenty-front-component-renderer:storybook:test:layoutci-front-component-renderer-status-check:if: always() && !cancelled()timeout-minutes: 5diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdxindex ac12eff48ef..32c3d7ae6fe 100644--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx@@ -995,7 +995,7 @@ To branch on the active scheme explicitly, read it with `useColorScheme()` from## Current limitations-Front components are under active development. Rendering, styling, handling events, measuring elements, body portals and browser storage work well. Anything that reaches _past_ those (calling a DOM method on a ref, observing element resizes) is missing or incomplete today, and most of it fails silently: no exception, and no TypeScript error either, since the scaffold is typed against the full browser DOM.+Front components are under active development. Rendering, styling, handling events, measuring elements, body portals and browser storage work well. Anything that reaches _past_ those (calling a DOM method on a ref, for example) is missing or incomplete today, and most of it fails silently: no exception, and no TypeScript error either, since the scaffold is typed against the full browser DOM.If one of these blocks you, [open an issue](https://github.com/twentyhq/twenty/issues/new/choose) so it gets prioritized.@@ -1009,11 +1009,12 @@ Elements can measure themselves: the host mirrors geometry into the sandbox, so| `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) |+| `window.getComputedStyle()` | Host layout values for measured elements and their parents; the rest, theme variables too, from inline styles |+| `ResizeObserver` | Works, from the mirror; `document.body` reports your widget's box |+| `IntersectionObserver` | `ReferenceError` (`typeof` guards do work) || `MutationObserver` | Works, including `subtree`, `attributeFilter`, old values and `takeRecords()` |-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.+Positioning from `getBoundingClientRect` and size observation through `ResizeObserver` both work from the same mirror, so resize callbacks trail the host by about a frame. 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`.diff --git a/packages/twenty-front-component-renderer/playwright.layout.config.ts b/packages/twenty-front-component-renderer/playwright.layout.config.tsnew file mode 100644index 00000000000..56f889c3a62--- /dev/null+++ b/packages/twenty-front-component-renderer/playwright.layout.config.ts@@ -0,0 +1,15 @@+import { defineConfig } from 'playwright/test';++export default defineConfig({+ testDir: './scripts/front-component-stories/native-tests',+ testMatch: 'layout-*.ts',+ fullyParallel: false,+ workers: 1,+ timeout: 60000,+ reporter: 'list',+ use: {+ baseURL: process.env.STORYBOOK_URL ?? 'http://localhost:6008',+ headless: true,+ viewport: { width: 1280, height: 960 },+ },+});diff --git a/packages/twenty-front-component-renderer/project.json b/packages/twenty-front-component-renderer/project.jsonindex e0545bc0727..befda18dcc7 100644--- a/packages/twenty-front-component-renderer/project.json+++ b/packages/twenty-front-component-renderer/project.json@@ -101,6 +101,7 @@"inputs": ["{projectRoot}/scripts/front-component-stories/**/*","!{projectRoot}/scripts/front-component-stories/__tests__/**/*",+ "!{projectRoot}/scripts/front-component-stories/native-tests/**/*","{projectRoot}/src/__stories__/html-tag/**/*","{projectRoot}/src/__stories__/host-api/**/*","{projectRoot}/src/__stories__/showcase/**/*",@@ -158,6 +159,14 @@"command": "node --import tsx --test scripts/front-component-stories/__tests__/image-input.browser.test.ts"}},+ "storybook:test:layout": {+ "executor": "nx:run-commands",+ "cache": false,+ "options": {+ "cwd": "{projectRoot}",+ "command": "playwright test --config playwright.layout.config.ts"+ }+ },"storybook:coverage": {}}}diff --git a/packages/twenty-front-component-renderer/scripts/front-component-stories/native-tests/layout-overflowing-list.ts b/packages/twenty-front-component-renderer/scripts/front-component-stories/native-tests/layout-overflowing-list.tsnew file mode 100644index 00000000000..b50943e1420--- /dev/null+++ b/packages/twenty-front-component-renderer/scripts/front-component-stories/native-tests/layout-overflowing-list.ts@@ -0,0 +1,79 @@+import { expect, test } from 'playwright/test';++for (const runtime of ['react', 'preact']) {+ test(`${runtime} measures initial and responsive OverflowingLists across independent renderer instances`, async ({+ page,+ }) => {+ await page.goto(+ `/iframe.html?id=frontcomponent-twenty-ui-gallery--overflowing-list-instances-${runtime}`,+ );+ const first = page.getByRole('group', { name: 'First renderer' });+ const second = page.getByRole('group', { name: 'Second renderer' });+ const firstTrigger = first.getByRole('button', {+ name: /Show all measured items$/,+ });+ const secondTrigger = second.getByRole('button', {+ name: /Show all measured items$/,+ });++ await expect(first.getByTestId('front-component-mounted')).toBeVisible({+ timeout: 30000,+ });+ await expect(second.getByTestId('front-component-mounted')).toBeVisible({+ timeout: 30000,+ });+ await expect(firstTrigger).toHaveText('+2');+ await expect(secondTrigger).toHaveText('+2');+ await expect(+ first.getByRole('button', { name: 'Measured Alpha' }),+ ).toBeVisible();+ await expect(+ first.getByRole('button', { name: 'Measured Delta' }),+ ).toHaveCount(0);+ await expect(+ second.getByRole('button', { name: 'Measured Alpha' }),+ ).toBeVisible();++ await first.getByRole('button', { name: 'Widen measured list' }).click();+ await expect(firstTrigger).toHaveCount(0);+ await expect(+ first.getByRole('button', { name: 'Measured Delta' }),+ ).toBeVisible();+ await expect(secondTrigger).toHaveText('+2');+ await expect(+ second.getByRole('button', { name: 'Measured Delta' }),+ ).toHaveCount(0);++ await first.getByRole('button', { name: 'Narrow measured list' }).click();+ await expect(firstTrigger).toHaveText('+1');+ await expect(+ first.getByRole('button', { name: 'Measured Bravo' }),+ ).toBeVisible();+ await expect(+ first.getByRole('button', { name: 'Measured Delta' }),+ ).toHaveCount(0);+ await expect(secondTrigger).toHaveText('+2');++ await page.getByRole('button', { name: 'Remove first renderer' }).click();+ await expect(first.getByTestId('front-component-mounted')).toHaveCount(0);+ await second.getByRole('button', { name: 'Widen measured list' }).click();+ await expect(secondTrigger).toHaveCount(0);+ await expect(+ second.getByRole('button', { name: 'Measured Delta' }),+ ).toBeVisible();+ await second.getByRole('button', { name: 'Narrow measured list' }).click();+ await expect(secondTrigger).toHaveText('+1');+ await expect(+ second.getByRole('button', { name: 'Measured Bravo' }),+ ).toBeVisible();++ await second.getByRole('button', { name: 'Remove measured list' }).click();+ await expect(+ second.getByRole('button', { name: 'Measured Alpha' }),+ ).toHaveCount(0);+ await second.getByRole('button', { name: 'Add target' }).click();+ await expect(+ second.getByRole('button', { name: /Show all targets$/ }),+ ).toHaveText('+3');+ });+}diff --git a/packages/twenty-front-component-renderer/scripts/front-component-stories/native-tests/layout-popups.ts b/packages/twenty-front-component-renderer/scripts/front-component-stories/native-tests/layout-popups.tsnew file mode 100644index 00000000000..b3537d89b93--- /dev/null+++ b/packages/twenty-front-component-renderer/scripts/front-component-stories/native-tests/layout-popups.ts@@ -0,0 +1,197 @@+import { expect, test, type Locator } from 'playwright/test';+import { isDefined } from 'twenty-shared/utils';+import { MOUNT_TIMEOUT } from '../../../src/__stories__/shared/test-utils/timeouts';+import { waitForAnimationFrames } from '../../../src/__stories__/shared/test-utils/waitForAnimationFrames';+import { MAXIMUM_DROPDOWN_TRIGGER_GAP } from '../../../src/__stories__/twenty-ui-gallery/constants/MaximumDropdownTriggerGap';+import { computePopupAnchorGapAndOverlap } from '../../../src/__stories__/twenty-ui-gallery/utils/computePopupAnchorGapAndOverlap';+import { GEOMETRY_IDLE_FRAME_THRESHOLD } from '../../../src/host/geometry/constants/GeometryIdleFrameThreshold';+import { FRONT_COMPONENT_PORTAL_MARGIN } from '../../../src/constants/FrontComponentPortalMargin';+import { readBounds } from './readBounds';++const POPUP_POSITION_ROUNDING_TOLERANCE = 1;++type ElementBounds = NonNullable<Awaited<ReturnType<Locator['boundingBox']>>>;++const isPopupAttachedToAnchor = ({+ anchor,+ popup,+ side,+}: {+ anchor: ElementBounds;+ popup: ElementBounds;+ side: string | null;+}) => {+ const isHorizontallyPositioned = side === 'left' || side === 'right';+ const isVerticallyPositioned = side === 'top' || side === 'bottom';++ if (!isHorizontallyPositioned && !isVerticallyPositioned) {+ return false;+ }++ const {+ popupAnchorGap,+ popupOverlapStart,+ popupOverlapEnd,+ anchorOverlapStart,+ anchorOverlapEnd,+ } = computePopupAnchorGapAndOverlap({ anchor, popup, side });++ return (+ popupAnchorGap >= -POPUP_POSITION_ROUNDING_TOLERANCE &&+ popupAnchorGap <= MAXIMUM_DROPDOWN_TRIGGER_GAP &&+ popupOverlapStart < anchorOverlapEnd &&+ popupOverlapEnd > anchorOverlapStart+ );+};++for (const runtime of ['react', 'preact']) {+ test(`${runtime} mirrors stylesheet layout, offset ancestry and inline custom properties`, async ({+ page,+ }) => {+ await page.goto(+ `/iframe.html?id=frontcomponent-twenty-ui-gallery--layout-measurements-${runtime}`,+ );+ await expect(page.getByTestId('geometry-layout-facts')).toContainText(+ '"columnGap":"14px"',+ { timeout: MOUNT_TIMEOUT },+ );+ await expect(page.getByTestId('geometry-layout-facts')).toContainText(+ '"direction":"rtl"',+ );+ await expect(page.getByTestId('geometry-layout-facts')).toContainText(+ '"display":"flex"',+ );+ await expect(page.getByTestId('geometry-layout-facts')).toContainText(+ '"offsetLeft":12',+ );+ await expect(page.getByTestId('geometry-layout-facts')).toContainText(+ '"offsetTop":14',+ );+ await expect(page.getByTestId('geometry-layout-facts')).toContainText(+ '"hasOwnedOffsetParent":true',+ );+ await expect(page.getByTestId('geometry-layout-facts')).toContainText(+ '"inlineAccent":"rgb(1, 2, 3)"',+ );+ });++ test(`${runtime} keeps popup placement inside owner and page bounds under transforms, RTL and scrolling`, async ({+ page,+ }) => {+ await page.goto(+ `/iframe.html?id=frontcomponent-twenty-ui-gallery--portal-geometry-${runtime}`,+ );+ const widget = page.getByRole('group', { name: 'Widget', exact: true });+ const frame = page.getByRole('region', { name: 'Widget scroll frame' });+ await expect(widget).toBeVisible();+ await frame.evaluate((node) => {+ node.style.direction = 'rtl';+ node.style.transform = 'scale(0.85)';+ node.style.transformOrigin = 'top left';+ node.style.position = 'relative';+ node.scrollTop = 35;+ });+ const trigger = page.getByRole('button', { name: 'Open menu' });+ await trigger.click();+ const menu = page.getByRole('menu');+ await expect(menu).toBeVisible();+ await expect+ .poll(async () => {+ const anchor = await trigger.boundingBox();+ const popup = await menu.boundingBox();+ const owner = await widget.boundingBox();+ if (!isDefined(anchor) || !isDefined(popup) || !isDefined(owner)) {+ return false;+ }+ const viewport = page.viewportSize()!;+ const side = await menu.getAttribute('data-side');+ return (+ isPopupAttachedToAnchor({ anchor, popup, side }) &&+ popup.x >= Math.max(0, owner.x - FRONT_COMPONENT_PORTAL_MARGIN) - 1 &&+ popup.y >= Math.max(0, owner.y - FRONT_COMPONENT_PORTAL_MARGIN) - 1 &&+ popup.x + popup.width <=+ Math.min(+ viewport.width,+ owner.x + owner.width + FRONT_COMPONENT_PORTAL_MARGIN,+ ) ++ 1 &&+ popup.y + popup.height <=+ Math.min(+ viewport.height,+ owner.y + owner.height + FRONT_COMPONENT_PORTAL_MARGIN,+ ) ++ 1+ );+ })+ .toBe(true);+ await page.keyboard.press('Escape');+ await expect(menu).not.toBeVisible();+ await frame.evaluate((node) => {+ const positionedFrame = node.parentElement;+ if (positionedFrame) positionedFrame.style.margin = '0';+ node.style.transform = '';+ node.scrollTop = 0;+ });+ await trigger.click();+ await expect(menu).toBeVisible();+ await expect+ .poll(async () => {+ const popup = await menu.boundingBox();+ const viewport = page.viewportSize()!;+ return (+ !!popup &&+ popup.x >= -1 &&+ popup.y >= -1 &&+ popup.x + popup.width <= viewport.width + 1 &&+ popup.y + popup.height <= viewport.height + 1+ );+ })+ .toBe(true);+ });+ test(`${runtime} popup follows an anchor moving after idle without resizing`, async ({+ page,+ }) => {+ await page.goto(+ `/iframe.html?id=frontcomponent-twenty-ui-gallery--portal-geometry-${runtime}`,+ );+ const trigger = page.getByRole('button', { name: 'Open menu' });+ await expect(trigger).toBeVisible({ timeout: MOUNT_TIMEOUT });+ await trigger.click();+ const menu = page.getByRole('menu');+ await expect(menu).toBeVisible();+ await page.evaluate(+ waitForAnimationFrames,+ GEOMETRY_IDLE_FRAME_THRESHOLD * 3,+ );+ const anchorBeforeMove = await readBounds(trigger);+ const popupBeforeMove = await readBounds(menu);++ await trigger.evaluate((node) => {+ node.style.transform = 'translateX(65px)';+ });+ await expect+ .poll(async () => {+ const anchor = await trigger.boundingBox();+ const popup = await menu.boundingBox();+ if (!isDefined(anchor) || !isDefined(popup)) {+ return false;+ }+ const side = await menu.getAttribute('data-side');+ return (+ isPopupAttachedToAnchor({ anchor, popup, side }) &&+ Math.abs(anchor.x - anchorBeforeMove.x - 65) < 1+ );+ })+ .toBe(true);+ const anchor = await readBounds(trigger);+ expect(anchor.width).toBeCloseTo(anchorBeforeMove.width);+ await expect+ .poll(async () => {+ const popup = await menu.boundingBox();+ return (+ isDefined(popup) && Math.abs(popup.x - popupBeforeMove.x - 65) < 1+ );+ })+ .toBe(true);+ });+}diff --git a/packages/twenty-front-component-renderer/scripts/front-component-stories/native-tests/readBounds.ts b/packages/twenty-front-component-renderer/scripts/front-component-stories/native-tests/readBounds.tsnew file mode 100644index 00000000000..d8431655808--- /dev/null+++ b/packages/twenty-front-component-renderer/scripts/front-component-stories/native-tests/readBounds.ts@@ -0,0 +1,12 @@+import { type Locator } from 'playwright/test';+import { isDefined } from 'twenty-shared/utils';++export const readBounds = async (locator: Locator) => {+ const bounds = await locator.boundingBox();++ if (!isDefined(bounds)) {+ throw new Error(`Bounds are unavailable for ${locator}`);+ }++ return bounds;+};diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsxindex ca91050f567..e50e4fa88a4 100644--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx@@ -32,15 +32,20 @@ import { RESPONSIVE_HOOKS_WIDGET_SIZING } from '@/__stories__/twenty-ui-gallery/import { dialogTest } from '@/__stories__/twenty-ui-gallery/utils/dialogTest';import { toastCountdownTest } from '@/__stories__/twenty-ui-gallery/utils/toastCountdownTest';import { type Meta } from '@storybook/react-vite';+import { expect, waitFor, within } from 'storybook/test';import {FRONT_COMPONENT_STORY_DEFAULT_ARGS,+ errorHandler,resetFrontComponentStoryMocks,} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';+import { MOUNT_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';import { type TwentyUiGalleryStory as Story } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryStory';import { statusControlsTest } from '@/__stories__/twenty-ui-gallery/utils/statusControlsTest';import { tagControlsTest } from '@/__stories__/twenty-ui-gallery/utils/tagControlsTest';import { PortalBoundsDecorator } from '@/__stories__/twenty-ui-gallery/components/PortalBoundsDecorator';+import { OverflowingListInstancesDecorator } from '@/__stories__/twenty-ui-gallery/components/OverflowingListInstancesDecorator';import { portalBoundsTest } from '@/__stories__/twenty-ui-gallery/utils/portalBoundsTest';import { createGalleryStory } from '@/__stories__/twenty-ui-gallery/utils/createGalleryStory';@@ -63,6 +68,7 @@ import { radioGroupTest } from '@/__stories__/twenty-ui-gallery/utils/radioGroupimport { segmentedControlTest } from '@/__stories__/twenty-ui-gallery/utils/segmentedControlTest';import { sliderRangeTest } from '@/__stories__/twenty-ui-gallery/utils/sliderRangeTest';import { sliderTest } from '@/__stories__/twenty-ui-gallery/utils/sliderTest';+import { sliderHiddenEdgeThumbTest } from '@/__stories__/twenty-ui-gallery/utils/sliderHiddenEdgeThumbTest';import { toastTest } from '@/__stories__/twenty-ui-gallery/utils/toastTest';import { avatarImageTest } from '@/__stories__/twenty-ui-gallery/utils/avatarImageTest';import { avatarControlsTest } from '@/__stories__/twenty-ui-gallery/utils/avatarControlsTest';@@ -510,7 +516,7 @@ export const CheckboxPreact: Story = createGalleryStory({export const SliderReact: Story = createGalleryStory({frontComponentBundleName: 'twenty-ui-slider',runtime: 'react',- play: sliderTest,+ play: sliderHiddenEdgeThumbTest,});export const SliderPreact: Story = createGalleryStory({frontComponentBundleName: 'twenty-ui-slider',@@ -790,3 +796,73 @@ export const AnimatedIconCrossfadePreact: Story = createGalleryStory({runtime: 'preact',play: animatedIconCrossfadeTest,});++const createMountOnlyPlay =+ ({+ testId,+ expectedCount = 1,+ }: {+ testId: string;+ expectedCount?: number;+ }): TwentyUiGalleryPlayFunction =>+ async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await waitFor(+ () => {+ const mountedComponents = canvas.getAllByTestId(testId);++ expect(mountedComponents).toHaveLength(expectedCount);+ for (const mountedComponent of mountedComponents) {+ expect(mountedComponent).toBeVisible();+ }+ },+ { timeout: MOUNT_TIMEOUT },+ );+ expect(errorHandler).not.toHaveBeenCalled();+ };++const galleryMountOnlyPlay = createMountOnlyPlay({+ testId: 'front-component-mounted',+});+const geometryMountOnlyPlay = createMountOnlyPlay({+ testId: 'geometry-measure-component',+});+const galleryInstancesMountOnlyPlay = createMountOnlyPlay({+ testId: 'front-component-mounted',+ expectedCount: 2,+});++export const PortalGeometryReact: Story = {+ ...PortalBoundsReact,+ play: galleryMountOnlyPlay,+};+export const PortalGeometryPreact: Story = {+ ...PortalBoundsPreact,+ play: galleryMountOnlyPlay,+};++export const LayoutMeasurementsReact: Story = createGalleryStory({+ frontComponentBundleName: 'geometry-measure',+ runtime: 'react',+ play: geometryMountOnlyPlay,+});+export const LayoutMeasurementsPreact: Story = createGalleryStory({+ frontComponentBundleName: 'geometry-measure',+ runtime: 'preact',+ play: geometryMountOnlyPlay,+});++export const OverflowingListInstancesReact: Story = createGalleryStory({+ frontComponentBundleName: 'twenty-ui-overflowing-list',+ runtime: 'react',+ decorators: [OverflowingListInstancesDecorator],+ play: galleryInstancesMountOnlyPlay,+});++export const OverflowingListInstancesPreact: Story = createGalleryStory({+ frontComponentBundleName: 'twenty-ui-overflowing-list',+ runtime: 'preact',+ decorators: [OverflowingListInstancesDecorator],+ play: galleryInstancesMountOnlyPlay,+});diff --git a/packages/twenty-front-component-renderer/src/__stories__/showcase/geometry-measure.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/showcase/geometry-measure.front-component.tsxindex 9398eb26cc0..5567e235236 100644--- a/packages/twenty-front-component-renderer/src/__stories__/showcase/geometry-measure.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/showcase/geometry-measure.front-component.tsx@@ -1,9 +1,22 @@-import { useEffect, useRef, useState } from 'react';+import { type CSSProperties, useEffect, useRef, useState } from 'react';import { defineFrontComponent } from 'twenty-sdk/define';const MEASURED_BOX_WIDTH = 240;const MEASURED_BOX_HEIGHT = 80;+type MeasuredBoxStyle = CSSProperties & Record<`--${string}`, string>;++const MEASURED_BOX_STYLE: MeasuredBoxStyle = {+ position: 'absolute',+ left: 12,+ top: 14,+ width: MEASURED_BOX_WIDTH,+ height: MEASURED_BOX_HEIGHT,+ backgroundColor: '#dbeafe',+ borderRadius: 8,+ '--measured-accent': 'rgb(1, 2, 3)',+};+const GeometryMeasureComponent = () => {const measuredBoxRef = useRef<HTMLDivElement>(null);const [measuredGeometry, setMeasuredGeometry] = useState({@@ -11,6 +24,13 @@ const GeometryMeasureComponent = () => {height: 0,offsetWidth: 0,innerWidth: 0,+ columnGap: '',+ direction: '',+ display: '',+ offsetLeft: 0,+ offsetTop: 0,+ hasOwnedOffsetParent: false,+ inlineAccent: '',});useEffect(() => {@@ -28,6 +48,15 @@ const GeometryMeasureComponent = () => {height: Math.round(rect.height),offsetWidth: measuredBox.offsetWidth,innerWidth: window.innerWidth,+ columnGap: getComputedStyle(measuredBox).columnGap,+ direction: getComputedStyle(measuredBox).direction,+ display: getComputedStyle(measuredBox).display,+ offsetLeft: measuredBox.offsetLeft,+ offsetTop: measuredBox.offsetTop,+ hasOwnedOffsetParent:+ measuredBox.offsetParent === measuredBox.parentElement,+ inlineAccent:+ getComputedStyle(measuredBox).getPropertyValue('--measured-accent'),});};@@ -41,16 +70,28 @@ const GeometryMeasureComponent = () => {data-testid="geometry-measure-component"style={{ fontFamily: 'system-ui, sans-serif', padding: 16 }}>- <div- ref={measuredBoxRef}- data-testid="geometry-measure-box"- style={{- width: MEASURED_BOX_WIDTH,- height: MEASURED_BOX_HEIGHT,- backgroundColor: '#dbeafe',- borderRadius: 8,- }}- />+ <style>+ {'.c05-measured-layout { display: flex; column-gap: 14px; }'}+ </style>+ <div style={{ position: 'relative', height: 120, direction: 'rtl' }}>+ <div+ className="c05-measured-layout"+ ref={measuredBoxRef}+ data-testid="geometry-measure-box"+ style={MEASURED_BOX_STYLE}+ />+ </div>+ <output data-testid="geometry-layout-facts">+ {JSON.stringify({+ columnGap: measuredGeometry.columnGap,+ direction: measuredGeometry.direction,+ display: measuredGeometry.display,+ offsetLeft: measuredGeometry.offsetLeft,+ offsetTop: measuredGeometry.offsetTop,+ hasOwnedOffsetParent: measuredGeometry.hasOwnedOffsetParent,+ inlineAccent: measuredGeometry.inlineAccent,+ })}+ </output><p data-testid="geometry-measure-width">width: {measuredGeometry.width}</p>diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.mdindex 78d17fd308c..635733ac931 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@@ -6,11 +6,11 @@ component stories. Each fixture has React and Preact stories built withPreact stories need Preact 11, which passes `ref` to function components as aregular prop like React 19. Preact 10 hands that ref to the component instance,so Dropdown-based popups never open there.-The field-controls fixture checks native input/textarea refs and change targets, typed textarea render composition, Field labels and controlled multiline value updates in React and Preact.+The layout fixtures mirror a bounded set of stylesheet and inherited layout properties, including logical paddings, borders and margins and individual transforms, for elements the worker already measures, plus native positioned ancestors and size observations. Reading a computed style enrolls an element only when one of its children is already measured, so container properties such as gaps follow the host. Theme custom properties are not mirrored, so they keep resolving through `var()` on the host, while inline custom properties still read back from the element's own style. Worker `ResizeObserver` entries report content, border and device-pixel content boxes from owned host snapshots, and `document.body` and `document.documentElement` report the renderer root box. They deliver the first valid measurement and later size changes, report a zero size when a measured target leaves the document, resume after it is reinserted, and stop after unobserve or disconnect. Position-only updates still use the existing geometry update path rather than resize notifications.-The standalone Toast countdown fixture checks remaining time after repeated content updates, zero-duration persistence, manual dismissal, progress suppression and restart, and overlapping hover/focus pauses in React and Preact. It does not cover `updateToast`, `ToastProvider` or `Toaster` in the worker. The SDK snackbar stories check the separate host notification API.+The field-controls fixture checks native input/textarea refs and change targets, typed textarea render composition, Field labels, controlled multiline value updates, positive Textarea height growth and shrink, and reflow after width changes in React and Preact. Auto-resize reads the host's intrinsic content measurement after a local block-size reset and reconciles delayed content measurements through the geometry update listener. Caller sizing overrides and detached controls end that reconciliation.-Textarea auto-resize remains a renderer limitation. Geometry reads use cached host snapshots, so resetting inline height and reading scrollHeight in the same turn cannot measure the updated layout. These stale reads can also produce cumulative height growth instead of fitting the current content. The field fixture verifies values, refs, events and accessibility without treating incidental height changes as resize acceptance. Standalone Textarea browser checks pass.+The standalone Toast countdown fixture checks remaining time after repeated content updates, zero-duration persistence, manual dismissal, progress suppression and restart, and overlapping hover/focus pauses in React and Preact. It does not cover `updateToast`, `ToastProvider` or `Toaster` in the worker. The SDK snackbar stories check the separate host notification API.NumberField checks locale formatting and localized paste, controlled empty values, uncontrolled typing, bounds, keyboard commits, pointer value changes, callback event details, accessible labels, native forms, refs and render composition in both runtimes. Sequential typing after clearing a formatted value can reset the caret and insert subsequent digits before earlier input. Formatted pointer edits can also restore stale display values when host blur races the worker update. Pointer button release does not emit its commit callback, although host blur can emit an input-blur commit. ScrubArea can enter its scrubbing state, but drag movement and release do not reach the worker window listeners; pointer lock and the custom scrub cursor are also unavailable. These renderer limits apply independently of the standalone React NumberField browser checks.@@ -223,16 +223,11 @@ Direct app-owned `Dialog`/`AlertDialog` modality and native browser dialog/popovAn invisible popup is not a compatibility pass.-Tabs still depends on C05 geometry acceptance for Indicator measurements and-physical activation direction. The worker lazily requests host snapshots on-first geometry reads and has no ResizeObserver to remeasure the initial-Indicator. Its first inactive-tab read returns a zero rectangle while the-active tab already has a snapshot, so a forward selection initially reports-`left` instead of `right`. The fixture pins both the zero-width Indicator and-incorrect initial direction with known-failure assertions while checking-selection, callback values/reasons, focus, panel relationships and native-composition. Passing these stories does not establish Indicator visibility or-physical-direction accuracy in the renderer.+Tabs geometry passes in both React and Preact with the C05 measurement+adapter. The fixture verifies that the Indicator is visible and aligns with+the active tab initially and after selection. The first forward selection+reports the physical activation direction `right`. Selection, callback+values/reasons, focus, panel relationships and native composition also pass.Native anchor Enter activation also remains a separate renderer limitation.Base UI recognizes native links by `tagName === 'A'`, while worker refs retain@@ -266,7 +261,8 @@ expected-to-fail by the runner.| Component | Current limitation || ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Popover, Select, CurrencyPicker, PhoneCountryPicker, CountrySelect (React and Preact) | Body portal content reaches the host inside the component portal area. These fixtures cover opening and visible content; search, selection, dismissal and focus restoration are not covered yet. |-| Slider | Thumbs stay hidden because the sandbox has no `ResizeObserver` to re-measure after the first geometry batch. |+| Slider (React) | Edge-aligned thumbs stay hidden until the value changes. Base UI 1.8 and 1.9 set up the thumb's `ResizeObserver` before React attaches the `Slider.Control` ref, so the thumb never re-measures once the first host geometry arrives ([mui/base-ui#5995](https://github.com/mui/base-ui/issues/5995), fix pending in [mui/base-ui#6000](https://github.com/mui/base-ui/pull/6000)). Preact attaches the ref first, so its thumbs appear. `thumbAlignment="center"` avoids the issue. |+| OverflowingList | Item widths come from the last host layout, because a worker cannot lay out the measuring state synchronously. The truncated last item is measured at its truncated width, so the visible count can differ from a native render when that item's full width decides whether it fits. || 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`,@@ -342,6 +338,14 @@ Then, from `packages/twenty-front-component-renderer`, run:npx vitest run --config vitest.storybook.config.ts TwentyUiGallery.stories.tsx```+For collision and anchor motion, and independent OverflowingList renderer cleanup, serve the fresh static Storybook on port 6008 and run the suite that CI runs as `storybook:test:layout`:++```sh+npx playwright test --config playwright.layout.config.ts+```++Set `STORYBOOK_URL` to use another Storybook URL.+The AvatarGroup, Autocomplete, CountrySelect and reading-directions fixtureslive in their own story files, so run them separately:diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/components/OverflowingListInstancesDecorator.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/components/OverflowingListInstancesDecorator.tsxnew file mode 100644index 00000000000..0ac73c708fb--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/components/OverflowingListInstancesDecorator.tsx@@ -0,0 +1,23 @@+import { type Decorator } from '@storybook/react-vite';+import { useState } from 'react';+import { Button } from 'twenty-ui/primitives/input';++export const OverflowingListInstancesDecorator: Decorator = (Story) => {+ const [isFirstRendererMounted, setIsFirstRendererMounted] = useState(true);++ return (+ <div>+ <Button onClick={() => setIsFirstRendererMounted(false)}>+ Remove first renderer+ </Button>+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: 24 }}>+ <div role="group" aria-label="First renderer">+ {isFirstRendererMounted && <Story />}+ </div>+ <div role="group" aria-label="Second renderer">+ <Story />+ </div>+ </div>+ </div>+ );+};diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/MaximumDropdownTriggerGap.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/MaximumDropdownTriggerGap.tsnew file mode 100644index 00000000000..7c44a29cb41--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/MaximumDropdownTriggerGap.ts@@ -0,0 +1 @@+export const MAXIMUM_DROPDOWN_TRIGGER_GAP = 16;diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-field-controls.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-field-controls.front-component.tsxindex 1ee6b4a4757..2c0d4ed1437 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-field-controls.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-field-controls.front-component.tsx@@ -19,6 +19,7 @@ const FieldControls = () => {const [controlValues, setControlValues] = useState('');const [email, setEmail] = useState('');const [notes, setNotes] = useState('');+ const [notesWidth, setNotesWidth] = useState('100%');const [reportedValues, setReportedValues] = useState('');return (@@ -74,6 +75,7 @@ const FieldControls = () => {onValueChange={setNotes}onChange={(event) => setNativeTarget(event.currentTarget.tagName)}rows={1}+ style={{ width: notesWidth }}autoResizemaxRows={6}render={(props, state) =>@@ -102,6 +104,22 @@ const FieldControls = () => {<Button type="button" onClick={() => setNotes('')}>Clear notes</Button>+ <Button+ type="button"+ onClick={() =>+ setNotes(+ 'Keep the team informed about the next meeting and share all follow up actions before the end of the week.',+ )+ }+ >+ Apply wrapping notes+ </Button>+ <Button type="button" onClick={() => setNotesWidth('140px')}>+ Narrow notes+ </Button>+ <Button type="button" onClick={() => setNotesWidth('100%')}>+ Widen notes+ </Button><p data-testid="native-target">{nativeTarget}</p><p data-testid="control-values">{controlValues}</p><Buttondiff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-overflowing-list.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-overflowing-list.front-component.tsxindex e0ebf51b1c7..d23fba0b8ca 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-overflowing-list.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-overflowing-list.front-component.tsx@@ -55,6 +55,8 @@ const OverflowingListExample = () => {<OverflowingListshowOverflowCountoverflowLabel="Show all measured items"+ role="group"+ aria-label="Measured list"style={{ width: listWidth }}>{INITIAL_TARGETS.map((target) => (@@ -65,6 +67,8 @@ const OverflowingListExample = () => {</OverflowingList>)}<Button onClick={() => setListWidth(500)}>Widen measured list</Button>+ <Button onClick={() => setListWidth(220)}>Narrow measured list</Button>+ <Button onClick={() => setListWidth(208)}>Fit one measured item</Button><Button onClick={() => setIsMeasuredListMounted(false)}>Remove measured list</Button>diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/computePopupAnchorGapAndOverlap.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/computePopupAnchorGapAndOverlap.tsnew file mode 100644index 00000000000..181470a2a5a--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/computePopupAnchorGapAndOverlap.ts@@ -0,0 +1,40 @@+type ElementBounds = {+ x: number;+ y: number;+ width: number;+ height: number;+};++export const computePopupAnchorGapAndOverlap = ({+ anchor,+ popup,+ side,+}: {+ anchor: ElementBounds;+ popup: ElementBounds;+ side: string | null;+}) => {+ const isHorizontallyPositioned = side === 'left' || side === 'right';+ const anchorRight = anchor.x + anchor.width;+ const anchorBottom = anchor.y + anchor.height;+ const popupRight = popup.x + popup.width;+ const popupBottom = popup.y + popup.height;++ if (isHorizontallyPositioned) {+ return {+ popupAnchorGap: Math.max(popup.x - anchorRight, anchor.x - popupRight),+ popupOverlapStart: popup.y,+ popupOverlapEnd: popupBottom,+ anchorOverlapStart: anchor.y,+ anchorOverlapEnd: anchorBottom,+ };+ }++ return {+ popupAnchorGap: Math.max(popup.y - anchorBottom, anchor.y - popupBottom),+ popupOverlapStart: popup.x,+ popupOverlapEnd: popupRight,+ anchorOverlapStart: anchor.x,+ anchorOverlapEnd: anchorRight,+ };+};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.tsindex ed76acad2aa..ab05860eb93 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@@ -5,7 +5,7 @@ import { getBuiltStoryComponentPathForRender } from '@/__stories__/utils/getBuiltype CreateGalleryStoryOptions = {frontComponentBundleName: string;runtime: 'react' | 'preact';- play: TwentyUiGalleryPlayFunction;+ play?: TwentyUiGalleryPlayFunction;decorators?: TwentyUiGalleryStory['decorators'];};diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/expectSliderGalleryMounted.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/expectSliderGalleryMounted.tsnew file mode 100644index 00000000000..97b31cafc88--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/expectSliderGalleryMounted.ts@@ -0,0 +1,20 @@+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';+import { expect, within } from 'storybook/test';++export const expectSliderGalleryMounted = async (+ canvasElement: HTMLElement,+): Promise<HTMLElement> => {+ const canvas = within(canvasElement);+ await expectFrontComponentMounted(canvas);+ const volume = within(canvas.getByRole('group', { name: 'Volume' }));+ const slider = volume.getByRole('slider', { hidden: true });+ expect(volume.getByRole('status')).toHaveTextContent('40');+ expect(slider).toHaveValue('40');+ const disabledVolume = within(+ canvas.getByRole('group', { name: 'Disabled volume' }),+ );+ expect(disabledVolume.getByRole('slider', { hidden: true })).toBeDisabled();+ expect(canvas.getByText('Volume: 40; Committed: 40')).toBeVisible();++ return slider;+};diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/fieldControlsTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/fieldControlsTest.tsindex d41cb157541..6170cfa6fc7 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/fieldControlsTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/fieldControlsTest.ts@@ -1,6 +1,9 @@import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';-import { TYPING_DELAY } from '@/__stories__/shared/test-utils/timeouts';+import {+ INTERACTION_TIMEOUT,+ TYPING_DELAY,+} from '@/__stories__/shared/test-utils/timeouts';import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';import { expect, userEvent, waitFor, within } from 'storybook/test';@@ -62,9 +65,60 @@ export const fieldControlsTest: TwentyUiGalleryPlayFunction = async ({);expect(notes.tagName).toBe('TEXTAREA');expect(notes).toHaveAttribute('data-filled');+ const shortNotesHeight = notes.getBoundingClientRect().height;await userEvent.click(canvas.getByRole('button', { name: 'Apply notes' }));await waitFor(() => expect(notes).toHaveValue('First\nSecond\nThird'));+ await waitFor(+ () =>+ expect(notes.getBoundingClientRect().height).toBeGreaterThan(+ shortNotesHeight,+ ),+ { timeout: INTERACTION_TIMEOUT },+ );+ const longNotesHeight = notes.getBoundingClientRect().height;await userEvent.click(canvas.getByRole('button', { name: 'Clear notes' }));await waitFor(() => expect(notes).toHaveValue(''));+ await waitFor(+ () =>+ expect(notes.getBoundingClientRect().height).toBeLessThan(+ longNotesHeight,+ ),+ { timeout: INTERACTION_TIMEOUT },+ );+ await userEvent.click(+ canvas.getByRole('button', { name: 'Apply wrapping notes' }),+ );+ await waitFor(() =>+ expect(notes).toHaveValue(+ 'Keep the team informed about the next meeting and share all follow up actions before the end of the week.',+ ),+ );+ await waitFor(() => expect(notes.scrollHeight).toBe(notes.clientHeight), {+ timeout: INTERACTION_TIMEOUT,+ });+ const wideNotesHeight = notes.getBoundingClientRect().height;+ await userEvent.click(canvas.getByRole('button', { name: 'Narrow notes' }));+ await waitFor(() => expect(getComputedStyle(notes).width).toBe('140px'), {+ timeout: INTERACTION_TIMEOUT,+ });+ await waitFor(() => expect(notes.scrollHeight).toBe(notes.clientHeight), {+ timeout: INTERACTION_TIMEOUT,+ });+ await waitFor(+ () =>+ expect(notes.getBoundingClientRect().height).toBeGreaterThan(+ wideNotesHeight,+ ),+ { timeout: INTERACTION_TIMEOUT },+ );+ const narrowNotesHeight = notes.getBoundingClientRect().height;+ await userEvent.click(canvas.getByRole('button', { name: 'Widen notes' }));+ await waitFor(+ () =>+ expect(notes.getBoundingClientRect().height).toBeLessThan(+ narrowNotesHeight,+ ),+ { timeout: INTERACTION_TIMEOUT },+ );expect(errorHandler).not.toHaveBeenCalled();};diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/listItemPopupOwnerTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/listItemPopupOwnerTest.tsindex 0b7459648c9..32c027c8a4b 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/listItemPopupOwnerTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/listItemPopupOwnerTest.ts@@ -1,5 +1,6 @@import { expect, userEvent, waitFor, within } from 'storybook/test';+import { INTERACTION_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';export const listItemPopupOwnerTest: TwentyUiGalleryPlayFunction = async ({@@ -19,7 +20,9 @@ export const listItemPopupOwnerTest: TwentyUiGalleryPlayFunction = async ({name: 'Unavailable notifications',});- await waitFor(() => expect(item).toBeVisible());+ await waitFor(() => expect(item).toBeVisible(), {+ timeout: INTERACTION_TIMEOUT,+ });expect(item.tagName).toBe('BUTTON');expect(item).toHaveAttribute('data-ref-tag', 'HTML-BUTTON');expect(disabledItem).toBeDisabled();diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListGeometryTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListGeometryTest.tsindex 9f84a1db451..bc2283812f9 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListGeometryTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/overflowingListGeometryTest.ts@@ -2,7 +2,9 @@ import { expect, userEvent, waitFor, within } from 'storybook/test';import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';+import { waitForAnimationFrames } from '@/__stories__/shared/test-utils/waitForAnimationFrames';import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';+import { GEOMETRY_IDLE_FRAME_THRESHOLD } from '@/host/geometry/constants/GeometryIdleFrameThreshold';export const overflowingListGeometryTest: TwentyUiGalleryPlayFunction = async ({canvasElement,@@ -24,6 +26,27 @@ export const overflowingListGeometryTest: TwentyUiGalleryPlayFunction = async ({canvas.queryByRole('button', { name: 'Measured Charlie' }),).toBeNull();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Fit one measured item' }),+ );+ await waitFor(() =>+ expect(+ canvas+ .getByRole('group', { name: 'Measured list' })+ .getBoundingClientRect().width,+ ).toBe(208),+ );+ await waitForAnimationFrames(GEOMETRY_IDLE_FRAME_THRESHOLD * 2);+ await expect(+ canvas.getByRole('button', { name: /Show all measured items$/ }),+ ).toHaveTextContent('+2');+ await expect(+ canvas.getByRole('button', { name: 'Measured Bravo' }),+ ).toBeVisible();+ await expect(+ canvas.queryByRole('button', { name: 'Measured Charlie' }),+ ).toBeNull();+await userEvent.click(canvas.getByRole('button', { name: 'Widen measured list' }),);@@ -36,6 +59,21 @@ export const overflowingListGeometryTest: TwentyUiGalleryPlayFunction = async ({canvas.getByRole('button', { name: 'Measured Delta' }),).toBeVisible();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Narrow measured list' }),+ );+ await waitFor(() =>+ expect(+ canvas.getByRole('button', { name: /Show all measured items$/ }),+ ).toHaveTextContent('+1'),+ );+ await expect(+ canvas.getByRole('button', { name: 'Measured Charlie' }),+ ).toBeInTheDocument();+ await expect(+ canvas.queryByRole('button', { name: 'Measured Delta' }),+ ).toBeNull();+await userEvent.click(canvas.getByRole('button', { name: 'Remove measured list' }),);diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/portalBoundsTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/portalBoundsTest.tsindex 90b3f300ef5..d590b8aac05 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/portalBoundsTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/portalBoundsTest.ts@@ -4,11 +4,12 @@ import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponeimport { expectElementToReceivePointer } from '@/__stories__/shared/test-utils/matchers/expectElementToReceivePointer';import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';import { waitForAnimationFrames } from '@/__stories__/shared/test-utils/waitForAnimationFrames';+import { MAXIMUM_DROPDOWN_TRIGGER_GAP } from '@/__stories__/twenty-ui-gallery/constants/MaximumDropdownTriggerGap';import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';+import { computePopupAnchorGapAndOverlap } from '@/__stories__/twenty-ui-gallery/utils/computePopupAnchorGapAndOverlap';import { FRONT_COMPONENT_PORTAL_MARGIN } from '@/constants/FrontComponentPortalMargin';import { GEOMETRY_IDLE_FRAME_THRESHOLD } from '@/host/geometry/constants/GeometryIdleFrameThreshold';-const MAXIMUM_DROPDOWN_TRIGGER_GAP = 16;const WIDGET_SCROLL_OFFSET = 40;const waitForGeometryTrackerToIdle = () =>@@ -65,34 +66,22 @@ const expectDropdownAttachedToTriggerWithinPortalArea = ({const menuRectangle = menu.getBoundingClientRect();const menuTriggerRectangle = menuTrigger.getBoundingClientRect();const ownerRectangle = ownerRoot.getBoundingClientRect();- const side = menu.getAttribute('data-side');- const isHorizontallyPositioned = side === 'left' || side === 'right';- const menuTriggerGap = isHorizontallyPositioned- ? Math.max(- menuRectangle.left - menuTriggerRectangle.right,- menuTriggerRectangle.left - menuRectangle.right,- )- : Math.max(- menuRectangle.top - menuTriggerRectangle.bottom,- menuTriggerRectangle.top - menuRectangle.bottom,- );- const menuOverlapStart = isHorizontallyPositioned- ? menuRectangle.top- : menuRectangle.left;- const menuOverlapEnd = isHorizontallyPositioned- ? menuRectangle.bottom- : menuRectangle.right;- const triggerOverlapStart = isHorizontallyPositioned- ? menuTriggerRectangle.top- : menuTriggerRectangle.left;- const triggerOverlapEnd = isHorizontallyPositioned- ? menuTriggerRectangle.bottom- : menuTriggerRectangle.right;-- expect(menuTriggerGap).toBeGreaterThanOrEqual(0);- expect(menuTriggerGap).toBeLessThanOrEqual(MAXIMUM_DROPDOWN_TRIGGER_GAP);- expect(menuOverlapStart).toBeLessThan(triggerOverlapEnd);- expect(menuOverlapEnd).toBeGreaterThan(triggerOverlapStart);+ const {+ popupAnchorGap,+ popupOverlapStart,+ popupOverlapEnd,+ anchorOverlapStart,+ anchorOverlapEnd,+ } = computePopupAnchorGapAndOverlap({+ anchor: menuTriggerRectangle,+ popup: menuRectangle,+ side: menu.getAttribute('data-side'),+ });++ expect(popupAnchorGap).toBeGreaterThanOrEqual(0);+ expect(popupAnchorGap).toBeLessThanOrEqual(MAXIMUM_DROPDOWN_TRIGGER_GAP);+ expect(popupOverlapStart).toBeLessThan(anchorOverlapEnd);+ expect(popupOverlapEnd).toBeGreaterThan(anchorOverlapStart);expect(menuRectangle.left).toBeGreaterThanOrEqual(ownerRectangle.left - FRONT_COMPONENT_PORTAL_MARGIN,);diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sliderHiddenEdgeThumbTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sliderHiddenEdgeThumbTest.tsnew file mode 100644index 00000000000..2a0cf59dfe6--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sliderHiddenEdgeThumbTest.ts@@ -0,0 +1,14 @@+import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';+import { expectAssertionToKeepFailing } from '@/__stories__/twenty-ui-gallery/utils/expectAssertionToKeepFailing';+import { expectSliderGalleryMounted } from '@/__stories__/twenty-ui-gallery/utils/expectSliderGalleryMounted';+import { expect } from 'storybook/test';++export const sliderHiddenEdgeThumbTest: TwentyUiGalleryPlayFunction = async ({+ canvasElement,+}) => {+ const slider = await expectSliderGalleryMounted(canvasElement);++ await expectAssertionToKeepFailing(() => expect(slider).toBeVisible());+ expect(errorHandler).not.toHaveBeenCalled();+};diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sliderTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sliderTest.tsindex 6a2775da679..b624407cd15 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sliderTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/sliderTest.ts@@ -1,27 +1,16 @@import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';-import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';import { INTERACTION_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';-import { expect, waitFor, within } from 'storybook/test';+import { expectSliderGalleryMounted } from '@/__stories__/twenty-ui-gallery/utils/expectSliderGalleryMounted';+import { expect, waitFor } from 'storybook/test';export const sliderTest: TwentyUiGalleryPlayFunction = async ({canvasElement,}) => {- const canvas = within(canvasElement);- await expectFrontComponentMounted(canvas);- const volume = within(canvas.getByRole('group', { name: 'Volume' }));- const slider = volume.getByRole('slider', { hidden: true });- expect(volume.getByRole('status')).toHaveTextContent('40');- expect(slider).toHaveValue('40');- const disabledVolume = within(- canvas.getByRole('group', { name: 'Disabled volume' }),- );- expect(disabledVolume.getByRole('slider', { hidden: true })).toBeDisabled();- await expect(- waitFor(() => expect(slider).toBeVisible(), {- timeout: INTERACTION_TIMEOUT,- }),- ).rejects.toThrow();- expect(canvas.getByText('Volume: 40; Committed: 40')).toBeVisible();+ const slider = await expectSliderGalleryMounted(canvasElement);++ await waitFor(() => expect(slider).toBeVisible(), {+ timeout: INTERACTION_TIMEOUT,+ });expect(errorHandler).not.toHaveBeenCalled();};diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tabsTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tabsTest.tsindex 7ff8e388566..5372f2b1c71 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tabsTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tabsTest.ts@@ -6,6 +6,28 @@ import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallerimport { expectAssertionToKeepFailing } from '@/__stories__/twenty-ui-gallery/utils/expectAssertionToKeepFailing';import { tabButtonTest } from '@/__stories__/twenty-ui-gallery/utils/tabButtonTest';+const INDICATOR_GEOMETRY_TOLERANCE = 2;++const expectIndicatorAlignedWithTab = ({+ indicator,+ tab,+}: {+ indicator: Element;+ tab: Element;+}) => {+ const indicatorRectangle = indicator.getBoundingClientRect();+ const tabRectangle = tab.getBoundingClientRect();++ expect(indicator).toBeVisible();+ expect(indicatorRectangle.width).toBeGreaterThan(0);+ expect(+ Math.abs(indicatorRectangle.width - tabRectangle.width),+ ).toBeLessThanOrEqual(INDICATOR_GEOMETRY_TOLERANCE);+ expect(+ Math.abs(indicatorRectangle.left - tabRectangle.left),+ ).toBeLessThanOrEqual(INDICATOR_GEOMETRY_TOLERANCE);+};+export const tabsTest: TwentyUiGalleryPlayFunction = async (context) => {const canvas = within(context.canvasElement);await expectFrontComponentMounted(canvas);@@ -50,8 +72,8 @@ export const tabsTest: TwentyUiGalleryPlayFunction = async (context) => {activity.getBoundingClientRect().left,);});- await expectAssertionToKeepFailing(() =>- expect(indicator.getBoundingClientRect().width).toBeGreaterThan(0),+ await waitFor(() =>+ expectIndicatorAlignedWithTab({ indicator, tab: overview }),);await userEvent.click(overview);await userEvent.keyboard('{ArrowRight}');@@ -76,7 +98,7 @@ export const tabsTest: TwentyUiGalleryPlayFunction = async (context) => {);expect(canvas.getByLabelText('Controlled change details').textContent,- ).toMatch(/^activity:none:(click|keydown):left$/);+ ).toMatch(/^activity:none:(click|keydown):right$/);expect(canvas.getByRole('tabpanel', { name: 'Activity' })).toBe(activityPanel,);@@ -85,10 +107,8 @@ export const tabsTest: TwentyUiGalleryPlayFunction = async (context) => {expect(activityPanel).toHaveAttribute('data-render-hidden', 'false');expect(overviewPanel).not.toBeVisible();});- await expectAssertionToKeepFailing(() =>- expect(- canvas.getByLabelText('Controlled change details').textContent,- ).toMatch(/^activity:none:(click|keydown):right$/),+ await waitFor(() =>+ expectIndicatorAlignedWithTab({ indicator, tab: activity }),);await userEvent.click(activity);expect(canvas.getByLabelText('Controlled change count')).toHaveTextContent(diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipEscapeDismissalTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipEscapeDismissalTest.tsindex 788849bd366..ec5b884c122 100644--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipEscapeDismissalTest.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/tooltipEscapeDismissalTest.ts@@ -38,13 +38,14 @@ export const tooltipEscapeDismissalTest: TwentyUiGalleryPlayFunction = async ({await user.keyboard('{Escape}');await waitFor(- () =>+ () => {expect(canvas.getByRole('status')).toHaveTextContent('Export help: closed',- ),+ );+ expect(page.queryByText(TOOLTIP_CONTENT)).not.toBeInTheDocument();+ },{ timeout: INTERACTION_TIMEOUT },);- expect(page.queryByText(TOOLTIP_CONTENT)).not.toBeInTheDocument();await user.tab();expect(canvas.getByRole('button', { name: 'Export details' })).toHaveFocus();await waitFor(diff --git a/packages/twenty-front-component-renderer/src/host/geometry/types/TextareaIntrinsicScrollHeightMeasurer.ts b/packages/twenty-front-component-renderer/src/host/geometry/types/TextareaIntrinsicScrollHeightMeasurer.tsnew file mode 100644index 00000000000..1983652a39c--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/geometry/types/TextareaIntrinsicScrollHeightMeasurer.ts@@ -0,0 +1,4 @@+export type TextareaIntrinsicScrollHeightMeasurer = {+ measure: (node: Element) => number | undefined;+ dispose: () => void;+};diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createGeometryTracker.test.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createGeometryTracker.test.tsindex e1323ad949f..954c4504b31 100644--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createGeometryTracker.test.ts+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createGeometryTracker.test.ts@@ -322,6 +322,37 @@ describe('createGeometryTracker', () => {expect(pushGeometryUpdates).toHaveBeenCalledTimes(1);});+ it('should omit an unchanged computed style from later pushes', () => {+ const { tracker, pushGeometryUpdates } = createArmedTracker();+ const observed = geometryGlobals.createStubNode({+ x: 0,+ y: 0,+ width: 10,+ height: 10,+ });++ observed.node.style.paddingTop = '2px';+ tracker.registerNode('1', observed.node);+ tracker.observe(['1']);+ geometryGlobals.flushAnimationFrame();++ observed.setGeometry({ x: 5, y: 0, width: 10, height: 10 });+ geometryGlobals.flushAnimationFrame();++ observed.node.style.paddingTop = '3px';+ geometryGlobals.flushAnimationFrame();++ const [firstBatch, secondBatch, thirdBatch] =+ pushGeometryUpdates.mock.calls.map(([batch]) => batch);++ expect(firstBatch.elements['1'].computedStyle['padding-top']).toBe('2px');+ expect(firstBatch.viewport.computedStyle).toBeDefined();+ expect(secondBatch.elements['1'].x).toBe(5);+ expect(secondBatch.elements['1'].computedStyle).toBeUndefined();+ expect(secondBatch.viewport.computedStyle).toBeUndefined();+ expect(thirdBatch.elements['1'].computedStyle['padding-top']).toBe('3px');+ });+it('should include the viewport in every pushed batch', () => {const { tracker, pushGeometryUpdates } = createArmedTracker();const observed = geometryGlobals.createStubNode({diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createTextareaIntrinsicScrollHeightMeasurer.test.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createTextareaIntrinsicScrollHeightMeasurer.test.tsnew file mode 100644index 00000000000..6edace90439--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/createTextareaIntrinsicScrollHeightMeasurer.test.ts@@ -0,0 +1,100 @@+import { createTextareaIntrinsicScrollHeightMeasurer } from '../createTextareaIntrinsicScrollHeightMeasurer';++const createAutoResizeTextarea = () => {+ const textarea = document.createElement('textarea');++ textarea.value = 'First\nSecond\nThird';+ textarea.rows = 1;+ textarea.style.blockSize = '130px';+ textarea.style.width = '240px';+ document.body.append(textarea);++ return textarea;+};++const findMeasurementTextareas = () =>+ document.body.querySelectorAll<HTMLTextAreaElement>(+ 'textarea[aria-hidden="true"]',+ );++describe('createTextareaIntrinsicScrollHeightMeasurer', () => {+ afterEach(() => {+ jest.restoreAllMocks();+ document.body.replaceChildren();+ });++ it('should keep elements other than textareas outside intrinsic measurements', () => {+ const measurer = createTextareaIntrinsicScrollHeightMeasurer();+ const element = document.createElement('div');++ expect(measurer.measure(element)).toBeUndefined();+ expect(findMeasurementTextareas()).toHaveLength(0);+ });++ it('should measure current content in a hidden textarea without mutating the source textarea', () => {+ const measurer = createTextareaIntrinsicScrollHeightMeasurer();+ const textarea = createAutoResizeTextarea();+ let measuredTextarea: HTMLTextAreaElement | null = null;+ jest+ .spyOn(Element.prototype, 'scrollHeight', 'get')+ .mockImplementation(function (this: Element) {+ measuredTextarea = this as HTMLTextAreaElement;+ return 64;+ });++ expect(measurer.measure(textarea)).toBe(64);+ expect(textarea.style.blockSize).toBe('130px');+ expect(measuredTextarea).not.toBe(textarea);+ expect(measuredTextarea).toHaveProperty('value', 'First\nSecond\nThird');+ expect(measuredTextarea).toHaveProperty('rows', 1);+ expect(measuredTextarea).toHaveProperty('style.blockSize', 'auto');+ expect(measuredTextarea).toHaveProperty('style.width', '240px');+ expect(measuredTextarea).toHaveProperty('style.visibility', 'hidden');+ });++ it('should reuse one hidden textarea and rewrite only what changed', () => {+ const measurer = createTextareaIntrinsicScrollHeightMeasurer();+ const textarea = createAutoResizeTextarea();++ measurer.measure(textarea);+ const measurementTextarea = findMeasurementTextareas()[0];+ const setProperty = jest.spyOn(measurementTextarea.style, 'setProperty');+ measurer.measure(textarea);++ expect(findMeasurementTextareas()).toHaveLength(1);+ expect(setProperty).not.toHaveBeenCalled();++ textarea.style.width = '140px';+ measurer.measure(textarea);++ expect(setProperty).toHaveBeenCalledTimes(1);+ expect(setProperty).toHaveBeenCalledWith('width', '140px');+ expect(findMeasurementTextareas()).toHaveLength(1);+ });++ it('should refresh intrinsic height when rendered metrics change without a value or style update', () => {+ const measurer = createTextareaIntrinsicScrollHeightMeasurer();+ const textarea = createAutoResizeTextarea();+ jest+ .spyOn(Element.prototype, 'scrollHeight', 'get')+ .mockReturnValueOnce(64)+ .mockReturnValueOnce(96);++ expect(measurer.measure(textarea)).toBe(64);+ expect(measurer.measure(textarea)).toBe(96);+ });++ it('should remove the hidden textarea when disposed and recreate it on the next measurement', () => {+ const measurer = createTextareaIntrinsicScrollHeightMeasurer();+ const textarea = createAutoResizeTextarea();++ measurer.measure(textarea);+ measurer.dispose();++ expect(findMeasurementTextareas()).toHaveLength(0);++ measurer.measure(textarea);++ expect(findMeasurementTextareas()).toHaveLength(1);+ });+});diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/isGeometrySnapshotEqualWithinEpsilon.test.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/isGeometrySnapshotEqualWithinEpsilon.test.tsindex f00f6a376f3..46fc262013b 100644--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/isGeometrySnapshotEqualWithinEpsilon.test.ts+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/isGeometrySnapshotEqualWithinEpsilon.test.ts@@ -5,48 +5,81 @@ const BASE_SNAPSHOT = { x: 10, y: 20, cursor: 'pointer' };describe('isGeometrySnapshotEqualWithinEpsilon', () => {it('should return false when the previous snapshot is null', () => {- expect(isGeometrySnapshotEqualWithinEpsilon(null, BASE_SNAPSHOT)).toBe(- false,- );+ expect(+ isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot: null,+ nextSnapshot: BASE_SNAPSHOT,+ }),+ ).toBe(false);});it('should return false when the previous snapshot is undefined', () => {- expect(isGeometrySnapshotEqualWithinEpsilon(undefined, BASE_SNAPSHOT)).toBe(- false,- );+ expect(+ isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot: undefined,+ nextSnapshot: BASE_SNAPSHOT,+ }),+ ).toBe(false);});it('should return true when the snapshots are equal', () => {expect(- isGeometrySnapshotEqualWithinEpsilon(BASE_SNAPSHOT, {- ...BASE_SNAPSHOT,+ isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot: BASE_SNAPSHOT,+ nextSnapshot: {+ ...BASE_SNAPSHOT,+ },}),).toBe(true);});it('should return true when a numeric value differs by less than the epsilon', () => {expect(- isGeometrySnapshotEqualWithinEpsilon(BASE_SNAPSHOT, {- ...BASE_SNAPSHOT,- x: BASE_SNAPSHOT.x + GEOMETRY_EPSILON_PIXELS / 2,+ isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot: BASE_SNAPSHOT,+ nextSnapshot: {+ ...BASE_SNAPSHOT,+ x: BASE_SNAPSHOT.x + GEOMETRY_EPSILON_PIXELS / 2,+ },}),).toBe(true);});it('should return false when a numeric value differs by more than the epsilon', () => {expect(- isGeometrySnapshotEqualWithinEpsilon(BASE_SNAPSHOT, {- ...BASE_SNAPSHOT,- y: BASE_SNAPSHOT.y + GEOMETRY_EPSILON_PIXELS * 2,+ isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot: BASE_SNAPSHOT,+ nextSnapshot: {+ ...BASE_SNAPSHOT,+ y: BASE_SNAPSHOT.y + GEOMETRY_EPSILON_PIXELS * 2,+ },}),).toBe(false);});it('should return false when a non-numeric value changes', () => {expect(- isGeometrySnapshotEqualWithinEpsilon(BASE_SNAPSHOT, {- ...BASE_SNAPSHOT,- cursor: 'default',+ isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot: BASE_SNAPSHOT,+ nextSnapshot: {+ ...BASE_SNAPSHOT,+ cursor: 'default',+ },+ }),+ ).toBe(false);+ });+ it('compares computed style values independently of snapshot object identity', () => {+ const previousSnapshot = { x: 10, computedStyle: { display: 'flex' } };+ expect(+ isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot,+ nextSnapshot: { x: 10, computedStyle: { display: 'flex' } },+ }),+ ).toBe(true);+ expect(+ isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot,+ nextSnapshot: { x: 10, computedStyle: { display: 'none' } },}),).toBe(false);});diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/measureNodeGeometry.test.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/measureNodeGeometry.test.tsindex 5c755c5bfc6..06494f4c934 100644--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/measureNodeGeometry.test.ts+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/__tests__/measureNodeGeometry.test.ts@@ -1,6 +1,7 @@import { measureNodeGeometry } from '../measureNodeGeometry';const ROOT_ORIGIN = { x: 0, y: 0 };+const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';const stubBoundingClientRect = (node: Element) => {node.getBoundingClientRect = () =>@@ -100,4 +101,82 @@ describe('measureNodeGeometry', () => {expect(snapshot.offsetWidth).toBe(0);expect(snapshot.offsetHeight).toBe(0);});+ it('preserves native offset ancestry instead of using viewport coordinates', () => {+ const node = document.createElement('div');+ stubBoundingClientRect(node);+ Object.defineProperty(node, 'offsetParent', {+ value: document.createElement('div'),+ });+ Object.defineProperty(node, 'offsetLeft', { value: 13 });+ Object.defineProperty(node, 'offsetTop', { value: 17 });+ const snapshot = measureNodeGeometry({+ node,+ rootContainerOrigin: ROOT_ORIGIN,+ resolveRemoteElementId: () => 'parent',+ });+ expect(snapshot.offsetLeft).toBe(13);+ expect(snapshot.offsetTop).toBe(17);+ });++ it('measures stylesheet layout and inherited direction', () => {+ const node = document.createElement('div');+ const stylesheet = document.createElement('style');+ stylesheet.textContent =+ '.measured-layout { display: flex; column-gap: 12px; overflow: hidden; }';+ document.head.append(stylesheet);+ node.className = 'measured-layout';+ node.style.direction = 'rtl';+ document.body.append(node);+ const snapshot = measureNodeGeometry({+ node,+ rootContainerOrigin: ROOT_ORIGIN,+ });+ expect(snapshot.computedStyle).toMatchObject({+ display: 'flex',+ 'column-gap': '12px',+ direction: 'rtl',+ });+ stylesheet.remove();+ node.remove();+ });++ it('measures the bounding box of SVG graphics inside an svg element', () => {+ const outerSvg = document.createElementNS(SVG_NAMESPACE, 'svg');+ const measuredGraphics = document.createElementNS(SVG_NAMESPACE, 'svg');+ const unmeasurableGraphics = document.createElementNS(SVG_NAMESPACE, 'svg');+ outerSvg.append(measuredGraphics, unmeasurableGraphics);+ Object.defineProperty(measuredGraphics, 'getBBox', {+ value: () => ({ x: 4, y: 6, width: 80, height: 40 }),+ });+ Object.defineProperty(unmeasurableGraphics, 'getBBox', {+ value: () => {+ throw new Error('The element is not rendered');+ },+ });++ const measureSvgBoundingBoxSize = (node: Element) => {+ stubBoundingClientRect(node);+ const { svgBoundingBoxWidth, svgBoundingBoxHeight } = measureNodeGeometry(+ {+ node,+ rootContainerOrigin: ROOT_ORIGIN,+ },+ );++ return { svgBoundingBoxWidth, svgBoundingBoxHeight };+ };++ expect(measureSvgBoundingBoxSize(measuredGraphics)).toEqual({+ svgBoundingBoxWidth: 80,+ svgBoundingBoxHeight: 40,+ });+ expect(measureSvgBoundingBoxSize(outerSvg)).toEqual({+ svgBoundingBoxWidth: undefined,+ svgBoundingBoxHeight: undefined,+ });+ expect(measureSvgBoundingBoxSize(unmeasurableGraphics)).toEqual({+ svgBoundingBoxWidth: undefined,+ svgBoundingBoxHeight: undefined,+ });+ });});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.tsindex 07b4f515c15..c47546ee0d8 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@@ -34,14 +34,17 @@ describe('measureViewportGeometry', () => {expect(viewport.rootContainerClientHeight).toBe(0);});- it('should not read computed styles', () => {- const getComputedStyle = jest.spyOn(window, 'getComputedStyle');+ it('should read the renderer root layout style without its custom properties', () => {const rootContainer = document.createElement('div');+ rootContainer.style.direction = 'rtl';+ rootContainer.style.setProperty('--t-background-primary', 'scoped-color');+ document.body.append(rootContainer);- measureViewportGeometry(rootContainer);+ const snapshot = measureViewportGeometry(rootContainer);- expect(getComputedStyle).not.toHaveBeenCalled();- getComputedStyle.mockRestore();+ expect(snapshot.computedStyle).toMatchObject({ direction: 'rtl' });+ expect(snapshot.computedStyle).not.toHaveProperty('--t-background-primary');+ rootContainer.remove();});it('should read the root container rect and client sizes', () => {diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryTracker.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryTracker.tsindex 69af31d7032..342b7ac8f71 100644--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryTracker.ts+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/createGeometryTracker.ts@@ -7,9 +7,11 @@ import { GEOMETRY_UNREGISTERED_OBSERVATION_EXPIRY_FRAMES } from '@/host/geometryimport { type GeometryTracker } from '@/host/geometry/types/GeometryTracker';import { type PushGeometryUpdates } from '@/host/geometry/types/PushGeometryUpdates';import { createGeometryWakeSources } from '@/host/geometry/utils/createGeometryWakeSources';+import { createTextareaIntrinsicScrollHeightMeasurer } from '@/host/geometry/utils/createTextareaIntrinsicScrollHeightMeasurer';import { isGeometrySnapshotEqualWithinEpsilon } from '@/host/geometry/utils/isGeometrySnapshotEqualWithinEpsilon';import { measureNodeGeometry } from '@/host/geometry/utils/measureNodeGeometry';import { measureViewportGeometry } from '@/host/geometry/utils/measureViewportGeometry';+import { omitUnchangedComputedStyle } from '@/host/geometry/utils/omitUnchangedComputedStyle';import { updateFrontComponentPortalLayer } from '@/host/geometry/utils/updateFrontComponentPortalLayer';import { sanitizeRemoteElementIds } from '@/host/geometry/utils/sanitizeRemoteElementIds';import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';@@ -46,6 +48,11 @@ export const createGeometryTracker = (): GeometryTracker => {};const wakeSources = createGeometryWakeSources(wake);+ const textareaIntrinsicScrollHeightMeasurer =+ createTextareaIntrinsicScrollHeightMeasurer();++ const resolveRegisteredRemoteElementId = (element: Element): string | null =>+ remoteElementIdByRegisteredNode.get(element) ?? null;const readViewportGeometry = (): ViewportGeometrySnapshot =>measureViewportGeometry(rootContainer);@@ -99,16 +106,27 @@ export const createGeometryTracker = (): GeometryTracker => {unregisteredObservedFrameCounts.delete(remoteElementId);- const snapshot = measureNodeGeometry({ node, rootContainerOrigin });+ const snapshot = measureNodeGeometry({+ node,+ rootContainerOrigin,+ resolveRemoteElementId: resolveRegisteredRemoteElementId,+ measureTextareaIntrinsicScrollHeight:+ textareaIntrinsicScrollHeightMeasurer.measure,+ });++ const previousSnapshot = lastElementSnapshots.get(remoteElementId);if (- !isGeometrySnapshotEqualWithinEpsilon(- lastElementSnapshots.get(remoteElementId),- snapshot,- )+ !isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot,+ nextSnapshot: snapshot,+ })) {lastElementSnapshots.set(remoteElementId, snapshot);- changedElements[remoteElementId] = snapshot;+ changedElements[remoteElementId] = omitUnchangedComputedStyle({+ previousSnapshot,+ nextSnapshot: snapshot,+ });}}@@ -124,10 +142,14 @@ export const createGeometryTracker = (): GeometryTracker => {wakeSources.detachElementSources();}- const hasViewportChanged = !isGeometrySnapshotEqualWithinEpsilon(- lastViewportSnapshot,- viewport,- );+ const hasViewportChanged = !isGeometrySnapshotEqualWithinEpsilon({+ previousSnapshot: lastViewportSnapshot,+ nextSnapshot: viewport,+ });+ const pushedViewport = omitUnchangedComputedStyle({+ previousSnapshot: lastViewportSnapshot,+ nextSnapshot: viewport,+ });lastViewportSnapshot = viewport;@@ -140,7 +162,7 @@ export const createGeometryTracker = (): GeometryTracker => {) {idleFrameCount = 0;pushGeometryUpdates({- viewport,+ viewport: pushedViewport,elements: changedElements,removedRemoteElementIds,});@@ -283,6 +305,7 @@ export const createGeometryTracker = (): GeometryTracker => {}wakeSources.detachAllSources();+ textareaIntrinsicScrollHeightMeasurer.dispose();observedRemoteElementIds.clear();lastElementSnapshots.clear();diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/createTextareaIntrinsicScrollHeightMeasurer.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/createTextareaIntrinsicScrollHeightMeasurer.tsnew file mode 100644index 00000000000..bdcd44965f7--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/createTextareaIntrinsicScrollHeightMeasurer.ts@@ -0,0 +1,135 @@+import { type TextareaIntrinsicScrollHeightMeasurer } from '@/host/geometry/types/TextareaIntrinsicScrollHeightMeasurer';+import { readComputedStyleProperties } from '@/host/geometry/utils/readComputedStyleProperties';++const TEXTAREA_MEASUREMENT_STYLE_PROPERTIES = [+ 'box-sizing',+ 'font-family',+ 'font-size',+ 'font-style',+ 'font-weight',+ 'font-stretch',+ 'font-variant-caps',+ 'font-variant-east-asian',+ 'font-variant-ligatures',+ 'font-variant-numeric',+ 'font-variant-position',+ 'font-variant-alternates',+ 'font-kerning',+ 'font-feature-settings',+ 'font-variation-settings',+ 'font-optical-sizing',+ 'font-size-adjust',+ 'font-synthesis-weight',+ 'font-synthesis-style',+ 'font-synthesis-small-caps',+ 'line-height',+ 'letter-spacing',+ 'word-spacing',+ 'text-indent',+ 'text-transform',+ 'text-rendering',+ 'white-space',+ 'word-break',+ 'overflow-wrap',+ 'hyphens',+ 'line-break',+ 'tab-size',+ 'writing-mode',+ 'direction',+ 'padding-top',+ 'padding-right',+ 'padding-bottom',+ 'padding-left',+ 'border-top-width',+ 'border-right-width',+ 'border-bottom-width',+ 'border-left-width',+ 'width',+ 'min-height',+ 'max-height',+ 'overflow-x',+ 'overflow-y',+] as const;++const createMeasurementTextarea = (+ ownerDocument: Document,+): HTMLTextAreaElement => {+ const measurementTextarea = ownerDocument.createElement('textarea');++ measurementTextarea.setAttribute('aria-hidden', 'true');+ measurementTextarea.tabIndex = -1;+ Object.assign(measurementTextarea.style, {+ blockSize: 'auto',+ position: 'fixed',+ visibility: 'hidden',+ pointerEvents: 'none',+ left: '-10000px',+ top: '0',+ margin: '0',+ });++ return measurementTextarea;+};++export const createTextareaIntrinsicScrollHeightMeasurer =+ (): TextareaIntrinsicScrollHeightMeasurer => {+ let measurementTextarea: HTMLTextAreaElement | null = null;+ const appliedStyleValues = new Map<string, string>();++ const resolveMeasurementTextarea = (+ ownerDocument: Document,+ ): HTMLTextAreaElement => {+ measurementTextarea ??= createMeasurementTextarea(ownerDocument);++ if (!measurementTextarea.isConnected) {+ ownerDocument.body.append(measurementTextarea);+ }++ return measurementTextarea;+ };++ const measure = (node: Element): number | undefined => {+ if (!(node instanceof HTMLTextAreaElement)) {+ return undefined;+ }++ const measurement = resolveMeasurementTextarea(node.ownerDocument);+ const measurementStyles = readComputedStyleProperties({+ node,+ propertyNames: TEXTAREA_MEASUREMENT_STYLE_PROPERTIES,+ });++ for (const [propertyName, value] of Object.entries(measurementStyles)) {+ if (appliedStyleValues.get(propertyName) !== value) {+ measurement.style.setProperty(propertyName, value);+ appliedStyleValues.set(propertyName, value);+ }+ }++ if (measurement.value !== node.value) {+ measurement.value = node.value;+ }++ if (measurement.rows !== node.rows) {+ measurement.rows = node.rows;+ }++ if (measurement.wrap !== node.wrap) {+ measurement.wrap = node.wrap;+ }++ if (measurement.placeholder !== node.placeholder) {+ measurement.placeholder = node.placeholder;+ }++ return measurement.scrollHeight;+ };++ const dispose = () => {+ measurementTextarea?.remove();+ measurementTextarea = null;+ appliedStyleValues.clear();+ };++ return { measure, dispose };+ };diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/isGeometrySnapshotEqualWithinEpsilon.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/isGeometrySnapshotEqualWithinEpsilon.tsindex 3b9f6b626e3..652e84c6374 100644--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/isGeometrySnapshotEqualWithinEpsilon.ts+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/isGeometrySnapshotEqualWithinEpsilon.ts@@ -1,25 +1,34 @@import { isNumber } from '@sniptt/guards';-import { isDefined } from 'twenty-shared/utils';+import { fastDeepEqual, isDefined } from 'twenty-shared/utils';import { GEOMETRY_EPSILON_PIXELS } from '@/host/geometry/constants/GeometryEpsilonPixels';+type SnapshotValue =+ | number+ | string+ | null+ | undefined+ | Record<string, string>;+export const isGeometrySnapshotEqualWithinEpsilon = <- TSnapshot extends Record<string, number | string | null>,->(- previousSnapshot: TSnapshot | null | undefined,- nextSnapshot: TSnapshot,-): boolean => {+ TSnapshot extends Record<string, SnapshotValue>,+>({+ previousSnapshot,+ nextSnapshot,+}: {+ previousSnapshot: TSnapshot | null | undefined;+ nextSnapshot: TSnapshot;+}): boolean => {if (!isDefined(previousSnapshot)) {return false;}- return Object.entries(nextSnapshot).every(([snapshotKey, nextValue]) => {+ return Object.keys(nextSnapshot).every((snapshotKey) => {const previousValue = previousSnapshot[snapshotKey];+ const nextValue = nextSnapshot[snapshotKey];- if (isNumber(nextValue) && isNumber(previousValue)) {- return Math.abs(previousValue - nextValue) < GEOMETRY_EPSILON_PIXELS;- }-- return previousValue === nextValue;+ return isNumber(previousValue) && isNumber(nextValue)+ ? Math.abs(previousValue - nextValue) < GEOMETRY_EPSILON_PIXELS+ : fastDeepEqual(previousValue, nextValue);});};diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/measureComputedLayoutStyle.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/measureComputedLayoutStyle.tsnew file mode 100644index 00000000000..7fef68a30d9--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/measureComputedLayoutStyle.ts@@ -0,0 +1,68 @@+import { readComputedStyleProperties } from '@/host/geometry/utils/readComputedStyleProperties';++const COMPUTED_LAYOUT_PROPERTIES = [+ 'display',+ 'visibility',+ 'direction',+ 'position',+ 'transform',+ 'translate',+ 'scale',+ 'rotate',+ 'perspective',+ 'filter',+ 'backdrop-filter',+ 'contain',+ 'container-type',+ 'will-change',+ 'content-visibility',+ 'overflow',+ 'overflow-x',+ 'overflow-y',+ 'width',+ 'height',+ 'min-width',+ 'min-height',+ 'max-width',+ 'max-height',+ 'box-sizing',+ 'column-gap',+ 'row-gap',+ 'writing-mode',+ 'padding-top',+ 'padding-right',+ 'padding-bottom',+ 'padding-left',+ 'padding-inline-start',+ 'padding-inline-end',+ 'padding-block-start',+ 'padding-block-end',+ 'border-top-width',+ 'border-right-width',+ 'border-bottom-width',+ 'border-left-width',+ 'border-inline-start-width',+ 'border-inline-end-width',+ 'border-block-start-width',+ 'border-block-end-width',+ 'margin-inline-start',+ 'margin-inline-end',+ 'margin-block-start',+ 'margin-block-end',+ 'scroll-padding-top',+ 'scroll-padding-right',+ 'scroll-padding-bottom',+ 'scroll-padding-left',+ 'scroll-margin-top',+ 'scroll-margin-right',+ 'scroll-margin-bottom',+ 'scroll-margin-left',+] as const;++export const measureComputedLayoutStyle = (+ node: Element,+): Record<string, string> =>+ readComputedStyleProperties({+ node,+ propertyNames: COMPUTED_LAYOUT_PROPERTIES,+ });diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/measureNodeGeometry.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/measureNodeGeometry.tsindex 26bfc954ffb..0fb581eefea 100644--- a/packages/twenty-front-component-renderer/src/host/geometry/utils/measureNodeGeometry.ts+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/measureNodeGeometry.ts@@ -1,7 +1,12 @@+import { isDefined } from 'twenty-shared/utils';+import { measureComputedLayoutStyle } from '@/host/geometry/utils/measureComputedLayoutStyle';+import { measureSvgBoundingBox } from '@/host/geometry/utils/measureSvgBoundingBox';import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';type MeasureNodeGeometryInput = {node: Element;+ resolveRemoteElementId?: (node: Element) => string | null;+ measureTextareaIntrinsicScrollHeight?: (node: Element) => number | undefined;rootContainerOrigin: {x: number;y: number;@@ -11,20 +16,35 @@ type MeasureNodeGeometryInput = {export const measureNodeGeometry = ({node,rootContainerOrigin,+ resolveRemoteElementId,+ measureTextareaIntrinsicScrollHeight,}: MeasureNodeGeometryInput): ElementGeometrySnapshot => {const { x, y, width, height } = node.getBoundingClientRect();const htmlNode = node instanceof HTMLElement ? node : null;+ const offsetParent = htmlNode?.offsetParent;+ const offsetParentRemoteElementId =+ offsetParent instanceof Element+ ? (resolveRemoteElementId?.(offsetParent) ?? null)+ : null;+ const hasOwnedOffsetParent = isDefined(offsetParentRemoteElementId);+ const svgBoundingBox = measureSvgBoundingBox(node);+return {+ offsetParentRemoteElementId,x,y,width,height,offsetWidth: htmlNode?.offsetWidth ?? 0,offsetHeight: htmlNode?.offsetHeight ?? 0,- offsetTop: y - rootContainerOrigin.y,- offsetLeft: x - rootContainerOrigin.x,+ offsetTop: hasOwnedOffsetParent+ ? (htmlNode?.offsetTop ?? 0)+ : y - rootContainerOrigin.y,+ offsetLeft: hasOwnedOffsetParent+ ? (htmlNode?.offsetLeft ?? 0)+ : x - rootContainerOrigin.x,clientWidth: node.clientWidth,clientHeight: node.clientHeight,clientTop: node.clientTop,@@ -33,5 +53,9 @@ export const measureNodeGeometry = ({scrollHeight: node.scrollHeight,scrollTop: node.scrollTop,scrollLeft: node.scrollLeft,+ computedStyle: measureComputedLayoutStyle(node),+ textareaIntrinsicScrollHeight: measureTextareaIntrinsicScrollHeight?.(node),+ svgBoundingBoxWidth: svgBoundingBox?.width,+ svgBoundingBoxHeight: svgBoundingBox?.height,};};diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/measureSvgBoundingBox.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/measureSvgBoundingBox.tsnew file mode 100644index 00000000000..3faf5a4cee9--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/measureSvgBoundingBox.ts@@ -0,0 +1,20 @@+import { isDefined } from 'twenty-shared/utils';++export const measureSvgBoundingBox = (+ node: Element,+): { width: number; height: number } | null => {+ if (+ !(node instanceof SVGGraphicsElement) ||+ !isDefined(node.ownerSVGElement)+ ) {+ return null;+ }++ try {+ const { width, height } = node.getBBox();++ return { width, height };+ } catch {+ return null;+ }+};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.tsindex 9ce0261850c..66e8eadf85f 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 { measureComputedLayoutStyle } from '@/host/geometry/utils/measureComputedLayoutStyle';import { readInputMediaFeatures } from '@/host/geometry/utils/readInputMediaFeatures';import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot';@@ -23,5 +24,8 @@ export const measureViewportGeometry = (rootContainerClientWidth: rootContainer?.clientWidth ?? 0,rootContainerClientHeight: rootContainer?.clientHeight ?? 0,...readInputMediaFeatures(),+ computedStyle: isDefined(rootContainer)+ ? measureComputedLayoutStyle(rootContainer)+ : {},};};diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/omitUnchangedComputedStyle.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/omitUnchangedComputedStyle.tsnew file mode 100644index 00000000000..2d4137ce8f2--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/omitUnchangedComputedStyle.ts@@ -0,0 +1,15 @@+import { fastDeepEqual, isDefined } from 'twenty-shared/utils';++export const omitUnchangedComputedStyle = <+ TSnapshot extends { computedStyle?: Record<string, string> },+>({+ previousSnapshot,+ nextSnapshot,+}: {+ previousSnapshot: TSnapshot | null | undefined;+ nextSnapshot: TSnapshot;+}): TSnapshot =>+ isDefined(previousSnapshot) &&+ fastDeepEqual(previousSnapshot.computedStyle, nextSnapshot.computedStyle)+ ? { ...nextSnapshot, computedStyle: undefined }+ : nextSnapshot;diff --git a/packages/twenty-front-component-renderer/src/host/geometry/utils/readComputedStyleProperties.ts b/packages/twenty-front-component-renderer/src/host/geometry/utils/readComputedStyleProperties.tsnew file mode 100644index 00000000000..fbb7f87bf3e--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/geometry/utils/readComputedStyleProperties.ts@@ -0,0 +1,21 @@+import { isDefined } from 'twenty-shared/utils';++export const readComputedStyleProperties = ({+ node,+ propertyNames,+}: {+ node: Element;+ propertyNames: readonly string[];+}): Record<string, string> => {+ const computedStyle = node.ownerDocument.defaultView?.getComputedStyle(node);++ if (!isDefined(computedStyle)) {+ return {};+ }++ const values: Record<string, string> = {};+ for (const propertyName of propertyNames) {+ values[propertyName] = computedStyle.getPropertyValue(propertyName);+ }+ return values;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/ElementWithStyle.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/ElementWithStyle.tsdeleted file mode 100644index f61f0c1d9fc..00000000000--- a/packages/twenty-front-component-renderer/src/polyfills/dom/types/ElementWithStyle.ts+++ /dev/null@@ -1,3 +0,0 @@-export type ElementWithStyle = {- style?: unknown;-};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installGetComputedStyle.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installGetComputedStyle.test.tsindex 195c3cd8422..c65e78223c1 100644--- a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installGetComputedStyle.test.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installGetComputedStyle.test.ts@@ -1,3 +1,8 @@+import { isFunction } from '@sniptt/guards';++import { createStyleProxy } from '@/polyfills/dom/utils/createStyleProxy';+import { createElementGeometrySnapshotFixture } from '@/testing/createElementGeometrySnapshotFixture';+import { createWorkerGeometryStoreStub } from '@/testing/createWorkerGeometryStoreStub';import { installGetComputedStyle } from '../installGetComputedStyle';type StyleDeclarationLike = {@@ -15,7 +20,10 @@ describe('installGetComputedStyle', () => {const polyfillWindow: Record<string, unknown> = {};const globalScope: Record<string, unknown> = { window: polyfillWindow };- installGetComputedStyle(globalScope);+ installGetComputedStyle({+ globalScope,+ geometryStore: createWorkerGeometryStoreStub(),+ });expect(typeof globalScope.getComputedStyle).toBe('function');expect(typeof polyfillWindow.getComputedStyle).toBe('function');@@ -23,7 +31,10 @@ describe('installGetComputedStyle', () => {it('should return the declared style of the element', () => {const globalScope: Record<string, unknown> = {};- installGetComputedStyle(globalScope);+ installGetComputedStyle({+ globalScope,+ geometryStore: createWorkerGeometryStoreStub(),+ });const style = { getPropertyValue: () => '14px', fontSize: '14px' };@@ -33,9 +44,30 @@ describe('installGetComputedStyle', () => {).toBe('14px');});+ it('reads declared values from the renderer style proxy before measurement', () => {+ const globalScope: Record<string, unknown> = {};+ installGetComputedStyle({+ globalScope,+ geometryStore: createWorkerGeometryStoreStub(),+ });+ const declaredStyle = createStyleProxy(() => {});+ declaredStyle.setProperty('font-size', '14px');++ const getComputedStyle = globalScope.getComputedStyle;+ if (!isFunction<GetComputedStyleLike, unknown>(getComputedStyle)) {+ throw new Error('getComputedStyle was not installed');+ }+ const computedStyle = getComputedStyle({ style: declaredStyle });++ expect(computedStyle.fontSize).toBe('14px');+ });+it('should return an empty declaration for an element without a style', () => {const globalScope: Record<string, unknown> = {};- installGetComputedStyle(globalScope);+ installGetComputedStyle({+ globalScope,+ geometryStore: createWorkerGeometryStoreStub(),+ });const declaration = (globalScope.getComputedStyle as GetComputedStyleLike)({},@@ -47,7 +79,10 @@ describe('installGetComputedStyle', () => {it('should return an empty declaration for a pseudo-element argument', () => {const globalScope: Record<string, unknown> = {};- installGetComputedStyle(globalScope);+ installGetComputedStyle({+ globalScope,+ geometryStore: createWorkerGeometryStoreStub(),+ });const style = { getPropertyValue: () => '14px', fontSize: '14px' };@@ -59,4 +94,103 @@ describe('installGetComputedStyle', () => {expect(declaration.getPropertyValue('font-size')).toBe('');expect(declaration.fontSize).toBe('');});+ it('should read measured values of an observed element through the same declaration without enrolling it', () => {+ const globalScope: Record<string, unknown> = {};+ let columnGap = '12px';+ const geometryStore = createWorkerGeometryStoreStub({+ readObservedElementSnapshot: () =>+ createElementGeometrySnapshotFixture({+ computedStyle: { 'column-gap': columnGap, display: 'flex' },+ }),+ });+ installGetComputedStyle({ globalScope, geometryStore });+ const style = (globalScope.getComputedStyle as GetComputedStyleLike)({+ style: { getPropertyValue: () => '99px' },+ });++ expect(style.getPropertyValue('Column-Gap')).toBe('12px');+ columnGap = '24px';+ expect(style.getPropertyValue('column-gap')).toBe('24px');+ expect(style.getPropertyValue('transition-duration')).toBe('99px');+ expect(geometryStore.resolveElementSnapshot).not.toHaveBeenCalled();+ });++ it('should fall back to the declared style for an element that is not measured', () => {+ const globalScope: Record<string, unknown> = {};+ const geometryStore = createWorkerGeometryStoreStub();+ installGetComputedStyle({ globalScope, geometryStore });+ const declaredStyle = createStyleProxy(() => {});+ declaredStyle.setProperty('display', 'grid');++ const style = (globalScope.getComputedStyle as GetComputedStyleLike)({+ style: declaredStyle,+ });++ expect(style.getPropertyValue('display')).toBe('grid');+ expect(geometryStore.resolveElementSnapshot).not.toHaveBeenCalled();+ });++ it('should enroll a container whose child element is already measured', () => {+ const globalScope: Record<string, unknown> = {};+ const measuredChild = { nodeType: 1 };+ const container = {+ childNodes: [{ nodeType: 3 }, measuredChild],+ style: { getPropertyValue: () => '0px' },+ };+ const geometryStore = createWorkerGeometryStoreStub({+ isElementMeasured: jest.fn((element) => element === measuredChild),+ resolveElementSnapshot: jest.fn(() =>+ createElementGeometrySnapshotFixture({+ computedStyle: { 'column-gap': '4px' },+ }),+ ),+ });+ installGetComputedStyle({ globalScope, geometryStore });++ const style = (globalScope.getComputedStyle as GetComputedStyleLike)(+ container,+ );++ expect(style.getPropertyValue('column-gap')).toBe('4px');+ expect(geometryStore.resolveElementSnapshot).toHaveBeenCalledWith(+ container,+ );+ });++ it('should keep Object.prototype members callable on the declaration', () => {+ const globalScope: Record<string, unknown> = {};+ installGetComputedStyle({+ globalScope,+ geometryStore: createWorkerGeometryStoreStub(),+ });++ const style = (globalScope.getComputedStyle as GetComputedStyleLike)({+ style: createStyleProxy(() => {}),+ });++ expect(() => `${style}`).not.toThrow();+ expect(style.hasOwnProperty('display')).toBe(false);+ expect(style.getPropertyValue('constructor')).toBe('');+ });++ it('should not read inherited members of a measured style as property values', () => {+ const globalScope: Record<string, unknown> = {};+ installGetComputedStyle({+ globalScope,+ geometryStore: createWorkerGeometryStoreStub({+ readObservedElementSnapshot: () =>+ createElementGeometrySnapshotFixture({+ computedStyle: { display: 'flex' },+ }),+ }),+ });++ const style = (globalScope.getComputedStyle as GetComputedStyleLike)({+ style: createStyleProxy(() => {}),+ });++ expect(style.getPropertyValue('display')).toBe('flex');+ expect(style.getPropertyValue('constructor')).toBe('');+ expect(style.getPropertyValue('__proto__')).toBe('');+ });});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/findAncestorByRemoteId.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/findAncestorByRemoteId.tsnew file mode 100644index 00000000000..ae8a1df9d26--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/findAncestorByRemoteId.ts@@ -0,0 +1,24 @@+import { remoteId } from '@remote-dom/core/elements';++import { type NodeLike } from '@/polyfills/dom/types/NodeLike';+import { isElementNode } from '@/polyfills/dom/utils/isElementNode';++export const findAncestorByRemoteId = ({+ node,+ remoteElementId,+}: {+ node: NodeLike;+ remoteElementId: string;+}): Element | null => {+ let ancestor: unknown = node.parentNode;++ while (isElementNode(ancestor)) {+ if (remoteId(ancestor) === remoteElementId) {+ return ancestor;+ }++ ancestor = ancestor.parentNode;+ }++ return null;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installGetComputedStyle.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installGetComputedStyle.tsindex 4afb956aa22..9ea83f3ef29 100644--- a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installGetComputedStyle.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installGetComputedStyle.ts@@ -1,27 +1,85 @@-import { isNonEmptyString, isObject } from '@sniptt/guards';-import { isDefined } from 'twenty-shared/utils';+import {+ isFunction,+ isNonEmptyString,+ isObject,+ isString,+} from '@sniptt/guards';-import { type ElementWithStyle } from '@/polyfills/dom/types/ElementWithStyle';import { createStyleProxy } from '@/polyfills/dom/utils/createStyleProxy';+import { isObjectPrototypeMember } from '@/polyfills/dom/utils/isObjectPrototypeMember';+import { resolveCssPropertyNameFromJsPropertyName } from '@/polyfills/dom/utils/resolveCssPropertyNameFromJsPropertyName';+import { type WorkerGeometryStore } from '@/polyfills/geometry/types/WorkerGeometryStore';+import { hasMeasuredChildElement } from '@/polyfills/geometry/utils/hasMeasuredChildElement';import { resolveGlobalScopeInstallTargets } from '@/polyfills/utils/resolveGlobalScopeInstallTargets';+import { normalizeCssPropertyName } from '@/utils/css/normalizeCssPropertyName';-export const installGetComputedStyle = (- globalScope: Record<string, unknown>,-): void => {- const createEmptyStyleDeclaration = () => createStyleProxy(() => {});-+export const installGetComputedStyle = ({+ globalScope,+ geometryStore,+}: {+ globalScope: Record<string, unknown>;+ geometryStore: WorkerGeometryStore;+}): void => {const getComputedStyle = (element: unknown, pseudoElement?: unknown) => {- if (isNonEmptyString(pseudoElement)) {- return createEmptyStyleDeclaration();+ if (isNonEmptyString(pseudoElement) || !isObject(element)) {+ return createStyleProxy(() => {});}- const declaredStyle = isObject(element)- ? (element as ElementWithStyle).style- : undefined;+ const declaredStyle = 'style' in element ? element.style : undefined;++ const readDeclaredProperty = (cssPropertyName: string): string => {+ if (!isObject(declaredStyle)) {+ return '';+ }+ const getDeclaredPropertyValue: unknown = Reflect.get(+ declaredStyle,+ 'getPropertyValue',+ );+ if (!isFunction(getDeclaredPropertyValue)) {+ return '';+ }+ const declaredValue: unknown = getDeclaredPropertyValue.call(+ declaredStyle,+ cssPropertyName,+ );+ return isString(declaredValue) ? declaredValue : '';+ };++ const readMeasuredSnapshot = () =>+ geometryStore.readObservedElementSnapshot(element) ??+ (hasMeasuredChildElement({ element, geometryStore })+ ? geometryStore.resolveElementSnapshot(element)+ : null);++ const readProperty = (propertyName: string): string => {+ const cssPropertyName = normalizeCssPropertyName(propertyName);+ const measuredValue = isObjectPrototypeMember(cssPropertyName)+ ? undefined+ : readMeasuredSnapshot()?.computedStyle?.[cssPropertyName];++ return measuredValue ?? readDeclaredProperty(cssPropertyName);+ };- return isDefined(declaredStyle)- ? declaredStyle- : createEmptyStyleDeclaration();+ return new Proxy(+ {},+ {+ get(target, property) {+ if (property === 'getPropertyValue') {+ return readProperty;+ }+ if (isObjectPrototypeMember(property)) {+ return Reflect.get(Object.prototype, property);+ }+ if (isString(property)) {+ return readProperty(+ resolveCssPropertyNameFromJsPropertyName(property),+ );+ }+ return Reflect.get(target, property);+ },+ set: () => false,+ },+ );};for (const installTarget of resolveGlobalScopeInstallTargets(globalScope)) {diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isElementNode.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isElementNode.tsnew file mode 100644index 00000000000..e3fa2f27620--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isElementNode.ts@@ -0,0 +1,6 @@+import { isObject } from '@sniptt/guards';++import { NODE_TYPE_BY_NAME } from '@/polyfills/dom/constants/NodeTypeByName';++export const isElementNode = (node: unknown): node is Element =>+ isObject(node) && Reflect.get(node, 'nodeType') === NODE_TYPE_BY_NAME.ELEMENT;diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/constants/EmptyElementGeometrySnapshot.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/constants/EmptyElementGeometrySnapshot.tsnew file mode 100644index 00000000000..2f93256131e--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/constants/EmptyElementGeometrySnapshot.ts@@ -0,0 +1,20 @@+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++export const EMPTY_ELEMENT_GEOMETRY_SNAPSHOT: ElementGeometrySnapshot = {+ x: 0,+ y: 0,+ width: 0,+ height: 0,+ offsetWidth: 0,+ offsetHeight: 0,+ offsetTop: 0,+ offsetLeft: 0,+ clientWidth: 0,+ clientHeight: 0,+ clientTop: 0,+ clientLeft: 0,+ scrollWidth: 0,+ scrollHeight: 0,+ scrollTop: 0,+ scrollLeft: 0,+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/constants/HostRenderedHtmlTagNames.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/constants/HostRenderedHtmlTagNames.tsnew file mode 100644index 00000000000..a55c5c9f3a2--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/constants/HostRenderedHtmlTagNames.ts@@ -0,0 +1,5 @@+import { HTML_TAG_NAME_BY_REMOTE_ELEMENT_TAG_NAME } from '@/polyfills/selectors/constants/HtmlTagNameByRemoteElementTagName';++export const HOST_RENDERED_HTML_TAG_NAMES: ReadonlySet<string> = new Set(+ HTML_TAG_NAME_BY_REMOTE_ELEMENT_TAG_NAME.values(),+);diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/types/ElementGeometryReader.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/types/ElementGeometryReader.tsnew file mode 100644index 00000000000..e193819cca8--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/types/ElementGeometryReader.ts@@ -0,0 +1,6 @@+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++export type ElementGeometryReader = {+ read: () => ElementGeometrySnapshot | null;+ release: () => void;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/types/SnapshotBoxDimensions.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/types/SnapshotBoxDimensions.tsnew file mode 100644index 00000000000..05fbee5f1af--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/types/SnapshotBoxDimensions.ts@@ -0,0 +1,4 @@+export type SnapshotBoxDimensions = {+ contentBox: { x: number; y: number; width: number; height: number };+ borderBox: { width: number; height: number };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/types/TextareaIntrinsicSizeElement.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/types/TextareaIntrinsicSizeElement.tsnew file mode 100644index 00000000000..58190cbd178--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/types/TextareaIntrinsicSizeElement.ts@@ -0,0 +1,6 @@+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';++export type TextareaIntrinsicSizeElement = SelectorElementLike & {+ isConnected?: boolean;+ style?: { blockSize: string };+};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.tsindex 3ba148d8621..c394afbef2f 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@@ -1,3 +1,4 @@+import { type ElementGeometryReader } from '@/polyfills/geometry/types/ElementGeometryReader';import { type GeometryObservationTransport } from '@/polyfills/geometry/types/GeometryObservationTransport';import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';import { type GeometryUpdateBatch } from '@/types/GeometryUpdateBatch';@@ -10,4 +11,9 @@ export type WorkerGeometryStore = {getViewportSnapshot: () => ViewportGeometrySnapshot | null;subscribeToGeometryUpdates: (listener: () => void) => () => void;resolveElementSnapshot: (element: object) => ElementGeometrySnapshot | null;+ readObservedElementSnapshot: (+ element: object,+ ) => ElementGeometrySnapshot | null;+ isElementMeasured: (element: object) => boolean;+ createElementGeometryReader: (element: object) => ElementGeometryReader;};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.tsindex c7f397951f3..b8348d22f72 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@@ -36,12 +36,18 @@ const flushMicrotasks = async () => {const createRootedStore = () => {const store = createWorkerGeometryStore();- const rootElement = { parentNode: null };+ const documentElement = { localName: 'html', parentNode: null };+ const rootElement = { localName: 'body', parentNode: documentElement };store.setRootElement(rootElement);- return { store, rootElement };+ return { store, rootElement, documentElement };};+const createHostElement = (parentNode: object) => ({+ localName: 'html-div',+ parentNode,+});+describe('createWorkerGeometryStore', () => {beforeEach(() => {nextRemoteElementId = 0;@@ -76,7 +82,7 @@ describe('createWorkerGeometryStore', () => {unobserveElementGeometry: jest.fn().mockResolvedValue(undefined),});- const element = { parentNode: rootElement };+ const element = createHostElement(rootElement);store.resolveElementSnapshot(element);store.resolveElementSnapshot(element);@@ -86,6 +92,107 @@ describe('createWorkerGeometryStore', () => {expect(observeElementGeometry).toHaveBeenCalledWith(['0']);});+ it('should report an element as measured once a read enrolls it', () => {+ const { store, rootElement } = createRootedStore();+ const element = createHostElement(rootElement);++ expect(store.isElementMeasured(element)).toBe(false);++ store.resolveElementSnapshot(element);++ expect(store.isElementMeasured(element)).toBe(true);+ expect(store.isElementMeasured(rootElement)).toBe(false);+ });++ it('should not enroll the remote root or elements the host renders without a node', async () => {+ const { store, rootElement } = createRootedStore();+ const observeElementGeometry = jest.fn().mockResolvedValue(undefined);+ store.connectTransport({+ observeElementGeometry,+ unobserveElementGeometry: jest.fn().mockResolvedValue(undefined),+ });+ const renderContainer = {+ localName: 'remote-fragment',+ parentNode: rootElement,+ };+ const plainElement = { localName: 'div', parentNode: renderContainer };++ expect(store.resolveElementSnapshot(rootElement)).toBeNull();+ expect(store.resolveElementSnapshot(renderContainer)).toBeNull();+ store.resolveElementSnapshot(plainElement);+ await flushMicrotasks();++ expect(observeElementGeometry).toHaveBeenCalledTimes(1);+ expect(observeElementGeometry).toHaveBeenCalledWith(['0']);+ });++ it('should read an observed snapshot without enrolling unobserved elements', async () => {+ const { store, rootElement } = createRootedStore();+ const observeElementGeometry = jest.fn().mockResolvedValue(undefined);+ store.connectTransport({+ observeElementGeometry,+ unobserveElementGeometry: jest.fn().mockResolvedValue(undefined),+ });+ const element = createHostElement(rootElement);++ expect(store.readObservedElementSnapshot(element)).toBeNull();+ await flushMicrotasks();+ expect(observeElementGeometry).not.toHaveBeenCalled();++ store.resolveElementSnapshot(element);+ store.applyGeometryBatch({ elements: { '0': createSnapshot(42) } });++ expect(store.readObservedElementSnapshot(element)?.width).toBe(42);+ });++ it('should resolve the remote root and its document element from the renderer root container without enrolling them', async () => {+ const { store, rootElement, documentElement } = createRootedStore();+ const observeElementGeometry = jest.fn().mockResolvedValue(undefined);+ store.connectTransport({+ observeElementGeometry,+ unobserveElementGeometry: jest.fn().mockResolvedValue(undefined),+ });++ expect(store.resolveElementSnapshot(rootElement)).toBeNull();++ store.applyGeometryBatch({+ viewport: createViewportGeometrySnapshotFixture({+ computedStyle: { direction: 'rtl' },+ scrollX: 30,+ scrollY: 700,+ rootContainerX: 120,+ rootContainerY: 45,+ rootContainerWidth: 640,+ rootContainerHeight: 480,+ rootContainerClientWidth: 630,+ rootContainerClientHeight: 470,+ }),+ });++ expect(store.resolveElementSnapshot(rootElement)).toMatchObject({+ computedStyle: { direction: 'rtl' },+ x: 120,+ y: 45,+ width: 640,+ height: 480,+ clientWidth: 630,+ clientHeight: 470,+ scrollTop: 0,+ scrollLeft: 0,+ });+ expect(store.readObservedElementSnapshot(documentElement)).toMatchObject({+ x: 120,+ y: 45,+ scrollTop: 700,+ scrollLeft: 30,+ });+ expect(store.createElementGeometryReader(rootElement).read()).toMatchObject(+ { clientWidth: 630, clientHeight: 470 },+ );+ await flushMicrotasks();+ expect(observeElementGeometry).not.toHaveBeenCalled();+ });+it('should coalesce a synchronous burst of enrollments into one call', async () => {const { store, rootElement } = createRootedStore();const observeElementGeometry = jest.fn().mockResolvedValue(undefined);@@ -94,9 +201,9 @@ describe('createWorkerGeometryStore', () => {unobserveElementGeometry: jest.fn().mockResolvedValue(undefined),});- store.resolveElementSnapshot({ parentNode: rootElement });- store.resolveElementSnapshot({ parentNode: rootElement });- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));+ store.resolveElementSnapshot(createHostElement(rootElement));+ store.resolveElementSnapshot(createHostElement(rootElement));await flushMicrotasks();expect(observeElementGeometry).toHaveBeenCalledTimes(1);@@ -106,7 +213,7 @@ describe('createWorkerGeometryStore', () => {it('should retain enrollments and flush them when the transport connects later', async () => {const { store, rootElement } = createRootedStore();- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));await flushMicrotasks();const observeElementGeometry = jest.fn().mockResolvedValue(undefined);@@ -120,7 +227,7 @@ describe('createWorkerGeometryStore', () => {it('should return the snapshot after a batch writes it', () => {const { store, rootElement } = createRootedStore();- const element = { parentNode: rootElement };+ const element = createHostElement(rootElement);store.resolveElementSnapshot(element);store.applyGeometryBatch({ elements: { '0': createSnapshot(42) } });@@ -130,8 +237,8 @@ describe('createWorkerGeometryStore', () => {it('should merge successive batches rather than replacing the element map', () => {const { store, rootElement } = createRootedStore();- const first = { parentNode: rootElement };- const second = { parentNode: rootElement };+ const first = createHostElement(rootElement);+ const second = createHostElement(rootElement);store.resolveElementSnapshot(first);store.resolveElementSnapshot(second);@@ -145,7 +252,7 @@ describe('createWorkerGeometryStore', () => {it('should delete entries listed in removedRemoteElementIds', () => {const { store, rootElement } = createRootedStore();- const element = { parentNode: rootElement };+ const element = createHostElement(rootElement);store.resolveElementSnapshot(element);store.applyGeometryBatch({ elements: { '0': createSnapshot(5) } });@@ -154,6 +261,37 @@ describe('createWorkerGeometryStore', () => {expect(store.resolveElementSnapshot(element)).toBeNull();});+ it('should keep the previous computed style when a batch omits an unchanged one', () => {+ const { store, rootElement } = createRootedStore();+ const element = createHostElement(rootElement);++ store.resolveElementSnapshot(element);+ store.applyGeometryBatch({+ viewport: createViewportGeometrySnapshotFixture({+ computedStyle: { direction: 'rtl' },+ }),+ elements: {+ '0': createElementGeometrySnapshotFixture({+ width: 1,+ computedStyle: { display: 'flex' },+ }),+ },+ });+ store.applyGeometryBatch({+ viewport: createViewportGeometrySnapshotFixture({ innerWidth: 900 }),+ elements: { '0': createElementGeometrySnapshotFixture({ width: 2 }) },+ });++ expect(store.readObservedElementSnapshot(element)).toMatchObject({+ width: 2,+ computedStyle: { display: 'flex' },+ });+ expect(store.getViewportSnapshot()).toMatchObject({+ innerWidth: 900,+ computedStyle: { direction: 'rtl' },+ });+ });+it('should replace the viewport snapshot on each batch that carries one', () => {const { store } = createRootedStore();@@ -205,7 +343,7 @@ describe('createWorkerGeometryStore', () => {jest.spyOn(console, 'warn').mockImplementation(() => {});for (let index = 0; index < 600; index += 1) {- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));}await flushMicrotasks();@@ -217,7 +355,7 @@ describe('createWorkerGeometryStore', () => {const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});for (let index = 0; index < 600; index += 1) {- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));}expect(warn).toHaveBeenCalledTimes(1);@@ -234,17 +372,17 @@ describe('createWorkerGeometryStore', () => {jest.spyOn(console, 'warn').mockImplementation(() => {});for (let index = 0; index < 500; index += 1) {- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));}await flushMicrotasks();- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));await flushMicrotasks();expect(observeElementGeometry).toHaveBeenCalledTimes(1);store.applyGeometryBatch({ removedRemoteElementIds: ['0', '1'] });- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));await flushMicrotasks();expect(observeElementGeometry).toHaveBeenCalledTimes(2);@@ -258,7 +396,7 @@ describe('createWorkerGeometryStore', () => {unobserveElementGeometry: jest.fn().mockResolvedValue(undefined),});- const element = { parentNode: rootElement };+ const element = createHostElement(rootElement);store.resolveElementSnapshot(element);await flushMicrotasks();@@ -281,8 +419,8 @@ describe('createWorkerGeometryStore', () => {unobserveElementGeometry,});- store.resolveElementSnapshot({ parentNode: rootElement });- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));+ store.resolveElementSnapshot(createHostElement(rootElement));await flushMicrotasks();store.applyGeometryBatch({ removedRemoteElementIds: ['0', 'unknown'] });@@ -314,10 +452,10 @@ describe('createWorkerGeometryStore', () => {unobserveElementGeometry: jest.fn().mockResolvedValue(undefined),});- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));await flushMicrotasks();- store.resolveElementSnapshot({ parentNode: rootElement });+ store.resolveElementSnapshot(createHostElement(rootElement));await flushMicrotasks();expect(warn).toHaveBeenCalledTimes(1);diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/installElementGeometryPolyfill.test.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/installElementGeometryPolyfill.test.tsindex e94054bb7b8..8b617195833 100644--- a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/installElementGeometryPolyfill.test.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/installElementGeometryPolyfill.test.ts@@ -1,11 +1,18 @@import { createElementGeometrySnapshotFixture } from '@/testing/createElementGeometrySnapshotFixture';-import { createViewportGeometrySnapshotFixture } from '@/testing/createViewportGeometrySnapshotFixture';+import { createSubscriptionStub } from '@/testing/createSubscriptionStub';import { createWorkerGeometryStoreStub } from '@/testing/createWorkerGeometryStoreStub';import { type WorkerGeometryStore } from '@/polyfills/geometry/types/WorkerGeometryStore';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';import { installElementGeometryPolyfill } from '../installElementGeometryPolyfill';class FakeElement {}+class FakeTextarea extends FakeElement {+ localName = 'html-textarea';+ isConnected = true;+ style = { blockSize: '' };+}+type GeometryPolyfilledElement = FakeElement & {getBoundingClientRect: () => DOMRect;offsetWidth: number;@@ -39,6 +46,54 @@ const installOn = (geometryStore: WorkerGeometryStore) => {return { documentBody, documentElement };};+const createTextareaSnapshot = () =>+ createElementGeometrySnapshotFixture({+ offsetHeight: 50,+ clientHeight: 48,+ scrollHeight: 48,+ textareaIntrinsicScrollHeight: 48,+ });++const installTextareaResizeFixture = ({+ initialSnapshot = createTextareaSnapshot(),+}: {+ initialSnapshot?: ElementGeometrySnapshot | null;+} = {}) => {+ let snapshot = initialSnapshot;+ const geometryUpdates = createSubscriptionStub();++ installOn(+ createWorkerGeometryStoreStub({+ resolveElementSnapshot: () => snapshot,+ subscribeToGeometryUpdates: geometryUpdates.subscribe,+ }),+ );++ const textarea = asPolyfilled(+ new FakeTextarea(),+ ) as GeometryPolyfilledElement & FakeTextarea;+ textarea.style.blockSize = 'auto';++ const resizeToContent = () => {+ textarea.style.blockSize = 'auto';+ const scrollHeight = textarea.scrollHeight;++ if (scrollHeight === 0) {+ return;+ }++ const borderBlockSize = textarea.offsetHeight - textarea.clientHeight;+ textarea.style.blockSize = `${scrollHeight + borderBlockSize}px`;+ };++ const pushSnapshot = (overrides: Partial<ElementGeometrySnapshot>) => {+ snapshot = { ...(snapshot ?? createTextareaSnapshot()), ...overrides };+ geometryUpdates.notify();+ };++ return { textarea, resizeToContent, pushSnapshot };+};+describe('installElementGeometryPolyfill', () => {it('should return a zero rect when the store has no snapshot', () => {installOn(createWorkerGeometryStoreStub());@@ -75,84 +130,89 @@ describe('installElementGeometryPolyfill', () => {expect(element.offsetWidth).toBe(5);expect(element.clientHeight).toBe(10);expect(element.scrollWidth).toBe(13);+ expect(element.scrollHeight).toBe(14);expect(element.scrollTop).toBe(15);});- it('should return 0 from every numeric getter when no snapshot exists', () => {- installOn(createWorkerGeometryStoreStub());-- const element = asPolyfilled(new FakeElement());-- expect(element.offsetWidth).toBe(0);- expect(element.clientHeight).toBe(0);- expect(element.scrollLeft).toBe(0);- });-- it('should synthesize body geometry from the viewport root container', () => {- const { documentBody } = installOn(+ it('should measure content when a textarea resets its block size', () => {+ installOn(createWorkerGeometryStoreStub({- getViewportSnapshot: () =>- createViewportGeometrySnapshotFixture({- rootContainerWidth: 640,- rootContainerHeight: 480,- rootContainerClientWidth: 630,- rootContainerClientHeight: 470,+ resolveElementSnapshot: () =>+ createElementGeometrySnapshotFixture({+ scrollHeight: 130,+ textareaIntrinsicScrollHeight: 48,}),}),);- const rect = asPolyfilled(documentBody).getBoundingClientRect();+ const textarea = asPolyfilled(+ new FakeTextarea(),+ ) as GeometryPolyfilledElement & FakeTextarea;+ textarea.style.blockSize = 'auto';- expect(rect.width).toBe(640);- expect(rect.height).toBe(480);- expect(asPolyfilled(documentBody).clientWidth).toBe(630);+ expect(textarea.scrollHeight).toBe(48);+ textarea.style.blockSize = '100px';+ expect(textarea.scrollHeight).toBe(130);});- it('should place document-scoped rects at the root container host-viewport position', () => {- const { documentBody, documentElement } = installOn(- createWorkerGeometryStoreStub({- getViewportSnapshot: () =>- createViewportGeometrySnapshotFixture({- rootContainerX: 120,- rootContainerY: 45,- rootContainerWidth: 640,- rootContainerHeight: 480,- }),- }),- );+ it('should resize a textarea after its controlled content reaches the host', () => {+ const { textarea, resizeToContent, pushSnapshot } =+ installTextareaResizeFixture();- const bodyRect = asPolyfilled(documentBody).getBoundingClientRect();- const documentElementRect =- asPolyfilled(documentElement).getBoundingClientRect();+ resizeToContent();+ pushSnapshot({ textareaIntrinsicScrollHeight: 80 });- expect(bodyRect.x).toBe(120);- expect(bodyRect.y).toBe(45);- expect(documentElementRect.x).toBe(120);- expect(documentElementRect.y).toBe(45);+ expect(textarea.style.blockSize).toBe('82px');++ pushSnapshot({ textareaIntrinsicScrollHeight: 32 });++ expect(textarea.style.blockSize).toBe('34px');});- it('should mirror host scroll offsets on documentElement only', () => {- const { documentBody, documentElement } = installOn(- createWorkerGeometryStoreStub({- getViewportSnapshot: () =>- createViewportGeometrySnapshotFixture({- scrollX: 30,- scrollY: 700,- }),- }),- );+ it('should keep the automatic block size until the first textarea measurement arrives', () => {+ const { textarea, resizeToContent, pushSnapshot } =+ installTextareaResizeFixture({ initialSnapshot: null });++ resizeToContent();++ expect(textarea.style.blockSize).toBe('auto');- expect(asPolyfilled(documentElement).scrollTop).toBe(700);- expect(asPolyfilled(documentElement).scrollLeft).toBe(30);- expect(asPolyfilled(documentBody).scrollTop).toBe(0);- expect(asPolyfilled(documentBody).scrollLeft).toBe(0);+ pushSnapshot({ textareaIntrinsicScrollHeight: 32 });++ expect(textarea.style.blockSize).toBe('34px');});- it('should return zero document-scoped geometry when no viewport snapshot exists', () => {- const { documentBody } = installOn(createWorkerGeometryStoreStub());+ it('should stop resizing a detached textarea', () => {+ const { textarea, resizeToContent, pushSnapshot } =+ installTextareaResizeFixture();++ resizeToContent();+ textarea.isConnected = false;+ pushSnapshot({});+ pushSnapshot({ textareaIntrinsicScrollHeight: 80 });++ expect(textarea.style.blockSize).toBe('50px');+ });++ it('should preserve caller sizing after a pending textarea content measurement', () => {+ const { textarea, pushSnapshot } = installTextareaResizeFixture();- expect(asPolyfilled(documentBody).getBoundingClientRect().width).toBe(0);- expect(asPolyfilled(documentBody).clientWidth).toBe(0);+ expect(textarea.scrollHeight).toBe(48);+ textarea.style.blockSize = '140px';+ pushSnapshot({ textareaIntrinsicScrollHeight: 80 });++ expect(textarea.style.blockSize).toBe('140px');+ });++ it('should return 0 from every numeric getter when no snapshot exists', () => {+ installOn(createWorkerGeometryStoreStub());++ const element = asPolyfilled(new FakeElement());++ expect(element.offsetWidth).toBe(0);+ expect(element.clientHeight).toBe(0);+ expect(element.scrollHeight).toBe(0);+ expect(element.scrollLeft).toBe(0);});it('should not throw when scrollTop is assigned and should keep reading the mirrored value', () => {diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/installResizeObserverPolyfill.test.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/installResizeObserverPolyfill.test.tsnew file mode 100644index 00000000000..30cf9bdbe45--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/installResizeObserverPolyfill.test.ts@@ -0,0 +1,777 @@+import { Window } from '@remote-dom/polyfill';+import { isDefined } from 'twenty-shared/utils';++import { createElementGeometrySnapshotFixture } from '@/testing/createElementGeometrySnapshotFixture';+import { createViewportGeometrySnapshotFixture } from '@/testing/createViewportGeometrySnapshotFixture';+import { isElementNode } from '@/polyfills/dom/utils/isElementNode';+import { createWorkerGeometryStore } from '@/polyfills/geometry/utils/createWorkerGeometryStore';+import { installResizeObserverPolyfill } from '@/polyfills/geometry/utils/installResizeObserverPolyfill';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++const remoteElementIds = new WeakMap<object, string>();+let nextRemoteElementId = 0;++jest.mock('@remote-dom/core/elements', () => ({+ remoteId: (element: object) => {+ const existingRemoteElementId = remoteElementIds.get(element);++ if (isDefined(existingRemoteElementId)) {+ return existingRemoteElementId;+ }++ const remoteElementId = String(nextRemoteElementId);+ nextRemoteElementId += 1;+ remoteElementIds.set(element, remoteElementId);++ return remoteElementId;+ },+}));++const flushMicrotasks = async () => {+ await Promise.resolve();+ await Promise.resolve();+};++const toElement = <TNode>(node: TNode): TNode & Element => {+ if (!isElementNode(node)) {+ throw new Error('Expected the remote-dom polyfill to create an element.');+ }++ return node;+};++const createSandbox = () => {+ const polyfillWindow = new Window();+ const { document } = polyfillWindow;+ const createElement = (tagName: string) =>+ toElement(document.createElement(tagName));+ const body = toElement(document.body);+ const root = createElement('div');+ const target = createElement('div');+ body.appendChild(root);+ root.appendChild(target);+ const geometryStore = createWorkerGeometryStore();+ geometryStore.setRootElement(body);+ const observeElementGeometry = jest.fn().mockResolvedValue(undefined);+ const unobserveElementGeometry = jest.fn().mockResolvedValue(undefined);+ geometryStore.connectTransport({+ observeElementGeometry,+ unobserveElementGeometry,+ });+ const globalScope: Record<string, unknown> = { window: polyfillWindow };+ installResizeObserverPolyfill({+ globalScope,+ geometryStore,+ });++ const applySnapshot = (overrides: Partial<ElementGeometrySnapshot> = {}) => {+ const remoteElementId = remoteElementIds.get(target);++ if (!isDefined(remoteElementId)) {+ throw new Error('The target must be observed before applying geometry.');+ }++ geometryStore.applyGeometryBatch({+ elements: {+ [remoteElementId]: createElementGeometrySnapshotFixture({+ width: 100,+ height: 50,+ offsetWidth: 100,+ offsetHeight: 50,+ clientWidth: 80,+ clientHeight: 30,+ ...overrides,+ }),+ },+ });+ };++ return {+ polyfillWindow,+ globalScope,+ body,+ createElement,+ root,+ target,+ geometryStore,+ observeElementGeometry,+ unobserveElementGeometry,+ applySnapshot,+ ResizeObserver: globalScope.ResizeObserver as typeof ResizeObserver,+ };+};++describe('installResizeObserverPolyfill', () => {+ beforeEach(() => {+ nextRemoteElementId = 0;+ jest.restoreAllMocks();+ });++ it('installs the same constructor in the worker and its owning window', () => {+ const { globalScope, polyfillWindow, ResizeObserver } = createSandbox();++ expect(globalScope.ResizeObserver).toBe(ResizeObserver);+ expect(Reflect.get(polyfillWindow, 'ResizeObserver')).toBe(ResizeObserver);+ });++ it('waits for initial host geometry and delivers the owned target and box shapes', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const callback = jest.fn();+ const observer = new ResizeObserver(callback);+ observer.observe(target);+ await flushMicrotasks();+ expect(callback).not.toHaveBeenCalled();++ applySnapshot({+ clientWidth: 85,+ clientHeight: 37,+ computedStyle: { 'padding-left': '5px', 'padding-top': '7px' },+ });+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(1);+ const [[entry], deliveredObserver] = callback.mock.calls[0];+ expect(deliveredObserver).toBe(observer);+ expect(entry.target).toBe(target);+ expect(entry.contentRect).toMatchObject({+ x: 5,+ y: 7,+ width: 80,+ height: 30,+ });+ expect(entry.contentBoxSize).toEqual([{ inlineSize: 80, blockSize: 30 }]);+ expect(entry.borderBoxSize).toEqual([{ inlineSize: 100, blockSize: 50 }]);+ expect(entry.devicePixelContentBoxSize).toEqual([+ { inlineSize: 80, blockSize: 30 },+ ]);+ });++ it('delivers an already measured target asynchronously', async () => {+ const { ResizeObserver, target, geometryStore, applySnapshot } =+ createSandbox();+ geometryStore.resolveElementSnapshot(target);+ applySnapshot();+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target);++ expect(callback).not.toHaveBeenCalled();+ await flushMicrotasks();+ expect(callback).toHaveBeenCalledTimes(1);+ });++ it('does not report position, scroll or viewport changes as content resizing', async () => {+ const { ResizeObserver, target, applySnapshot, geometryStore } =+ createSandbox();+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target);+ applySnapshot();+ await flushMicrotasks();++ applySnapshot({ x: 300, y: 400, scrollTop: 200, scrollHeight: 700 });+ geometryStore.applyGeometryBatch({+ viewport: createViewportGeometrySnapshotFixture({ innerWidth: 600 }),+ });+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(1);+ });++ it('coalesces geometry updates and delivers only targets whose selected size changed', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const callback = jest.fn();+ const observer = new ResizeObserver(callback);+ observer.observe(target);+ observer.observe(target);+ applySnapshot();+ applySnapshot({ clientWidth: 110 });+ applySnapshot({ clientWidth: 120 });+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback.mock.calls[0][0]).toHaveLength(1);+ expect(callback.mock.calls[0][0][0].contentRect.width).toBe(120);++ applySnapshot({ clientWidth: 120, clientHeight: 60 });+ await flushMicrotasks();+ expect(callback).toHaveBeenCalledTimes(2);+ });++ it('uses content or border size according to each observation option', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const contentCallback = jest.fn();+ const borderCallback = jest.fn();+ new ResizeObserver(contentCallback).observe(target);+ new ResizeObserver(borderCallback).observe(target, { box: 'border-box' });+ applySnapshot();+ await flushMicrotasks();++ applySnapshot({ offsetWidth: 130 });+ await flushMicrotasks();+ expect(contentCallback).toHaveBeenCalledTimes(1);+ expect(borderCallback).toHaveBeenCalledTimes(2);++ applySnapshot({ offsetWidth: 130, clientWidth: 60 });+ await flushMicrotasks();+ expect(contentCallback).toHaveBeenCalledTimes(2);+ expect(borderCallback).toHaveBeenCalledTimes(2);+ });++ it('reports subpixel resizes from the host computed width and height', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target);+ const applyComputedWidth = (width: string) =>+ applySnapshot({+ offsetWidth: 100,+ offsetHeight: 40,+ clientWidth: 100,+ clientHeight: 40,+ computedStyle: { width, height: '40px' },+ });++ applyComputedWidth('100.1px');+ await flushMicrotasks();+ applyComputedWidth('100.4px');+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(2);+ expect(callback.mock.calls[0][0][0].contentBoxSize).toEqual([+ { inlineSize: 100.1, blockSize: 40 },+ ]);+ const [[entry]] = callback.mock.calls[1];+ expect(entry.contentRect.width).toBe(100.4);+ expect(entry.contentBoxSize).toEqual([+ { inlineSize: 100.4, blockSize: 40 },+ ]);+ expect(entry.borderBoxSize).toEqual([{ inlineSize: 100.4, blockSize: 40 }]);+ });++ it('removes border-box edges and scrollbars from the host computed size', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target);++ applySnapshot({+ offsetWidth: 200,+ offsetHeight: 100,+ clientWidth: 175,+ clientHeight: 90,+ computedStyle: {+ width: '200px',+ height: '100px',+ 'box-sizing': 'border-box',+ 'padding-left': '10px',+ 'padding-right': '10px',+ 'border-left-width': '5px',+ 'border-right-width': '5px',+ 'border-top-width': '5px',+ 'border-bottom-width': '5px',+ 'overflow-y': 'scroll',+ },+ });+ await flushMicrotasks();++ const [[entry]] = callback.mock.calls[0];+ expect(entry.contentRect).toMatchObject({+ x: 10,+ y: 0,+ width: 155,+ height: 90,+ });+ expect(entry.contentBoxSize).toEqual([{ inlineSize: 155, blockSize: 90 }]);+ expect(entry.borderBoxSize).toEqual([{ inlineSize: 200, blockSize: 100 }]);+ });++ it('reports SVG graphics sizes from their host bounding box', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target);+ const applySvgBoundingBoxWidth = (svgBoundingBoxWidth: number) =>+ applySnapshot({+ offsetWidth: 0,+ offsetHeight: 0,+ clientWidth: 0,+ clientHeight: 0,+ svgBoundingBoxWidth,+ svgBoundingBoxHeight: 40,+ });++ applySvgBoundingBoxWidth(80);+ await flushMicrotasks();+ applySvgBoundingBoxWidth(120);+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(2);+ expect(callback.mock.calls[0][0][0].contentRect).toMatchObject({+ x: 0,+ y: 0,+ width: 80,+ height: 40,+ });+ expect(callback.mock.calls[1][0][0].contentBoxSize).toEqual([+ { inlineSize: 120, blockSize: 40 },+ ]);+ expect(callback.mock.calls[1][0][0].borderBoxSize).toEqual([+ { inlineSize: 120, blockSize: 40 },+ ]);+ });++ it('unobserves one target while keeping other measured targets delivered', async () => {+ const {+ ResizeObserver,+ target,+ createElement,+ root,+ geometryStore,+ applySnapshot,+ } = createSandbox();+ const secondTarget = createElement('div');+ root.appendChild(secondTarget);+ const callback = jest.fn();+ const observer = new ResizeObserver(callback);+ observer.observe(target);+ observer.observe(secondTarget);+ applySnapshot();+ const secondRemoteElementId = remoteElementIds.get(secondTarget);++ if (!isDefined(secondRemoteElementId)) {+ throw new Error(+ 'The second target must be observed before applying geometry.',+ );+ }+ geometryStore.applyGeometryBatch({+ elements: {+ [secondRemoteElementId]: createElementGeometrySnapshotFixture({+ clientWidth: 70,+ clientHeight: 20,+ }),+ },+ });+ await flushMicrotasks();+ expect(+ callback.mock.calls[0][0].map(+ (entry: ResizeObserverEntry) => entry.target,+ ),+ ).toEqual([target, secondTarget]);++ observer.unobserve(target);+ applySnapshot({ clientWidth: 200 });+ geometryStore.applyGeometryBatch({+ elements: {+ [secondRemoteElementId]: createElementGeometrySnapshotFixture({+ clientWidth: 90,+ clientHeight: 20,+ }),+ },+ });+ await flushMicrotasks();+ expect(+ callback.mock.calls[1][0].map(+ (entry: ResizeObserverEntry) => entry.target,+ ),+ ).toEqual([secondTarget]);++ observer.unobserve(secondTarget);+ applySnapshot({ clientWidth: 300 });+ await flushMicrotasks();+ expect(callback).toHaveBeenCalledTimes(2);+ });++ it('releases host capacity while observing and unobserving connected targets', async () => {+ const {+ ResizeObserver,+ createElement,+ root,+ observeElementGeometry,+ unobserveElementGeometry,+ } = createSandbox();+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});+ const observer = new ResizeObserver(jest.fn());++ for (let index = 0; index < 501; index += 1) {+ const target = createElement('div');+ root.appendChild(target);+ observer.observe(target);+ await flushMicrotasks();+ observer.unobserve(target);+ }++ await flushMicrotasks();++ expect(observeElementGeometry).toHaveBeenCalledTimes(501);+ expect(unobserveElementGeometry).toHaveBeenCalledTimes(501);+ expect(warn).not.toHaveBeenCalled();+ });++ it('retries a capacity-blocked target when another connected observation releases its slot', async () => {+ const {+ ResizeObserver,+ createElement,+ root,+ target,+ observeElementGeometry,+ } = createSandbox();+ jest.spyOn(console, 'warn').mockImplementation(() => {});+ const observer = new ResizeObserver(jest.fn());+ observer.observe(target);++ for (let index = 1; index < 500; index += 1) {+ const observedTarget = createElement('div');+ root.appendChild(observedTarget);+ observer.observe(observedTarget);+ }++ await flushMicrotasks();+ const pendingTarget = createElement('div');+ root.appendChild(pendingTarget);+ const pendingObserver = new ResizeObserver(jest.fn());+ pendingObserver.observe(pendingTarget);+ await flushMicrotasks();+ expect(observeElementGeometry).toHaveBeenCalledTimes(1);++ observer.unobserve(target);+ await flushMicrotasks();+ await flushMicrotasks();++ expect(observeElementGeometry).toHaveBeenCalledTimes(2);+ expect(observeElementGeometry).toHaveBeenLastCalledWith([+ remoteElementIds.get(pendingTarget),+ ]);+ });++ it('preserves measured geometry when a target is reobserved within the same update', async () => {+ const {+ ResizeObserver,+ target,+ applySnapshot,+ observeElementGeometry,+ unobserveElementGeometry,+ } = createSandbox();+ const callback = jest.fn();+ const observer = new ResizeObserver(callback);+ observer.observe(target);+ applySnapshot();+ await flushMicrotasks();+ callback.mockClear();++ observer.unobserve(target);+ observer.observe(target);+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback.mock.calls[0][0][0].contentRect.width).toBe(80);+ expect(observeElementGeometry).toHaveBeenCalledTimes(1);+ expect(unobserveElementGeometry).not.toHaveBeenCalled();+ });++ it('releases shared host geometry only after the last observer stops', async () => {+ const { ResizeObserver, target, unobserveElementGeometry } =+ createSandbox();+ const firstObserver = new ResizeObserver(jest.fn());+ const secondObserver = new ResizeObserver(jest.fn());+ firstObserver.observe(target);+ secondObserver.observe(target);+ await flushMicrotasks();++ firstObserver.unobserve(target);+ expect(unobserveElementGeometry).not.toHaveBeenCalled();++ secondObserver.disconnect();+ await flushMicrotasks();+ expect(unobserveElementGeometry).toHaveBeenCalledWith([+ remoteElementIds.get(target),+ ]);+ });++ it('cancels enrollment when unobserved before its host request is sent', async () => {+ const {+ ResizeObserver,+ target,+ observeElementGeometry,+ unobserveElementGeometry,+ } = createSandbox();+ const observer = new ResizeObserver(jest.fn());+ observer.observe(target);+ observer.unobserve(target);+ await flushMicrotasks();++ expect(observeElementGeometry).not.toHaveBeenCalled();+ expect(unobserveElementGeometry).not.toHaveBeenCalled();+ });++ it('reuses one geometry reader when the observed box changes', async () => {+ const { ResizeObserver, target, unobserveElementGeometry } =+ createSandbox();+ const observer = new ResizeObserver(jest.fn());+ observer.observe(target);+ observer.observe(target, { box: 'border-box' });+ await flushMicrotasks();+ observer.disconnect();+ await flushMicrotasks();++ expect(unobserveElementGeometry).toHaveBeenCalledTimes(1);+ });++ it('releases all connected targets on disconnect', async () => {+ const {+ ResizeObserver,+ target,+ createElement,+ root,+ unobserveElementGeometry,+ } = createSandbox();+ const secondTarget = createElement('div');+ root.appendChild(secondTarget);+ const observer = new ResizeObserver(jest.fn());+ observer.observe(target);+ observer.observe(secondTarget);+ await flushMicrotasks();+ observer.disconnect();+ observer.disconnect();+ await flushMicrotasks();++ expect(unobserveElementGeometry.mock.calls).toEqual([+ [[remoteElementIds.get(target)]],+ [[remoteElementIds.get(secondTarget)]],+ ]);+ });++ it('keeps host geometry needed by a direct measurement after observer teardown', async () => {+ const {+ ResizeObserver,+ target,+ geometryStore,+ applySnapshot,+ unobserveElementGeometry,+ } = createSandbox();+ const observer = new ResizeObserver(jest.fn());+ observer.observe(target);+ geometryStore.resolveElementSnapshot(target);+ applySnapshot();+ await flushMicrotasks();++ observer.disconnect();+ await flushMicrotasks();+ applySnapshot({ width: 140 });++ expect(unobserveElementGeometry).not.toHaveBeenCalled();+ expect(geometryStore.resolveElementSnapshot(target)?.width).toBe(140);+ });++ it('reports logical block and inline sizes for vertical writing mode', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target);+ applySnapshot({ computedStyle: { 'writing-mode': 'vertical-rl' } });+ await flushMicrotasks();++ expect(callback.mock.calls[0][0][0].contentBoxSize).toEqual([+ { inlineSize: 30, blockSize: 80 },+ ]);+ expect(callback.mock.calls[0][0][0].borderBoxSize).toEqual([+ { inlineSize: 50, blockSize: 100 },+ ]);+ });++ it('uses the scoped viewport scale for device pixel sizes', async () => {+ const { ResizeObserver, target, geometryStore, applySnapshot } =+ createSandbox();+ geometryStore.applyGeometryBatch({+ viewport: createViewportGeometrySnapshotFixture({ devicePixelRatio: 2 }),+ });+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target, {+ box: 'device-pixel-content-box',+ });+ applySnapshot();+ await flushMicrotasks();++ expect(callback.mock.calls[0][0][0].devicePixelContentBoxSize).toEqual([+ { inlineSize: 160, blockSize: 60 },+ ]);+ });++ it('supports zero-sized measured elements without inventing an unmeasured delivery', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target);+ applySnapshot({ clientWidth: 0, clientHeight: 0 });+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback.mock.calls[0][0][0].contentRect.width).toBe(0);+ });++ it('stops queued delivery on unobserve and can observe the target again', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const callback = jest.fn();+ const observer = new ResizeObserver(callback);+ observer.observe(target);+ applySnapshot();+ observer.unobserve(target);+ await flushMicrotasks();+ expect(callback).not.toHaveBeenCalled();++ observer.observe(target);+ await flushMicrotasks();+ expect(callback).not.toHaveBeenCalled();++ applySnapshot();+ await flushMicrotasks();+ expect(callback).toHaveBeenCalledTimes(1);+ });++ it('disconnects one observer and leaves other observers working', async () => {+ const { ResizeObserver, target, applySnapshot } = createSandbox();+ const disconnectedCallback = jest.fn();+ const liveCallback = jest.fn();+ const disconnectedObserver = new ResizeObserver(disconnectedCallback);+ disconnectedObserver.observe(target);+ new ResizeObserver(liveCallback).observe(target);+ disconnectedObserver.disconnect();+ applySnapshot();+ await flushMicrotasks();++ expect(disconnectedCallback).not.toHaveBeenCalled();+ expect(liveCallback).toHaveBeenCalledTimes(1);+ });++ it('should report a zero size when a measured target is removed and resume after reinsertion', async () => {+ const {+ ResizeObserver,+ target,+ root,+ body,+ applySnapshot,+ observeElementGeometry,+ unobserveElementGeometry,+ } = createSandbox();+ const callback = jest.fn();+ const observer = new ResizeObserver(callback);+ observer.observe(target);+ applySnapshot();+ await flushMicrotasks();+ callback.mockClear();++ applySnapshot({ clientWidth: 120 });+ body.removeChild(root);+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback.mock.calls[0][0][0].contentRect.width).toBe(0);+ expect(callback.mock.calls[0][0][0].contentBoxSize).toEqual([+ { inlineSize: 0, blockSize: 0 },+ ]);+ expect(unobserveElementGeometry).toHaveBeenCalledWith([+ remoteElementIds.get(target),+ ]);++ body.appendChild(root);+ await flushMicrotasks();+ expect(observeElementGeometry).toHaveBeenCalledTimes(2);++ applySnapshot({ clientWidth: 140 });+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(2);+ expect(callback.mock.calls[1][0][0].contentRect.width).toBe(140);+ });++ it('should observe the document body through the renderer root size without enrolling host-less elements', async () => {+ const {+ ResizeObserver,+ createElement,+ body,+ root,+ geometryStore,+ observeElementGeometry,+ } = createSandbox();+ const renderContainer = createElement('remote-fragment');+ root.appendChild(renderContainer);+ const bodyCallback = jest.fn();+ const renderContainerCallback = jest.fn();+ new ResizeObserver(bodyCallback).observe(body);+ new ResizeObserver(renderContainerCallback).observe(renderContainer);++ geometryStore.applyGeometryBatch({+ viewport: createViewportGeometrySnapshotFixture({+ rootContainerWidth: 320,+ rootContainerHeight: 200,+ rootContainerClientWidth: 300,+ rootContainerClientHeight: 180,+ }),+ });+ await flushMicrotasks();++ expect(bodyCallback).toHaveBeenCalledTimes(1);+ expect(bodyCallback.mock.calls[0][0][0].target).toBe(body);+ expect(bodyCallback.mock.calls[0][0][0].contentBoxSize).toEqual([+ { inlineSize: 300, blockSize: 180 },+ ]);+ expect(renderContainerCallback).not.toHaveBeenCalled();+ expect(observeElementGeometry).not.toHaveBeenCalled();+ });++ it('keeps observation when a target moves between connected parents in one update', async () => {+ const { ResizeObserver, target, root, createElement, applySnapshot } =+ createSandbox();+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target);+ const nextParent = createElement('div');+ root.appendChild(nextParent);+ root.removeChild(target);+ nextParent.appendChild(target);+ applySnapshot();+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(1);+ });++ it('waits for an initially detached target to connect before requesting its first measured delivery', async () => {+ const { ResizeObserver, target, root, applySnapshot } = createSandbox();+ root.removeChild(target);+ const callback = jest.fn();+ new ResizeObserver(callback).observe(target);+ await flushMicrotasks();+ expect(callback).not.toHaveBeenCalled();++ root.appendChild(target);+ await flushMicrotasks();+ applySnapshot();+ await flushMicrotasks();++ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback.mock.calls[0][0][0].target).toBe(target);+ });++ it('isolates observer delivery and teardown between renderer instances', async () => {+ const first = createSandbox();+ const second = createSandbox();+ const firstCallback = jest.fn();+ const secondCallback = jest.fn();+ new first.ResizeObserver(firstCallback).observe(first.target);+ new second.ResizeObserver(secondCallback).observe(second.target);+ first.applySnapshot();+ await flushMicrotasks();+ expect(firstCallback).toHaveBeenCalledTimes(1);+ expect(secondCallback).not.toHaveBeenCalled();++ first.body.removeChild(first.root);+ second.applySnapshot();+ await flushMicrotasks();+ expect(firstCallback).toHaveBeenCalledTimes(2);+ expect(firstCallback.mock.calls[1][0][0].contentRect.width).toBe(0);+ expect(secondCallback).toHaveBeenCalledTimes(1);+ expect(secondCallback.mock.calls[0][0][0].target).toBe(second.target);+ });++ it('rejects invalid callbacks and targets', () => {+ const { ResizeObserver } = createSandbox();+ const observer = new ResizeObserver(jest.fn());++ expect(() => Reflect.construct(ResizeObserver, [null])).toThrow(TypeError);+ expect(() => Reflect.apply(observer.observe, observer, [{}])).toThrow(+ TypeError,+ );+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/isHostRenderedElement.test.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/isHostRenderedElement.test.tsnew file mode 100644index 00000000000..219ae5974a0--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/__tests__/isHostRenderedElement.test.ts@@ -0,0 +1,22 @@+import { isHostRenderedElement } from '../isHostRenderedElement';++describe('isHostRenderedElement', () => {+ it('should accept allowed elements rendered by the host', () => {+ expect(isHostRenderedElement({ localName: 'html-div' })).toBe(true);+ expect(isHostRenderedElement({ localName: 'html-svg' })).toBe(true);+ });++ it.each([+ 'html-clippath',+ 'html-lineargradient',+ 'html-radialgradient',+ 'html-foreignobject',+ ])('should accept the camel-cased SVG element %s', (localName) => {+ expect(isHostRenderedElement({ localName })).toBe(true);+ });++ it('should reject elements the host does not render', () => {+ expect(isHostRenderedElement({ localName: 'remote-fragment' })).toBe(false);+ expect(isHostRenderedElement({})).toBe(false);+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createDocumentScopedElementGeometrySnapshot.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createDocumentScopedElementGeometrySnapshot.tsnew file mode 100644index 00000000000..bac8beefed5--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createDocumentScopedElementGeometrySnapshot.ts@@ -0,0 +1,26 @@+import { EMPTY_ELEMENT_GEOMETRY_SNAPSHOT } from '@/polyfills/geometry/constants/EmptyElementGeometrySnapshot';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';+import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot';++export const createDocumentScopedElementGeometrySnapshot = ({+ viewport,+ isDocumentElement,+}: {+ viewport: ViewportGeometrySnapshot;+ isDocumentElement: boolean;+}): ElementGeometrySnapshot => ({+ ...EMPTY_ELEMENT_GEOMETRY_SNAPSHOT,+ computedStyle: viewport.computedStyle,+ x: viewport.rootContainerX,+ y: viewport.rootContainerY,+ width: viewport.rootContainerWidth,+ height: viewport.rootContainerHeight,+ offsetWidth: viewport.rootContainerWidth,+ offsetHeight: viewport.rootContainerHeight,+ clientWidth: viewport.rootContainerClientWidth,+ clientHeight: viewport.rootContainerClientHeight,+ scrollWidth: viewport.rootContainerClientWidth,+ scrollHeight: viewport.rootContainerClientHeight,+ scrollTop: isDocumentElement ? viewport.scrollY : 0,+ scrollLeft: isDocumentElement ? viewport.scrollX : 0,+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createElementGeometryOwnerships.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createElementGeometryOwnerships.tsnew file mode 100644index 00000000000..cf1812c082c--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createElementGeometryOwnerships.ts@@ -0,0 +1,140 @@+import { isDefined } from 'twenty-shared/utils';++import { type ElementGeometryReader } from '@/polyfills/geometry/types/ElementGeometryReader';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++type ElementGeometryOwnership = {+ remoteElementId: string | null;+ readerCount: number;+ hasDirectReader: boolean;+ hasScheduledRelease: boolean;+};++export const createElementGeometryOwnerships = ({+ isObservedRemoteElementId,+ isPendingObservation,+ releaseRemoteElement,+}: {+ isObservedRemoteElementId: (remoteElementId: string) => boolean;+ isPendingObservation: (remoteElementId: string) => boolean;+ releaseRemoteElement: (remoteElementId: string) => void;+}) => {+ const elementOwnerships = new WeakMap<object, ElementGeometryOwnership>();++ const getElementOwnership = (element: object): ElementGeometryOwnership => {+ const existingOwnership = elementOwnerships.get(element);++ if (isDefined(existingOwnership)) {+ return existingOwnership;+ }++ const ownership: ElementGeometryOwnership = {+ remoteElementId: null,+ readerCount: 0,+ hasDirectReader: false,+ hasScheduledRelease: false,+ };+ elementOwnerships.set(element, ownership);++ return ownership;+ };++ const hasRemainingReader = (ownership: ElementGeometryOwnership): boolean =>+ ownership.hasDirectReader || ownership.readerCount > 0;++ const readObservedRemoteElementId = (element: object): string | null => {+ const remoteElementId = elementOwnerships.get(element)?.remoteElementId;++ return isDefined(remoteElementId) &&+ isObservedRemoteElementId(remoteElementId)+ ? remoteElementId+ : null;+ };++ const assignRemoteElementId = ({+ element,+ remoteElementId,+ }: {+ element: object;+ remoteElementId: string | null;+ }): void => {+ getElementOwnership(element).remoteElementId = remoteElementId;+ };++ const markDirectReader = (element: object): void => {+ const ownership = getElementOwnership(element);++ if (isDefined(ownership.remoteElementId)) {+ ownership.hasDirectReader = true;+ }+ };++ const releaseWhenUnused = (ownership: ElementGeometryOwnership): void => {+ ownership.hasScheduledRelease = false;+ const remoteElementId = ownership.remoteElementId;++ if (hasRemainingReader(ownership) || !isDefined(remoteElementId)) {+ return;+ }++ ownership.remoteElementId = null;+ releaseRemoteElement(remoteElementId);+ };++ const createElementGeometryReader = ({+ element,+ readSnapshot,+ }: {+ element: object;+ readSnapshot: (element: object) => ElementGeometrySnapshot | null;+ }): ElementGeometryReader => {+ const ownership = getElementOwnership(element);+ const elementRef = new WeakRef(element);+ ownership.readerCount += 1;+ let isReleased = false;++ return {+ read: () => {+ const currentElement = elementRef.deref();++ if (isReleased || !isDefined(currentElement)) {+ return null;+ }++ return readSnapshot(currentElement);+ },+ release: () => {+ if (isReleased) {+ return;+ }++ isReleased = true;+ ownership.readerCount -= 1;+ const remoteElementId = ownership.remoteElementId;++ if (hasRemainingReader(ownership) || !isDefined(remoteElementId)) {+ return;+ }++ if (isPendingObservation(remoteElementId)) {+ releaseWhenUnused(ownership);+ return;+ }++ if (ownership.hasScheduledRelease) {+ return;+ }++ ownership.hasScheduledRelease = true;+ queueMicrotask(() => releaseWhenUnused(ownership));+ },+ };+ };++ return {+ readObservedRemoteElementId,+ assignRemoteElementId,+ markDirectReader,+ createElementGeometryReader,+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createResizeObserverClass.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createResizeObserverClass.tsnew file mode 100644index 00000000000..098d4280490--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createResizeObserverClass.ts@@ -0,0 +1,233 @@+import { type Hooks } from '@remote-dom/polyfill';+import { isFunction } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++import { isElementNode } from '@/polyfills/dom/utils/isElementNode';+import { EMPTY_ELEMENT_GEOMETRY_SNAPSHOT } from '@/polyfills/geometry/constants/EmptyElementGeometrySnapshot';+import { type ElementGeometryReader } from '@/polyfills/geometry/types/ElementGeometryReader';+import { type WorkerGeometryStore } from '@/polyfills/geometry/types/WorkerGeometryStore';+import { createResizeObserverEntry } from '@/polyfills/geometry/utils/createResizeObserverEntry';+import { resolveResizeObserverBoxSize } from '@/polyfills/geometry/utils/resolveResizeObserverBoxSize';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++const DEFAULT_DEVICE_PIXEL_RATIO = 1;+const DEFAULT_OBSERVATION_BOX = 'content-box';++type Observation = {+ box: ResizeObserverBoxOptions;+ lastSize: ResizeObserverSize | null;+ geometryReader: ElementGeometryReader | null;+};++type CreateResizeObserverClassInput = {+ geometryStore: WorkerGeometryStore;+ hooks: Partial<Hooks> | null;+ reportCallbackError: (error: unknown) => void;+};++const isVisibleSize = (size: ResizeObserverSize | null): boolean =>+ isDefined(size) && (size.inlineSize !== 0 || size.blockSize !== 0);++export const createResizeObserverClass = ({+ geometryStore,+ hooks,+ reportCallbackError,+}: CreateResizeObserverClassInput) => {+ const activeObserverSchedules = new Set<() => void>();++ const scheduleActiveObserverDeliveries = () => {+ for (const scheduleObserverDelivery of activeObserverSchedules) {+ scheduleObserverDelivery();+ }+ };++ if (isDefined(hooks)) {+ const previousInsertChildHook = hooks.insertChild;+ const previousRemoveChildHook = hooks.removeChild;++ hooks.insertChild = (parent, node, index) => {+ previousInsertChildHook?.(parent, node, index);+ scheduleActiveObserverDeliveries();+ };++ hooks.removeChild = (parent, node, index) => {+ previousRemoveChildHook?.(parent, node, index);+ scheduleActiveObserverDeliveries();+ };+ }++ geometryStore.subscribeToGeometryUpdates(scheduleActiveObserverDeliveries);++ const readObservationSnapshot = ({+ target,+ observation,+ }: {+ target: Element;+ observation: Observation;+ }): ElementGeometrySnapshot | null => {+ if (!target.isConnected) {+ observation.geometryReader?.release();+ observation.geometryReader = null;++ return isVisibleSize(observation.lastSize)+ ? EMPTY_ELEMENT_GEOMETRY_SNAPSHOT+ : null;+ }++ observation.geometryReader ??=+ geometryStore.createElementGeometryReader(target);++ return observation.geometryReader.read();+ };++ class ResizeObserverImplementation implements ResizeObserver {+ #callback: ResizeObserverCallback;+ #observations = new Map<WeakRef<Element>, Observation>();+ #targetRefs = new WeakMap<Element, WeakRef<Element>>();+ #hasScheduledDelivery = false;++ constructor(callback: ResizeObserverCallback) {+ if (!isFunction(callback)) {+ throw new TypeError('ResizeObserver requires a callback function.');+ }++ this.#callback = callback;+ }++ #stopWhenEmpty = () => {+ if (this.#observations.size > 0) {+ return;+ }++ activeObserverSchedules.delete(this.#scheduleDelivery);+ };++ #deliver = () => {+ this.#hasScheduledDelivery = false;++ const devicePixelRatio =+ geometryStore.getViewportSnapshot()?.devicePixelRatio ??+ DEFAULT_DEVICE_PIXEL_RATIO;+ const entries: ResizeObserverEntry[] = [];++ for (const [targetRef, observation] of this.#observations) {+ const target = targetRef.deref();++ if (!isDefined(target)) {+ observation.geometryReader?.release();+ this.#observations.delete(targetRef);+ continue;+ }++ const snapshot = readObservationSnapshot({ target, observation });++ if (!isDefined(snapshot)) {+ continue;+ }++ const size = resolveResizeObserverBoxSize({+ snapshot,+ box: observation.box,+ devicePixelRatio,+ });+ const hasSizeChanged =+ size.inlineSize !== observation.lastSize?.inlineSize ||+ size.blockSize !== observation.lastSize?.blockSize;++ if (!hasSizeChanged) {+ continue;+ }++ observation.lastSize = size;+ entries.push(+ createResizeObserverEntry({ target, snapshot, devicePixelRatio }),+ );+ }++ this.#stopWhenEmpty();++ if (entries.length === 0) {+ return;+ }++ try {+ this.#callback(entries, this);+ } catch (error) {+ reportCallbackError(error);+ }+ };++ #scheduleDelivery = () => {+ if (this.#hasScheduledDelivery || this.#observations.size === 0) {+ return;+ }++ this.#hasScheduledDelivery = true;+ queueMicrotask(this.#deliver);+ };++ observe(target: Element, options: ResizeObserverOptions = {}): void {+ if (!isElementNode(target)) {+ throw new TypeError('ResizeObserver requires an Element target.');+ }++ const box = options.box ?? DEFAULT_OBSERVATION_BOX;+ const isSupportedBox =+ box === 'content-box' ||+ box === 'border-box' ||+ box === 'device-pixel-content-box';++ if (!isSupportedBox) {+ throw new TypeError(+ 'ResizeObserver received an unsupported box option.',+ );+ }++ const existingTargetRef = this.#targetRefs.get(target);+ const targetRef = existingTargetRef ?? new WeakRef(target);+ const existingObservation = this.#observations.get(targetRef);++ if (existingObservation?.box === box) {+ return;+ }++ const geometryReader =+ existingObservation?.geometryReader ??+ (target.isConnected+ ? geometryStore.createElementGeometryReader(target)+ : null);++ this.#targetRefs.set(target, targetRef);+ this.#observations.set(targetRef, {+ box,+ lastSize: null,+ geometryReader,+ });+ geometryReader?.read();+ activeObserverSchedules.add(this.#scheduleDelivery);+ this.#scheduleDelivery();+ }++ unobserve(target: Element): void {+ const targetRef = this.#targetRefs.get(target);++ if (isDefined(targetRef)) {+ this.#observations.get(targetRef)?.geometryReader?.release();+ this.#observations.delete(targetRef);+ }++ this.#stopWhenEmpty();+ }++ disconnect(): void {+ for (const observation of this.#observations.values()) {+ observation.geometryReader?.release();+ }++ this.#observations.clear();+ this.#stopWhenEmpty();+ }+ }++ return ResizeObserverImplementation;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createResizeObserverEntry.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createResizeObserverEntry.tsnew file mode 100644index 00000000000..a793cf176d9--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createResizeObserverEntry.ts@@ -0,0 +1,31 @@+import { createDomRectFromSnapshot } from '@/polyfills/geometry/utils/createDomRectFromSnapshot';+import { resolveResizeObserverBoxSize } from '@/polyfills/geometry/utils/resolveResizeObserverBoxSize';+import { resolveSnapshotBoxDimensions } from '@/polyfills/geometry/utils/resolveSnapshotBoxDimensions';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++type CreateResizeObserverEntryInput = {+ target: Element;+ snapshot: ElementGeometrySnapshot;+ devicePixelRatio: number;+};++export const createResizeObserverEntry = ({+ target,+ snapshot,+ devicePixelRatio,+}: CreateResizeObserverEntryInput): ResizeObserverEntry => {+ const createBoxSizes = (box: ResizeObserverBoxOptions) =>+ Object.freeze([+ resolveResizeObserverBoxSize({ snapshot, box, devicePixelRatio }),+ ]);++ return {+ target,+ contentRect: createDomRectFromSnapshot(+ resolveSnapshotBoxDimensions(snapshot).contentBox,+ ),+ contentBoxSize: createBoxSizes('content-box'),+ borderBoxSize: createBoxSizes('border-box'),+ devicePixelContentBoxSize: createBoxSizes('device-pixel-content-box'),+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createTextareaIntrinsicSizeReader.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createTextareaIntrinsicSizeReader.tsnew file mode 100644index 00000000000..06d790daf98--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/createTextareaIntrinsicSizeReader.ts@@ -0,0 +1,106 @@+import { isDefined } from 'twenty-shared/utils';++import { type TextareaIntrinsicSizeElement } from '@/polyfills/geometry/types/TextareaIntrinsicSizeElement';+import { type WorkerGeometryStore } from '@/polyfills/geometry/types/WorkerGeometryStore';+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++type ReadTextareaIntrinsicSizeInput = {+ element: TextareaIntrinsicSizeElement;+ snapshot: ElementGeometrySnapshot | null;+};++type TextareaPendingMeasurement = {+ blockSize: string;+ hasReceivedSnapshot: boolean;+};++const formatTextareaBlockSize = ({+ scrollHeight,+ snapshot,+}: {+ scrollHeight: number;+ snapshot: ElementGeometrySnapshot;+}): string => {+ const borderBlockSize = snapshot.offsetHeight - snapshot.clientHeight;++ return `${scrollHeight + borderBlockSize}px`;+};++export const createTextareaIntrinsicSizeReader = (+ geometryStore: WorkerGeometryStore,+) => {+ const pendingMeasurements = new Map<+ TextareaIntrinsicSizeElement,+ TextareaPendingMeasurement+ >();++ geometryStore.subscribeToGeometryUpdates(() => {+ for (const [textarea, measurement] of pendingMeasurements) {+ if (textarea.style?.blockSize !== measurement.blockSize) {+ pendingMeasurements.delete(textarea);+ continue;+ }++ const snapshot = geometryStore.resolveElementSnapshot(textarea);+ const isDetached = !textarea.isConnected;+ const hasLostSnapshot =+ !isDefined(snapshot) && measurement.hasReceivedSnapshot;++ if (isDetached || hasLostSnapshot) {+ pendingMeasurements.delete(textarea);+ continue;+ }++ if (!isDefined(snapshot)) {+ continue;+ }++ if (!isDefined(snapshot.textareaIntrinsicScrollHeight)) {+ pendingMeasurements.delete(textarea);+ continue;+ }++ const blockSize = formatTextareaBlockSize({+ scrollHeight: snapshot.textareaIntrinsicScrollHeight,+ snapshot,+ });+ if (measurement.blockSize !== blockSize && isDefined(textarea.style)) {+ textarea.style.blockSize = blockSize;+ }++ pendingMeasurements.set(textarea, {+ blockSize,+ hasReceivedSnapshot: true,+ });+ }+ });++ return ({ element, snapshot }: ReadTextareaIntrinsicSizeInput): number => {+ const isMeasuringTextareaContent =+ resolveHtmlTagNameOfElement(element) === 'textarea' &&+ element.style?.blockSize === 'auto';++ if (!isMeasuringTextareaContent) {+ return snapshot?.scrollHeight ?? 0;+ }++ if (!isDefined(snapshot)) {+ pendingMeasurements.set(element, {+ blockSize: 'auto',+ hasReceivedSnapshot: false,+ });++ return 0;+ }++ const scrollHeight =+ snapshot.textareaIntrinsicScrollHeight ?? snapshot.scrollHeight;+ pendingMeasurements.set(element, {+ blockSize: formatTextareaBlockSize({ scrollHeight, snapshot }),+ hasReceivedSnapshot: true,+ });++ return scrollHeight;+ };+};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.tsindex 8cdfde6245a..ecc4fc23af7 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@@ -2,26 +2,31 @@ import { remoteId } from '@remote-dom/core/elements';import { isDefined } from 'twenty-shared/utils';import { MAX_OBSERVED_GEOMETRY_ELEMENTS } from '@/constants/MaxObservedGeometryElements';+import { type NodeLike } from '@/polyfills/dom/types/NodeLike';import { GEOMETRY_OBSERVATION_LIMIT_WARNING } from '@/polyfills/geometry/constants/GeometryObservationLimitWarning';import { GEOMETRY_TRANSPORT_FAILURE_WARNING } from '@/polyfills/geometry/constants/GeometryTransportFailureWarning';import { type GeometryObservationTransport } from '@/polyfills/geometry/types/GeometryObservationTransport';import { type WorkerGeometryStore } from '@/polyfills/geometry/types/WorkerGeometryStore';+import { createDocumentScopedElementGeometrySnapshot } from '@/polyfills/geometry/utils/createDocumentScopedElementGeometrySnapshot';+import { createElementGeometryOwnerships } from '@/polyfills/geometry/utils/createElementGeometryOwnerships';import { isElementUnderRemoteRoot } from '@/polyfills/geometry/utils/isElementUnderRemoteRoot';+import { isHostRenderedElement } from '@/polyfills/geometry/utils/isHostRenderedElement';+import { restoreUnchangedComputedStyle } from '@/polyfills/geometry/utils/restoreUnchangedComputedStyle';import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';import { type GeometryUpdateBatch } from '@/types/GeometryUpdateBatch';import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot';export const createWorkerGeometryStore = (): WorkerGeometryStore => {const elementSnapshots = new Map<string, ElementGeometrySnapshot>();- 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 rootElement: NodeLike | null = null;let transport: GeometryObservationTransport | null = null;let viewportSnapshot: ViewportGeometrySnapshot | null = null;let hasScheduledObservationFlush = false;+ let hasScheduledGeometryUpdateNotification = false;let hasWarnedAboutObservationLimit = false;let hasWarnedAboutTransportFailure = false;@@ -34,6 +39,26 @@ export const createWorkerGeometryStore = (): WorkerGeometryStore => {console.warn(GEOMETRY_TRANSPORT_FAILURE_WARNING);};+ const notifyGeometryUpdateListeners = (): void => {+ for (const geometryUpdateListener of [...geometryUpdateListeners]) {+ geometryUpdateListener();+ }+ };++ const flushGeometryUpdateNotification = (): void => {+ hasScheduledGeometryUpdateNotification = false;+ notifyGeometryUpdateListeners();+ };++ const scheduleGeometryUpdateNotification = (): void => {+ if (hasScheduledGeometryUpdateNotification) {+ return;+ }++ hasScheduledGeometryUpdateNotification = true;+ queueMicrotask(flushGeometryUpdateNotification);+ };+const flushPendingObservations = (): void => {hasScheduledObservationFlush = false;@@ -70,7 +95,6 @@ export const createWorkerGeometryStore = (): WorkerGeometryStore => {const remoteElementId = remoteId(element as Node);- enrolledRemoteElementIds.set(element, remoteElementId);observedRemoteElementIds.add(remoteElementId);pendingObservationIds.add(remoteElementId);scheduleObservationFlush();@@ -78,42 +102,125 @@ export const createWorkerGeometryStore = (): WorkerGeometryStore => {return remoteElementId;};- const resolveElementSnapshot = (+ const releaseRemoteElement = (remoteElementId: string): void => {+ elementSnapshots.delete(remoteElementId);+ const wasPending = pendingObservationIds.delete(remoteElementId);+ const wasAtObservationLimit =+ observedRemoteElementIds.size >= MAX_OBSERVED_GEOMETRY_ELEMENTS;+ const wasObserved = observedRemoteElementIds.delete(remoteElementId);++ if (wasObserved && wasAtObservationLimit) {+ scheduleGeometryUpdateNotification();+ }++ if (wasPending || !wasObserved || !isDefined(transport)) {+ return;+ }++ transport+ .unobserveElementGeometry([remoteElementId])+ .catch(warnAboutTransportFailure);+ };++ const elementGeometryOwnerships = createElementGeometryOwnerships({+ isObservedRemoteElementId: (remoteElementId) =>+ observedRemoteElementIds.has(remoteElementId),+ isPendingObservation: (remoteElementId) =>+ pendingObservationIds.has(remoteElementId),+ releaseRemoteElement,+ });++ const isDocumentScopedElement = (element: object): boolean =>+ isDefined(rootElement) &&+ (element === rootElement || element === rootElement.parentNode);++ const readDocumentScopedSnapshot = (element: object,- ): ElementGeometrySnapshot | null => {- const enrolledRemoteElementId = enrolledRemoteElementIds.get(element);+ ): ElementGeometrySnapshot | null =>+ isDefined(viewportSnapshot)+ ? createDocumentScopedElementGeometrySnapshot({+ viewport: viewportSnapshot,+ isDocumentElement: element !== rootElement,+ })+ : null;++ const readElementSnapshot = (+ remoteElementId: string | null,+ ): ElementGeometrySnapshot | null =>+ isDefined(remoteElementId)+ ? (elementSnapshots.get(remoteElementId) ?? null)+ : null;++ const resolveSnapshot = (element: object): ElementGeometrySnapshot | null => {+ if (isDocumentScopedElement(element)) {+ return readDocumentScopedSnapshot(element);+ }- if (isDefined(enrolledRemoteElementId)) {- if (observedRemoteElementIds.has(enrolledRemoteElementId)) {- return elementSnapshots.get(enrolledRemoteElementId) ?? null;- }+ const observedRemoteElementId =+ elementGeometryOwnerships.readObservedRemoteElementId(element);- enrolledRemoteElementIds.delete(element);+ if (isDefined(observedRemoteElementId)) {+ return readElementSnapshot(observedRemoteElementId);}- if (!isElementUnderRemoteRoot(element, rootElement)) {+ if (+ !isElementUnderRemoteRoot(element, rootElement) ||+ !isHostRenderedElement(element)+ ) {return null;}const remoteElementId = enrollElement(element);+ elementGeometryOwnerships.assignRemoteElementId({+ element,+ remoteElementId,+ });- if (!isDefined(remoteElementId)) {- return null;- }+ return readElementSnapshot(remoteElementId);+ };- return elementSnapshots.get(remoteElementId) ?? null;+ const resolveElementSnapshot = (+ element: object,+ ): ElementGeometrySnapshot | null => {+ const snapshot = resolveSnapshot(element);+ elementGeometryOwnerships.markDirectReader(element);++ return snapshot;};+ const readObservedElementSnapshot = (+ element: object,+ ): ElementGeometrySnapshot | null =>+ isDocumentScopedElement(element)+ ? readDocumentScopedSnapshot(element)+ : readElementSnapshot(+ elementGeometryOwnerships.readObservedRemoteElementId(element),+ );++ const isElementMeasured = (element: object): boolean =>+ isDefined(elementGeometryOwnerships.readObservedRemoteElementId(element));+const applyGeometryBatch = (batch: GeometryUpdateBatch): void => {if (isDefined(batch.viewport)) {- viewportSnapshot = batch.viewport;+ viewportSnapshot = restoreUnchangedComputedStyle({+ previousSnapshot: viewportSnapshot,+ nextSnapshot: batch.viewport,+ });}if (isDefined(batch.elements)) {for (const [remoteElementId, snapshot] of Object.entries(batch.elements,)) {- elementSnapshots.set(remoteElementId, snapshot);+ if (observedRemoteElementIds.has(remoteElementId)) {+ elementSnapshots.set(+ remoteElementId,+ restoreUnchangedComputedStyle({+ previousSnapshot: elementSnapshots.get(remoteElementId),+ nextSnapshot: snapshot,+ }),+ );+ }}}@@ -136,9 +243,7 @@ export const createWorkerGeometryStore = (): WorkerGeometryStore => {}}- for (const geometryUpdateListener of [...geometryUpdateListeners]) {- geometryUpdateListener();- }+ notifyGeometryUpdateListeners();};return {@@ -159,5 +264,12 @@ export const createWorkerGeometryStore = (): WorkerGeometryStore => {};},resolveElementSnapshot,+ readObservedElementSnapshot,+ isElementMeasured,+ createElementGeometryReader: (element: object) =>+ elementGeometryOwnerships.createElementGeometryReader({+ element,+ readSnapshot: resolveSnapshot,+ }),};};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/hasMeasuredChildElement.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/hasMeasuredChildElement.tsnew file mode 100644index 00000000000..a49515955c0--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/hasMeasuredChildElement.ts@@ -0,0 +1,24 @@+import { isDefined } from 'twenty-shared/utils';++import { type ElementLike } from '@/polyfills/dom/types/ElementLike';+import { isElementNode } from '@/polyfills/dom/utils/isElementNode';+import { type WorkerGeometryStore } from '@/polyfills/geometry/types/WorkerGeometryStore';++export const hasMeasuredChildElement = ({+ element,+ geometryStore,+}: {+ element: ElementLike;+ geometryStore: WorkerGeometryStore;+}): boolean => {+ const childNodes = element.childNodes;++ if (!isDefined(childNodes)) {+ return false;+ }++ return Array.from(childNodes).some(+ (childNode) =>+ isElementNode(childNode) && geometryStore.isElementMeasured(childNode),+ );+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/installElementGeometryPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/installElementGeometryPolyfill.tsindex 11c694e5a48..1518f88ad20 100644--- a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/installElementGeometryPolyfill.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/installElementGeometryPolyfill.ts@@ -1,28 +1,12 @@import { isDefined } from 'twenty-shared/utils';+import { findAncestorByRemoteId } from '@/polyfills/dom/utils/findAncestorByRemoteId';+import { type TextareaIntrinsicSizeElement } from '@/polyfills/geometry/types/TextareaIntrinsicSizeElement';import { type WorkerGeometryStore } from '@/polyfills/geometry/types/WorkerGeometryStore';import { createDomRectFromSnapshot } from '@/polyfills/geometry/utils/createDomRectFromSnapshot';+import { createTextareaIntrinsicSizeReader } from '@/polyfills/geometry/utils/createTextareaIntrinsicSizeReader';import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';-const EMPTY_ELEMENT_GEOMETRY_SNAPSHOT: ElementGeometrySnapshot = {- x: 0,- y: 0,- width: 0,- height: 0,- offsetWidth: 0,- offsetHeight: 0,- offsetTop: 0,- offsetLeft: 0,- clientWidth: 0,- clientHeight: 0,- clientTop: 0,- clientLeft: 0,- scrollWidth: 0,- scrollHeight: 0,- scrollTop: 0,- scrollLeft: 0,-};-type InstallElementGeometryPolyfillInput = {elementPrototype: object;documentTarget: { body?: unknown; documentElement?: unknown };@@ -34,44 +18,11 @@ export const installElementGeometryPolyfill = ({documentTarget,geometryStore,}: InstallElementGeometryPolyfillInput): void => {- const isDocumentScopedElement = (element: object): boolean =>- element === documentTarget.body ||- element === documentTarget.documentElement;-- const resolveDocumentScopedSnapshotInHostViewportFrame = (- element: object,- ): ElementGeometrySnapshot => {- const viewport = geometryStore.getViewportSnapshot();-- if (!isDefined(viewport)) {- return EMPTY_ELEMENT_GEOMETRY_SNAPSHOT;- }-- const isDocumentElement = element === documentTarget.documentElement;-- return {- ...EMPTY_ELEMENT_GEOMETRY_SNAPSHOT,- x: viewport.rootContainerX,- y: viewport.rootContainerY,- width: viewport.rootContainerWidth,- height: viewport.rootContainerHeight,- offsetWidth: viewport.rootContainerWidth,- offsetHeight: viewport.rootContainerHeight,- clientWidth: viewport.rootContainerClientWidth,- clientHeight: viewport.rootContainerClientHeight,- scrollWidth: viewport.rootContainerClientWidth,- scrollHeight: viewport.rootContainerClientHeight,- scrollTop: isDocumentElement ? viewport.scrollY : 0,- scrollLeft: isDocumentElement ? viewport.scrollX : 0,- };- };+ const readTextareaIntrinsicSize =+ createTextareaIntrinsicSizeReader(geometryStore);const resolveSnapshot = (element: object): ElementGeometrySnapshot | null => {try {- if (isDocumentScopedElement(element)) {- return resolveDocumentScopedSnapshotInHostViewportFrame(element);- }-return geometryStore.resolveElementSnapshot(element);} catch {return null;@@ -86,10 +37,13 @@ export const installElementGeometryPolyfill = ({writable: true,});- const defineGeometryGetter = (- propertyName: keyof ElementGeometrySnapshot,- { hasNoOpSetter = false }: { hasNoOpSetter?: boolean } = {},- ): void => {+ const defineGeometryGetter = ({+ propertyName,+ hasNoOpSetter = false,+ }: {+ propertyName: keyof ElementGeometrySnapshot;+ hasNoOpSetter?: boolean;+ }): void => {Object.defineProperty(elementPrototype, propertyName, {get(this: object) {return resolveSnapshot(this)?.[propertyName] ?? 0;@@ -109,22 +63,46 @@ export const installElementGeometryPolyfill = ({'clientTop','clientLeft','scrollWidth',- 'scrollHeight',] as const) {- defineGeometryGetter(propertyName);+ defineGeometryGetter({ propertyName });}for (const propertyName of ['scrollTop', 'scrollLeft'] as const) {- defineGeometryGetter(propertyName, { hasNoOpSetter: true });+ defineGeometryGetter({ propertyName, hasNoOpSetter: true });}+ Object.defineProperty(elementPrototype, 'scrollHeight', {+ get(this: TextareaIntrinsicSizeElement) {+ return readTextareaIntrinsicSize({+ element: this,+ snapshot: resolveSnapshot(this),+ });+ },+ configurable: true,+ });+Object.defineProperty(elementPrototype, 'offsetParent', {get(this: object) {- if (isDocumentScopedElement(this)) {+ if (+ this === documentTarget.body ||+ this === documentTarget.documentElement+ ) {return null;}- return documentTarget.body ?? null;+ const offsetParentRemoteElementId =+ geometryStore.readObservedElementSnapshot(+ this,+ )?.offsetParentRemoteElementId;++ if (!isDefined(offsetParentRemoteElementId)) {+ return documentTarget.body ?? null;+ }++ return findAncestorByRemoteId({+ node: this,+ remoteElementId: offsetParentRemoteElementId,+ });},configurable: true,});diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/installResizeObserverPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/installResizeObserverPolyfill.tsnew file mode 100644index 00000000000..b1c14ad7514--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/installResizeObserverPolyfill.ts@@ -0,0 +1,33 @@+import { type WorkerGeometryStore } from '@/polyfills/geometry/types/WorkerGeometryStore';+import { createResizeObserverClass } from '@/polyfills/geometry/utils/createResizeObserverClass';+import { resolvePolyfillHooks } from '@/polyfills/dom/utils/resolvePolyfillHooks';+import { reportErrorToPolyfillWindow } from '@/polyfills/utils/reportErrorToPolyfillWindow';+import { resolveGlobalScopeInstallTargets } from '@/polyfills/utils/resolveGlobalScopeInstallTargets';+import { resolvePolyfillWindow } from '@/polyfills/utils/resolvePolyfillWindow';++type InstallResizeObserverPolyfillInput = {+ globalScope: Record<string, unknown>;+ geometryStore: WorkerGeometryStore;+};++export const installResizeObserverPolyfill = ({+ globalScope,+ geometryStore,+}: InstallResizeObserverPolyfillInput): void => {+ const installTargets = resolveGlobalScopeInstallTargets(globalScope);+ const polyfillWindow = resolvePolyfillWindow(globalScope);+ const ResizeObserverImplementation = createResizeObserverClass({+ geometryStore,+ hooks: resolvePolyfillHooks(installTargets),+ reportCallbackError: (error) =>+ reportErrorToPolyfillWindow({ polyfillWindow, error }),+ });++ for (const installTarget of installTargets) {+ Object.defineProperty(installTarget, 'ResizeObserver', {+ value: ResizeObserverImplementation,+ configurable: true,+ writable: true,+ });+ }+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/isHostRenderedElement.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/isHostRenderedElement.tsnew file mode 100644index 00000000000..39d31d32403--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/isHostRenderedElement.ts@@ -0,0 +1,6 @@+import { HOST_RENDERED_HTML_TAG_NAMES } from '@/polyfills/geometry/constants/HostRenderedHtmlTagNames';+import { type SelectorElementLike } from '@/polyfills/selectors/types/SelectorElementLike';+import { resolveHtmlTagNameOfElement } from '@/polyfills/selectors/utils/resolveHtmlTagNameOfElement';++export const isHostRenderedElement = (element: SelectorElementLike): boolean =>+ HOST_RENDERED_HTML_TAG_NAMES.has(resolveHtmlTagNameOfElement(element));diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/readSnapshotBorderWidths.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/readSnapshotBorderWidths.tsnew file mode 100644index 00000000000..fb587390dfb--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/readSnapshotBorderWidths.ts@@ -0,0 +1,14 @@+import { readSnapshotComputedLength } from '@/polyfills/geometry/utils/readSnapshotComputedLength';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++export const readSnapshotBorderWidths = (snapshot: ElementGeometrySnapshot) => {+ const readBorderWidth = (propertyName: string) =>+ readSnapshotComputedLength({ snapshot, propertyName }) || 0;++ return {+ left: readBorderWidth('border-left-width'),+ top: readBorderWidth('border-top-width'),+ right: readBorderWidth('border-right-width'),+ bottom: readBorderWidth('border-bottom-width'),+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/readSnapshotComputedLength.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/readSnapshotComputedLength.tsnew file mode 100644index 00000000000..16444461754--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/readSnapshotComputedLength.ts@@ -0,0 +1,9 @@+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++export const readSnapshotComputedLength = ({+ snapshot,+ propertyName,+}: {+ snapshot: ElementGeometrySnapshot;+ propertyName: string;+}): number => parseFloat(snapshot.computedStyle?.[propertyName] ?? '');diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/readSnapshotPadding.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/readSnapshotPadding.tsnew file mode 100644index 00000000000..54689bd6710--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/readSnapshotPadding.ts@@ -0,0 +1,14 @@+import { readSnapshotComputedLength } from '@/polyfills/geometry/utils/readSnapshotComputedLength';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++export const readSnapshotPadding = (snapshot: ElementGeometrySnapshot) => {+ const readPadding = (propertyName: string) =>+ readSnapshotComputedLength({ snapshot, propertyName }) || 0;++ return {+ left: readPadding('padding-left'),+ top: readPadding('padding-top'),+ right: readPadding('padding-right'),+ bottom: readPadding('padding-bottom'),+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveClientBoxDimensions.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveClientBoxDimensions.tsnew file mode 100644index 00000000000..a326c850a21--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveClientBoxDimensions.ts@@ -0,0 +1,19 @@+import { type SnapshotBoxDimensions } from '@/polyfills/geometry/types/SnapshotBoxDimensions';+import { readSnapshotPadding } from '@/polyfills/geometry/utils/readSnapshotPadding';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++export const resolveClientBoxDimensions = (+ snapshot: ElementGeometrySnapshot,+): SnapshotBoxDimensions => {+ const padding = readSnapshotPadding(snapshot);++ return {+ contentBox: {+ x: padding.left,+ y: padding.top,+ width: Math.max(0, snapshot.clientWidth - padding.left - padding.right),+ height: Math.max(0, snapshot.clientHeight - padding.top - padding.bottom),+ },+ borderBox: { width: snapshot.offsetWidth, height: snapshot.offsetHeight },+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveComputedBoxDimensions.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveComputedBoxDimensions.tsnew file mode 100644index 00000000000..0d3ca8fd3ba--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveComputedBoxDimensions.ts@@ -0,0 +1,100 @@+import { type SnapshotBoxDimensions } from '@/polyfills/geometry/types/SnapshotBoxDimensions';+import { readSnapshotBorderWidths } from '@/polyfills/geometry/utils/readSnapshotBorderWidths';+import { readSnapshotComputedLength } from '@/polyfills/geometry/utils/readSnapshotComputedLength';+import { readSnapshotPadding } from '@/polyfills/geometry/utils/readSnapshotPadding';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++const SCROLLABLE_OVERFLOW_VALUES: ReadonlySet<string> = new Set([+ 'auto',+ 'scroll',+]);++const hasLayoutBox = ({+ offsetWidth,+ offsetHeight,+ width,+ height,+}: ElementGeometrySnapshot): boolean =>+ offsetWidth > 0 || offsetHeight > 0 || width > 0 || height > 0;++const readScrollbarThickness = ({+ overflow,+ borderBoxSize,+ borderSize,+ clientSize,+}: {+ overflow: string | undefined;+ borderBoxSize: number;+ borderSize: number;+ clientSize: number;+}): number =>+ SCROLLABLE_OVERFLOW_VALUES.has(overflow ?? '')+ ? Math.max(0, Math.round(borderBoxSize - borderSize - clientSize))+ : 0;++export const resolveComputedBoxDimensions = (+ snapshot: ElementGeometrySnapshot,+): SnapshotBoxDimensions | null => {+ const computedWidth = readSnapshotComputedLength({+ snapshot,+ propertyName: 'width',+ });+ const computedHeight = readSnapshotComputedLength({+ snapshot,+ propertyName: 'height',+ });++ if (+ !hasLayoutBox(snapshot) ||+ !Number.isFinite(computedWidth) ||+ !Number.isFinite(computedHeight)+ ) {+ return null;+ }++ const padding = readSnapshotPadding(snapshot);+ const borderWidths = readSnapshotBorderWidths(snapshot);+ const horizontalEdges =+ padding.left + padding.right + borderWidths.left + borderWidths.right;+ const verticalEdges =+ padding.top + padding.bottom + borderWidths.top + borderWidths.bottom;+ const verticalScrollbarWidth = readScrollbarThickness({+ overflow: snapshot.computedStyle?.['overflow-y'],+ borderBoxSize: snapshot.offsetWidth,+ borderSize: borderWidths.left + borderWidths.right,+ clientSize: snapshot.clientWidth,+ });+ const horizontalScrollbarHeight = readScrollbarThickness({+ overflow: snapshot.computedStyle?.['overflow-x'],+ borderBoxSize: snapshot.offsetHeight,+ borderSize: borderWidths.top + borderWidths.bottom,+ clientSize: snapshot.clientHeight,+ });+ const isBorderBoxSizing =+ snapshot.computedStyle?.['box-sizing'] === 'border-box';+ const contentWidth = Math.max(+ 0,+ computedWidth -+ (isBorderBoxSizing ? horizontalEdges : 0) -+ verticalScrollbarWidth,+ );+ const contentHeight = Math.max(+ 0,+ computedHeight -+ (isBorderBoxSizing ? verticalEdges : 0) -+ horizontalScrollbarHeight,+ );++ return {+ contentBox: {+ x: padding.left,+ y: padding.top,+ width: contentWidth,+ height: contentHeight,+ },+ borderBox: {+ width: contentWidth + horizontalEdges + verticalScrollbarWidth,+ height: contentHeight + verticalEdges + horizontalScrollbarHeight,+ },+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveResizeObserverBoxSize.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveResizeObserverBoxSize.tsnew file mode 100644index 00000000000..27ed930e195--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveResizeObserverBoxSize.ts@@ -0,0 +1,46 @@+import { resolveSnapshotBoxDimensions } from '@/polyfills/geometry/utils/resolveSnapshotBoxDimensions';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++const DEFAULT_WRITING_MODE = 'horizontal-tb';++type ResolveResizeObserverBoxSizeInput = {+ snapshot: ElementGeometrySnapshot;+ box: ResizeObserverBoxOptions;+ devicePixelRatio: number;+};++const resolveBoxDimensions = ({+ snapshot,+ box,+ devicePixelRatio,+}: ResolveResizeObserverBoxSizeInput): { width: number; height: number } => {+ const { contentBox, borderBox } = resolveSnapshotBoxDimensions(snapshot);++ if (box === 'border-box') {+ return borderBox;+ }++ if (box === 'device-pixel-content-box') {+ return {+ width: Math.round(contentBox.width * devicePixelRatio),+ height: Math.round(contentBox.height * devicePixelRatio),+ };+ }++ return contentBox;+};++export const resolveResizeObserverBoxSize = (+ input: ResolveResizeObserverBoxSizeInput,+): ResizeObserverSize => {+ const { width, height } = resolveBoxDimensions(input);+ const writingMode =+ input.snapshot.computedStyle?.['writing-mode'] ?? DEFAULT_WRITING_MODE;+ const isVerticalWritingMode =+ writingMode.startsWith('vertical') || writingMode.startsWith('sideways');++ return Object.freeze({+ inlineSize: isVerticalWritingMode ? height : width,+ blockSize: isVerticalWritingMode ? width : height,+ });+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveSnapshotBoxDimensions.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveSnapshotBoxDimensions.tsnew file mode 100644index 00000000000..1f8eb14bbe6--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveSnapshotBoxDimensions.ts@@ -0,0 +1,12 @@+import { type SnapshotBoxDimensions } from '@/polyfills/geometry/types/SnapshotBoxDimensions';+import { resolveClientBoxDimensions } from '@/polyfills/geometry/utils/resolveClientBoxDimensions';+import { resolveComputedBoxDimensions } from '@/polyfills/geometry/utils/resolveComputedBoxDimensions';+import { resolveSvgBoxDimensions } from '@/polyfills/geometry/utils/resolveSvgBoxDimensions';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++export const resolveSnapshotBoxDimensions = (+ snapshot: ElementGeometrySnapshot,+): SnapshotBoxDimensions =>+ resolveSvgBoxDimensions(snapshot) ??+ resolveComputedBoxDimensions(snapshot) ??+ resolveClientBoxDimensions(snapshot);diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveSvgBoxDimensions.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveSvgBoxDimensions.tsnew file mode 100644index 00000000000..7552ac53bcd--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/resolveSvgBoxDimensions.ts@@ -0,0 +1,20 @@+import { isDefined } from 'twenty-shared/utils';++import { type SnapshotBoxDimensions } from '@/polyfills/geometry/types/SnapshotBoxDimensions';+import { type ElementGeometrySnapshot } from '@/types/ElementGeometrySnapshot';++export const resolveSvgBoxDimensions = ({+ svgBoundingBoxWidth,+ svgBoundingBoxHeight,+}: ElementGeometrySnapshot): SnapshotBoxDimensions | null =>+ isDefined(svgBoundingBoxWidth) && isDefined(svgBoundingBoxHeight)+ ? {+ contentBox: {+ x: 0,+ y: 0,+ width: svgBoundingBoxWidth,+ height: svgBoundingBoxHeight,+ },+ borderBox: { width: svgBoundingBoxWidth, height: svgBoundingBoxHeight },+ }+ : null;diff --git a/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/restoreUnchangedComputedStyle.ts b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/restoreUnchangedComputedStyle.tsnew file mode 100644index 00000000000..efc01ea0f8b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/geometry/utils/restoreUnchangedComputedStyle.ts@@ -0,0 +1,12 @@+export const restoreUnchangedComputedStyle = <+ TSnapshot extends { computedStyle?: Record<string, string> },+>({+ previousSnapshot,+ nextSnapshot,+}: {+ previousSnapshot: TSnapshot | null | undefined;+ nextSnapshot: TSnapshot;+}): TSnapshot => ({+ ...nextSnapshot,+ computedStyle: nextSnapshot.computedStyle ?? previousSnapshot?.computedStyle,+});diff --git a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.tsindex d2dafa1e412..78595f7689b 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@@ -44,6 +44,7 @@ import { installSelectorMethodsPolyfill } from '@/polyfills/selectors/utils/instimport { workerGeometryStore } from '@/polyfills/geometry/states/workerGeometryStore';import { installElementGeometryPolyfill } from '@/polyfills/geometry/utils/installElementGeometryPolyfill';import { installVisualViewportPolyfill } from '@/polyfills/geometry/utils/installVisualViewportPolyfill';+import { installResizeObserverPolyfill } from '@/polyfills/geometry/utils/installResizeObserverPolyfill';import { installWindowGeometryPolyfill } from '@/polyfills/geometry/utils/installWindowGeometryPolyfill';import { mediaQueryEnvironmentSource } from '@/polyfills/media-query/states/mediaQueryEnvironmentSource';import { workerMediaBridge } from '@/polyfills/media/states/workerMediaBridge';@@ -137,7 +138,10 @@ installHostEventRetargetingPolyfill(HTMLElement.prototype);installElementClickMethodPolyfill(HTMLElement.prototype);installInputClickActivationPolyfill(HtmlInputElement.prototype);-installGetComputedStyle(toGlobalScopeRecord(globalThis));+installGetComputedStyle({+ globalScope: toGlobalScopeRecord(globalThis),+ geometryStore: workerGeometryStore,+});installMutationObserver({globalScope: toGlobalScopeRecord(globalThis),@@ -159,6 +163,11 @@ installVisualViewportPolyfill({geometryStore: workerGeometryStore,});+installResizeObserverPolyfill({+ globalScope: toGlobalScopeRecord(globalThis),+ geometryStore: workerGeometryStore,+});+installWindowAliasesPolyfill({globalScope: toGlobalScopeRecord(globalThis),});diff --git a/packages/twenty-front-component-renderer/src/testing/createWorkerGeometryStoreStub.ts b/packages/twenty-front-component-renderer/src/testing/createWorkerGeometryStoreStub.tsindex c8138e48a86..5c690418d43 100644--- a/packages/twenty-front-component-renderer/src/testing/createWorkerGeometryStoreStub.ts+++ b/packages/twenty-front-component-renderer/src/testing/createWorkerGeometryStoreStub.ts@@ -9,5 +9,11 @@ export const createWorkerGeometryStoreStub = (getViewportSnapshot: jest.fn(() => null),subscribeToGeometryUpdates: jest.fn(() => () => {}),resolveElementSnapshot: jest.fn(() => null),+ readObservedElementSnapshot: jest.fn(() => null),+ isElementMeasured: jest.fn(() => false),+ createElementGeometryReader: jest.fn(() => ({+ read: () => null,+ release: () => {},+ })),...overrides,});diff --git a/packages/twenty-front-component-renderer/src/types/ElementGeometrySnapshot.ts b/packages/twenty-front-component-renderer/src/types/ElementGeometrySnapshot.tsindex ef21c8606d5..af3c4e276e4 100644--- a/packages/twenty-front-component-renderer/src/types/ElementGeometrySnapshot.ts+++ b/packages/twenty-front-component-renderer/src/types/ElementGeometrySnapshot.ts@@ -1,4 +1,6 @@export type ElementGeometrySnapshot = {+ computedStyle?: Record<string, string>;+ offsetParentRemoteElementId?: string | null;x: number;y: number;width: number;@@ -13,6 +15,9 @@ export type ElementGeometrySnapshot = {clientLeft: number;scrollWidth: number;scrollHeight: number;+ textareaIntrinsicScrollHeight?: number;+ svgBoundingBoxWidth?: number;+ svgBoundingBoxHeight?: number;scrollTop: number;scrollLeft: number;};diff --git a/packages/twenty-front-component-renderer/src/types/ViewportGeometrySnapshot.ts b/packages/twenty-front-component-renderer/src/types/ViewportGeometrySnapshot.tsindex 369d450ad1a..e3ec980b3d7 100644--- a/packages/twenty-front-component-renderer/src/types/ViewportGeometrySnapshot.ts+++ b/packages/twenty-front-component-renderer/src/types/ViewportGeometrySnapshot.ts@@ -1,6 +1,7 @@import { type InputMediaFeatures } from '@/types/InputMediaFeatures';export type ViewportGeometrySnapshot = InputMediaFeatures & {+ computedStyle?: Record<string, string>;innerWidth: number;innerHeight: number;devicePixelRatio: number;