Files
webstudio/apps/builder/app/shared/copy-paste/init-copy-paste.ts
T
Ivan Starkov b97c55e494 fix: broken copy paste when inputs or text selection were used before (#3894)
## Description

In some cases copy/paste didn't work

## Steps for reproduction

1. Focus on an input in the style panel (width, style source) or name
input in settings. Select the text, then copy and paste any instance in
the Navigator tree or on the Canvas.
2. Edit text in a paragraph on the Canvas. Select text (single or
multiple lines), then press Cmd+X. The paragraph should not be deleted.
3. Select CSS preview text, then select an instance in the Navigator.
Press Cmd+C, then Cmd+V.

## Code Review

- [ ] hi @kof, I need you to do
  - conceptual review (architecture, feature-correctness)
  - detailed review (read every line)
  - test it on preview

## Before requesting a review

- [ ] made a self-review
- [ ] added inline comments where things may be not obvious (the "why",
not "what")

## Before merging

- [ ] tested locally and on preview environment (preview dev login:
5de6)
- [ ] updated [test
cases](https://github.com/webstudio-is/webstudio/blob/main/apps/builder/docs/test-cases.md)
document
- [ ] added tests
- [ ] if any new env variables are added, added them to `.env` file
2024-08-07 22:56:00 +03:00

142 lines
4.6 KiB
TypeScript

import { toastError } from "../error/toast-error";
import {
$authTokenPermissions,
$textEditingInstanceSelector,
} from "../nano-states";
const isTextEditing = (event: ClipboardEvent) => {
// Text is edited on the Canvas using the default Canvas text editor settings.
if ($textEditingInstanceSelector.get() != null) {
return true;
}
// Text is edited inside an input, textarea, or contenteditable (i.e. codemirror editor) field.
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement ||
(event.target instanceof HTMLElement &&
event.target.closest("[contenteditable]"))
) {
return true;
}
return false;
};
/**
*
* # Note:
* validateClipboardEvent determines when to use default copy/paste behavior or if a WebStudio instance will be copied, pasted, or cut.
* # How to test:
* 1. Focus on an input in the style panel (width, style source) or name input in settings. Select the text, then copy and paste any instance in the Navigator tree or on the Canvas.
* 2. Edit text in a paragraph on the Canvas. Select text (single or multiple lines), then press Cmd+X. The paragraph should not be deleted.
* 3. Select CSS preview text, then select an instance in the Navigator. Press Cmd+C, then Cmd+V.
**/
const validateClipboardEvent = (event: ClipboardEvent) => {
if (event.clipboardData === null) {
return false;
}
if (isTextEditing(event)) {
return false;
}
// Allows native selection of text in the Builder panels, such as CSS Preview.
if (event.type === "copy") {
const isInBuilderContext = window.self === window.top;
if (isInBuilderContext) {
// Note on event.target:
//
// The spec (https://w3c.github.io/clipboard-apis/#to-fire-a-clipboard-event)
// says that if the context is not editable, the target should be the focused node.
//
// But in practice it seems that the target is based
// on where the cursor is, rather than which element has focus.
// For example, if a <button> has focus, the target is the <body> element.
// If some text is selected, the target is a wrapping element of the text.
// (at least in Chrome).
// We are using the behavior described above: if some text is selected, the target is usually (at least in the cases we need) not the body.
if (event.target !== window.document.body) {
return false;
}
}
}
if ($authTokenPermissions.get().canCopy === false) {
toastError("Copying has been disabled by the project owner");
return false;
}
return true;
};
const defaultMimeType = "application/json";
type Plugin = {
mimeType?: string;
onCopy?: () => undefined | string;
onCut?: () => undefined | string;
onPaste?: (data: string) => boolean | Promise<boolean>;
};
export const initCopyPaste = (plugins: Plugin[]) => {
const handleCopy = async (event: ClipboardEvent) => {
if (validateClipboardEvent(event) === false) {
return;
}
for (const { mimeType = defaultMimeType, onCopy } of plugins) {
const data = await onCopy?.();
if (data) {
// must prevent default, otherwise setData() will not work
event.preventDefault();
event.clipboardData?.setData(mimeType, data);
break;
}
}
};
const handleCut = (event: ClipboardEvent) => {
if (validateClipboardEvent(event) === false) {
return;
}
for (const { mimeType = defaultMimeType, onCut } of plugins) {
const data = onCut?.();
if (data) {
// must prevent default, otherwise setData() will not work
event.preventDefault();
event.clipboardData?.setData(mimeType, data);
break;
}
}
};
const handlePaste = (event: ClipboardEvent) => {
if (validateClipboardEvent(event) === false) {
return;
}
for (const { mimeType = defaultMimeType, onPaste } of plugins) {
// this shouldn't matter, but just in case
event.preventDefault();
const data = event.clipboardData?.getData(mimeType).trim();
if (data && onPaste?.(data)) {
break;
}
}
};
document.addEventListener("copy", handleCopy);
document.addEventListener("cut", handleCut);
// Capture is required so we get the element before content-editable removes it
// This way we can detect when we are inside content-editable and ignore the event
document.addEventListener("paste", handlePaste, { capture: true });
return () => {
document.removeEventListener("copy", handleCopy);
document.removeEventListener("cut", handleCut);
document.removeEventListener("paste", handlePaste, { capture: true });
};
};