The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Support classList in front components (#24191)
Raphaël Bosi9a8b4633f16b
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdxindex 0139436f6a1..69d6bed5163 100644--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx@@ -814,12 +814,13 @@ A `ref` gives you a sandbox element, not an `HTMLElement`.| What you write | What happens | Use instead ||----------------|--------------|-------------|| `ref.current.focus()`, `.click()`, `.select()`, `.setSelectionRange()`, `.scrollIntoView()`, `video.play()` | Throws | Controlled components; read values from `event.target` |-| `element.classList.add(...)` | Throws (`classList` is `undefined`) | Build the `className` string yourself || `document.createTreeWalker()` | Throws | `querySelector()` / `querySelectorAll()` and `getElementById()` work; `getElementsByClassName()` works too, but returns a static collection, not a live `HTMLCollection` || `document.activeElement` | Always `undefined` | Track focus with `onFocus` / `onBlur` || `canvas` | Renders nothing, no error | SVG, or draw offscreen and show the result in an `img` element || `createPortal(node, document.body)` | Renders nothing, while `isConnected` reports success | Overlays inline with `position: absolute`, or pass the library your own container element |+`element.classList` works, backed by the `class` attribute: `add`, `remove`, `toggle`, `replace`, `contains`, `item`, `length`, `value` and iteration all behave as they do in a browser, and `className` stays in sync.+The portal gap is why Radix, Headless UI, MUI and react-select popovers render nothing by default. Most accept a container prop; point it at an element you rendered.### Eventsdiff --git a/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsxindex c94ae94efa2..adb06e37614 100644--- a/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx@@ -6,7 +6,11 @@ import {FRONT_COMPONENT_STORY_DEFAULT_ARGS,resetFrontComponentStoryMocks,} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';-import { MOUNT_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';+import { expectJsonDataAttribute } from '@/__stories__/shared/test-utils/matchers/expectJsonDataAttribute';+import {+ INTERACTION_TIMEOUT,+ MOUNT_TIMEOUT,+} from '@/__stories__/shared/test-utils/timeouts';import { getBuiltStoryComponentPathForRender } from '@/__stories__/utils/getBuiltStoryComponentPathForRender';import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';@@ -52,36 +56,84 @@ const mutationObserverTest: Story['play'] = async ({ canvasElement }) => {await userEvent.click(addItemButton);await userEvent.click(addItemButton);+ await expectJsonDataAttribute({+ canvas,+ testId: 'mutation-observer-status',+ attributeName: 'data-observed-records',+ expectedValue: EXPECTED_OBSERVED_MUTATIONS,+ });++ expect(errorHandler).not.toHaveBeenCalled();+};++const EXPECTED_CLASS_LIST_REPORT = {+ tokens: ['initial-class', 'mapboxgl-map', 'replaced', 'toggled-on'],+ value: 'initial-class mapboxgl-map replaced toggled-on',+};++const classListTest: Story['play'] = async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ const runButton = await canvas.findByTestId(+ 'class-list-run',+ {},+ { timeout: MOUNT_TIMEOUT },+ );++ await userEvent.click(runButton);++ await expectJsonDataAttribute({+ canvas,+ testId: 'class-list-status',+ attributeName: 'data-class-list-report',+ expectedValue: EXPECTED_CLASS_LIST_REPORT,+ });+await waitFor(() => {- expect(- JSON.parse(- canvas- .getByTestId('mutation-observer-status')- .getAttribute('data-observed-records') ?? '[]',- ),- ).toEqual(EXPECTED_OBSERVED_MUTATIONS);+ expect(canvas.getByTestId('class-list-container').className).toBe(+ EXPECTED_CLASS_LIST_REPORT.value,+ );},- { timeout: MOUNT_TIMEOUT },+ { timeout: INTERACTION_TIMEOUT },);expect(errorHandler).not.toHaveBeenCalled();};-const createStory = (name: string, runtime?: 'preact'): Story => ({+const createStory = ({+ name,+ play,+ runtime,+}: {+ name: string;+ play: Story['play'];+ runtime?: 'preact';+}): Story => ({args: {componentUrl: getBuiltStoryComponentPathForRender(`${name}.front-component`,runtime,),},- play: mutationObserverTest,+ play,});-export const MutationObserverReact: Story = createStory(- 'mutation-observer-example',-);-export const MutationObserverPreact: Story = createStory(- 'mutation-observer-example',- 'preact',-);+export const MutationObserverReact: Story = createStory({+ name: 'mutation-observer-example',+ play: mutationObserverTest,+});+export const MutationObserverPreact: Story = createStory({+ name: 'mutation-observer-example',+ play: mutationObserverTest,+ runtime: 'preact',+});+export const ClassListReact: Story = createStory({+ name: 'class-list-example',+ play: classListTest,+});+export const ClassListPreact: Story = createStory({+ name: 'class-list-example',+ play: classListTest,+ runtime: 'preact',+});diff --git a/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/README.md b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/README.mdindex ad0f44765bb..e20a158c707 100644--- a/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/README.md+++ b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/README.md@@ -100,6 +100,8 @@ No relative `./` or `../` imports inside `src/__stories__/`.- `expectFrontComponentValue({ canvas, expected })` — waits for the`data-testid="front-component-value"` element rendered by the fixture todisplay the expected string.+- `expectJsonDataAttribute({ canvas, testId, attributeName, expectedValue })` —+ waits for a `data-*` attribute holding JSON to parse to the expected value.- `expectAttributesReflected({ canvas, attributes })` /`expectPropertiesReflected({ canvas, properties })` — used byproperty-reflection stories to assert host DOM mirror values.diff --git a/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/matchers/expectJsonDataAttribute.ts b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/matchers/expectJsonDataAttribute.tsnew file mode 100644index 00000000000..1d8343c090b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/matchers/expectJsonDataAttribute.ts@@ -0,0 +1,32 @@+import { expect, waitFor, type within } from 'storybook/test';++import { INTERACTION_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';++type Canvas = ReturnType<typeof within>;++type ExpectJsonDataAttributeParams = {+ canvas: Canvas;+ testId: string;+ attributeName: string;+ expectedValue: unknown;+ timeout?: number;+};++export const expectJsonDataAttribute = async ({+ canvas,+ testId,+ attributeName,+ expectedValue,+ timeout = INTERACTION_TIMEOUT,+}: ExpectJsonDataAttributeParams): Promise<void> => {+ await waitFor(+ () => {+ expect(+ JSON.parse(+ canvas.getByTestId(testId).getAttribute(attributeName) ?? 'null',+ ),+ ).toEqual(expectedValue);+ },+ { timeout },+ );+};diff --git a/packages/twenty-front-component-renderer/src/__stories__/showcase/class-list-example.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/showcase/class-list-example.front-component.tsxnew file mode 100644index 00000000000..8ee2d8a348b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/showcase/class-list-example.front-component.tsx@@ -0,0 +1,63 @@+import { defineFrontComponent } from 'twenty-sdk/define';+import { useRef, useState } from 'react';++type ClassListReport = {+ tokens: string[];+ value: string;+};++const ClassListComponent = () => {+ const containerRef = useRef<HTMLDivElement>(null);+ const [classListReport, setClassListReport] =+ useState<ClassListReport | null>(null);++ const runClassListOperations = () => {+ const container = containerRef.current;++ if (container === null) {+ return;+ }++ container.classList.add('mapboxgl-map');+ container.classList.add('added-then-removed', 'kept');+ container.classList.remove('added-then-removed');+ container.classList.toggle('toggled-on');+ container.classList.replace('kept', 'replaced');++ setClassListReport({+ tokens: Array.from(container.classList),+ value: container.classList.value,+ });+ };++ return (+ <div+ data-testid="class-list-component"+ style={{ fontFamily: 'system-ui, sans-serif', padding: 16 }}+ >+ <button data-testid="class-list-run" onClick={runClassListOperations}>+ Run classList operations+ </button>+ <div+ ref={containerRef}+ className="initial-class"+ data-testid="class-list-container"+ >+ classList target+ </div>+ <p+ data-testid="class-list-status"+ data-class-list-report={JSON.stringify(classListReport)}+ >+ classList report ready: {String(classListReport !== null)}+ </p>+ </div>+ );+};++export default defineFrontComponent({+ universalIdentifier: 'test-20ui0-0000-0000-0000-000000000114',+ name: 'class-list-component',+ description: 'Asserts element.classList works inside the sandbox worker',+ component: ClassListComponent,+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/constants/AsciiWhitespaceRegex.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/AsciiWhitespaceRegex.tsnew file mode 100644index 00000000000..b2a89f29ab1--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/AsciiWhitespaceRegex.ts@@ -0,0 +1 @@+export const ASCII_WHITESPACE_REGEX = /[\t\n\f\r ]+/;diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/ElementWithAttributes.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/ElementWithAttributes.tsnew file mode 100644index 00000000000..dedd69b3863--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/ElementWithAttributes.ts@@ -0,0 +1,5 @@+export type ElementWithAttributes = {+ getAttribute: (attributeName: string) => string | null;+ setAttribute: (attributeName: string, attributeValue: string) => void;+ removeAttribute: (attributeName: string) => void;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerClassTokenList.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerClassTokenList.tsnew file mode 100644index 00000000000..c7da470581d--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerClassTokenList.ts@@ -0,0 +1,26 @@+export type WorkerClassTokenList = {+ readonly [index: number]: string;+ readonly length: number;+ value: string;+ add: (...tokens: string[]) => void;+ remove: (...tokens: string[]) => void;+ toggle: (token: string, force?: boolean) => boolean;+ replace: (oldToken: string, newToken: string) => boolean;+ contains: (token: string) => boolean;+ item: (index: number) => string | null;+ supports: (token: string) => boolean;+ forEach: (+ callback: (+ token: string,+ tokenIndex: number,+ tokenList: WorkerClassTokenList,+ ) => void,+ thisArgument?: unknown,+ ) => void;+ entries: () => IterableIterator<[number, string]>;+ keys: () => IterableIterator<number>;+ values: () => IterableIterator<string>;+ toString: () => string;+ readonly [Symbol.toStringTag]: string;+ [Symbol.iterator]: () => IterableIterator<string>;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/createClassTokenList.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/createClassTokenList.test.tsnew file mode 100644index 00000000000..994fbf4c09a--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/createClassTokenList.test.ts@@ -0,0 +1,504 @@+import { type WorkerClassTokenList } from '@/polyfills/dom/types/WorkerClassTokenList';+import { createClassTokenList } from '@/polyfills/dom/utils/createClassTokenList';++class FakeElement {+ private attributes = new Map<string, string>();++ constructor(classAttribute?: string) {+ if (classAttribute !== undefined) {+ this.attributes.set('class', classAttribute);+ }+ }++ getAttribute(attributeName: string): string | null {+ return this.attributes.get(attributeName) ?? null;+ }++ setAttribute(attributeName: string, attributeValue: string): void {+ this.attributes.set(attributeName, attributeValue);+ }++ removeAttribute(attributeName: string): void {+ this.attributes.delete(attributeName);+ }+}++type TokenMutator = [+ methodName: string,+ callWithToken: (classTokenList: WorkerClassTokenList, token: string) => void,+];++const TOKEN_MUTATORS: TokenMutator[] = [+ ['add', (classTokenList, token) => classTokenList.add(token)],+ ['remove', (classTokenList, token) => classTokenList.remove(token)],+ ['toggle', (classTokenList, token) => classTokenList.toggle(token)],+ [+ 'replace',+ (classTokenList, token) => classTokenList.replace(token, 'valid'),+ ],+];++describe('createClassTokenList', () => {+ describe('add', () => {+ it('should create the class attribute when adding to an element without one', () => {+ const element = new FakeElement();+ const classTokenList = createClassTokenList(element);++ classTokenList.add('mapboxgl-map');++ expect(element.getAttribute('class')).toBe('mapboxgl-map');+ });++ it('should append tokens while preserving existing ones', () => {+ const element = new FakeElement('first');+ const classTokenList = createClassTokenList(element);++ classTokenList.add('second', 'third');++ expect(element.getAttribute('class')).toBe('first second third');+ });++ it('should not duplicate a token that is already present', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);++ classTokenList.add('first');++ expect(element.getAttribute('class')).toBe('first second');+ });++ it('should normalize surrounding whitespace when rewriting the attribute', () => {+ const element = new FakeElement(' first \t second ');+ const classTokenList = createClassTokenList(element);++ classTokenList.add('third');++ expect(element.getAttribute('class')).toBe('first second third');+ });++ it('should validate every token before mutating anything', () => {+ const element = new FakeElement();+ const classTokenList = createClassTokenList(element);++ expect(() => classTokenList.add('valid', '')).toThrow(+ expect.objectContaining({ name: 'SyntaxError' }),+ );++ expect(element.getAttribute('class')).toBeNull();+ });+ });++ describe('remove', () => {+ it('should remove the requested tokens and keep the others', () => {+ const element = new FakeElement('first second third');+ const classTokenList = createClassTokenList(element);++ classTokenList.remove('first', 'third');++ expect(element.getAttribute('class')).toBe('second');+ });++ it('should leave an empty attribute after removing the last token', () => {+ const element = new FakeElement('only');+ const classTokenList = createClassTokenList(element);++ classTokenList.remove('only');++ expect(element.getAttribute('class')).toBe('');+ });++ it('should not create the attribute when removing from an element without one', () => {+ const element = new FakeElement();+ const classTokenList = createClassTokenList(element);++ classTokenList.remove('absent');++ expect(element.getAttribute('class')).toBeNull();+ });+ });++ describe('toggle', () => {+ it('should add an absent token and return true', () => {+ const element = new FakeElement();+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.toggle('open')).toBe(true);+ expect(element.getAttribute('class')).toBe('open');+ });++ it('should remove a present token and return false', () => {+ const element = new FakeElement('open');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.toggle('open')).toBe(false);+ expect(element.getAttribute('class')).toBe('');+ });++ it('should keep a present token when forced on', () => {+ const element = new FakeElement('open');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.toggle('open', true)).toBe(true);+ expect(element.getAttribute('class')).toBe('open');+ });++ it('should not add an absent token when forced off', () => {+ const element = new FakeElement();+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.toggle('open', false)).toBe(false);+ expect(element.getAttribute('class')).toBeNull();+ });+ });++ describe('replace', () => {+ it('should replace a token in place', () => {+ const element = new FakeElement('first second third');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.replace('second', 'replaced')).toBe(true);+ expect(element.getAttribute('class')).toBe('first replaced third');+ });++ it('should return false without mutating when the old token is absent', () => {+ const element = new FakeElement(' first ');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.replace('absent', 'replaced')).toBe(false);+ expect(element.getAttribute('class')).toBe(' first ');+ });++ it('should collapse duplicates of the new token like the ordered set replace', () => {+ const element = new FakeElement('first second third');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.replace('third', 'first')).toBe(true);+ expect(element.getAttribute('class')).toBe('first second');+ });++ it('should validate the replacement token', () => {+ const classTokenList = createClassTokenList(new FakeElement());++ expect(() => classTokenList.replace('old', 'has space')).toThrow(+ expect.objectContaining({ name: 'InvalidCharacterError' }),+ );+ });+ });++ describe('contains', () => {+ it('should report token presence without throwing on invalid tokens', () => {+ const element = new FakeElement('present');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.contains('present')).toBe(true);+ expect(classTokenList.contains('absent')).toBe(false);+ expect(classTokenList.contains('')).toBe(false);+ expect(classTokenList.contains('two tokens')).toBe(false);+ });+ });++ describe('item and length', () => {+ it('should expose tokens by index and count them deduplicated', () => {+ const element = new FakeElement(' first second first ');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.length).toBe(2);+ expect(classTokenList.item(0)).toBe('first');+ expect(classTokenList.item(1)).toBe('second');+ expect(classTokenList.item(2)).toBeNull();+ });+ });++ describe('value and toString', () => {+ it('should return the raw attribute value', () => {+ const element = new FakeElement(' raw value ');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.value).toBe(' raw value ');+ expect(classTokenList.toString()).toBe(' raw value ');+ expect(String(classTokenList)).toBe(' raw value ');+ });++ it('should return an empty string for an element without a class', () => {+ const classTokenList = createClassTokenList(new FakeElement());++ expect(classTokenList.value).toBe('');+ expect(classTokenList.toString()).toBe('');+ });++ it('should write the assigned value as is', () => {+ const element = new FakeElement();+ const classTokenList = createClassTokenList(element);++ classTokenList.value = ' first second ';++ expect(element.getAttribute('class')).toBe(' first second ');+ expect(classTokenList.length).toBe(2);+ });+ });++ describe('iteration', () => {+ it('should iterate tokens with the spread operator and for of', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);++ expect([...classTokenList]).toEqual(['first', 'second']);++ const iterated: string[] = [];++ for (const token of classTokenList) {+ iterated.push(token);+ }++ expect(iterated).toEqual(['first', 'second']);+ });++ it('should expose entries, keys and values iterators', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);++ expect([...classTokenList.entries()]).toEqual([+ [0, 'first'],+ [1, 'second'],+ ]);+ expect([...classTokenList.keys()]).toEqual([0, 1]);+ expect([...classTokenList.values()]).toEqual(['first', 'second']);+ });++ it('should call the forEach callback with token, index, list and thisArg', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);+ const thisArg = { marker: true };+ const calls: unknown[][] = [];++ classTokenList.forEach(function (this: unknown, ...callbackArguments) {+ calls.push([this, ...callbackArguments]);+ }, thisArg);++ expect(calls).toEqual([+ [thisArg, 'first', 0, classTokenList],+ [thisArg, 'second', 1, classTokenList],+ ]);+ });++ it('should keep a values iterator live across a class change', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);+ const valuesIterator = classTokenList.values();++ expect(valuesIterator.next().value).toBe('first');++ element.setAttribute('class', 'first replacement third');++ expect([...valuesIterator]).toEqual(['replacement', 'third']);+ });++ it('should keep entries and keys iterators live across a class change', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);+ const entriesIterator = classTokenList.entries();+ const keysIterator = classTokenList.keys();++ entriesIterator.next();+ keysIterator.next();++ element.setAttribute('class', 'first replacement third');++ expect([...entriesIterator]).toEqual([+ [1, 'replacement'],+ [2, 'third'],+ ]);+ expect([...keysIterator]).toEqual([1, 2]);+ });++ it('should let for of observe a class change made inside the loop', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);+ const iterated: string[] = [];++ for (const token of classTokenList) {+ iterated.push(token);++ if (token === 'first') {+ element.setAttribute('class', 'first replacement third');+ }+ }++ expect(iterated).toEqual(['first', 'replacement', 'third']);+ });++ it('should skip the shifted token when forEach removes the current one', () => {+ const element = new FakeElement('first second third');+ const classTokenList = createClassTokenList(element);+ const visited: string[] = [];++ classTokenList.forEach((token) => {+ visited.push(token);++ if (token === 'first') {+ classTokenList.remove('first');+ }+ });++ expect(visited).toEqual(['first', 'third']);+ });++ it('should not extend a forEach pass with a token added during it', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);+ const visited: string[] = [];++ classTokenList.forEach((token) => {+ visited.push(token);++ if (token === 'first') {+ classTokenList.add('third');+ }+ });++ expect(visited).toEqual(['first', 'second']);+ });+ });++ describe('supports', () => {+ it('should throw a TypeError because the class attribute has no supported tokens', () => {+ const classTokenList = createClassTokenList(new FakeElement());++ expect(() => classTokenList.supports('anything')).toThrow(TypeError);+ });+ });++ describe('toggle force conversion', () => {+ it('should treat an explicitly null force as false like the DOM does', () => {+ const element = new FakeElement();+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.toggle('open', null as unknown as undefined)).toBe(+ false,+ );+ expect(element.getAttribute('class')).toBeNull();+ });++ it('should not rewrite the attribute when forcing a present token on', () => {+ const element = new FakeElement(' first second ');+ const setAttribute = jest.spyOn(element, 'setAttribute');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.toggle('first', true)).toBe(true);++ expect(setAttribute).not.toHaveBeenCalled();+ expect(element.getAttribute('class')).toBe(' first second ');+ });++ it('should not rewrite the attribute when forcing an absent token off', () => {+ const element = new FakeElement(' first second ');+ const setAttribute = jest.spyOn(element, 'setAttribute');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.toggle('absent', false)).toBe(false);++ expect(setAttribute).not.toHaveBeenCalled();+ expect(element.getAttribute('class')).toBe(' first second ');+ });+ });++ describe('indexed access', () => {+ it('should expose tokens as indexed properties', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList[0]).toBe('first');+ expect(classTokenList[1]).toBe('second');+ expect(classTokenList[2]).toBeUndefined();+ });++ it('should support the array like idioms that read length and indices', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);++ expect(Array.prototype.slice.call(classTokenList)).toEqual([+ 'first',+ 'second',+ ]);+ expect(Object.keys(classTokenList)).toEqual(['0', '1']);+ expect(JSON.stringify(classTokenList)).toBe('{"0":"first","1":"second"}');+ });++ it('should report indexed properties through the in operator', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);++ expect('0' in classTokenList).toBe(true);+ expect('1' in classTokenList).toBe(true);+ expect('2' in classTokenList).toBe(false);+ expect('add' in classTokenList).toBe(true);+ });++ it('should not treat keys beyond the array index range as indices', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);++ const outOfRangeKey = String(2 ** 32);++ expect(+ (classTokenList as unknown as Record<string, unknown>)[outOfRangeKey],+ ).toBeUndefined();+ expect(outOfRangeKey in classTokenList).toBe(false);+ });++ it('should reject numeric writes so enumeration stays consistent', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);++ expect(() => {+ (classTokenList as unknown as Record<number, string>)[5] = 'expando';+ }).toThrow(TypeError);++ element.setAttribute('class', 'a b c d e f');++ expect(Object.keys(classTokenList)).toEqual([+ '0',+ '1',+ '2',+ '3',+ '4',+ '5',+ ]);+ });++ it('should convert item indices the way an unsigned long conversion does', () => {+ const element = new FakeElement('first second');+ const classTokenList = createClassTokenList(element);++ expect(classTokenList.item(1.5)).toBe('second');+ expect(classTokenList.item(NaN)).toBe('first');+ expect(classTokenList.item(-1)).toBeNull();+ });+ });++ describe('branding', () => {+ it('should report itself as a DOMTokenList', () => {+ const classTokenList = createClassTokenList(new FakeElement());++ expect(Object.prototype.toString.call(classTokenList)).toBe(+ '[object DOMTokenList]',+ );+ });+ });++ describe.each(TOKEN_MUTATORS)(+ '%s token validation',+ (_methodName, callWithToken) => {+ it.each([+ ['', 'SyntaxError'],+ ['two tokens', 'InvalidCharacterError'],+ ])('should throw for %p', (invalidToken, exceptionName) => {+ const classTokenList = createClassTokenList(new FakeElement());++ expect(() => callWithToken(classTokenList, invalidToken)).toThrow(+ expect.objectContaining({ name: exceptionName }),+ );+ });+ },+ );+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installClassAttributeAccessors.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installClassAttributeAccessors.test.tsnew file mode 100644index 00000000000..20672e2bb65--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installClassAttributeAccessors.test.ts@@ -0,0 +1,218 @@+import { HOOKS, Window } from '@remote-dom/polyfill';++import { type WorkerMutationRecord } from '@/polyfills/dom/types/WorkerMutationRecord';+import { type createMutationObserverClass } from '@/polyfills/dom/utils/createMutationObserverClass';+import { installClassAttributeAccessors } from '@/polyfills/dom/utils/installClassAttributeAccessors';+import { installMutationObserver } from '@/polyfills/dom/utils/installMutationObserver';++const createSandboxDocument = (polyfillWindow = new Window()): Document => {+ installClassAttributeAccessors({+ elementPrototype: polyfillWindow.Element.prototype,+ remoteElementPrototypes: [],+ });++ return polyfillWindow.document as unknown as Document;+};++describe('installClassAttributeAccessors', () => {+ describe('className', () => {+ it('should read the class attribute back through the className property', () => {+ const document = createSandboxDocument();++ const element = document.createElement('div');+ element.setAttribute('class', 'from-attribute');++ expect(element.className).toBe('from-attribute');+ });++ it('should return an empty string for an element without a class attribute', () => {+ const document = createSandboxDocument();++ expect(document.createElement('div').className).toBe('');+ });++ it('should write the class attribute when the className property is assigned', () => {+ const document = createSandboxDocument();++ const element = document.createElement('div');+ element.className = 'from-property';++ expect(element.getAttribute('class')).toBe('from-property');+ });++ it('should clear the class attribute when className is assigned null', () => {+ const document = createSandboxDocument();++ const element = document.createElement('div');+ element.className = 'present';++ (element as { className: unknown }).className = null;++ expect(element.hasAttribute('class')).toBe(false);+ expect(element.className).toBe('');+ });++ it('should stringify non string assignments like the DOM does', () => {+ const document = createSandboxDocument();++ const element = document.createElement('div');+ (element as { className: unknown }).className = 42;++ expect(element.getAttribute('class')).toBe('42');+ });++ it('should refuse a read on the prototype itself', () => {+ const polyfillWindow = new Window();+ createSandboxDocument(polyfillWindow);++ expect(+ () =>+ (+ polyfillWindow.Element.prototype as unknown as {+ className: unknown;+ }+ ).className,+ ).toThrow(TypeError);+ });+ });++ describe('classList', () => {+ it('should expose classList on every element sharing the prototype', () => {+ const document = createSandboxDocument();++ const element = document.createElement('div');++ expect(typeof element.classList.add).toBe('function');+ expect(typeof document.body.classList.add).toBe('function');+ expect(typeof document.documentElement.classList.add).toBe('function');+ });++ it('should refuse a read on the prototype itself', () => {+ const polyfillWindow = new Window();+ createSandboxDocument(polyfillWindow);++ expect(+ () =>+ (+ polyfillWindow.Element.prototype as unknown as {+ classList: unknown;+ }+ ).classList,+ ).toThrow(TypeError);+ });++ it('should return the same facade on every access', () => {+ const document = createSandboxDocument();++ const element = document.createElement('div');++ expect(element.classList).toBe(element.classList);+ });++ it('should give every element its own facade', () => {+ const document = createSandboxDocument();++ const firstElement = document.createElement('div');+ const secondElement = document.createElement('div');++ expect(firstElement.classList).not.toBe(secondElement.classList);++ firstElement.classList.add('only-on-first');++ expect(secondElement.classList.contains('only-on-first')).toBe(false);+ });++ it('should round trip with the class attribute in both directions', () => {+ const document = createSandboxDocument();++ const element = document.createElement('div');+ element.setAttribute('class', 'from-attribute');++ expect(element.classList.contains('from-attribute')).toBe(true);++ element.classList.add('from-class-list');++ expect(element.getAttribute('class')).toBe(+ 'from-attribute from-class-list',+ );+ });++ it('should assign the class attribute when classList itself is assigned', () => {+ const document = createSandboxDocument();++ const element = document.createElement('div');+ (element as { classList: unknown }).classList = 'first second';++ expect(element.getAttribute('class')).toBe('first second');+ });++ it('should run a classList write through the same attribute hook as setAttribute', () => {+ const polyfillWindow = new Window();+ const setAttributeArguments: unknown[][] = [];+ polyfillWindow[HOOKS].setAttribute = (...args) =>+ setAttributeArguments.push(args);++ const document = createSandboxDocument(polyfillWindow);++ const classListElement = document.createElement('div');+ document.body.appendChild(classListElement);+ classListElement.classList.add('added-through-class-list');++ const setAttributeElement = document.createElement('div');+ document.body.appendChild(setAttributeElement);+ setAttributeElement.setAttribute('class', 'added-through-set-attribute');++ expect(setAttributeArguments).toEqual([+ [classListElement, 'class', 'added-through-class-list', null],+ [setAttributeElement, 'class', 'added-through-set-attribute', null],+ ]);+ });++ it('should emit a MutationObserver attributes record for a classList write on a base element', async () => {+ const polyfillWindow = new Window();+ const globalScope: Record<string, unknown> = { window: polyfillWindow };++ installMutationObserver({ globalScope });++ const document = createSandboxDocument(polyfillWindow);+ const MutationObserver = globalScope.MutationObserver as ReturnType<+ typeof createMutationObserverClass+ >;+ const deliveries: WorkerMutationRecord[][] = [];++ const element = document.createElement('div');+ element.setAttribute('class', 'initial');++ new MutationObserver((records) => deliveries.push(records)).observe(+ element,+ { attributes: true, attributeOldValue: true },+ );++ element.classList.add('added');++ await Promise.resolve();+ await Promise.resolve();++ expect(deliveries).toHaveLength(1);+ expect(deliveries[0]).toHaveLength(1);++ const [record] = deliveries[0];+ expect(record.type).toBe('attributes');+ expect(record.attributeName).toBe('class');+ expect(record.oldValue).toBe('initial');+ });+ });++ it('should keep className and classList in agreement in both directions', () => {+ const document = createSandboxDocument();++ const element = document.createElement('div');+ element.className = 'first';++ expect(element.classList.contains('first')).toBe(true);++ element.classList.add('second');++ expect(element.className).toBe('first second');+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installClassAttributeAccessorsOnRemoteElements.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installClassAttributeAccessorsOnRemoteElements.test.tsnew file mode 100644index 00000000000..08551efacce--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installClassAttributeAccessorsOnRemoteElements.test.ts@@ -0,0 +1,132 @@+import '@/remote/generated/remote-elements';++import { installClassAttributeAccessors } from '@/polyfills/dom/utils/installClassAttributeAccessors';+import { installGetElementsByClassName } from '@/polyfills/dom/utils/installGetElementsByClassName';+import { patchRemoteElementAttributes } from '@/remote/elements/utils/patchRemoteElementAttributes';+import { resolveRemoteElementPrototypes } from '@/remote/elements/utils/resolveRemoteElementPrototypes';++const createHtmlDivElement = (): HTMLElement =>+ document.createElement('html-div');++describe('installClassAttributeAccessors on remote elements', () => {+ beforeAll(() => {+ patchRemoteElementAttributes();+ installClassAttributeAccessors({+ elementPrototype: Element.prototype,+ remoteElementPrototypes: resolveRemoteElementPrototypes(),+ });+ installGetElementsByClassName(Element.prototype);+ });++ it('should read classes assigned to the className remote property', () => {+ const element = createHtmlDivElement();++ element.className = 'from-react second';++ expect(element.classList.contains('from-react')).toBe(true);+ expect(element.classList.length).toBe(2);+ expect(element.classList.value).toBe('from-react second');+ });++ it('should preserve the react authored classes when adding through classList', () => {+ const element = createHtmlDivElement();++ element.className = 'from-react';+ element.classList.add('mapboxgl-map');++ expect(element.className).toBe('from-react mapboxgl-map');+ });++ it('should round trip consecutive classList writes through the remote property', () => {+ const element = createHtmlDivElement();++ element.classList.add('first');+ element.classList.add('second');+ element.classList.remove('first');++ expect(element.className).toBe('second');+ });++ it('should read an empty className on a fresh element while the attribute stays absent', () => {+ const element = createHtmlDivElement();++ expect(element.className).toBe('');+ expect(element.getAttribute('class')).toBeNull();+ expect(element.hasAttribute('class')).toBe(false);+ });++ it('should append through className without an undefined token', () => {+ const element = createHtmlDivElement();++ element.className += ' x';++ expect(element.className).toBe(' x');+ expect(element.classList.contains('x')).toBe(true);+ expect(element.classList.contains('undefined')).toBe(false);+ });++ it('should clear the class attribute when className is assigned null', () => {+ const element = createHtmlDivElement();+ element.className = 'present';++ (element as { className: unknown }).className = null;++ expect(element.hasAttribute('class')).toBe(false);+ expect(element.className).toBe('');+ });++ it('should forward class writes to the host as the className property', () => {+ const element = createHtmlDivElement();+ const updateRemoteProperty = jest.spyOn(+ element as unknown as {+ updateRemoteProperty: (propertyName: string, value?: unknown) => void;+ },+ 'updateRemoteProperty',+ );++ element.classList.add('first');+ element.removeAttribute('class');++ expect(updateRemoteProperty.mock.calls).toEqual([+ ['className', 'first'],+ ['className', undefined],+ ]);+ });++ it('should produce a mutation record for a classList write', async () => {+ const element = createHtmlDivElement();+ element.className = 'initial';++ const deliveries: MutationRecord[][] = [];+ const observer = new MutationObserver((records) =>+ deliveries.push(records),+ );+ observer.observe(element, { attributes: true, attributeFilter: ['class'] });++ element.classList.add('added');++ await Promise.resolve();+ await Promise.resolve();++ expect(element.className).toBe('initial added');+ expect(deliveries).toHaveLength(1);+ expect(deliveries[0][0].attributeName).toBe('class');++ observer.disconnect();+ });++ it('should let getElementsByClassName match a remote element classed by react', () => {+ const rootElement = createHtmlDivElement();+ const target = createHtmlDivElement();++ target.className = 'recharts-layer recharts-line';+ rootElement.appendChild(target);++ const matches = rootElement.getElementsByClassName(+ 'recharts-layer recharts-line',+ );++ expect(matches).toHaveLength(1);+ expect(matches[0]).toBe(target);+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installGetElementsByClassName.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installGetElementsByClassName.test.tsindex abc2e759879..b7c0e17ed78 100644--- a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installGetElementsByClassName.test.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installGetElementsByClassName.test.ts@@ -1,8 +1,9 @@+import { installClassAttributeAccessors } from '../installClassAttributeAccessors';import { installGetElementsByClassName } from '../installGetElementsByClassName';class FakeElement {childNodes: FakeElement[] = [];- className?: string;+ declare className: string;private attributes = new Map<string, string>();constructor(classAttribute?: string) {@@ -15,11 +16,19 @@ class FakeElement {return this.attributes.get(attributeName) ?? null;}+ setAttribute(attributeName: string, attributeValue: string): void {+ this.attributes.set(attributeName, attributeValue);+ }+append(...children: FakeElement[]): void {this.childNodes.push(...children);}}+installClassAttributeAccessors({+ elementPrototype: FakeElement.prototype,+ remoteElementPrototypes: [],+});installGetElementsByClassName(FakeElement.prototype);type ClassNameQueryResult = FakeElement[] & {@@ -50,7 +59,7 @@ describe('installGetElementsByClassName', () => {expect(matches[0]).toBe(target);});- it('should match an element whose classes are reflected via the className property', () => {+ it('should match an element classed through the reflected className property', () => {const rootElement = new FakeElement();const target = new FakeElement();target.className = 'recharts-layer recharts-line';diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createClassTokenList.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createClassTokenList.tsnew file mode 100644index 00000000000..a7ec33521ff--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createClassTokenList.ts@@ -0,0 +1,159 @@+import { isDefined } from 'twenty-shared/utils';++import { type ElementWithAttributes } from '@/polyfills/dom/types/ElementWithAttributes';+import { type WorkerClassTokenList } from '@/polyfills/dom/types/WorkerClassTokenList';+import { createIndexedClassTokenList } from '@/polyfills/dom/utils/createIndexedClassTokenList';+import { normalizeItemIndex } from '@/polyfills/dom/utils/normalizeItemIndex';+import { parseClassTokenList } from '@/polyfills/dom/utils/parseClassTokenList';+import { serializeClassTokenList } from '@/polyfills/dom/utils/serializeClassTokenList';+import { toValidClassTokenOrThrow } from '@/polyfills/dom/utils/toValidClassTokenOrThrow';++class ClassTokenList implements WorkerClassTokenList {+ readonly [index: number]: string;++ private readonly element!: ElementWithAttributes;++ constructor(element: ElementWithAttributes) {+ Object.defineProperty(this, 'element', {+ value: element,+ enumerable: false,+ });+ }++ private readCurrentTokens(): string[] {+ return parseClassTokenList(this.element.getAttribute('class') ?? '');+ }++ private writeTokens(tokens: string[]): void {+ if (tokens.length === 0 && !isDefined(this.element.getAttribute('class'))) {+ return;+ }++ this.element.setAttribute('class', serializeClassTokenList(tokens));+ }++ get length(): number {+ return this.readCurrentTokens().length;+ }++ get value(): string {+ return this.element.getAttribute('class') ?? '';+ }++ set value(newValue: string) {+ this.element.setAttribute('class', String(newValue));+ }++ add(...tokens: string[]): void {+ const tokensToAdd = tokens.map(toValidClassTokenOrThrow);++ this.writeTokens([...this.readCurrentTokens(), ...tokensToAdd]);+ }++ remove(...tokens: string[]): void {+ const tokensToRemove = tokens.map(toValidClassTokenOrThrow);++ this.writeTokens(+ this.readCurrentTokens().filter(+ (currentToken) => !tokensToRemove.includes(currentToken),+ ),+ );+ }++ toggle(token: string, force?: boolean): boolean {+ const tokenToToggle = toValidClassTokenOrThrow(token);++ const currentTokens = this.readCurrentTokens();+ const isPresent = currentTokens.includes(tokenToToggle);+ const shouldBePresent = force === undefined ? !isPresent : Boolean(force);++ if (shouldBePresent === isPresent) {+ return shouldBePresent;+ }++ this.writeTokens(+ shouldBePresent+ ? [...currentTokens, tokenToToggle]+ : currentTokens.filter(+ (currentToken) => currentToken !== tokenToToggle,+ ),+ );++ return shouldBePresent;+ }++ replace(oldToken: string, newToken: string): boolean {+ const oldTokenToReplace = toValidClassTokenOrThrow(oldToken);+ const newTokenToInsert = toValidClassTokenOrThrow(newToken);++ const currentTokens = this.readCurrentTokens();++ if (!currentTokens.includes(oldTokenToReplace)) {+ return false;+ }++ this.writeTokens(+ currentTokens.map((currentToken) =>+ currentToken === oldTokenToReplace ? newTokenToInsert : currentToken,+ ),+ );++ return true;+ }++ contains(token: string): boolean {+ return this.readCurrentTokens().includes(String(token));+ }++ item(index: number): string | null {+ return this.readCurrentTokens()[normalizeItemIndex(index)] ?? null;+ }++ supports(): boolean {+ throw new TypeError(+ "Failed to execute 'supports': the class attribute has no supported tokens.",+ );+ }++ forEach(+ callback: (+ token: string,+ tokenIndex: number,+ tokenList: WorkerClassTokenList,+ ) => void,+ thisArgument?: unknown,+ ): void {+ Array.prototype.forEach.call(this, (token: string, tokenIndex: number) => {+ callback.call(thisArgument, token, tokenIndex, this);+ });+ }++ entries(): IterableIterator<[number, string]> {+ return Array.prototype.entries.call(this);+ }++ keys(): IterableIterator<number> {+ return Array.prototype.keys.call(this);+ }++ values(): IterableIterator<string> {+ return Array.prototype.values.call(this);+ }++ toString(): string {+ return this.value;+ }++ get [Symbol.toStringTag](): string {+ return 'DOMTokenList';+ }++ [Symbol.iterator](): IterableIterator<string> {+ return this.values();+ }+}++export const createClassTokenList = (+ element: ElementWithAttributes,+): WorkerClassTokenList =>+ createIndexedClassTokenList(new ClassTokenList(element));diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createIndexedClassTokenList.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createIndexedClassTokenList.tsnew file mode 100644index 00000000000..c731c9d8c77--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createIndexedClassTokenList.ts@@ -0,0 +1,72 @@+import { isNonNegativeInteger, isString } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++import { type WorkerClassTokenList } from '@/polyfills/dom/types/WorkerClassTokenList';++const MAX_ARRAY_INDEX = 2 ** 32 - 2;++const parseIndexPropertyKey = (property: string | symbol): number | null => {+ if (!isString(property)) {+ return null;+ }++ const tokenIndex = Number(property);++ const isCanonicalIndexKey =+ isNonNegativeInteger(tokenIndex) &&+ tokenIndex <= MAX_ARRAY_INDEX &&+ String(tokenIndex) === property;++ return isCanonicalIndexKey ? tokenIndex : null;+};++const INDEXED_CLASS_TOKEN_LIST_PROXY_HANDLER: ProxyHandler<WorkerClassTokenList> =+ {+ get: (tokenList, property, receiver) => {+ const tokenIndex = parseIndexPropertyKey(property);++ return isDefined(tokenIndex)+ ? (tokenList.item(tokenIndex) ?? undefined)+ : Reflect.get(tokenList, property, receiver);+ },+ has: (tokenList, property) => {+ const tokenIndex = parseIndexPropertyKey(property);++ return isDefined(tokenIndex)+ ? tokenList.item(tokenIndex) !== null+ : Reflect.has(tokenList, property);+ },+ getOwnPropertyDescriptor: (tokenList, property) => {+ const tokenIndex = parseIndexPropertyKey(property);++ if (!isDefined(tokenIndex)) {+ return Reflect.getOwnPropertyDescriptor(tokenList, property);+ }++ const token = tokenList.item(tokenIndex);++ if (token === null) {+ return undefined;+ }++ return {+ value: token,+ writable: false,+ enumerable: true,+ configurable: true,+ };+ },+ defineProperty: (tokenList, property, descriptor) =>+ isDefined(parseIndexPropertyKey(property))+ ? false+ : Reflect.defineProperty(tokenList, property, descriptor),+ ownKeys: (tokenList) => [+ ...Array.from(tokenList.keys(), String),+ ...Reflect.ownKeys(tokenList),+ ],+ };++export const createIndexedClassTokenList = (+ classTokenList: WorkerClassTokenList,+): WorkerClassTokenList =>+ new Proxy(classTokenList, INDEXED_CLASS_TOKEN_LIST_PROXY_HANDLER);diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installClassAttributeAccessors.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installClassAttributeAccessors.tsnew file mode 100644index 00000000000..18b7c43b21b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installClassAttributeAccessors.ts@@ -0,0 +1,80 @@+import { isDefined } from 'twenty-shared/utils';++import { type ElementWithAttributes } from '@/polyfills/dom/types/ElementWithAttributes';+import { type WorkerClassTokenList } from '@/polyfills/dom/types/WorkerClassTokenList';+import { createClassTokenList } from '@/polyfills/dom/utils/createClassTokenList';++type InstallClassAttributeAccessorsInput = {+ elementPrototype: object;+ remoteElementPrototypes: object[];+};++export const installClassAttributeAccessors = ({+ elementPrototype,+ remoteElementPrototypes,+}: InstallClassAttributeAccessorsInput): void => {+ const classTokenListByElement = new WeakMap<+ ElementWithAttributes,+ WorkerClassTokenList+ >();++ const resolveClassTokenList = (+ element: ElementWithAttributes,+ ): WorkerClassTokenList => {+ const existingClassTokenList = classTokenListByElement.get(element);++ if (isDefined(existingClassTokenList)) {+ return existingClassTokenList;+ }++ const createdClassTokenList = createClassTokenList(element);+ classTokenListByElement.set(element, createdClassTokenList);++ return createdClassTokenList;+ };++ const readClassName = (element: ElementWithAttributes): string =>+ element.getAttribute('class') ?? '';++ const defineClassAttributeAccessor = (+ prototype: object,+ propertyName: 'className' | 'classList',+ read: (element: ElementWithAttributes) => unknown,+ ): void => {+ const throwOnPrototypeAccess = (accessedObject: unknown): void => {+ if (accessedObject === prototype) {+ throw new TypeError('Illegal invocation');+ }+ };++ Object.defineProperty(prototype, propertyName, {+ get(this: ElementWithAttributes) {+ throwOnPrototypeAccess(this);++ return read(this);+ },+ set(this: ElementWithAttributes, newValue: unknown) {+ throwOnPrototypeAccess(this);++ if (!isDefined(newValue)) {+ this.removeAttribute('class');++ return;+ }++ this.setAttribute('class', String(newValue));+ },+ configurable: true,+ });+ };++ defineClassAttributeAccessor(+ elementPrototype,+ 'classList',+ resolveClassTokenList,+ );++ for (const prototype of [elementPrototype, ...remoteElementPrototypes]) {+ defineClassAttributeAccessor(prototype, 'className', readClassName);+ }+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installGetElementsByClassName.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installGetElementsByClassName.tsindex 806ff42f848..e72aac53a99 100644--- a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installGetElementsByClassName.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installGetElementsByClassName.ts@@ -1,34 +1,14 @@-import { isFunction, isNonEmptyString } from '@sniptt/guards';-import { type ElementLike } from '@/polyfills/dom/types/ElementLike';import { iterateElementSubtree } from '@/polyfills/dom/utils/iterateElementSubtree';--const resolveClassNameValue = (element: ElementLike): string | null => {- if (isFunction(element.getAttribute)) {- const classAttribute = element.getAttribute('class');-- if (isNonEmptyString(classAttribute)) {- return classAttribute;- }- }-- const reflectedClassName = (element as ElementLike & { className?: unknown })- .className;-- return isNonEmptyString(reflectedClassName) ? reflectedClassName : null;-};+import { parseClassTokenList } from '@/polyfills/dom/utils/parseClassTokenList';const hasEveryClassNameToken = (element: ElementLike,classNameTokens: string[],): boolean => {- const classNameValue = resolveClassNameValue(element);-- if (!isNonEmptyString(classNameValue)) {- return false;- }-- const elementTokens = classNameValue.split(/\s+/);+ const elementTokens = parseClassTokenList(+ element.getAttribute?.('class') ?? '',+ );return classNameTokens.every((classNameToken) =>elementTokens.includes(classNameToken),@@ -38,9 +18,7 @@ const hasEveryClassNameToken = (export const installGetElementsByClassName = (installTarget: object): void => {Object.defineProperty(installTarget, 'getElementsByClassName', {value: function (this: ElementLike, classNames: string) {- const classNameTokens = String(classNames)- .split(/\s+/)- .filter(isNonEmptyString);+ const classNameTokens = parseClassTokenList(String(classNames));const matches: ElementLike[] = [];diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/normalizeItemIndex.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/normalizeItemIndex.tsnew file mode 100644index 00000000000..f677d0b46eb--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/normalizeItemIndex.ts@@ -0,0 +1 @@+export const normalizeItemIndex = (index: number): number => index >>> 0;diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/parseClassTokenList.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/parseClassTokenList.tsnew file mode 100644index 00000000000..504815e0c9e--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/parseClassTokenList.ts@@ -0,0 +1,9 @@+import { isNonEmptyString } from '@sniptt/guards';++import { ASCII_WHITESPACE_REGEX } from '@/polyfills/dom/constants/AsciiWhitespaceRegex';++export const parseClassTokenList = (classAttributeValue: string): string[] => [+ ...new Set(+ classAttributeValue.split(ASCII_WHITESPACE_REGEX).filter(isNonEmptyString),+ ),+];diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/serializeClassTokenList.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/serializeClassTokenList.tsnew file mode 100644index 00000000000..958891b9832--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/serializeClassTokenList.ts@@ -0,0 +1,2 @@+export const serializeClassTokenList = (tokens: string[]): string =>+ [...new Set(tokens)].join(' ');diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/toValidClassTokenOrThrow.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/toValidClassTokenOrThrow.tsnew file mode 100644index 00000000000..962071bb5a8--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/toValidClassTokenOrThrow.ts@@ -0,0 +1,24 @@+import { isNonEmptyString } from '@sniptt/guards';++import { ASCII_WHITESPACE_REGEX } from '@/polyfills/dom/constants/AsciiWhitespaceRegex';+import { createDomException } from '@/polyfills/utils/createDomException';++export const toValidClassTokenOrThrow = (token: unknown): string => {+ const tokenAsString = String(token);++ if (!isNonEmptyString(tokenAsString)) {+ throw createDomException(+ 'The token provided must not be empty.',+ 'SyntaxError',+ );+ }++ if (ASCII_WHITESPACE_REGEX.test(tokenAsString)) {+ throw createDomException(+ `The token provided ('${tokenAsString}') contains HTML space characters, which are not valid in tokens.`,+ 'InvalidCharacterError',+ );+ }++ return tokenAsString;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaRecorderClass.ts b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaRecorderClass.tsindex 19677140bea..ad2a9dbff24 100644--- a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaRecorderClass.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaRecorderClass.ts@@ -1,7 +1,7 @@import { isDefined } from 'twenty-shared/utils';import { type WorkerMediaBridge } from '@/polyfills/media/types/WorkerMediaBridge';-import { createDomException } from '@/polyfills/media/utils/createDomException';+import { createDomException } from '@/polyfills/utils/createDomException';import { type WorkerMediaStreamInstance } from '@/polyfills/media/utils/createMediaStreamClass';export type WorkerMediaRecorderState = 'inactive' | 'recording' | 'paused';diff --git a/packages/twenty-front-component-renderer/src/polyfills/media/utils/installMediaCapturePolyfills.ts b/packages/twenty-front-component-renderer/src/polyfills/media/utils/installMediaCapturePolyfills.tsindex 3fe77b8da69..5a034178200 100644--- a/packages/twenty-front-component-renderer/src/polyfills/media/utils/installMediaCapturePolyfills.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/media/utils/installMediaCapturePolyfills.ts@@ -1,7 +1,7 @@import { isDefined } from 'twenty-shared/utils';import { type WorkerMediaBridge } from '@/polyfills/media/types/WorkerMediaBridge';-import { createDomException } from '@/polyfills/media/utils/createDomException';+import { createDomException } from '@/polyfills/utils/createDomException';import { createMediaRecorderClass } from '@/polyfills/media/utils/createMediaRecorderClass';import {createMediaStreamClass,diff --git a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createDomException.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/createDomException.tssimilarity index 65%rename from packages/twenty-front-component-renderer/src/polyfills/media/utils/createDomException.tsrename to packages/twenty-front-component-renderer/src/polyfills/utils/createDomException.tsindex 44be5ddcf27..522669f000a 100644--- a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createDomException.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/createDomException.ts@@ -1,5 +1,3 @@-// Media polyfill failures mirror native error shapes so application code can-// branch on error.name the way it would against the real APIs.export const createDomException = (message: string, name: string): Error => {if (typeof DOMException === 'function') {return new DOMException(message, name);diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/patchRemoteElementAttributes.test.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/patchRemoteElementAttributes.test.tsindex 433d9791096..c9f54ec5ac6 100644--- a/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/patchRemoteElementAttributes.test.ts+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/patchRemoteElementAttributes.test.ts@@ -1,5 +1,8 @@import '@/remote/generated/remote-elements';+import { installClassAttributeAccessors } from '@/polyfills/dom/utils/installClassAttributeAccessors';+import { resolveRemoteElementPrototypes } from '@/remote/elements/utils/resolveRemoteElementPrototypes';+import { patchRemoteElementAttributes } from '../patchRemoteElementAttributes';const createHtmlDivElement = (): HTMLElement =>@@ -8,6 +11,10 @@ const createHtmlDivElement = (): HTMLElement =>describe('patchRemoteElementAttributes', () => {beforeAll(() => {patchRemoteElementAttributes();+ installClassAttributeAccessors({+ elementPrototype: Element.prototype,+ remoteElementPrototypes: resolveRemoteElementPrototypes(),+ });});describe('getAttribute on property-mapped attributes', () => {diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/patchRemoteElementAttributes.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/patchRemoteElementAttributes.tsindex 6e2c3b48dcb..f372f547576 100644--- a/packages/twenty-front-component-renderer/src/remote/elements/utils/patchRemoteElementAttributes.ts+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/patchRemoteElementAttributes.ts@@ -4,7 +4,6 @@ import { ALLOWED_HTML_ELEMENTS } from '@/constants/AllowedHtmlElements';import { isAriaOrDataAttribute } from '@/remote/elements/utils/isAriaOrDataAttribute';const PROPERTY_MAPPED_ATTRIBUTES = [- { attributeName: 'class', elementPropertyName: 'className' },{ attributeName: 'for', elementPropertyName: 'htmlFor' },{ attributeName: 'tabindex', elementPropertyName: 'tabIndex' },{ attributeName: 'srcdoc', elementPropertyName: 'srcDoc' },@@ -22,6 +21,7 @@ const ATTRIBUTE_NAME_TO_ELEMENT_PROPERTY_NAME = new Map<string, string>(type RemoteElementWithAttributeUpdater = Element &Record<string, unknown> & {updateRemoteAttribute: (attributeName: string, value?: string) => void;+ updateRemoteProperty: (propertyName: string, value?: unknown) => void;};type RemoteElementConstructor = CustomElementConstructor & {@@ -116,6 +116,10 @@ export const patchRemoteElementAttributes = (): void => {originalSetAttribute.call(this, attributeName, attributeValue);+ if (attributeName === 'class') {+ this.updateRemoteProperty('className', attributeValue);+ }+if (shouldForwardAttributeAcrossBoundary(attributeName)) {this.updateRemoteAttribute(attributeName, attributeValue);}@@ -139,6 +143,10 @@ export const patchRemoteElementAttributes = (): void => {originalRemoveAttribute.call(this, attributeName);+ if (attributeName === 'class') {+ this.updateRemoteProperty('className', undefined);+ }+if (shouldForwardAttributeAcrossBoundary(attributeName)) {this.updateRemoteAttribute(attributeName);}diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/resolveRemoteElementPrototypes.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/resolveRemoteElementPrototypes.tsnew file mode 100644index 00000000000..5596080cbdd--- /dev/null+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/resolveRemoteElementPrototypes.ts@@ -0,0 +1,8 @@+import { isDefined } from 'twenty-shared/utils';++import { ALLOWED_HTML_ELEMENTS } from '@/constants/AllowedHtmlElements';++export const resolveRemoteElementPrototypes = (): object[] =>+ ALLOWED_HTML_ELEMENTS.map(+ ({ tag }): object | undefined => customElements.get(tag)?.prototype,+ ).filter(isDefined);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 ce8fc69f691..7b79e989661 100644--- a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts+++ b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts@@ -10,6 +10,7 @@ import { isDefined } from 'twenty-shared/utils';import { frontComponentHostCommunicationApi } from '@/remote/worker/thread/states/frontComponentHostCommunicationApi';import { HTML_TAG_TO_CUSTOM_ELEMENT_TAG } from '@/constants/HtmlTagToCustomElementTag';import { installClipboardPolyfill } from '@/polyfills/clipboard/utils/installClipboardPolyfill';+import { installClassAttributeAccessors } from '@/polyfills/dom/utils/installClassAttributeAccessors';import { installDocumentGetElementById } from '@/polyfills/dom/utils/installDocumentGetElementById';import { installGetComputedStyle } from '@/polyfills/dom/utils/installGetComputedStyle';import { installGetElementsByClassName } from '@/polyfills/dom/utils/installGetElementsByClassName';@@ -27,6 +28,7 @@ import { installWindowAliasesPolyfill } from '@/polyfills/window-aliases/utils/iimport { exposeGlobals } from '@/utils/exposeGlobals';import { installStylePropertyOnRemoteElements } from '@/remote/elements/utils/installStylePropertyOnRemoteElements';import { patchRemoteElementAttributes } from '@/remote/elements/utils/patchRemoteElementAttributes';+import { resolveRemoteElementPrototypes } from '@/remote/elements/utils/resolveRemoteElementPrototypes';import { buildFrontComponentHostCommunicationApiFromThreadImports } from '@/remote/worker/thread/utils/buildFrontComponentHostCommunicationApiFromThreadImports';import { handleCommandConfirmationModalResult } from '@/remote/worker/thread/utils/handleCommandConfirmationModalResult';import { installErrorEventBridge } from '@/remote/worker/thread/utils/installErrorEventBridge';@@ -44,6 +46,10 @@ installErrorEventBridge();installDocumentGetElementById(document);installGetElementsByClassName(Element.prototype);installGetElementsByClassName(document);+installClassAttributeAccessors({+ elementPrototype: Element.prototype,+ remoteElementPrototypes: resolveRemoteElementPrototypes(),+});installLocalStyleOnBaseElements(Element.prototype);installGetComputedStyle(toGlobalScopeRecord(globalThis));