From ef4fdf4e0b86972dc776fcca7e5596388a0caaa2 Mon Sep 17 00:00:00 2001 From: Vishal Raj <9031842908.vk@gmail.com> Date: Sat, 14 Nov 2026 13:14:05 +0530 Subject: [PATCH 1/2] [lexical-playground] Bug Fix: Safe clipboard permission query in ContextMenuPlugin In Firefox and other non-Chromium browsers, navigator.permissions.query({ name: 'clipboard-read' }) throws a TypeError because 'clipboard-read' is not a supported PermissionDescriptor name. This unhandled rejection broke the Paste and Paste as Plain Text actions in the Lexical context menu. Safely query permissions within a try/catch guard and fallback gracefully to direct clipboard read operations. Also clean up redundant duplicate clipboard.read() invocations and handle empty clipboard items. Signed-off-by: Vishal Raj <9031842908.vk@gmail.com> --- .../__tests__/unit/ContextMenuPlugin.test.tsx | 249 ++++++++++++++++++ .../src/plugins/ContextMenuPlugin/index.tsx | 104 ++++---- 2 files changed, 307 insertions(+), 46 deletions(-) create mode 100644 packages/lexical-playground/__tests__/unit/ContextMenuPlugin.test.tsx diff --git a/packages/lexical-playground/__tests__/unit/ContextMenuPlugin.test.tsx b/packages/lexical-playground/__tests__/unit/ContextMenuPlugin.test.tsx new file mode 100644 index 000000000000..d88922a6fce8 --- /dev/null +++ b/packages/lexical-playground/__tests__/unit/ContextMenuPlugin.test.tsx @@ -0,0 +1,249 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import {LexicalComposer} from '@lexical/react/LexicalComposer'; +import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext'; +import {ContentEditable} from '@lexical/react/LexicalContentEditable'; +import {RichTextPlugin} from '@lexical/react/LexicalRichTextPlugin'; +import { + COMMAND_PRIORITY_CRITICAL, + type LexicalEditor, + PASTE_COMMAND, +} from 'lexical'; +import * as React from 'react'; +import {act} from 'react'; +import {createRoot, type Root} from 'react-dom/client'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import ContextMenuPlugin from '../../src/plugins/ContextMenuPlugin'; + +describe('ContextMenuPlugin Clipboard', () => { + let container: HTMLDivElement; + let reactRoot: Root; + let editor: LexicalEditor; + + function CaptureEditor() { + const [contextEditor] = useLexicalComposerContext(); + editor = contextEditor; + return null; + } + + beforeEach(() => { + container = document.createElement('div'); + document.body.appendChild(container); + reactRoot = createRoot(container); + vi.stubGlobal('alert', vi.fn()); + }); + + afterEach(async () => { + await act(async () => { + reactRoot.unmount(); + }); + container.remove(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + async function renderPlugin(): Promise { + await act(async () => { + reactRoot.render( + { + throw error; + }, + }}> + + } + ErrorBoundary={({children}) => <>{children}} + /> + + , + ); + }); + } + + async function openContextMenu(): Promise { + const rootElement = container.querySelector( + '[contenteditable="true"]', + ) as HTMLElement; + const event = new MouseEvent('contextmenu', { + bubbles: true, + cancelable: true, + clientX: 50, + clientY: 50, + }); + await act(async () => { + rootElement.dispatchEvent(event); + }); + } + + function getMenuItem(text: string): HTMLElement | null { + const items = Array.from( + document.querySelectorAll('.PlaygroundEditorTheme__contextMenuItem'), + ); + return ( + (items.find(item => item.textContent?.includes(text)) as HTMLElement) ?? + null + ); + } + + it('pastes successfully when navigator.permissions.query throws (e.g. Firefox)', async () => { + const mockPasteHandler = vi.fn(() => true); + + const mockClipboardItem = { + getType: vi.fn( + async () => new Blob(['hello world'], {type: 'text/plain'}), + ), + types: ['text/plain'], + }; + + vi.stubGlobal('navigator', { + clipboard: { + read: vi.fn(async () => [mockClipboardItem]), + readText: vi.fn(async () => 'hello world'), + }, + permissions: { + query: vi.fn(async () => { + throw new TypeError( + "'clipboard-read' (value of 'name' member of PermissionDescriptor) is not a valid PermissionName.", + ); + }), + }, + }); + + await renderPlugin(); + editor.registerCommand( + PASTE_COMMAND, + mockPasteHandler, + COMMAND_PRIORITY_CRITICAL, + ); + + await openContextMenu(); + const pasteOption = getMenuItem('Paste'); + expect(pasteOption).not.toBeNull(); + + await act(async () => { + pasteOption!.click(); + }); + + expect(mockPasteHandler).toHaveBeenCalledTimes(1); + const dispatchedEvent = mockPasteHandler.mock.calls[0][0] as ClipboardEvent; + expect(dispatchedEvent.clipboardData?.getData('text/plain')).toBe( + 'hello world', + ); + expect(alert).not.toHaveBeenCalled(); + }); + + it('pastes plain text successfully when navigator.permissions.query throws (e.g. Firefox)', async () => { + const mockPasteHandler = vi.fn(() => true); + + vi.stubGlobal('navigator', { + clipboard: { + readText: vi.fn(async () => 'plain text content'), + }, + permissions: { + query: vi.fn(async () => { + throw new TypeError('unsupported PermissionName'); + }), + }, + }); + + await renderPlugin(); + editor.registerCommand( + PASTE_COMMAND, + mockPasteHandler, + COMMAND_PRIORITY_CRITICAL, + ); + + await openContextMenu(); + const pastePlainTextOption = getMenuItem('Paste as Plain Text'); + expect(pastePlainTextOption).not.toBeNull(); + + await act(async () => { + pastePlainTextOption!.click(); + }); + + expect(mockPasteHandler).toHaveBeenCalledTimes(1); + const dispatchedEvent = mockPasteHandler.mock.calls[0][0] as ClipboardEvent; + expect(dispatchedEvent.clipboardData?.getData('text/plain')).toBe( + 'plain text content', + ); + expect(alert).not.toHaveBeenCalled(); + }); + + it('shows alert and blocks paste when clipboard-read permission is denied', async () => { + const mockPasteHandler = vi.fn(() => true); + + vi.stubGlobal('navigator', { + clipboard: { + read: vi.fn(), + }, + permissions: { + query: vi.fn(async () => ({state: 'denied'})), + }, + }); + + await renderPlugin(); + editor.registerCommand( + PASTE_COMMAND, + mockPasteHandler, + COMMAND_PRIORITY_CRITICAL, + ); + + await openContextMenu(); + const pasteOption = getMenuItem('Paste'); + expect(pasteOption).not.toBeNull(); + + await act(async () => { + pasteOption!.click(); + }); + + expect(alert).toHaveBeenCalledWith('Not allowed to paste from clipboard.'); + expect(mockPasteHandler).not.toHaveBeenCalled(); + }); + + it('handles NotAllowedError when clipboard.read() rejects with permission denial', async () => { + const mockPasteHandler = vi.fn(() => true); + + vi.stubGlobal('navigator', { + clipboard: { + read: vi.fn(async () => { + const err = new Error('The request is not allowed'); + err.name = 'NotAllowedError'; + throw err; + }), + }, + permissions: { + query: vi.fn(async () => { + throw new TypeError('unsupported'); + }), + }, + }); + + await renderPlugin(); + editor.registerCommand( + PASTE_COMMAND, + mockPasteHandler, + COMMAND_PRIORITY_CRITICAL, + ); + + await openContextMenu(); + const pasteOption = getMenuItem('Paste'); + expect(pasteOption).not.toBeNull(); + + await act(async () => { + pasteOption!.click(); + }); + + expect(alert).toHaveBeenCalledWith('Not allowed to paste from clipboard.'); + expect(mockPasteHandler).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/lexical-playground/src/plugins/ContextMenuPlugin/index.tsx b/packages/lexical-playground/src/plugins/ContextMenuPlugin/index.tsx index 382e68ff9be5..5ecf00a3ee21 100644 --- a/packages/lexical-playground/src/plugins/ContextMenuPlugin/index.tsx +++ b/packages/lexical-playground/src/plugins/ContextMenuPlugin/index.tsx @@ -28,6 +28,25 @@ import {type JSX, useMemo} from 'react'; import {PLAYGROUND_TRANSFORMERS} from '../MarkdownTransformers'; +async function isClipboardReadDenied(): Promise { + if ( + navigator.permissions && + typeof navigator.permissions.query === 'function' + ) { + try { + const permission = await navigator.permissions.query({ + // @ts-expect-error These types are incorrect. + name: 'clipboard-read', + }); + return permission.state === 'denied'; + } catch { + // navigator.permissions.query with 'clipboard-read' is not supported in all browsers (e.g. Firefox) + return false; + } + } + return false; +} + export default function ContextMenuPlugin({ shouldPreserveNewLinesInMarkdown, }: { @@ -81,37 +100,35 @@ export default function ContextMenuPlugin({ ), }), new NodeContextMenuOption(`Paste`, { - $onSelect: () => { - navigator.clipboard.read().then(async function (...args) { - const data = new DataTransfer(); + $onSelect: async () => { + if (await isClipboardReadDenied()) { + alert('Not allowed to paste from clipboard.'); + return; + } + try { const readClipboardItems = await navigator.clipboard.read(); const item = readClipboardItems[0]; + if (!item) { + return; + } - if (navigator.permissions) { - const permission = await navigator.permissions.query({ - // @ts-expect-error These types are incorrect. - name: 'clipboard-read', - }); - if (permission.state === 'denied') { - alert('Not allowed to paste from clipboard.'); - return; - } - - for (const type of item.types) { - const dataString = await (await item.getType(type)).text(); - data.setData(type, dataString); - } + const data = new DataTransfer(); + for (const type of item.types) { + const dataString = await (await item.getType(type)).text(); + data.setData(type, dataString); + } - const event = new ClipboardEvent('paste', { - clipboardData: data, - }); + const event = new ClipboardEvent('paste', { + clipboardData: data, + }); - editor.dispatchCommand(PASTE_COMMAND, event); - } else { - alert('Your browser does not support navigator.permissions'); + editor.dispatchCommand(PASTE_COMMAND, event); + } catch (error: unknown) { + if (error instanceof Error && error.name === 'NotAllowedError') { + alert('Not allowed to paste from clipboard.'); } - }); + } }, disabled: false, icon: ( @@ -119,31 +136,26 @@ export default function ContextMenuPlugin({ ), }), new NodeContextMenuOption(`Paste as Plain Text`, { - $onSelect: () => { - navigator.clipboard.read().then(async function (...args) { - if (navigator.permissions) { - const permission = await navigator.permissions.query({ - // @ts-expect-error These types are incorrect. - name: 'clipboard-read', - }); - - if (permission.state === 'denied') { - alert('Not allowed to paste from clipboard.'); - return; - } + $onSelect: async () => { + if (await isClipboardReadDenied()) { + alert('Not allowed to paste from clipboard.'); + return; + } - const data = new DataTransfer(); - const clipboardText = await navigator.clipboard.readText(); - data.setData('text/plain', clipboardText); + try { + const clipboardText = await navigator.clipboard.readText(); + const data = new DataTransfer(); + data.setData('text/plain', clipboardText); - const event = new ClipboardEvent('paste', { - clipboardData: data, - }); - editor.dispatchCommand(PASTE_COMMAND, event); - } else { - alert('Your browser does not support navigator.permissions'); + const event = new ClipboardEvent('paste', { + clipboardData: data, + }); + editor.dispatchCommand(PASTE_COMMAND, event); + } catch (error: unknown) { + if (error instanceof Error && error.name === 'NotAllowedError') { + alert('Not allowed to paste from clipboard.'); } - }); + } }, disabled: false, icon: ( From 1eaf5936e048546d3872c0f8e0ea14774e02fcf4 Mon Sep 17 00:00:00 2001 From: Vishal Raj <9031842908.vk@gmail.com> Date: Sat, 14 Nov 2026 14:15:56 +0530 Subject: [PATCH 2/2] [lexical-playground] Bug Fix: Attach clipboardData after construction for Firefox compatibility Firefox ignores clipboardData passed in ClipboardEventInit, causing pasted content to be dropped. Attach clipboardData via Object.defineProperty after constructing the ClipboardEvent in both Paste and Paste as Plain Text actions. Also type mockPasteHandler with PasteCommandType in ContextMenuPlugin unit tests to fix tsc type checking, and log non-permission errors to console for debuggability. Signed-off-by: Vishal Raj <9031842908.vk@gmail.com> --- .../__tests__/unit/ContextMenuPlugin.test.tsx | 9 +++++---- .../src/plugins/ContextMenuPlugin/index.tsx | 17 +++++++++++------ 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/lexical-playground/__tests__/unit/ContextMenuPlugin.test.tsx b/packages/lexical-playground/__tests__/unit/ContextMenuPlugin.test.tsx index d88922a6fce8..827ca814dbab 100644 --- a/packages/lexical-playground/__tests__/unit/ContextMenuPlugin.test.tsx +++ b/packages/lexical-playground/__tests__/unit/ContextMenuPlugin.test.tsx @@ -14,6 +14,7 @@ import { COMMAND_PRIORITY_CRITICAL, type LexicalEditor, PASTE_COMMAND, + type PasteCommandType, } from 'lexical'; import * as React from 'react'; import {act} from 'react'; @@ -96,7 +97,7 @@ describe('ContextMenuPlugin Clipboard', () => { } it('pastes successfully when navigator.permissions.query throws (e.g. Firefox)', async () => { - const mockPasteHandler = vi.fn(() => true); + const mockPasteHandler = vi.fn((_event: PasteCommandType) => true); const mockClipboardItem = { getType: vi.fn( @@ -143,7 +144,7 @@ describe('ContextMenuPlugin Clipboard', () => { }); it('pastes plain text successfully when navigator.permissions.query throws (e.g. Firefox)', async () => { - const mockPasteHandler = vi.fn(() => true); + const mockPasteHandler = vi.fn((_event: PasteCommandType) => true); vi.stubGlobal('navigator', { clipboard: { @@ -180,7 +181,7 @@ describe('ContextMenuPlugin Clipboard', () => { }); it('shows alert and blocks paste when clipboard-read permission is denied', async () => { - const mockPasteHandler = vi.fn(() => true); + const mockPasteHandler = vi.fn((_event: PasteCommandType) => true); vi.stubGlobal('navigator', { clipboard: { @@ -211,7 +212,7 @@ describe('ContextMenuPlugin Clipboard', () => { }); it('handles NotAllowedError when clipboard.read() rejects with permission denial', async () => { - const mockPasteHandler = vi.fn(() => true); + const mockPasteHandler = vi.fn((_event: PasteCommandType) => true); vi.stubGlobal('navigator', { clipboard: { diff --git a/packages/lexical-playground/src/plugins/ContextMenuPlugin/index.tsx b/packages/lexical-playground/src/plugins/ContextMenuPlugin/index.tsx index 5ecf00a3ee21..e5f12166ffc5 100644 --- a/packages/lexical-playground/src/plugins/ContextMenuPlugin/index.tsx +++ b/packages/lexical-playground/src/plugins/ContextMenuPlugin/index.tsx @@ -119,14 +119,16 @@ export default function ContextMenuPlugin({ data.setData(type, dataString); } - const event = new ClipboardEvent('paste', { - clipboardData: data, - }); + const event = new ClipboardEvent('paste'); + // Firefox ignores clipboardData in ClipboardEventInit. + Object.defineProperty(event, 'clipboardData', {value: data}); editor.dispatchCommand(PASTE_COMMAND, event); } catch (error: unknown) { if (error instanceof Error && error.name === 'NotAllowedError') { alert('Not allowed to paste from clipboard.'); + } else { + console.error(error); } } }, @@ -147,13 +149,16 @@ export default function ContextMenuPlugin({ const data = new DataTransfer(); data.setData('text/plain', clipboardText); - const event = new ClipboardEvent('paste', { - clipboardData: data, - }); + const event = new ClipboardEvent('paste'); + // Firefox ignores clipboardData in ClipboardEventInit. + Object.defineProperty(event, 'clipboardData', {value: data}); + editor.dispatchCommand(PASTE_COMMAND, event); } catch (error: unknown) { if (error instanceof Error && error.name === 'NotAllowedError') { alert('Not allowed to paste from clipboard.'); + } else { + console.error(error); } } },