Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion devtools/visual-testing/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { defineStory } from '@superdoc-testing/helpers';
import { clickOnLine } from '../../helpers/index.js';

const WAIT_MS = 300;
const WAIT_LONG_MS = 600;

export default defineStory({
name: 'slash-menu-paste',
description: 'Verify the slash menu shows a Paste action and that pasting formatted HTML preserves formatting.',
tickets: ['SD-1302'],
startDocument: null,
hideCaret: true,

async run(page, helpers): Promise<void> {
const { step, type, newLine, press, waitForStable, milestone } = helpers;

await step('Type a normal line', async () => {
await type('Normal line');
await newLine();
await waitForStable(WAIT_MS);
await milestone('before-paste', 'One line typed, cursor on second line.');
});

await step('Open slash menu via right-click to show Paste option', async () => {
const lines = page.locator('.superdoc-line');
const lastLine = lines.last();
const box = await lastLine.boundingBox();
if (!box) throw new Error('Last line not visible');

await page.mouse.click(box.x + 20, box.y + box.height / 2, { button: 'right' });
await waitForStable(WAIT_MS);

const menu = page.locator('.slash-menu');
await menu.waitFor({ state: 'visible', timeout: 5000 });
await waitForStable(WAIT_MS);

await milestone('slash-menu-open', 'Slash menu visible with Paste action.');
});

await step('Dismiss menu and paste bold HTML via editor API', async () => {
await press('Escape');
await waitForStable(WAIT_MS);

// Reposition cursor on line 2 (lost when slash menu closed)
await clickOnLine(page, 1);
await waitForStable(WAIT_MS);

// Paste formatted HTML directly via ProseMirror's pasteHTML API.
// This exercises the same rendering path as the slash menu paste action
// without depending on browser clipboard permissions.
// A clipboard event shim is required — pasteHTML internally accesses
// event.clipboardData.getData().
await page.evaluate(
`(function() {
var view = window.editor && window.editor.view;
if (!view) return;
var html = '<b>Bold pasted text</b>';
var text = 'Bold pasted text';
var fakeEvent = {
type: 'paste',
preventDefault: function() {},
stopPropagation: function() {},
clipboardData: {
getData: function(type) {
if (type === 'text/html') return html;
if (type === 'text/plain') return text;
return '';
}
}
};
if (typeof view.pasteHTML === 'function') {
view.pasteHTML(html, fakeEvent);
} else if (window.editor.commands && window.editor.commands.insertContent) {
window.editor.commands.insertContent(html);
}
})()`,
);

await waitForStable(WAIT_LONG_MS);
await milestone('after-paste', 'Bold text pasted on line 2 — formatting should be preserved.');
});
},
});
57 changes: 47 additions & 10 deletions packages/super-editor/src/components/slash-menu/menuItems.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,32 @@ import TableActions from '../toolbar/TableActions.vue';
import LinkInput from '../toolbar/LinkInput.vue';
import { TEXTS, ICONS, TRIGGERS } from './constants.js';
import { isTrackedChangeActionAllowed } from '@extensions/track-changes/permission-helpers.js';
import { readClipboardRaw } from '../../core/utilities/clipboardUtils.js';
import { handleClipboardPaste } from '../../core/InputRule.js';

/**
* Build a minimal clipboard event-like object so ProseMirror paste hooks
* can access text/html and text/plain data.
* @param {{ html?: string, text?: string }} clipboard
* @returns {{ clipboardData: { getData: (type: string) => string } }}
*/
const createPasteEventShim = (clipboard) => {
const html = clipboard?.html || '';
const text = clipboard?.text || '';

return {
type: 'paste',
preventDefault: () => {},
stopPropagation: () => {},
clipboardData: {
getData: (type) => {
if (type === 'text/html') return html;
if (type === 'text/plain') return text;
return '';
},
},
};
};

/**
* Check if a module is enabled based on editor options
Expand Down Expand Up @@ -257,16 +283,27 @@ export function getItems(context, customItems = [], includeDefaultItems = true)
label: TEXTS.paste,
icon: ICONS.paste,
isDefault: true,
action: (editor) => {
// Use execCommand('paste') - triggers native paste without permission prompt
// This works because it's triggered by user interaction (clicking the menu item)
const editorDom = editor.view?.dom;
if (editorDom) {
editorDom.focus();
// execCommand paste is allowed when triggered by user action
const success = document.execCommand('paste');
if (!success) {
console.warn('[Paste] execCommand paste failed - clipboard may be empty or inaccessible');
action: async (editor) => {
const { view } = editor ?? {};
if (!view) return;
view.dom.focus();
const { html, text } = await readClipboardRaw();
const handled = html ? handleClipboardPaste({ editor, view }, html) : false;
if (!handled) {
const pasteEvent = createPasteEventShim({ html, text });

if (html && typeof view.pasteHTML === 'function') {
view.pasteHTML(html, pasteEvent);
return;
}

if (text && typeof view.pasteText === 'function') {
view.pasteText(text, pasteEvent);
return;
}

if (text && editor.commands?.insertContent) {
editor.commands.insertContent(text, { contentType: 'text' });
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import { getItems } from '../menuItems.js';
import { createMockEditor, createMockContext, assertMenuSectionsStructure, SlashMenuConfigs } from './testHelpers.js';
import { TRIGGERS } from '../constants.js';

const clipboardMocks = vi.hoisted(() => ({
readClipboardRaw: vi.fn(),
handleClipboardPaste: vi.fn(() => true),
}));

vi.mock('../../cursor-helpers.js', async () => {
const actual = await vi.importActual('../../cursor-helpers.js');
return {
Expand Down Expand Up @@ -47,8 +52,12 @@ vi.mock('../../toolbar/AIWriter.vue', () => ({ default: { template: '<div>AIWrit
vi.mock('../../toolbar/TableActions.vue', () => ({ default: { template: '<div>TableActions</div>' } }));
vi.mock('../../toolbar/LinkInput.vue', () => ({ default: { template: '<div>LinkInput</div>' } }));

vi.mock('../../core/InputRule.js', () => ({
handleClipboardPaste: vi.fn(() => true),
vi.mock('../../../core/utilities/clipboardUtils.js', () => ({
readClipboardRaw: clipboardMocks.readClipboardRaw,
}));

vi.mock('../../../core/InputRule.js', () => ({
handleClipboardPaste: clipboardMocks.handleClipboardPaste,
}));

vi.mock('@extensions/track-changes/permission-helpers.js', () => ({
Expand Down Expand Up @@ -435,4 +444,99 @@ describe('menuItems.js', () => {
expect(removeItem).toBeDefined();
});
});

describe('getItems - paste action behavior', () => {
it('should not force plain-text insert when HTML paste is unhandled', async () => {
const insertContent = vi.fn();
mockEditor = createMockEditor({
commands: { insertContent },
});
mockEditor.view.dom.focus = vi.fn();
mockEditor.view.pasteHTML = vi.fn();
mockContext = createMockContext({
editor: mockEditor,
trigger: TRIGGERS.click,
});

clipboardMocks.readClipboardRaw.mockResolvedValue({
html: '<p>word html</p>',
text: 'word html',
});
clipboardMocks.handleClipboardPaste.mockReturnValue(false);

const sections = getItems(mockContext);
const pasteAction = sections
.find((section) => section.id === 'clipboard')
?.items.find((item) => item.id === 'paste')?.action;

expect(pasteAction).toBeTypeOf('function');
await pasteAction(mockEditor);

expect(clipboardMocks.handleClipboardPaste).toHaveBeenCalledWith(
{ editor: mockEditor, view: mockEditor.view },
'<p>word html</p>',
);
expect(mockEditor.view.pasteHTML).toHaveBeenCalledWith('<p>word html</p>', expect.any(Object));
expect(insertContent).not.toHaveBeenCalled();
});

it('should use pasteText when clipboard has text but no HTML', async () => {
const insertContent = vi.fn();
mockEditor = createMockEditor({
commands: { insertContent },
});
mockEditor.view.dom.focus = vi.fn();
mockEditor.view.pasteText = vi.fn();
mockContext = createMockContext({
editor: mockEditor,
trigger: TRIGGERS.click,
});

clipboardMocks.readClipboardRaw.mockResolvedValue({
html: '',
text: 'plain text content',
});
clipboardMocks.handleClipboardPaste.mockReturnValue(false);

const sections = getItems(mockContext);
const pasteAction = sections
.find((section) => section.id === 'clipboard')
?.items.find((item) => item.id === 'paste')?.action;

await pasteAction(mockEditor);

expect(mockEditor.view.pasteText).toHaveBeenCalledWith('plain text content', expect.any(Object));
expect(insertContent).not.toHaveBeenCalled();
});

it('should fall back to insertContent when view has no pasteHTML or pasteText', async () => {
const insertContent = vi.fn();
mockEditor = createMockEditor({
commands: { insertContent },
});
mockEditor.view.dom.focus = vi.fn();
// No pasteHTML or pasteText on view
delete mockEditor.view.pasteHTML;
delete mockEditor.view.pasteText;
mockContext = createMockContext({
editor: mockEditor,
trigger: TRIGGERS.click,
});

clipboardMocks.readClipboardRaw.mockResolvedValue({
html: '',
text: 'fallback text',
});
clipboardMocks.handleClipboardPaste.mockReturnValue(false);

const sections = getItems(mockContext);
const pasteAction = sections
.find((section) => section.id === 'clipboard')
?.items.find((item) => item.id === 'paste')?.action;

await pasteAction(mockEditor);

expect(insertContent).toHaveBeenCalledWith('fallback text', { contentType: 'text' });
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
* @returns {Promise<boolean>} Whether clipboard read permission is granted
*/
export function ensureClipboardPermission(): Promise<boolean>;
/**
* Reads raw HTML and text from the system clipboard (for use in paste actions).
*/
export function readClipboardRaw(): Promise<{ html: string; text: string }>;
/**
* Reads content from the system clipboard and parses it into a ProseMirror fragment.
* Attempts to read HTML first, falling back to plain text if necessary.
Expand Down
50 changes: 36 additions & 14 deletions packages/super-editor/src/core/utilities/clipboardUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,36 +53,58 @@ export async function ensureClipboardPermission() {
}

/**
* Reads content from the system clipboard and parses it into a ProseMirror fragment.
* Attempts to read HTML first, falling back to plain text if necessary.
* @param {EditorState} state - The ProseMirror editor state, used for schema and parsing.
* @returns {Promise<Fragment|ProseMirrorNode|null>} A promise that resolves to a ProseMirror fragment or text node, or null if reading fails.
* Reads raw HTML and text from the system clipboard (for use in paste actions).
* @returns {Promise<{ html: string, text: string }>}
*/
export async function readFromClipboard(state) {
export async function readClipboardRaw() {
Comment thread
harbournick marked this conversation as resolved.
let html = '';
let text = '';
const hasPermission = await ensureClipboardPermission();

if (hasPermission && navigator.clipboard && navigator.clipboard.read) {
if (!navigator.clipboard) {
return { html, text: text || '' };
}

if (hasPermission && navigator.clipboard.read) {
try {
const items = await navigator.clipboard.read();
for (const item of items) {
if (item.types.includes('text/html')) {
html = await (await item.getType('text/html')).text();
break;
} else if (item.types.includes('text/plain')) {
}
if (item.types.includes('text/plain')) {
text = await (await item.getType('text/plain')).text();
}
}
} catch {
// Fallback to plain text read; may still fail if permission denied
try {
text = await navigator.clipboard.readText();
} catch {}
// clipboard.read() may throw in restricted contexts (e.g. iframe sandbox,
// browser permission denied) — fall through to readText fallback below.
}
}

// Always attempt readText as a best-effort fallback. This keeps paste
// functional in environments where permission querying is unsupported but
// clipboard.readText() is still available.
if (!text && navigator.clipboard.readText) {
try {
text = await navigator.clipboard.readText();
} catch {
// readText() may also be blocked by permission policy — safe to ignore
// since we return whatever we've gathered so far.
}
} else {
// permissions denied or API unavailable; leave content empty
}

return { html, text: text || '' };
}

/**
* Reads content from the system clipboard and parses it into a ProseMirror fragment.
* Attempts to read HTML first, falling back to plain text if necessary.
* @param {EditorState} state - The ProseMirror editor state, used for schema and parsing.
* @returns {Promise<Fragment|ProseMirrorNode|null>} A promise that resolves to a ProseMirror fragment or text node, or null if reading fails.
*/
export async function readFromClipboard(state) {
const { html, text } = await readClipboardRaw();
let content = null;
if (html) {
try {
Expand Down
Loading
Loading