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.
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-09 15:10:49 +01:00
1 parent ee277769ff
commit 1b9ae61fa1
51 files changed
+3825 -267

No files matched your search

+63 -37
View File
@@ -247,9 +247,9 @@ const preserveOriginalVarLonghands = (
);
}
// Recover unresolved var()->longhand mapping when shorthand expansion drops
// Recover var()->longhand mapping when shorthand expansion drops
// the var() token (e.g. outline/border cases that default to currentcolor).
for (const varText of getFallbacklessVarTexts(value)) {
for (const varText of getVarTexts(value)) {
const varName = getVarNameFromVarText(varText);
if (varName === undefined) {
continue;
@@ -298,17 +298,14 @@ const preserveOriginalVarLonghands = (
return serialized.includes('"type":"var"') || serialized.includes("var(");
});
const firstFallbacklessVarText = getFallbacklessVarTexts(value)[0];
const firstVarText = getVarTexts(value)[0];
if (firstFallbacklessVarText !== undefined) {
if (firstVarText !== undefined) {
for (const [prop, styleValue] of parsedCss) {
if (styleValue.type !== "invalid") {
continue;
}
parsedCss.set(
prop,
parseCssValueLonghand(prop, firstFallbacklessVarText)
);
parsedCss.set(prop, parseCssValueLonghand(prop, firstVarText));
}
}
@@ -318,12 +315,9 @@ const preserveOriginalVarLonghands = (
// When no var() survived at all, keep the first unresolved var() on all
// parsed longhands so authored references are not lost.
if (!hasAnyPreservedVar) {
if (firstFallbacklessVarText !== undefined) {
if (firstVarText !== undefined) {
for (const prop of parsedCss.keys()) {
parsedCss.set(
prop,
parseCssValueLonghand(prop, firstFallbacklessVarText)
);
parsedCss.set(prop, parseCssValueLonghand(prop, firstVarText));
}
}
}
@@ -395,7 +389,7 @@ const getSingleFallbacklessVarText = (value: string): string | undefined => {
}
};
const getFallbacklessVarTexts = (value: string): string[] => {
const getVarTexts = (value: string): string[] => {
try {
const ast = csstree.parse(value, { context: "value" });
const vars: string[] = [];
@@ -408,7 +402,7 @@ const getFallbacklessVarTexts = (value: string): string[] => {
return;
}
const parsedVar = parseCssVar(fnNode);
if (!parsedVar || parsedVar.fallback !== undefined) {
if (!parsedVar) {
return;
}
vars.push(csstree.generate(fnNode));
@@ -422,7 +416,7 @@ const getFallbacklessVarTexts = (value: string): string[] => {
};
const getVarNameFromVarText = (varText: string): string | undefined => {
const match = varText.trim().match(/^var\(\s*(--[\w-]+)\s*\)$/);
const match = varText.trim().match(/^var\(\s*(--[\w-]+)/);
return match?.[1];
};
@@ -713,10 +707,11 @@ export type ParseCssResult = {
* to be resolved together as if they apply to the same element.
*/
export const extractCssCustomProperties = (
css: string
css: string,
parsedAst?: csstree.CssNode
): Map<string, string> => {
const map = new Map<string, string>();
const ast = cssTreeTryParse(css);
const ast = parsedAst ?? cssTreeTryParse(css);
if (ast === undefined) {
return map;
}
@@ -738,9 +733,16 @@ export const extractCssCustomProperties = (
export const parseCss = (
css: string,
cssVars: Map<string, string>
cssVars: Map<string, string>,
// Callers may reuse a css-tree AST parsed with positions: true.
parsedAst?: csstree.CssNode,
options: {
preserveShorthandVariables?: boolean;
preserveNonPixelWidth?: boolean;
parseSelector?: (selector: csstree.Selector) => Selector;
} = {}
): ParseCssResult => {
const ast = cssTreeTryParse(css);
const ast = parsedAst ?? cssTreeTryParse(css);
const stylesMap = new Map<string, ParsedStyleDecl>();
const errors: string[] = [];
@@ -756,6 +758,7 @@ export const parseCss = (
// border-color: rgb(x y z / var(--op)); --op: 0.6;
// resolve correctly regardless of declaration order.
const customProperties = new Map<string, string>();
const emptyCustomProperties = new Map<string, string>();
const collectRuleCustomProperties = (rule: csstree.Rule) => {
customProperties.clear();
@@ -833,6 +836,7 @@ export const parseCss = (
if (
node.type === "Dimension" &&
node.unit !== "px" &&
options.preserveNonPixelWidth !== true &&
(currentFeatureName === "min-width" ||
currentFeatureName === "max-width")
) {
@@ -870,6 +874,10 @@ export const parseCss = (
if (node.type !== "Selector") {
continue;
}
if (options.parseSelector !== undefined) {
selectors.push(options.parseSelector(node));
continue;
}
let selector: Selector | undefined = undefined;
const children = node.children.toArray();
const startsWithNesting = children[0]?.type === "NestingSelector";
@@ -898,14 +906,14 @@ export const parseCss = (
case "PseudoClassSelector": {
// First pseudo selector is not a state but an element selector, e.g. :root
if (selector) {
state = `:${childNode.name}`;
state = csstree.generate(childNode);
} else {
name = `:${childNode.name}`;
name = csstree.generate(childNode);
}
break;
}
case "PseudoElementSelector":
state = `::${childNode.name}`;
state = csstree.generate(childNode);
break;
case "Combinator":
// " " vs " > "
@@ -917,7 +925,7 @@ export const parseCss = (
if (selector) {
selector.name += name;
if (state) {
selector.state = state;
selector.state = `${selector.state ?? ""}${state}`;
}
} else {
selector = { name, state };
@@ -943,15 +951,26 @@ export const parseCss = (
const substituted = substituteVarsInShorthand(
property,
stringValue,
customProperties,
options.preserveShorthandVariables
? emptyCustomProperties
: customProperties,
cssVars
);
if (substituted !== undefined) {
parsedCss = substituted.result;
for (const varName of substituted.droppedVars) {
errors.push(
`"${property}" was not applied because ${varName} could not be resolved`
);
parsedCss =
options.preserveShorthandVariables && stringValue.includes("var(")
? preserveOriginalVarLonghands(
property,
stringValue,
substituted.result
)
: substituted.result;
if (!options.preserveShorthandVariables) {
for (const varName of substituted.droppedVars) {
errors.push(
`"${property}" was not applied because ${varName} could not be resolved`
);
}
}
} else {
parsedCss = parseCssValue(property, stringValue);
@@ -1168,7 +1187,8 @@ type ParsedBreakpoint = {
};
export const parseMediaQuery = (
mediaQuery: string
mediaQuery: string,
options: { preserveNonPixelWidth?: boolean } = {}
): undefined | ParsedBreakpoint => {
const ast = csstree.parse(mediaQuery, { context: "mediaQuery" });
let minWidth: undefined | number;
@@ -1196,12 +1216,18 @@ export const parseMediaQuery = (
otherFeatures.push(cleaned);
}
}
if (node.type === "Dimension" && node.unit === "px") {
const value = Number(node.value);
if (currentWidthProperty === "minWidth") {
minWidth = value;
} else if (currentWidthProperty === "maxWidth") {
maxWidth = value;
if (node.type === "Dimension" && currentWidthProperty !== undefined) {
if (node.unit === "px") {
const value = Number(node.value);
if (currentWidthProperty === "minWidth") {
minWidth = value;
} else {
maxWidth = value;
}
} else if (options.preserveNonPixelWidth) {
const property =
currentWidthProperty === "minWidth" ? "min-width" : "max-width";
otherFeatures.push(`${property}:${node.value}${node.unit}`);
}
currentWidthProperty = undefined;
}