Skip to content

The open alternative to Salesforce, designed for AI.

Reflect remote element properties in getAttribute (#26517)

Raphaël Bosi02fab2140a6d
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
index 379df68a2b1..223637bfa4f 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
@@ -18,7 +18,7 @@ import {
} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
import { type TwentyUiGalleryStory as Story } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryStory';
import {
- createCheckboxTest,
+ checkboxTest,
createFieldControlsTest,
createRadioGroupPreactTest,
sliderTest,
@@ -201,10 +201,7 @@ export const ThemeTokensPreact: Story = createGalleryStory({
export const FieldControlsReact: Story = createGalleryStory({
frontComponentBundleName: 'twenty-ui-field-controls',
runtime: 'react',
- // React serializes boolean ARIA as empty strings and loses Textarea's
- // change handler.
play: createFieldControlsTest({
- expectedAriaInvalid: '',
expectedReportedValues: /^Email: alice; Notes:$/,
}),
});
@@ -212,7 +209,6 @@ export const FieldControlsPreact: Story = createGalleryStory({
frontComponentBundleName: 'twenty-ui-field-controls',
runtime: 'preact',
play: createFieldControlsTest({
- expectedAriaInvalid: 'true',
expectedReportedValues: 'Email: alice; Notes: Follow up',
}),
});
@@ -367,12 +363,12 @@ export const SwitchPreact: Story = createGalleryStory({
export const CheckboxReact: Story = createGalleryStory({
frontComponentBundleName: 'twenty-ui-checkbox',
runtime: 'react',
- play: createCheckboxTest({ expectedAriaTrue: '' }),
+ play: checkboxTest,
});
export const CheckboxPreact: Story = createGalleryStory({
frontComponentBundleName: 'twenty-ui-checkbox',
runtime: 'preact',
- play: createCheckboxTest({ expectedAriaTrue: 'true' }),
+ play: checkboxTest,
});
export const SliderReact: Story = createGalleryStory({
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
index 244595181bb..1c76d368f23 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
@@ -45,7 +45,7 @@ No stories are skipped or marked as expected-to-fail by the runner.
| Component | Current limitation |
| --- | --- |
-| Field controls | Forwarded events lack the native event used for `composedPath`. React serializes boolean `aria-invalid` as an empty string; Textarea's cloned render element loses its change handler in React. The value report checks the state received by the component after typing. |
+| Field controls | Forwarded events lack the `nativeEvent` Base UI reads for `composedPath`. Textarea's cloned render element loses its change handler in React. The value report checks the state received by the component after typing. |
| Tabs | React cannot mount without `compareDocumentPosition`; Preact activation fails on the missing native event for `composedPath`. |
| RadioGroup | Ordering its radios needs `compareDocumentPosition`, which the sandbox DOM does not implement. |
| SegmentedControl | Ordering its radios needs `compareDocumentPosition`, so React cannot mount it. In the Preact input gallery it mounts and fails on first focus instead. Selecting would also need `PointerEvent` and native radio activation. |
@@ -55,12 +55,15 @@ No stories are skipped or marked as expected-to-fail by the runner.
| Tooltip | `TooltipReact` opens on hover but remains open after Escape because React drops the handlers Base UI adds through `React.cloneElement`. |
| Responsive hooks | The sandbox has no `window.matchMedia`, so `useIsMobile` and `useIsTouchDevice` return `false` whatever the host viewport or input. The fixture asserts that fallback and must assert host-derived values once a media-query bridge lands. |
-The worker DOM now provides `Element.matches`, `closest`, and `querySelector`
-backed by `css-select`, which matches the sandbox's custom element tags by
-their HTML tag names. `TooltipPreact` therefore covers hover opening and Escape
-dismissal. Pointer leave still needs the `Node.contains` fix and document-level
-`mousemove` delivery for the safe polygon, and the compound tooltip's title and
-description are not covered yet.
+The worker DOM now provides `Element.matches`, `closest`, `querySelector` backed
+by `css-select`, and property accessors for boolean ARIA attributes so React and
+Preact forward `true`/`false` instead of empty strings and remove the attribute
+when the prop is cleared. `getAttribute` and the selector engine read the remote
+properties React and Preact set, and the selector engine matches the sandbox's
+custom element tags by their HTML tag names. `TooltipPreact` therefore covers
+hover opening and Escape dismissal. Pointer leave still needs the `Node.contains`
+fix and document-level `mousemove` delivery for the safe polygon, and the
+compound tooltip's title and description are not covered yet.
Once the remaining gaps are fixed, extend the stories to verify selection,
disabled items, keyboard navigation, and overlay content, dismissal, and focus
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/componentInteractionTests.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/componentInteractionTests.ts
index 911c64e1d36..b6f1195f0b3 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/componentInteractionTests.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/componentInteractionTests.ts
@@ -11,59 +11,49 @@ import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-galler
import { expectSandboxErrors } from '@/__stories__/twenty-ui-gallery/utils/expectSandboxErrors';
type CreateFieldControlsTestOptions = {
- expectedAriaInvalid: '' | 'true';
expectedReportedValues: string | RegExp;
};
-// React serializes true boolean ARIA attributes as empty strings in the sandbox.
-type CreateCheckboxTestOptions = {
- expectedAriaTrue: '' | 'true';
-};
-
-export const createCheckboxTest =
- ({
- expectedAriaTrue,
- }: CreateCheckboxTestOptions): TwentyUiGalleryPlayFunction =>
- async ({ canvasElement }) => {
- const canvas = within(canvasElement);
- await expectFrontComponentMounted(canvas);
-
- const checkbox = canvas.getByRole('checkbox', { name: 'Select account' });
- const uncontrolled = canvas.getByRole('checkbox', {
- name: 'Uncontrolled selection',
- });
- expect(checkbox).not.toBeChecked();
- expect(uncontrolled).toHaveAttribute('aria-checked', expectedAriaTrue);
- expect(
- canvas.getByRole('checkbox', { name: 'Partial selection' }),
- ).toBePartiallyChecked();
- const disabled = canvas.getByRole('checkbox', {
- name: 'Disabled selection',
- });
- expect(disabled).toHaveAttribute('aria-disabled', expectedAriaTrue);
- await userEvent.click(disabled);
- expect(disabled).not.toBeChecked();
+export const checkboxTest: TwentyUiGalleryPlayFunction = async ({
+ canvasElement,
+}) => {
+ const canvas = within(canvasElement);
+ await expectFrontComponentMounted(canvas);
- const readOnly = canvas.getByRole('checkbox', {
- name: 'Read-only selection',
- });
- await userEvent.click(readOnly);
- expect(readOnly).toHaveAttribute('aria-checked', expectedAriaTrue);
- expect(errorHandler).not.toHaveBeenCalled();
+ const checkbox = canvas.getByRole('checkbox', { name: 'Select account' });
+ const uncontrolled = canvas.getByRole('checkbox', {
+ name: 'Uncontrolled selection',
+ });
+ expect(checkbox).not.toBeChecked();
+ expect(uncontrolled).toBeChecked();
+ expect(
+ canvas.getByRole('checkbox', { name: 'Partial selection' }),
+ ).toBePartiallyChecked();
+ const disabled = canvas.getByRole('checkbox', {
+ name: 'Disabled selection',
+ });
+ expect(disabled).toHaveAttribute('aria-disabled', 'true');
+ await userEvent.click(disabled);
+ expect(disabled).not.toBeChecked();
+
+ const readOnly = canvas.getByRole('checkbox', {
+ name: 'Read-only selection',
+ });
+ await userEvent.click(readOnly);
+ expect(readOnly).toBeChecked();
+ expect(errorHandler).not.toHaveBeenCalled();
- // Checkbox activation forwards a click through an unavailable PointerEvent.
- await userEvent.click(checkbox);
- await expectSandboxErrors({
- requiredErrors: [SANDBOX_ERROR_PATTERNS.POINTER_EVENT_CONSTRUCTOR],
- });
- expect(canvas.getByRole('status')).toHaveTextContent(
- 'Selection: unselected; Changes: 0',
- );
- };
+ await userEvent.click(checkbox);
+ await expectSandboxErrors({
+ requiredErrors: [SANDBOX_ERROR_PATTERNS.POINTER_EVENT_CONSTRUCTOR],
+ });
+ expect(canvas.getByRole('status')).toHaveTextContent(
+ 'Selection: unselected; Changes: 0',
+ );
+};
export const createFieldControlsTest =
({
- expectedAriaInvalid,
expectedReportedValues,
}: CreateFieldControlsTestOptions): TwentyUiGalleryPlayFunction =>
async ({ canvasElement }) => {
@@ -76,7 +66,7 @@ export const createFieldControlsTest =
expect(email).toHaveAccessibleDescription('Use your work email');
expect(
canvas.getByRole('textbox', { name: 'Required name' }),
- ).toHaveAttribute('aria-invalid', expectedAriaInvalid);
+ ).toHaveAttribute('aria-invalid', 'true');
expect(canvas.getByText('Name is required')).toBeVisible();
expect(canvas.getByRole('textbox', { name: 'Reference' })).toHaveValue(
'REF-42',
diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installDocumentGetElementById.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installDocumentGetElementById.test.ts
index 1c7890687af..3b755bec23b 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installDocumentGetElementById.test.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installDocumentGetElementById.test.ts
@@ -1,3 +1,7 @@
+import '@/remote/generated/remote-elements';
+
+import { patchRemoteElementAttributes } from '@/remote/elements/utils/patchRemoteElementAttributes';
+
import { installDocumentGetElementById } from '../installDocumentGetElementById';
type FakeNode = {
@@ -66,6 +70,20 @@ describe('installDocumentGetElementById', () => {
expect(documentTarget.getElementById('probe')).toBe(target);
});
+ it('should find a remote element whose id was set as a property', () => {
+ patchRemoteElementAttributes();
+
+ const documentTarget = createDocumentTarget();
+ const remoteElement = document.createElement(
+ 'html-div',
+ ) as unknown as HTMLElement;
+
+ remoteElement.id = 'set-by-react';
+ documentTarget.childNodes.push(remoteElement as unknown as FakeNode);
+
+ expect(documentTarget.getElementById('set-by-react')).toBe(remoteElement);
+ });
+
it('should not override an existing getElementById', () => {
const existingGetElementById = jest.fn();
const documentTarget = {
diff --git a/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteElements.test.ts b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteElements.test.ts
new file mode 100644
index 00000000000..f6423e09169
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/polyfills/selectors/utils/__tests__/installSelectorMethodsPolyfillOnRemoteElements.test.ts
@@ -0,0 +1,77 @@
+import '@/remote/generated/remote-elements';
+
+import { installStylePropertyOnRemoteElements } from '@/remote/elements/utils/installStylePropertyOnRemoteElements';
+import { patchRemoteElementAttributes } from '@/remote/elements/utils/patchRemoteElementAttributes';
+
+import { installSelectorMethodsPolyfill } from '../installSelectorMethodsPolyfill';
+
+type RemoteElementWithProperties = HTMLElement & Record<string, unknown>;
+
+const createRemoteElement = (tagName: string): RemoteElementWithProperties => {
+ const element = document.createElement(
+ tagName,
+ ) as RemoteElementWithProperties;
+
+ installSelectorMethodsPolyfill({
+ elementPrototype: element,
+ querySelectorTargets: [element],
+ resolveActiveElement: () => null,
+ });
+
+ return element;
+};
+
+describe('installSelectorMethodsPolyfill on remote elements', () => {
+ beforeAll(() => {
+ installStylePropertyOnRemoteElements();
+ patchRemoteElementAttributes();
+ });
+
+ it('should read declared remote properties and ignore inherited accessors', () => {
+ const button = createRemoteElement('html-button');
+
+ button.tabIndex = -1;
+ button.style.color = 'red';
+
+ expect(button.matches('[tabindex="-1"]')).toBe(true);
+ expect(button.matches('[style]')).toBe(true);
+ expect(button.matches('[slot]')).toBe(false);
+ expect(button.matches('[lang]')).toBe(false);
+ });
+
+ it('should match a role set as a property the same way getAttribute reads it', () => {
+ const input = createRemoteElement('html-input');
+
+ input.role = 'combobox';
+
+ expect(input.matches('[role="combobox"]')).toBe(true);
+ expect(input.getAttribute('role')).toBe('combobox');
+ });
+
+ it('should match boolean aria-hidden and draggable properties', () => {
+ const hiddenIcon = createRemoteElement('html-span');
+ const visibleIcon = createRemoteElement('html-span');
+ const draggableCard = createRemoteElement('html-div');
+ const fixedCard = createRemoteElement('html-div');
+
+ hiddenIcon['aria-hidden'] = true;
+ visibleIcon['aria-hidden'] = false;
+ draggableCard.draggable = true;
+ fixedCard.draggable = false;
+
+ expect(hiddenIcon.matches('[aria-hidden="true"]')).toBe(true);
+ expect(visibleIcon.matches('[aria-hidden]')).toBe(false);
+ expect(draggableCard.matches('[draggable="true"]')).toBe(true);
+ expect(fixedCard.matches('[draggable="false"]')).toBe(true);
+ });
+
+ it('should prefer the live property over a stale attribute', () => {
+ const input = createRemoteElement('html-input');
+
+ input.setAttribute('aria-label', 'First label');
+ input['aria-label'] = 'Second label';
+
+ expect(input.matches('[aria-label="Second label"]')).toBe(true);
+ expect(input.matches('[aria-label="First label"]')).toBe(false);
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/constants/AriaAttributeNamesAcceptingBooleanValues.ts b/packages/twenty-front-component-renderer/src/remote/elements/constants/AriaAttributeNamesAcceptingBooleanValues.ts
new file mode 100644
index 00000000000..c1f957893b2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/constants/AriaAttributeNamesAcceptingBooleanValues.ts
@@ -0,0 +1,19 @@
+export const ARIA_ATTRIBUTE_NAMES_ACCEPTING_BOOLEAN_VALUES = new Set([
+ 'aria-atomic',
+ 'aria-busy',
+ 'aria-checked',
+ 'aria-current',
+ 'aria-disabled',
+ 'aria-expanded',
+ 'aria-grabbed',
+ 'aria-haspopup',
+ 'aria-hidden',
+ 'aria-invalid',
+ 'aria-modal',
+ 'aria-multiline',
+ 'aria-multiselectable',
+ 'aria-pressed',
+ 'aria-readonly',
+ 'aria-required',
+ 'aria-selected',
+]);
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/constants/BooleanishAttributeNames.ts b/packages/twenty-front-component-renderer/src/remote/elements/constants/BooleanishAttributeNames.ts
new file mode 100644
index 00000000000..9b2a11ce0c3
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/constants/BooleanishAttributeNames.ts
@@ -0,0 +1 @@
+export const BOOLEANISH_ATTRIBUTE_NAMES = new Set(['draggable']);
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/installAriaBooleanPropertyAccessors.test.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/installAriaBooleanPropertyAccessors.test.ts
new file mode 100644
index 00000000000..30d7420c1a6
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/__tests__/installAriaBooleanPropertyAccessors.test.ts
@@ -0,0 +1,107 @@
+import '@/remote/generated/remote-elements';
+
+import { patchRemoteElementAttributes } from '@/remote/elements/utils/patchRemoteElementAttributes';
+
+import { installAriaBooleanPropertyAccessors } from '../installAriaBooleanPropertyAccessors';
+
+type RemoteElementWithAriaAccessors = HTMLElement &
+ Record<string, unknown> & {
+ updateRemoteAttribute: (attributeName: string, value?: string) => void;
+ };
+
+const createHtmlDivElement = (): RemoteElementWithAriaAccessors =>
+ document.createElement('html-div') as RemoteElementWithAriaAccessors;
+
+describe('installAriaBooleanPropertyAccessors', () => {
+ beforeAll(() => {
+ patchRemoteElementAttributes();
+ installAriaBooleanPropertyAccessors();
+ });
+
+ it('should expose boolean aria attributes as properties', () => {
+ const element = createHtmlDivElement();
+
+ expect('aria-invalid' in element).toBe(true);
+ expect('aria-expanded' in element).toBe(true);
+ expect('aria-describedby' in element).toBe(false);
+ });
+
+ it('should write a true property as the true attribute value and forward it', () => {
+ const element = createHtmlDivElement();
+ const updateRemoteAttribute = jest.spyOn(element, 'updateRemoteAttribute');
+
+ element['aria-invalid'] = true;
+
+ expect(element.getAttribute('aria-invalid')).toBe('true');
+ expect(element['aria-invalid']).toBe('true');
+ expect(updateRemoteAttribute).toHaveBeenCalledWith('aria-invalid', 'true');
+ });
+
+ it('should write a false property as the false attribute value', () => {
+ const element = createHtmlDivElement();
+
+ element['aria-expanded'] = false;
+
+ expect(element.getAttribute('aria-expanded')).toBe('false');
+ });
+
+ it('should keep token values such as mixed', () => {
+ const element = createHtmlDivElement();
+
+ element['aria-checked'] = 'mixed';
+
+ expect(element.getAttribute('aria-checked')).toBe('mixed');
+ });
+
+ it('should remove the attribute for a nullish property', () => {
+ const element = createHtmlDivElement();
+ element['aria-selected'] = true;
+ const updateRemoteAttribute = jest.spyOn(element, 'updateRemoteAttribute');
+
+ element['aria-selected'] = null;
+
+ expect(element.hasAttribute('aria-selected')).toBe(false);
+ expect(element['aria-selected']).toBeNull();
+ expect(updateRemoteAttribute).toHaveBeenCalledWith('aria-selected');
+ });
+
+ it('should remove the attribute for an empty string property', () => {
+ const element = createHtmlDivElement();
+ element['aria-disabled'] = true;
+ const updateRemoteAttribute = jest.spyOn(element, 'updateRemoteAttribute');
+
+ element['aria-disabled'] = '';
+
+ expect(element.hasAttribute('aria-disabled')).toBe(false);
+ expect(updateRemoteAttribute).toHaveBeenCalledWith('aria-disabled');
+ });
+
+ it('should throw when the accessor is read or written on the prototype', () => {
+ const prototype = Object.getPrototypeOf(
+ createHtmlDivElement(),
+ ) as RemoteElementWithAriaAccessors;
+
+ expect(() => prototype['aria-invalid']).toThrow('Illegal invocation');
+ expect(() => {
+ prototype['aria-invalid'] = true;
+ }).toThrow('Illegal invocation');
+ });
+
+ it('should leave an explicit empty attribute value untouched', () => {
+ const element = createHtmlDivElement();
+
+ element.setAttribute('aria-invalid', '');
+
+ expect(element.getAttribute('aria-invalid')).toBe('');
+ });
+
+ it('should leave aria attributes that remote-dom declares as properties on the property path', () => {
+ const element = createHtmlDivElement();
+ const updateRemoteAttribute = jest.spyOn(element, 'updateRemoteAttribute');
+
+ element['aria-hidden'] = true;
+
+ expect(element['aria-hidden']).toBe(true);
+ expect(updateRemoteAttribute).not.toHaveBeenCalled();
+ });
+});
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.ts
index c4b90ba912c..eefaca21390 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,6 +1,7 @@
import '@/remote/generated/remote-elements';
import { installClassAttributeAccessors } from '@/polyfills/dom/utils/installClassAttributeAccessors';
+import { installStylePropertyOnRemoteElements } from '@/remote/elements/utils/installStylePropertyOnRemoteElements';
import { resolveRemoteElementPrototypes } from '@/remote/elements/utils/resolveRemoteElementPrototypes';
import { patchRemoteElementAttributes } from '../patchRemoteElementAttributes';
@@ -22,6 +23,7 @@ const createHtmlSvgElement = (): RemoteSvgElement =>
describe('patchRemoteElementAttributes', () => {
beforeAll(() => {
+ installStylePropertyOnRemoteElements();
patchRemoteElementAttributes();
installClassAttributeAccessors({
elementPrototype: Element.prototype,
@@ -258,6 +260,168 @@ describe('patchRemoteElementAttributes', () => {
});
});
+ describe('remote properties read through attribute methods', () => {
+ it('should read a string property that React or Preact assigned directly', () => {
+ const element =
+ createHtmlDivElement() as RemoteElementWithPropertyUpdater &
+ Record<string, unknown>;
+
+ element.role = 'combobox';
+ element['aria-label'] = 'Account';
+
+ expect(element.getAttribute('role')).toBe('combobox');
+ expect(element.hasAttribute('role')).toBe(true);
+ expect(element.getAttribute('aria-label')).toBe('Account');
+ });
+
+ it('should serialize a true aria-hidden property the way the page renders it', () => {
+ const element =
+ createHtmlDivElement() as RemoteElementWithPropertyUpdater &
+ Record<string, unknown>;
+
+ element['aria-hidden'] = true;
+
+ expect(element.getAttribute('aria-hidden')).toBe('true');
+ });
+
+ it('should treat a false aria-hidden property like a missing attribute', () => {
+ const element =
+ createHtmlDivElement() as RemoteElementWithPropertyUpdater &
+ Record<string, unknown>;
+
+ element['aria-hidden'] = false;
+
+ expect(element.getAttribute('aria-hidden')).toBeNull();
+ expect(element.hasAttribute('aria-hidden')).toBe(false);
+ });
+
+ it('should read back an aria-hidden attribute written as false', () => {
+ const element = createHtmlDivElement();
+
+ element.setAttribute('aria-hidden', 'false');
+
+ expect(element.getAttribute('aria-hidden')).toBe('false');
+ expect(element.hasAttribute('aria-hidden')).toBe(true);
+ });
+
+ it('should drop a stale aria-hidden attribute once the property is false', () => {
+ const element =
+ createHtmlDivElement() as RemoteElementWithPropertyUpdater &
+ Record<string, unknown>;
+
+ element.setAttribute('aria-hidden', 'true');
+ element['aria-hidden'] = false;
+
+ expect(element.getAttribute('aria-hidden')).toBeNull();
+ expect(element.getAttributeNames()).not.toContain('aria-hidden');
+ });
+
+ it('should list properties assigned directly among the attribute names', () => {
+ const element =
+ createHtmlDivElement() as RemoteElementWithPropertyUpdater &
+ Record<string, unknown>;
+
+ element.role = 'combobox';
+ element['aria-label'] = 'Account';
+
+ expect(element.getAttributeNames()).toEqual(['role', 'aria-label']);
+ });
+
+ it('should serialize boolean draggable values as true and false', () => {
+ const draggableElement = createHtmlDivElement();
+ const fixedElement = createHtmlDivElement();
+
+ draggableElement.draggable = true;
+ fixedElement.draggable = false;
+
+ expect(draggableElement.getAttribute('draggable')).toBe('true');
+ expect(fixedElement.getAttribute('draggable')).toBe('false');
+ });
+
+ it('should serialize boolean HTML attributes as present or absent', () => {
+ const button = document.createElement(
+ 'html-button',
+ ) as RemoteElementWithPropertyUpdater & { disabled: boolean };
+
+ button.disabled = true;
+ expect(button.getAttribute('disabled')).toBe('');
+
+ button.disabled = false;
+ expect(button.hasAttribute('disabled')).toBe(false);
+ });
+
+ it('should report the live property instead of the attribute it replaced', () => {
+ const element =
+ createHtmlDivElement() as RemoteElementWithPropertyUpdater &
+ Record<string, unknown>;
+
+ element.setAttribute('aria-label', 'First label');
+ element['aria-label'] = 'Second label';
+
+ expect(element.getAttribute('aria-label')).toBe('Second label');
+ });
+
+ it('should read inline styles written through the style property', () => {
+ const element = createHtmlDivElement();
+
+ element.style.color = 'red';
+
+ expect(element.getAttribute('style')).toBe('color:red');
+ });
+
+ it('should drop a property assigned directly once its attribute is removed', () => {
+ const element = createHtmlDivElement();
+
+ element.id = 'account';
+ element.removeAttribute('id');
+
+ expect(element.getAttribute('id')).toBeNull();
+ expect(element.hasAttribute('id')).toBe(false);
+ });
+
+ it('should drop inline styles once the style attribute is removed', () => {
+ const element = createHtmlDivElement();
+
+ element.setAttribute('style', 'color: red');
+ element.removeAttribute('style');
+
+ expect(element.getAttribute('style')).toBeNull();
+ });
+
+ it('should restore an attribute value over a newer property', () => {
+ const element =
+ createHtmlDivElement() as RemoteElementWithPropertyUpdater &
+ Record<string, unknown>;
+
+ element.setAttribute('aria-label', 'First label');
+ element['aria-label'] = 'Second label';
+ element.setAttribute('aria-label', 'First label');
+
+ expect(element.getAttribute('aria-label')).toBe('First label');
+ });
+
+ it('should keep the checked attribute as the default checked state', () => {
+ const input = document.createElement(
+ 'html-input',
+ ) as RemoteElementWithPropertyUpdater & { checked: boolean };
+
+ input.setAttribute('checked', '');
+ input.checked = false;
+
+ expect(input.getAttribute('checked')).toBe('');
+ });
+
+ it('should keep the selected attribute as the default selected state', () => {
+ const option = document.createElement(
+ 'html-option',
+ ) as RemoteElementWithPropertyUpdater & { selected: boolean };
+
+ option.selected = true;
+
+ expect(option.hasAttribute('selected')).toBe(false);
+ });
+ });
+
describe('attribute names colliding with Object prototype keys', () => {
it('should store them as real attributes instead of mapping them to a property', () => {
const element = createHtmlDivElement();
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/installAriaBooleanPropertyAccessors.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/installAriaBooleanPropertyAccessors.ts
new file mode 100644
index 00000000000..aebd36743bc
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/installAriaBooleanPropertyAccessors.ts
@@ -0,0 +1,57 @@
+import { type RemoteElementConstructor as RemoteDomElementConstructor } from '@remote-dom/core/elements';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ALLOWED_HTML_ELEMENTS } from '@/constants/AllowedHtmlElements';
+import { ARIA_ATTRIBUTE_NAMES_ACCEPTING_BOOLEAN_VALUES } from '@/remote/elements/constants/AriaAttributeNamesAcceptingBooleanValues';
+
+type RemoteElementConstructor = CustomElementConstructor &
+ Partial<Pick<RemoteDomElementConstructor, 'remotePropertyDefinitions'>>;
+
+const shouldRemoveAriaAttribute = (value: unknown): boolean =>
+ !isDefined(value) || value === '';
+
+export const installAriaBooleanPropertyAccessors = (): void => {
+ for (const allowedHtmlElement of ALLOWED_HTML_ELEMENTS) {
+ const elementConstructor = customElements.get(allowedHtmlElement.tag) as
+ | RemoteElementConstructor
+ | undefined;
+
+ if (!isDefined(elementConstructor)) {
+ continue;
+ }
+
+ const { prototype } = elementConstructor;
+
+ const throwOnPrototypeAccess = (accessedObject: unknown): void => {
+ if (accessedObject === prototype) {
+ throw new TypeError('Illegal invocation');
+ }
+ };
+
+ for (const attributeName of ARIA_ATTRIBUTE_NAMES_ACCEPTING_BOOLEAN_VALUES) {
+ if (elementConstructor.remotePropertyDefinitions?.has(attributeName)) {
+ continue;
+ }
+
+ Object.defineProperty(prototype, attributeName, {
+ get(this: Element) {
+ throwOnPrototypeAccess(this);
+
+ return this.getAttribute(attributeName);
+ },
+ set(this: Element, value: unknown) {
+ throwOnPrototypeAccess(this);
+
+ if (shouldRemoveAriaAttribute(value)) {
+ this.removeAttribute(attributeName);
+
+ return;
+ }
+
+ this.setAttribute(attributeName, String(value));
+ },
+ configurable: true,
+ });
+ }
+ }
+};
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/installStylePropertyOnRemoteElements.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/installStylePropertyOnRemoteElements.ts
index c22097f9a4d..d631a0d7d68 100644
--- a/packages/twenty-front-component-renderer/src/remote/elements/utils/installStylePropertyOnRemoteElements.ts
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/installStylePropertyOnRemoteElements.ts
@@ -45,9 +45,7 @@ export const installStylePropertyOnRemoteElements = (): void => {
return resolveStyleProxy(this);
},
set(this: RemoteElementLike, value: unknown) {
- if (isString(value)) {
- resolveStyleProxy(this).cssText = value;
- }
+ resolveStyleProxy(this).cssText = isString(value) ? value : '';
},
configurable: true,
});
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/isBooleanishAttributeName.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/isBooleanishAttributeName.ts
new file mode 100644
index 00000000000..e28c1feedc2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/isBooleanishAttributeName.ts
@@ -0,0 +1,7 @@
+import { BOOLEANISH_ATTRIBUTE_NAMES } from '@/remote/elements/constants/BooleanishAttributeNames';
+
+const ARIA_ATTRIBUTE_PREFIX = 'aria-';
+
+export const isBooleanishAttributeName = (attributeName: string): boolean =>
+ attributeName.startsWith(ARIA_ATTRIBUTE_PREFIX) ||
+ BOOLEANISH_ATTRIBUTE_NAMES.has(attributeName);
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.ts
index 3237046fffa..0a6a7af8378 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
@@ -3,6 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { ALLOWED_HTML_ELEMENTS } from '@/constants/AllowedHtmlElements';
import { isAriaOrDataAttribute } from '@/remote/elements/utils/isAriaOrDataAttribute';
+import { serializeRemotePropertyAsAttributeValue } from '@/remote/elements/utils/serializeRemotePropertyAsAttributeValue';
const PROPERTY_MAPPED_ATTRIBUTES = [
{ attributeName: 'for', elementPropertyName: 'htmlFor' },
@@ -10,6 +11,19 @@ const PROPERTY_MAPPED_ATTRIBUTES = [
{ attributeName: 'srcdoc', elementPropertyName: 'srcDoc' },
];
+const PROPERTY_NAMES_WHOSE_ATTRIBUTE_HOLDS_THE_DEFAULT_STATE = [
+ 'checked',
+ 'selected',
+];
+
+const UNREFLECTED_REMOTE_PROPERTY_NAMES = new Set([
+ 'className',
+ ...PROPERTY_MAPPED_ATTRIBUTES.map(
+ ({ elementPropertyName }) => elementPropertyName,
+ ),
+ ...PROPERTY_NAMES_WHOSE_ATTRIBUTE_HOLDS_THE_DEFAULT_STATE,
+]);
+
const ATTRIBUTE_NAME_TO_ELEMENT_PROPERTY_NAME = new Map<string, string>(
PROPERTY_MAPPED_ATTRIBUTES.flatMap(
({ attributeName, elementPropertyName }): [string, string][] => [
@@ -21,6 +35,11 @@ const ATTRIBUTE_NAME_TO_ELEMENT_PROPERTY_NAME = new Map<string, string>(
type RemoteElementWithAttributeUpdater = Element &
Record<string, unknown> & {
+ attributeChangedCallback: (
+ attributeName: string,
+ oldValue: string | null,
+ newValue: string | null,
+ ) => void;
updateRemoteAttribute: (attributeName: string, value?: string) => void;
updateRemoteProperty: (propertyName: string, value?: unknown) => void;
};
@@ -31,6 +50,44 @@ type RemoteElementConstructor = CustomElementConstructor &
prototype: RemoteElementWithAttributeUpdater;
};
+type RemotePropertyDefinition = {
+ name: string;
+ type?: unknown;
+ attribute?: string;
+};
+
+const readRemotePropertyAsAttributeValue = ({
+ element,
+ attributeName,
+ remotePropertyDefinition,
+ readAttributeValueWrittenBySetAttribute,
+}: {
+ element: RemoteElementWithAttributeUpdater;
+ attributeName: string;
+ remotePropertyDefinition: RemotePropertyDefinition;
+ readAttributeValueWrittenBySetAttribute: (
+ attributeName: string,
+ ) => string | null;
+}): string | null => {
+ const propertyValue = element[remotePropertyDefinition.name];
+ const serializedValue = serializeRemotePropertyAsAttributeValue({
+ attributeName,
+ propertyValue,
+ hasRemoteDomFalseDefault: remotePropertyDefinition.type === Boolean,
+ });
+ const isFalseSerializedAsAbsent =
+ propertyValue === false && !isDefined(serializedValue);
+
+ if (!isFalseSerializedAsAbsent) {
+ return serializedValue;
+ }
+
+ const isFalseWrittenBySetAttribute =
+ readAttributeValueWrittenBySetAttribute(attributeName) === 'false';
+
+ return isFalseWrittenBySetAttribute ? 'false' : null;
+};
+
export const patchRemoteElementAttributes = (): void => {
for (const allowedHtmlElement of ALLOWED_HTML_ELEMENTS) {
const elementConstructor = customElements.get(allowedHtmlElement.tag) as
@@ -70,6 +127,40 @@ export const patchRemoteElementAttributes = (): void => {
: attributeName;
};
+ const remotePropertyDefinitionByAttributeName = new Map<
+ string,
+ RemotePropertyDefinition
+ >();
+
+ for (const remotePropertyDefinition of elementConstructor.remotePropertyDefinitions?.values() ??
+ []) {
+ if (
+ isDefined(remotePropertyDefinition.attribute) &&
+ !UNREFLECTED_REMOTE_PROPERTY_NAMES.has(remotePropertyDefinition.name)
+ ) {
+ remotePropertyDefinitionByAttributeName.set(
+ remotePropertyDefinition.attribute,
+ remotePropertyDefinition,
+ );
+ }
+ }
+
+ const overwriteReflectedRemotePropertyWithAttributeValue = ({
+ element,
+ attributeName,
+ attributeValue,
+ }: {
+ element: RemoteElementWithAttributeUpdater;
+ attributeName: string;
+ attributeValue: string | null;
+ }): void => {
+ if (!remotePropertyDefinitionByAttributeName.has(attributeName)) {
+ return;
+ }
+
+ element.attributeChangedCallback(attributeName, null, attributeValue);
+ };
+
const originalGetAttribute = elementConstructor.prototype.getAttribute;
elementConstructor.prototype.getAttribute = function (
@@ -88,6 +179,19 @@ export const patchRemoteElementAttributes = (): void => {
: null;
}
+ const remotePropertyDefinition =
+ remotePropertyDefinitionByAttributeName.get(attributeName);
+
+ if (isDefined(remotePropertyDefinition)) {
+ return readRemotePropertyAsAttributeValue({
+ element: this,
+ attributeName,
+ remotePropertyDefinition,
+ readAttributeValueWrittenBySetAttribute: (writtenAttributeName) =>
+ originalGetAttribute.call(this, writtenAttributeName),
+ });
+ }
+
return originalGetAttribute.call(this, attributeName);
};
@@ -105,6 +209,13 @@ export const patchRemoteElementAttributes = (): void => {
return isDefined(this[mappedElementPropertyName]);
}
+ const remotePropertyDefinition =
+ remotePropertyDefinitionByAttributeName.get(attributeName);
+
+ if (isDefined(remotePropertyDefinition)) {
+ return isDefined(this.getAttribute(attributeName));
+ }
+
return originalHasAttribute.call(this, attributeName);
};
@@ -114,11 +225,31 @@ export const patchRemoteElementAttributes = (): void => {
elementConstructor.prototype.getAttributeNames = function (
this: RemoteElementWithAttributeUpdater,
) {
+ const isReflectedAttributePresent = (attributeName: string): boolean =>
+ isDefined(this.getAttribute(attributeName));
+ const storedAttributeNames = originalGetAttributeNames
+ .call(this)
+ .filter(
+ (attributeName: string) =>
+ !remotePropertyDefinitionByAttributeName.has(attributeName) ||
+ isReflectedAttributePresent(attributeName),
+ );
+ const reflectedAttributeNames = [
+ ...remotePropertyDefinitionByAttributeName.keys(),
+ ].filter(
+ (attributeName) =>
+ !storedAttributeNames.includes(attributeName) &&
+ isReflectedAttributePresent(attributeName),
+ );
const mappedAttributeNames = PROPERTY_MAPPED_ATTRIBUTES.filter(
({ elementPropertyName }) => isDefined(this[elementPropertyName]),
).map(({ attributeName }) => attributeName);
- return [...originalGetAttributeNames.call(this), ...mappedAttributeNames];
+ return [
+ ...storedAttributeNames,
+ ...reflectedAttributeNames,
+ ...mappedAttributeNames,
+ ];
};
const originalSetAttribute = elementConstructor.prototype.setAttribute;
@@ -139,6 +270,11 @@ export const patchRemoteElementAttributes = (): void => {
}
originalSetAttribute.call(this, attributeName, attributeValue);
+ overwriteReflectedRemotePropertyWithAttributeValue({
+ element: this,
+ attributeName,
+ attributeValue,
+ });
if (attributeName === 'class') {
this.updateRemoteProperty('className', attributeValue);
@@ -167,6 +303,11 @@ export const patchRemoteElementAttributes = (): void => {
}
originalRemoveAttribute.call(this, attributeName);
+ overwriteReflectedRemotePropertyWithAttributeValue({
+ element: this,
+ attributeName,
+ attributeValue: null,
+ });
if (attributeName === 'class') {
this.updateRemoteProperty('className', undefined);
diff --git a/packages/twenty-front-component-renderer/src/remote/elements/utils/serializeRemotePropertyAsAttributeValue.ts b/packages/twenty-front-component-renderer/src/remote/elements/utils/serializeRemotePropertyAsAttributeValue.ts
new file mode 100644
index 00000000000..737f6758ee2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/remote/elements/utils/serializeRemotePropertyAsAttributeValue.ts
@@ -0,0 +1,69 @@
+import {
+ isBoolean,
+ isNonEmptyString,
+ isNumber,
+ isObject,
+ isString,
+} from '@sniptt/guards';
+
+import { isBooleanishAttributeName } from '@/remote/elements/utils/isBooleanishAttributeName';
+
+type StyleDeclarationLike = {
+ cssText?: unknown;
+};
+
+const serializeBooleanPropertyValue = ({
+ attributeName,
+ propertyValue,
+ hasRemoteDomFalseDefault,
+}: {
+ attributeName: string;
+ propertyValue: boolean;
+ hasRemoteDomFalseDefault: boolean;
+}): string | null => {
+ const isBooleanishAttribute = isBooleanishAttributeName(attributeName);
+
+ if (propertyValue) {
+ return isBooleanishAttribute ? 'true' : '';
+ }
+
+ const isFalseDistinguishableFromUnset = !hasRemoteDomFalseDefault;
+
+ return isBooleanishAttribute && isFalseDistinguishableFromUnset
+ ? 'false'
+ : null;
+};
+
+export const serializeRemotePropertyAsAttributeValue = ({
+ attributeName,
+ propertyValue,
+ hasRemoteDomFalseDefault,
+}: {
+ attributeName: string;
+ propertyValue: unknown;
+ hasRemoteDomFalseDefault: boolean;
+}): string | null => {
+ if (isString(propertyValue)) {
+ return propertyValue;
+ }
+
+ if (isNumber(propertyValue)) {
+ return String(propertyValue);
+ }
+
+ if (isBoolean(propertyValue)) {
+ return serializeBooleanPropertyValue({
+ attributeName,
+ propertyValue,
+ hasRemoteDomFalseDefault,
+ });
+ }
+
+ if (attributeName === 'style' && isObject(propertyValue)) {
+ const cssText = (propertyValue as StyleDeclarationLike).cssText;
+
+ return isNonEmptyString(cssText) ? cssText : null;
+ }
+
+ return null;
+};
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts
index 63ca1f416e1..f18045a2558 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
@@ -27,6 +27,7 @@ import { toGlobalScopeRecord } from '@/polyfills/utils/toGlobalScopeRecord';
import { installStorageBridge } from '@/polyfills/storage/utils/installStorageBridge';
import { installWindowAliasesPolyfill } from '@/polyfills/window-aliases/utils/installWindowAliasesPolyfill';
import { exposeGlobals } from '@/utils/exposeGlobals';
+import { installAriaBooleanPropertyAccessors } from '@/remote/elements/utils/installAriaBooleanPropertyAccessors';
import { installStylePropertyOnRemoteElements } from '@/remote/elements/utils/installStylePropertyOnRemoteElements';
import { patchRemoteElementAttributes } from '@/remote/elements/utils/patchRemoteElementAttributes';
import { resolveRemoteElementPrototypes } from '@/remote/elements/utils/resolveRemoteElementPrototypes';
@@ -42,6 +43,7 @@ import { createClonableErrorThreadSerialization } from '@/utils/clonable-error/c
installStylePropertyOnRemoteElements();
patchRemoteElementAttributes();
+installAriaBooleanPropertyAccessors();
installErrorEventBridge();
installDocumentGetElementById(document);