The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Polyfill navigator.clipboard.writeText for front components (#24195)
Félix Malfait98d75fcba689
diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigator-clipboard.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigator-clipboard.front-component.tsxnew file mode 100644index 00000000000..3eed99d2a7c--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigator-clipboard.front-component.tsx@@ -0,0 +1,55 @@+import { useState } from 'react';+import { defineFrontComponent } from 'twenty-sdk/define';++import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';+import {+ BUTTON_STYLE,+ STATUS_STYLE,+} from '@/__stories__/shared/front-components/styles';++// Deliberately uses the standard web API rather than the SDK helper: this is+// what a third-party library calls, and it only works if the worker polyfill+// installed navigator.clipboard in the real sandbox realm.+const HostApiNavigatorClipboardFrontComponent = () => {+ const [status, setStatus] = useState('idle');++ const handleClick = async () => {+ try {+ if (typeof navigator.clipboard?.writeText !== 'function') {+ setStatus('clipboard:missing');++ return;+ }++ await navigator.clipboard.writeText('Hello standard clipboard');+ setStatus('clipboard:success');+ } catch (error) {+ setStatus(+ `clipboard:error:${error instanceof Error ? error.message : String(error)}`,+ );+ }+ };++ return (+ <FrontComponentCard title="host-api:navigator-clipboard">+ <button+ data-testid="subject"+ type="button"+ onClick={handleClick}+ style={BUTTON_STYLE}+ >+ Copy+ </button>+ <span data-testid="api-status" style={STATUS_STYLE}>+ {status}+ </span>+ </FrontComponentCard>+ );+};++export default defineFrontComponent({+ universalIdentifier: 'fc-host-clipboard-00000000-0000-0000-0000-000000000021',+ name: 'host-api-navigator-clipboard-front-component',+ description: 'Front component covering the navigator.clipboard polyfill',+ component: HostApiNavigatorClipboardFrontComponent,+});diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/navigator-clipboard.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/navigator-clipboard.stories.tsxnew file mode 100644index 00000000000..0e5c56e8c22--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/navigator-clipboard.stories.tsx@@ -0,0 +1,65 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, userEvent, waitFor, within } from 'storybook/test';+import { isDefined } from 'twenty-shared/utils';++import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';+import {+ FRONT_COMPONENT_STORY_DEFAULT_ARGS,+ resetFrontComponentStoryMocks,+} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';+import { runFrontComponentStory } from '@/__stories__/shared/test-utils/runFrontComponentStory';+import {+ HOST_API_TIMEOUT,+ INTERACTION_TIMEOUT,+} from '@/__stories__/shared/test-utils/timeouts';++const meta: Meta<typeof FrontComponentRenderer> = {+ title: 'FrontComponent/HostApi/NavigatorClipboard',+ component: FrontComponentRenderer,+ parameters: { layout: 'centered' },+ args: FRONT_COMPONENT_STORY_DEFAULT_ARGS,+ beforeEach: resetFrontComponentStoryMocks,+};++export default meta;++type Story = StoryObj<typeof FrontComponentRenderer>;++// Runs the real sandbox: iframe, worker, and bridge in an actual browser, so+// it fails if the polyfill never reaches the worker realm — which the unit+// tests of the install function cannot detect.+export const NavigatorClipboard: Story = runFrontComponentStory({+ frontComponentBundleName: 'host-api-navigator-clipboard',+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const api = args.frontComponentHostCommunicationApi;++ if (!isDefined(api)) {+ throw new Error('frontComponentHostCommunicationApi is required');+ }++ await expectFrontComponentMounted(canvas);++ const subject = await canvas.findByTestId('subject');++ await userEvent.click(subject);++ await waitFor(+ () => {+ expect(api.copyToClipboard).toHaveBeenCalledWith(+ 'Hello standard clipboard',+ );+ },+ { timeout: HOST_API_TIMEOUT },+ );++ expect(+ await canvas.findByText(+ 'clipboard:success',+ {},+ { timeout: INTERACTION_TIMEOUT },+ ),+ ).toBeVisible();+ },+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/__tests__/installClipboardPolyfill.test.ts b/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/__tests__/installClipboardPolyfill.test.tsnew file mode 100644index 00000000000..e5f467eab67--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/__tests__/installClipboardPolyfill.test.ts@@ -0,0 +1,51 @@+import { installClipboardPolyfill } from '@/polyfills/clipboard/utils/installClipboardPolyfill';++describe('installClipboardPolyfill', () => {+ it('should delegate writeText to the host copyToClipboard', async () => {+ const copyToClipboard = jest.fn().mockResolvedValue(undefined);+ const targetNavigator = {} as {+ clipboard?: { writeText: (text: string) => Promise<void> };+ };+ const globalScope: Record<string, unknown> = { navigator: targetNavigator };++ installClipboardPolyfill({ globalScope, copyToClipboard });++ await targetNavigator.clipboard?.writeText('copied text');++ expect(copyToClipboard).toHaveBeenCalledTimes(1);+ expect(copyToClipboard).toHaveBeenCalledWith('copied text');+ });++ it('should leave an existing clipboard implementation in place', () => {+ const nativeClipboard = { writeText: jest.fn() };+ const globalScope: Record<string, unknown> = {+ navigator: { clipboard: nativeClipboard },+ };++ installClipboardPolyfill({+ globalScope,+ copyToClipboard: jest.fn(),+ });++ expect((globalScope.navigator as { clipboard: unknown }).clipboard).toBe(+ nativeClipboard,+ );+ });++ it('should install a navigator on the polyfill window when it has none', async () => {+ const copyToClipboard = jest.fn().mockResolvedValue(undefined);+ const polyfillWindow: Record<string, unknown> = {};+ const globalScope: Record<string, unknown> = { window: polyfillWindow };++ installClipboardPolyfill({ globalScope, copyToClipboard });++ const installedNavigator = polyfillWindow.navigator as {+ clipboard: { writeText: (text: string) => Promise<void> };+ };++ await installedNavigator.clipboard.writeText('from the window');++ expect(copyToClipboard).toHaveBeenCalledTimes(1);+ expect(copyToClipboard).toHaveBeenCalledWith('from the window');+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/installClipboardPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/installClipboardPolyfill.tsnew file mode 100644index 00000000000..c05b1761296--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/installClipboardPolyfill.ts@@ -0,0 +1,44 @@+import { isDefined } from 'twenty-shared/utils';++import { resolveGlobalScopeInstallTargets } from '@/polyfills/utils/resolveGlobalScopeInstallTargets';++type NavigatorWithClipboard = {+ clipboard?: { writeText: (text: string) => Promise<void> };+};++type InstallClipboardPolyfillInput = {+ globalScope: Record<string, unknown>;+ copyToClipboard: (text: string) => Promise<void>;+};++// Libraries call the standard navigator.clipboard.writeText; the worker has+// no clipboard access, so the write is delegated to the host. Only writeText+// is polyfilled: reading the clipboard is not a capability the host grants.+export const installClipboardPolyfill = ({+ globalScope,+ copyToClipboard,+}: InstallClipboardPolyfillInput): void => {+ const clipboard = {+ writeText: (text: string): Promise<void> => copyToClipboard(String(text)),+ };++ for (const installTarget of resolveGlobalScopeInstallTargets(globalScope)) {+ const targetNavigator = (installTarget.navigator ??+ globalScope.navigator) as NavigatorWithClipboard | undefined;++ if (!isDefined(targetNavigator)) {+ installTarget.navigator = { clipboard };+ continue;+ }++ installTarget.navigator ??= targetNavigator;++ // A native worker clipboard, if a browser ever ships one, wins.+ if (!isDefined(targetNavigator.clipboard)) {+ Object.defineProperty(targetNavigator, 'clipboard', {+ configurable: true,+ value: clipboard,+ });+ }+ }+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/toGlobalScopeRecord.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/toGlobalScopeRecord.tsnew file mode 100644index 00000000000..a3a9a6d2a00--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/toGlobalScopeRecord.ts@@ -0,0 +1,6 @@+// Lib global types carry no index signature, but at runtime the worker+// global scope is an ordinary mutable object the polyfills install onto.+// The one assertion lives here so call sites stay cast-free.+export const toGlobalScopeRecord = (+ globalScope: object,+): Record<string, unknown> => globalScope as Record<string, unknown>;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 8e5b954bc51..6332f07135d 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@@ -9,6 +9,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 { installDocumentGetElementById } from '@/polyfills/dom/utils/installDocumentGetElementById';import { installGetComputedStyle } from '@/polyfills/dom/utils/installGetComputedStyle';import { installGetElementsByClassName } from '@/polyfills/dom/utils/installGetElementsByClassName';@@ -18,6 +19,7 @@ import { workerGeometryStore } from '@/polyfills/geometry/states/workerGeometrySimport { installElementGeometryPolyfill } from '@/polyfills/geometry/utils/installElementGeometryPolyfill';import { installWindowGeometryPolyfill } from '@/polyfills/geometry/utils/installWindowGeometryPolyfill';import { frontComponentStorageBridges } from '@/polyfills/storage/states/frontComponentStorageBridges';+import { toGlobalScopeRecord } from '@/polyfills/utils/toGlobalScopeRecord';import { installStorageBridge } from '@/polyfills/storage/utils/installStorageBridge';import { exposeGlobals } from '@/utils/exposeGlobals';import { installStylePropertyOnRemoteElements } from '@/remote/elements/utils/installStylePropertyOnRemoteElements';@@ -41,10 +43,10 @@ installGetElementsByClassName(Element.prototype);installGetElementsByClassName(document);installLocalStyleOnBaseElements(Element.prototype);-installGetComputedStyle(globalThis as unknown as Record<string, unknown>);+installGetComputedStyle(toGlobalScopeRecord(globalThis));installMutationObserver({- globalScope: globalThis as unknown as Record<string, unknown>,+ globalScope: toGlobalScopeRecord(globalThis),});installElementGeometryPolyfill({@@ -54,15 +56,31 @@ installElementGeometryPolyfill({});installWindowGeometryPolyfill({- globalScope: globalThis as unknown as Record<string, unknown>,+ globalScope: toGlobalScopeRecord(globalThis),geometryStore: workerGeometryStore,});installStorageBridge({- globalScope: globalThis as unknown as Record<string, unknown>,+ globalScope: toGlobalScopeRecord(globalThis),storageBridges: frontComponentStorageBridges,});+installClipboardPolyfill({+ globalScope: toGlobalScopeRecord(globalThis),+ // Resolved lazily: the host communication api is populated after worker+ // boot, so the polyfill must not capture the function at install time.+ copyToClipboard: (text) => {+ const copyToClipboardFunction =+ frontComponentHostCommunicationApi.copyToClipboard;++ if (!isDefined(copyToClipboardFunction)) {+ return Promise.reject(new Error('copyToClipboardFunction is not set'));+ }++ return copyToClipboardFunction(text);+ },+});+exposeGlobals({__HTML_TAG_TO_CUSTOM_ELEMENT_TAG__: HTML_TAG_TO_CUSTOM_ELEMENT_TAG,});