Files
webstudio/apps/builder/app/shared/copy-paste/copy-paste.ts
T
Oleg Isonen 1b9ae61fa1 feat: Copy and paste tokens across projects (#6660)
Closes #5727

Copy a design token from its menu and paste it into another project or
the style source input. Paste creates and attaches a new numbered token
(for example, `Button copy 1`). It carries all breakpoint styles,
referenced CSS variables, images, and fonts, and creates missing
breakpoints. MCP offers the same copy and paste commands; `instanceId`
attaches the token when supplied.

The clipboard format is CSS with one `@webstudio/token-css/v1` comment.
The old JSON format is removed. HTML and CSS use the same Webstudio
pragma parser, and token CSS reuses the existing CSS declaration parser.
Builder and MCP share token copy, parsing, paste, fragment asset import,
and asset reference remapping. The latest cleanup also reuses the
existing copy-name helper.

Repeated Builder pastes reuse the existing content-hash asset
deduplication path, including SVG and fonts. The source bytes still
download and hash on each paste. MCP downloads and uploads asset bytes
on each paste, using the upload path's deduplication; both projects must
use the same Webstudio origin for assets.

- [x] Implement CSS token copy and paste in Builder and MCP, including
selection attachment and numbered names.
- [x] Preserve breakpoint styles, variable dependencies, image and font
assets, and missing breakpoints.
- [x] Detect token CSS pasted into the style source input.
- [x] Remove the JSON transfer format and update Builder and MCP
documentation.
- [x] Reuse CSS parsing, asset transfer, naming, and existing upload
deduplication paths.
- [x] Resolve review findings, including shorthand variables and
selector state positions.
- [x] Verify focused tests, typechecks, lint, formatting, package
boundaries, and the approved Storybook visual check.
- [x] Trace existing CSS editor and HTML paste flows; reuse their
parser, declaration mapper, and CSS variable reference collector.
- [x] Preserve breakpoint cascade order when copying equal media
conditions; add a regression and resolve the review thread.
- [x] Share CSS variable traversal between collection and renaming;
preserve nested fallbacks and resolve the review comment.
- [x] Discover and remap image URLs inside raw variable fallbacks; share
the CSS value traversal and resolve the review comment.
- [x] Preserve fallback variables in mixed shorthands and custom
non-pixel breakpoint styles; add regressions and resolve review threads.
- [x] Preserve combined width and custom media conditions in token CSS;
add a regression and resolve the review thread.
- [x] Preserve range-syntax custom breakpoints in token CSS; add a
regression and resolve the review thread.
- [x] Preserve negated custom and width media conditions; add
regressions and resolve the review thread.
- [x] Preserve boolean operators between width conditions; add a
regression and resolve the review thread.
- [x] Monitor required CI checks for the latest commit.
- [x] Reuse the existing asset usage collector for copied token image
and font dependencies; verify token and asset usage tests.
- [x] Review documentation impact of this internal refactor (none; no
user-facing behavior or contract changed).

The reuse audit traced CSS editor, HTML paste, instance/page paste,
asset usage, and MCP from input to state change. Token copy now uses the
existing asset usage collector for image and variable-backed font
dependencies. CSS parsing, declaration mapping, variable traversal,
breakpoint matching, asset import/remapping, copy naming, and
Builder/MCP token mutation also have shared owners. Fragment insertion
may reuse tokens and merge overflow breakpoints; token paste must always
create a numbered copy and report overflow. The regex-based rename path
remains for arbitrary authored text; token transfer uses syntax-aware
rewriting to avoid changing text outside `var()`. The asset collector
refactor changes no user-facing behavior. The follow-up parser fixes
keep fallback variables, non-pixel breakpoint styles, and combined media
conditions, range syntax, negation, and width-condition operators intact
when copied. No documentation or fixture inputs changed. Focused token,
asset usage, HTML, and CSS parser tests, affected typechecks, lint,
formatting, package boundaries, and `git diff --check` passed. Agent
evaluations were offered and declined.
2026-11-09 15:10:49 +01:00

516 lines
14 KiB
TypeScript

import { toastError } from "../error/toast-error";
import {
$authTokenPermissions,
$textEditingInstanceSelector,
} from "../nano-states";
import { instanceText, instanceJson } from "./plugin-instance";
import {
pageText,
copyFolderData,
copyPageData,
copyTemplateData,
handlePastePage,
} from "./plugin-page";
import { html } from "./plugin-html";
import { jsx } from "./plugin-jsx";
import { markdown } from "./plugin-markdown";
import { webflow } from "./plugin-webflow/plugin-webflow";
import { designTokens } from "./plugin-design-tokens";
import { token, copyTokenData } from "./plugin-token";
import { builderApi } from "../builder-api";
import { readClipboardText } from "../clipboard";
import { $selectedInstance } from "../nano-states";
import { $dataSources, $instances, $resources } from "../sync/data-stores";
import { serverSyncStore } from "../sync/sync-stores";
import { findAvailableVariables } from "@webstudio-is/project-build/runtime";
import { validateDataVariableName } from "~/builder/shared/data-variable-utils";
import {
deserializeVariable,
isVariableClipboardData,
} from "./variable-clipboard";
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 text in a Builder panel, 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.
if (event.type === "copy") {
const isInBuilderContext = window.self === window.top;
const selection = window.getSelection();
if (isInBuilderContext && selection && selection.isCollapsed === false) {
return false;
}
}
return validateCopyPermission();
};
const validateCopyPermission = () => {
if ($authTokenPermissions.get().canCopy === false) {
toastError("Copying has been disabled by the project owner");
return false;
}
return true;
};
export type Plugin = {
name: string;
mimeType: string;
onCopy?: () => undefined | string | Promise<undefined | string>;
// Delete the source only after writeClipboard confirms the data was saved.
onCut?: (
writeClipboard: (data: string) => Promise<boolean>
) => undefined | Promise<undefined | string>;
onPaste?: (data: string) => PasteResult | Promise<PasteResult>;
};
export type PasteResult =
| { success: true; data: { handled: false } }
| { success: true; data: { handled: true } }
| { success: false; error: string };
export const pasteIgnored: PasteResult = {
success: true,
data: { handled: false },
};
export const pasteHandled: PasteResult = {
success: true,
data: { handled: true },
};
const isPasteHandled = (result: PasteResult) =>
result.success === false || result.data.handled;
const reportPasteResult = (result: PasteResult) => {
if (result.success === false) {
builderApi.toast.error(result.error);
}
};
const textMimeType = "text/plain";
const variableClipboard: Plugin = {
name: "variable",
mimeType: textMimeType,
onPaste: (text) => {
if (isVariableClipboardData(text) === false) {
return pasteIgnored;
}
const instance = $selectedInstance.get();
if (!instance) {
return pasteHandled;
}
try {
const copied = deserializeVariable(
text,
instance.id,
new Map(
findAvailableVariables({
startingInstanceId: instance.id,
instances: $instances.get(),
dataSources: $dataSources.get(),
}).map((variable) => [variable.id, variable])
)
);
const originalName = copied.variable.name;
let suffix = 2;
let error = validateDataVariableName(
copied.variable.name,
undefined,
instance.id
);
while (error?.type === "duplicate") {
copied.variable.name = `${originalName} ${suffix++}`;
error = validateDataVariableName(
copied.variable.name,
undefined,
instance.id
);
}
if (error) {
return { success: false, error: error.message };
}
if (copied.resource) {
copied.resource.name = copied.variable.name;
}
serverSyncStore.createTransaction(
[$dataSources, $resources],
(dataSources, resources) => {
dataSources.set(copied.variable.id, copied.variable);
if (copied.resource) {
resources.set(copied.resource.id, copied.resource);
}
}
);
return pasteHandled;
} catch (error) {
return {
success: false,
error:
error instanceof Error ? error.message : "Unable to paste variable",
};
}
},
};
const readClipboardData = (
mimeTypes: Array<string>,
clipboardData: null | DataTransfer
) => {
const dataByMimeType = new Map<string, string>();
for (const mimeType of mimeTypes) {
if (dataByMimeType.has(mimeType) === false) {
dataByMimeType.set(
mimeType,
clipboardData?.getData(mimeType).trim() ?? ""
);
}
}
return dataByMimeType;
};
let pasteClipboardText: undefined | ((text: string) => Promise<void>);
const registerPasteClipboardText = (
handler: (text: string) => Promise<void>,
signal: AbortSignal
) => {
pasteClipboardText = handler;
signal.addEventListener("abort", () => {
if (pasteClipboardText === handler) {
pasteClipboardText = undefined;
}
});
};
const validatePasteCommand = () => {
if ($textEditingInstanceSelector.get() != null) {
return false;
}
return validateCopyPermission();
};
const initPlugins = ({
plugins,
signal,
}: {
plugins: Array<Plugin>;
signal: AbortSignal;
}) => {
const handleCopy = (event: ClipboardEvent) => {
if (validateClipboardEvent(event) === false) {
return;
}
for (const { mimeType, onCopy } of plugins) {
const data = onCopy?.();
if (data instanceof Promise) {
event.preventDefault();
void data
.then((value) => {
if (value !== undefined) {
event.clipboardData?.setData(mimeType, value);
}
return writeClipboardText(value);
})
.catch(() =>
builderApi.toast.error(
"Could not prepare the selected content for copying."
)
);
break;
}
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 { onCut } of plugins) {
const operation = onCut?.(writeClipboardText);
if (operation !== undefined) {
event.preventDefault();
operation.catch(() => {
builderApi.toast.error("Could not cut the selected content.");
});
break;
}
}
};
const pasteData = async (dataByMimeType: Map<string, string>) => {
for (const { mimeType, onPaste } of plugins) {
if (onPaste === undefined) {
continue;
}
const data = dataByMimeType.get(mimeType);
if (data === undefined || data === "") {
continue;
}
const result = await onPaste(data);
if (isPasteHandled(result)) {
reportPasteResult(result);
break;
}
}
};
const handlePaste = async (event: ClipboardEvent) => {
if (validateClipboardEvent(event) === false) {
return;
}
event.preventDefault();
await pasteData(
readClipboardData(
plugins.map((plugin) => plugin.mimeType),
event.clipboardData
)
);
};
const handlePasteText = async (text: string) => {
if (validatePasteCommand() === false) {
return;
}
await pasteData(new Map([[textMimeType, text.trim()]]));
};
document.addEventListener("copy", handleCopy, { signal });
document.addEventListener("cut", handleCut, { signal });
// 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, signal });
registerPasteClipboardText(handlePasteText, signal);
};
export const initCopyPaste = ({ signal }: { signal: AbortSignal }) => {
initPlugins({
plugins: [
variableClipboard,
token,
pageText,
instanceJson,
instanceText,
designTokens,
jsx,
html,
markdown,
webflow,
],
signal,
});
};
export const initCopyPasteForContentEditMode = ({
signal,
}: {
signal: AbortSignal;
}) => {
const showUnsupportedCopyMessage = () => {
builderApi.toast.info("This selection cannot be copied here.");
};
const showUnsupportedPasteMessage = () => {
builderApi.toast.info("This clipboard data cannot be pasted here.");
};
const showCutDesignModeOnlyMessage = () => {
builderApi.toast.info("Cutting is allowed in design mode only.");
};
const handleCopy = (event: ClipboardEvent) => {
if (validateClipboardEvent(event) === false) {
return;
}
const data = instanceText.onCopy?.();
if (data instanceof Promise) {
event.preventDefault();
void data
.then((value) => {
if (value !== undefined) {
event.clipboardData?.setData(instanceText.mimeType, value);
}
return writeClipboardText(value);
})
.catch(() => undefined);
return;
}
if (data) {
event.preventDefault();
event.clipboardData?.setData(instanceText.mimeType, data);
return;
}
showUnsupportedCopyMessage();
};
const handlePaste = async (event: ClipboardEvent) => {
if (validateClipboardEvent(event) === false) {
return;
}
const dataByMimeType = readClipboardData(
[instanceJson.mimeType, instanceText.mimeType],
event.clipboardData
);
const jsonData = dataByMimeType.get(instanceJson.mimeType);
if (jsonData) {
event.preventDefault();
const result = await instanceJson.onPaste(jsonData);
if (isPasteHandled(result)) {
reportPasteResult(result);
return;
}
showUnsupportedPasteMessage();
return;
}
const textData = dataByMimeType.get(instanceText.mimeType);
if (textData) {
event.preventDefault();
const result = await instanceText.onPaste(textData);
if (isPasteHandled(result)) {
reportPasteResult(result);
return;
}
showUnsupportedPasteMessage();
return;
}
showUnsupportedPasteMessage();
};
const handlePasteText = async (text: string) => {
if (validatePasteCommand() === false) {
return;
}
const textData = text.trim();
if (textData === "") {
showUnsupportedPasteMessage();
return;
}
const result = await instanceText.onPaste(textData);
if (isPasteHandled(result)) {
reportPasteResult(result);
return;
}
showUnsupportedPasteMessage();
};
const handleCut = (event: ClipboardEvent) => {
if (validateClipboardEvent(event) === false) {
return;
}
showCutDesignModeOnlyMessage();
};
document.addEventListener("copy", handleCopy, { signal });
document.addEventListener("cut", handleCut, { signal });
// 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,
signal,
});
registerPasteClipboardText(handlePasteText, signal);
};
const writeClipboardText = async (
data: string | undefined | Promise<string | undefined>
) => {
data = await data;
if (data && validateCopyPermission()) {
await navigator.clipboard.writeText(data);
return true;
}
return false;
};
// Public API for programmatic copy/paste/cut operations
export const copyInstance = () => {
return writeClipboardText(instanceText.onCopy?.());
};
export const copyToken = async (tokenId: string) =>
writeClipboardText(copyTokenData(tokenId));
export const pasteToken = async (data: string) => {
const result = await token.onPaste?.(data);
if (result !== undefined) {
reportPasteResult(result);
}
};
export const copyPage = (pageId: string) => {
return writeClipboardText(copyPageData(pageId));
};
export const copyFolder = (folderId: string) => {
return writeClipboardText(copyFolderData(folderId));
};
export const copyTemplate = (templateId: string) => {
return writeClipboardText(copyTemplateData(templateId));
};
export const pastePage = async (targetFolderId?: string) => {
const text = await readClipboardText();
if (text === undefined) {
return false;
}
const result = await handlePastePage(text, targetFolderId);
reportPasteResult(result);
return isPasteHandled(result);
};
export const emitPaste = async () => {
const text = await readClipboardText();
if (text === undefined) {
return;
}
await pasteClipboardText?.(text);
};
export const cutInstance = async () => {
await instanceText.onCut?.(writeClipboardText);
};