mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
feat: Add global styles with Tag styles (#6666)
## What this adds A developer can style an HTML tag once and have that style apply across every page, including content imported into Content Blocks. The selected element's matching **Tag style** appears first in Style Sources. Its chip is temporary; its saved styles remain global. ## Plan and todos 1. [x] Add a distinct `tag` style source with a fixed tag and ID. Create it on the first edit, without a migration or instance attachment. 2. [x] Emit Tag style CSS in the canvas and published output after presets and before instance styles. Keep normal CSS specificity and source order. Include global styles when collecting page assets. 3. [x] Show only the selected element's Tag style in the picker. Keep its temporary chip first and fixed, and identify it in the property source tooltip. 4. [x] Support scoped descendant tag selectors in ordinary tokens, while limiting Tag styles to states of their own tag. 5. [x] Regenerate the runtime contract and cover CSS output, selector validation, runtime updates, and style provenance with focused tests. 6. [x] Revalidate and version the eight stored fixture bundles for the renamed source type, then rerun fixture checks. 7. [x] Use the raw lowercase tag name as the Tag style label, use a singular picker heading, and fix scoped tag-state preview so only matching descendants are highlighted. 8. [x] Let Global root select and edit the `html` Tag style with the same temporary, fixed-first behavior as other tags. 9. [x] Name the feature Tag styles in the UI and code, and replace the draft-only saved type and ID. 10. [x] Rebase onto `main`, keep the publish CSS validation integration working, and move the PR to `5657.staging`. 11. [x] Review the new PR's CI and staging deployment. 12. [x] Make Tag styles discoverable through MCP, verify the existing edit path, and add focused coverage. 13. [x] Update Tag styles product docs and add paired light/dark screenshots. 14. [x] Pin the visual regression runner to supported Ubuntu and review the visual diff. 15. [x] Make the selected Tag style source distinct from unselected tokens in dark mode, review both themes, and refresh documentation screenshots. 16. [x] Copy and paste Tag styles through the style source menu, merging declarations into the matching tag with pasted values winning. 17. [x] Copy and paste Local styles into the selected instance’s Local source, merge with pasted declarations winning, and share one source-transfer command pair with Tag styles. 18. [x] Adjust the compact MCP schema size budget for the new source type input, then rerun the CLI schema test and CI. 19. [x] Add Tag style to the shared design-system style-source color and label variants, and use its shared color in the Builder. 20. [x] Restore the style source and input colors from `main`; use the Slot global color for Tag styles in Builder and design-system variants; refresh and review paired documentation screenshots. 21. [x] Monitor CI for `aba723fc0a` to completion. 22. [x] Address the four canvas cascade and live-preview review comments, add focused regression coverage, and verify the Builder and published CSS agree. 23. [x] Review documentation impact and monitor CI for the review fixes. 24. [x] Normalize the HTTP client paste-style-source result for Token clipboard data, preserve paste-design-token, and verify both response shapes. 25. [x] Use `tag` for Style panel items and verify the picker and menu. 26. [x] Check CI for the Style panel rename. 27. [x] Use `tag` across saved Tag style records, Builder items, and CLI and MCP inputs and results. Keep existing Tag style IDs and the CSS clipboard format. 28. [x] Regenerate runtime contracts and MCP docs, refresh fixture bundle versions, and verify the updated schema, CSS, and transfers. 29. [x] Check CI for the saved style source rename. 30. [x] Fix Select option descriptions clipping in narrow menus, allow wrapped descriptions to grow vertically, and review documentation impact (no docs update needed). 31. [x] Fix marketplace consent checkbox vertical alignment and keep checked and unchecked dimensions identical; add both states to Storybook and review documentation impact (no docs update needed). 32. [x] Resolve Tag-style review comments for selected-state cascade preview, active-state discovery, and html Tag CSS-variable clipboard dependencies. 33. [x] Describe Copy for Tag styles, disable copying empty sources, and keep the style source menu width stable while descriptions change. 34. [x] Increase the splash screen logo-to-progress gap by 8px in total. 35. [x] Align the style source menu to the chip’s left edge when space allows, and determine Copy availability from all saved declarations. 36. [x] Keep arrow-key navigation inside the open style source menu so it does not toggle the combobox. 37. [x] Move focus left and right across source chips, input, and Local at the matching caret boundaries. 38. [x] Preserve instance-style precedence while previewing ephemeral Tag-state edits. 39. [x] Synchronize temporary Tag style selection to the canvas so saved Tag-state previews render. 40. [x] Keep the selected Tag style in autocomplete and ensure keyboard events reach the combobox once. 41. [x] Show a 1px keyboard focus outline one pixel outside each style source chip, and open the focused source’s menu with Arrow Down. 42. [x] Preserve Tag-state preview precedence across breakpoints and include matching Tag states without requiring the temporary chip. 43. [x] Rename the autocomplete section labels to “Tag” and “Tokens.” 44. [x] Return focus to the input when Escape closes a style source menu. 45. [x] Rename Tag style color recipe and design-system variant keys from `tagStyle` to `tag`. 46. [x] Review and simplify style-source changes while preserving keyboard behavior. 47. [x] Simplify style source menu alignment offset arguments to numbers. 48. [x] Import React’s `KeyboardEvent` type directly without an alias. ## Deferred and blocked - **Agent evaluations:** Repository guidance requires separate approval before running them. ## Technical choices and compatibility Tag styles use the same global purple and contrasting text as Slot outlines. The style source field, inactive chips, and their hover behavior match `main`; the earlier neutral color experiments in this PR are superseded. Tag styles are saved with `type: "tag"` and an ID such as `tag-style:button`. Projects from released versions need no migration. Draft development records with `type: "tagStyle"` are incompatible with this revision. They emit CSS even when no instance uses them. Ordinary tokens still need an instance selection and can target descendants such as `.card p`. The CSS cascade decides conflicts; there is no custom priority rule. Token, Tag, and Local styles share the existing `copy-design-token` and `paste-design-token` MCP/CLI commands. Copy accepts `styleSourceId` and `sourceType` (`token`, `tag`, or `local`). The older `tokenId` input remains valid. The CSS clipboard payload identifies the source type on paste. Tokens still create a numbered copy. Tag styles merge into the matching global tag, and Local styles merge into the selected instance’s Local source, creating it when needed. Pasted declarations win for matching properties, states, and breakpoints. All three share asset and breakpoint transfer. The original Tag style feature added about 435 net non-test lines. This follow-up reuses the Token transfer path for Tag and Local styles and adds no new MCP/CLI commands. Older clients that do not recognize the new source type may need to update before editing a project that contains Tag styles. ## Verification - Imported React’s `KeyboardEvent` type directly; no alias is needed. Oxfmt and `git diff --check` passed. - Replaced `Pick<DOMRect, "left">` alignment-helper inputs with `number`, and updated the existing focused assertion. Oxfmt and `git diff --check` passed; tests were not run locally. - Style-source simplification reviewed by a Sol medium subagent: consolidated duplicate input arrow checks, removing 13 non-test lines. Oxfmt and `git diff --check` passed; tests were not run locally. - On `2a11120b69`: renamed Tag color recipe and Label/NestedIconLabel variant keys from `tagStyle` to `tag` without changing colors. The focus outline is 1px, offset outside the chip. Oxfmt and `git diff --check` passed; CI is running. - On `80803a5094`: moved the source chip focus outline one pixel outside its bounds and return focus to the input when Escape closes its menu. Oxfmt and `git diff --check` passed. Tests were not run locally; CI is running. - On `55681dda89`: formatted the keyboard handler with Oxfmt after CI caught the line wrap; `pnpm dlx oxfmt@0.58.0` and `git diff --check` passed. Tests were not run locally. - On `3b00225d33`: arrow navigation now traverses source chips in both directions, with the input between global sources and Local. `git diff --check` passed; local tests were not run. No documentation update is needed. - On `256ad1e797`: increased the splash logo-to-progress distance by another 4px (8px total from the original spacing). `git diff --check` passed. No documentation or tests changed. - On `4167ba4b85`: moved the keyboard focus ring from the inner label button to the full source chip edge. `git diff --check` passed; local formatting was unavailable because this worktree has no installed `oxfmt` executable. No documentation or tests changed. - On `4167ba4b85`: moved the keyboard focus ring from the inner label button to the full source chip edge. `git diff --check` passed; formatting was unavailable because this worktree has no installed `oxfmt` executable. No docs or tests are affected. - Passed on `3b4a2bc3ce`: style-source input tests (10), formatting, and diff checks. The autocomplete section labels now read “Tag” and “Tokens.” - Passed on `bb2c60d3e4`: canvas style tests (65), formatting, and diff checks. Tag state previews use lower selector specificity than instance styles across breakpoints, and matching Tag states participate even when the temporary Tag chip is absent. The full Builder typecheck uses a local shared dependency tree with unrelated stale color-variable declarations; CI is rerunning. - Passed on `7bac6f25cb`: style-source input tests (10), formatting, and diff checks. Keyboard focus now has a visible ring, and Arrow Down opens the focused source menu, including on an unselected source. - Passed on `11df83f889`: style-source input tests (10), formatting, and diff checks. Arrow-key autocomplete now retains the selected Tag style ahead of Tokens; the combobox key handler runs once per input event. The local Builder typecheck has only the pre-existing shared color-variable declaration errors; CI is rerunning. - Passed on `10060fac6c`: sync-store tests (15), formatting, and diff checks. Temporary Tag style selection now synchronizes to the canvas for saved-state previews. - Passed on `b775384f2f`: Builder canvas/style-source tests (75), formatting, and diff checks. Ephemeral Tag-state edits now respect the effective source reported by the style model when an instance declaration overrides them. CI is running. - Passed on `87d5f0529e`: style source input/menu tests (12), formatting, and diff checks. Arrow-key focus moves between the input, last global source, and Local source; open menu arrow keys no longer bubble to the outer combobox. CI is running. - Passed on `1e34af257f`: Builder style source menu tests (10), formatting, and diff checks. Menu aligns to the chip’s left edge, with viewport collision handling retained. Copy availability now checks saved declarations across states and breakpoints. CI is running. - Passed on `699bd8ee81`: formatting and diff checks. Increased the logo-to-progress gap by 4px using the next spacing token. CI is running. - Passed on `af8affb589`: style source menu browser tests (6), formatting, and diff checks. Copy now has a focused description, is disabled without declarations, and the menu keeps its 176px width when the description changes. CI is running. - Passed on `1485781bca`: focused HTTP-client tests (52), project-build token-transfer tests (27), and Builder canvas tests (67); formatting and diff checks passed. CI is running. Local HTTP-client typecheck passed. Project-build and Builder typechecks could not complete because the temporary shared `node_modules` links resolved workspace packages incompletely; errors were missing package exports/dependencies and color variable declarations. - Passed on `bae690edc4` (with Select fix `b1e49b1cfd`): checkbox browser regression (both states remain 14×14 px and align to the first label line), design-system and Builder typechecks, focused lint and formatting, and diff check. Reviewed the checked and unchecked Storybook example in light and dark themes. Docs review found no user-facing documentation change needed; no fixture inputs or outputs are affected. - Passed on `b1e49b1cfd`: the focused Select description browser regression passed in light and dark themes (2 tests); design-system and Builder typechecks, focused lint and formatting, and diff check passed. Reviewed the narrow Select dropdown story in both themes; the description wraps without clipping. Docs review found no user-facing documentation update needed. - CI on `ba274d0dec` passed, including Linux and Windows fixture sync and builds, staging and development deployments, and all ten Builder browser shards. Shard 6 passed on retry after Chromium failed to start in the original run. The approved visual rerun passed after comparison with `6f2404d987` confirmed all 272 story results and all 549 screenshots were identical. - Passed on `ba274d0dec`: focused SDK (14), project-build (353), Builder (78), CLI (168), protocol (15), and HTTP-client (51) tests. Builder, SDK, project-build, protocol, CLI, and MCP docs typechecks passed. The HTTP-client typecheck passed with an unrelated local test edit excluded. The SDK test for `type: "tag"` failed with the earlier schema and passed with the updated schema. Generated contracts and MCP docs, focused lint and formatting, package boundaries, and diff check passed. All eight validated bundles use `bundle-1u9ug3c`, and all eight local fixture builds passed. - CI on `6f2404d987`: 34 latest checks passed and 4 were skipped, including all ten Builder browser shards and the approved visual comparison. The five previously approved visual differences had identical screenshots. - Passed on `6f2404d987`: 16 focused Builder browser tests, Builder typecheck, focused lint and formatting, package boundaries, and diff check. Only the Style panel item value changes. No documentation, fixture, clipboard, or saved project changes. - Passed on `aba723fc0a`: design-system and Builder type checks, focused lint and formatting, package boundaries, and diff check. Restored main's field and inactive source colors; Tag styles now use Slot's `--background-accent-secondary` and matching foreground. Refreshed and reviewed the paired light/dark source screenshots; the menu screenshots were unchanged. All 51 check runs completed; the approved visual comparison and all ten Builder browser shards passed. The earlier unapproved visual comparison showed the intended color changes. - Passed on `bd39fb09e5`: Builder typecheck, focused lint and format, package boundaries, and diff check. The style source field keeps its default 8% neutral fill while no longer following the theme surface-contrast slider, so the track (4%), field (8%), chip hover (about 10%), and selected Tag style (14% light / 22% dark) stay ordered. The default-theme docs screenshots remain accurate; no documentation text changed. All CI checks completed. The approved visual comparison passed with the same six differences as the prior revision; all ten Builder browser shards passed after two shards were retried for CI Chromium startup errors. - Passed on `5c782e8d09`: design-system and Builder type checks, focused lint and formatting, package boundaries, and diff check. The shared Tag color now drives the Builder chip and label variants. Documentation review found no product behavior or screenshot change; the palette story now shows Tag. All 49 CI check runs completed: the approved visual rerun and all ten Builder browser shards passed. The initial unapproved visual comparison reported the expected story changes before approval. - Passed on `091dea695c`: Builder and design-system type checks, lint, package boundaries, formatting, and Storybook inspection of idle, hover, and selected sources in both themes. Refreshed the light docs screenshot; the dark idle screenshot is unchanged. - On `53826757d6`, CI completed: 43 passed, 5 skipped, and one superseded visual run was cancelled. The approved visual check and all ten Builder browser shards passed. - Passed on `53826757d6`: design-system and Builder type checks, lint, package boundaries, formatting, and paired light/dark Storybook inspection. The light screenshot is unchanged; the dark screenshot was refreshed. - Passed on `50bc57eb70`: the focused 11-test CLI schema file, formatting, and diff checks. The MCP handshake is 224,046 bytes with the three source type options; the budget is now 224,500 bytes. - Passed on `3c38222811`: focused runtime (270), Builder (3), CLI (5), and HTTP client (51) tests; five package type checks; lint; package boundaries; generated API and docs checks. The paired light/dark screenshots were reviewed. Local fixture inputs and outputs are unchanged by this follow-up. - Passed: workspace type checks, lint, package boundaries, generated contract regeneration, focused SDK/CSS-data/runtime/Builder tests, token-transfer and copy/paste tests, all local fixture builds, and fixture bundle tests. - Passed: CLI prebuild suite (152 tests) and the 54-test publish validation file after fixing its fixture. - Blocked: remote fixture sync reports a bundle-version mismatch against the development API. Agent evaluations require separate approval. - Passed on `38d1705f8a`: Builder app, project-build, CLI, core, and package CI suites; all ten Builder browser shards; Linux and Windows fixture checks; visual regression; and staging/development builds. Oxfmt and `git diff --check` passed locally. Local Vitest was unavailable because this worktree has no installed `node_modules`. Ref #5657 - Rebased onto `main` at `0589b18ce` and moved to `5657.staging`. Focused checks, five package type checks, generated API, lint, formatting, and package boundaries passed locally. On `9e38ff743b`, 38 CI checks passed, one was skipped, and visual regression found the intended Tag style color change. Staging deployment and all ten browser test shards passed. A focused Tag style story and paired light/dark documentation screenshots were reviewed. - MCP discovery and edit support passed focused project-build, protocol, CLI, type, lint, and generated-doc checks locally. The missing runtime cutover and HTTP client entries were fixed; both package suites now pass on the latest commit. - Tag styles docs now explain global application, temporary source selection, states, and CSS cascade. Two paired screenshots show the source and states menu; Storybook rendering, Builder typecheck, formatting, and relative links passed. Visual regression now passes on Ubuntu 24.04 with the reviewed change approved. - On `a8a3c27423`, all 44 CI checks completed: 39 passed and 5 were skipped. Visual regression and all ten Builder browser shards passed. Replaces #6663. - Review fixes on `f9af16d063`: canvas root presets now yield to `html` Tag styles; responsive Tag styles no longer displace instance styles in the style model; selected Tag states and descendant selectors update during live edits. The existing Tag styles documentation needs no change for these bug fixes. Builder focused tests (133), SDK CSS tests (11), Builder typecheck, lint, formatting, and diff checks passed locally. Each new regression test was verified against the old behavior. No fixture inputs or outputs changed. CI completed on `f9af16d063`: 35 latest checks passed and 3 were skipped, including all ten Builder browser shards and the approved visual check. 49. [x] Move the Tag and Token focus outline to the chip edge; no documentation update is needed. 50. [x] Return focus to the style source input when Escape closes its autocomplete; no documentation update is needed. 51. [x] Return focus to the style source input when Escape closes a source chip menu; no documentation update is needed. 52. [x] Add a regression test that Escape in a style source chip menu returns focus to the input; no documentation update is needed. 53. [x] Avoid duplicating an html Tag's own variables as root dependencies when copying it. 54. [x] Exclude descendant selectors from active-state matching. 55. [x] Preserve Tag state preview specificity over base styles and instance state precedence during saved and ephemeral previews. 56. [x] Restore the style source dropdown's default Radix placement from main; remove the custom chip offset.
This commit is contained in:
1 parent
112505e854
commit
2b9ce760bb
92 files changed
+3907
-356
No files matched your search
@@ -22,6 +22,7 @@ import {
|
||||
$selectedInstancePathWithRoot,
|
||||
$selectedBreakpointId,
|
||||
$selectedStyleState,
|
||||
$temporaryTagStyleId,
|
||||
selectInstance,
|
||||
$virtualInstances,
|
||||
} from "~/shared/nano-states";
|
||||
@@ -123,7 +124,11 @@ export const PropertyInfo = ({
|
||||
: undefined;
|
||||
if (styleSource) {
|
||||
const styleSourceName =
|
||||
styleSource.type === "token" ? styleSource.name : "Local";
|
||||
styleSource.type === "token"
|
||||
? styleSource.name
|
||||
: styleSource.type === "tag"
|
||||
? styleSource.tag
|
||||
: "Local";
|
||||
if (source.state) {
|
||||
const stateLabel =
|
||||
meta?.states?.find((item) => item.selector === source.state)?.label ??
|
||||
@@ -156,6 +161,9 @@ export const PropertyInfo = ({
|
||||
}
|
||||
selectInstance(target.instanceSelector);
|
||||
if (source.styleSourceId) {
|
||||
if (styleSources.get(source.styleSourceId)?.type === "tag") {
|
||||
$temporaryTagStyleId.set(source.styleSourceId);
|
||||
}
|
||||
selectStyleSource(source.styleSourceId, source.state);
|
||||
} else {
|
||||
$selectedStyleState.set(source.state);
|
||||
@@ -178,7 +186,13 @@ export const PropertyInfo = ({
|
||||
key: `style:${label}`,
|
||||
label,
|
||||
source,
|
||||
color: label === "Local" ? ("local" as const) : ("token" as const),
|
||||
color:
|
||||
source.styleSourceId &&
|
||||
styleSources.get(source.styleSourceId)?.type === "tag"
|
||||
? ("tag" as const)
|
||||
: label === "Local"
|
||||
? ("local" as const)
|
||||
: ("token" as const),
|
||||
})),
|
||||
...Array.from(instanceSources, ([label, source]) => ({
|
||||
key: `instance:${label}`,
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
$props,
|
||||
$styles,
|
||||
$styleSourceSelections,
|
||||
$styleSources,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import {
|
||||
getComputedStyleDecl,
|
||||
@@ -133,12 +134,16 @@ const getDefinedStyles = ({
|
||||
matchingBreakpoints: matchingBreakpointsArray,
|
||||
styleSourceSelections,
|
||||
styles,
|
||||
tagStyleIds,
|
||||
instanceTags,
|
||||
}: {
|
||||
instancePath: InstancePath;
|
||||
metas: Map<string, WsComponentMeta>;
|
||||
matchingBreakpoints: Breakpoint["id"][];
|
||||
styleSourceSelections: StyleSourceSelections;
|
||||
styles: Styles;
|
||||
tagStyleIds: Map<string, string>;
|
||||
instanceTags: Map<Instance["id"], HtmlTags>;
|
||||
}) => {
|
||||
type Defined = {
|
||||
property: CssProperty;
|
||||
@@ -171,6 +176,15 @@ const getDefinedStyles = ({
|
||||
}
|
||||
}
|
||||
}
|
||||
const tag = instanceTags.get(instance.id);
|
||||
const tagStyleId = tag ? tagStyleIds.get(tag) : undefined;
|
||||
if (tagStyleId) {
|
||||
if (instance.id === startingInstanceSelector[0]) {
|
||||
instanceStyleSources.add(tagStyleId);
|
||||
} else {
|
||||
inheritedStyleSources.add(tagStyleId);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const styleDecl of styles.values()) {
|
||||
const property = hyphenateProperty(styleDecl.property);
|
||||
@@ -212,6 +226,7 @@ const getDefinedStyles = ({
|
||||
export const $styleObjectModel = computed(
|
||||
[
|
||||
$styles,
|
||||
$styleSources,
|
||||
$styleSourceSelections,
|
||||
$presetStyles,
|
||||
$instanceTags,
|
||||
@@ -221,6 +236,7 @@ export const $styleObjectModel = computed(
|
||||
],
|
||||
(
|
||||
styles,
|
||||
styleSources,
|
||||
styleSourceSelections,
|
||||
presetStyles,
|
||||
instanceTags,
|
||||
@@ -228,8 +244,15 @@ export const $styleObjectModel = computed(
|
||||
matchingBreakpoints,
|
||||
matchingStates
|
||||
): StyleObjectModel => {
|
||||
const tagStyleIds = new Map<string, string>();
|
||||
for (const source of styleSources.values()) {
|
||||
if (source.type === "tag") {
|
||||
tagStyleIds.set(source.tag, source.id);
|
||||
}
|
||||
}
|
||||
return {
|
||||
styles,
|
||||
tagStyleIds,
|
||||
styleSourceSelections,
|
||||
presetStyles,
|
||||
instanceTags,
|
||||
@@ -268,6 +291,8 @@ export const $computedStyleDeclarations = computed(
|
||||
matchingBreakpoints,
|
||||
styleSourceSelections,
|
||||
styles,
|
||||
tagStyleIds: model.tagStyleIds,
|
||||
instanceTags: model.instanceTags,
|
||||
});
|
||||
// In advanced mode we assume user knows the properties they need, so we don't need to show these.
|
||||
// @todo will be fully deleted https://github.com/webstudio-is/webstudio/issues/4871
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { enableMapSet } from "immer";
|
||||
import { expect, test, describe } from "vitest";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import type { StyleDecl } from "@webstudio-is/sdk";
|
||||
import {
|
||||
coreMetas,
|
||||
getTagStyleId,
|
||||
ROOT_INSTANCE_ID,
|
||||
type StyleDecl,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { $selectedStyleSources } from "~/shared/nano-states";
|
||||
import {
|
||||
$registeredComponentMetas,
|
||||
$selectedStyleSources,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$assets,
|
||||
$breakpoints,
|
||||
@@ -25,6 +33,7 @@ const {
|
||||
duplicateStyleSource,
|
||||
getComponentStates,
|
||||
reorderStyleSources,
|
||||
$availableStyleSources,
|
||||
} = __testing__;
|
||||
|
||||
enableMapSet();
|
||||
@@ -51,6 +60,23 @@ const setupSelectedBody = () => {
|
||||
selectInstance(["body"]);
|
||||
};
|
||||
|
||||
test("Global root offers only the html Tag style first", () => {
|
||||
setupSelectedBody();
|
||||
$registeredComponentMetas.set(new Map(Object.entries(coreMetas)));
|
||||
$styleSources.set(
|
||||
new Map([
|
||||
[getTagStyleId("p"), { type: "tag", id: getTagStyleId("p"), tag: "p" }],
|
||||
["token", { type: "token", id: "token", name: "Token" }],
|
||||
])
|
||||
);
|
||||
selectInstance([ROOT_INSTANCE_ID]);
|
||||
|
||||
expect($availableStyleSources.get().map(({ id }) => id)).toEqual([
|
||||
getTagStyleId("html"),
|
||||
"token",
|
||||
]);
|
||||
});
|
||||
|
||||
describe("getComponentStates", () => {
|
||||
test("returns predefined states for tag", () => {
|
||||
const result = getComponentStates({
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
type StyleDecl,
|
||||
type StyleSource,
|
||||
type StyleSourceToken,
|
||||
getTagStyleId,
|
||||
getTagFromStyleId,
|
||||
isTagStyleTag,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { type RenameStyleSourceError } from "@webstudio-is/project-build/runtime";
|
||||
import { type ItemSource, StyleSourceInput } from "./style-source";
|
||||
@@ -24,6 +27,7 @@ import {
|
||||
$selectedInstanceStyleSources,
|
||||
$selectedOrLastStyleSourceSelector,
|
||||
$selectedStyleState,
|
||||
$temporaryTagStyleId,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$styleSourceSelections,
|
||||
@@ -34,7 +38,11 @@ import { executeRuntimeMutation } from "~/shared/instance-utils/data";
|
||||
import { subscribe } from "~/shared/pubsub";
|
||||
import { $selectedInstance } from "~/shared/nano-states";
|
||||
import { $instanceTags } from "./shared/model";
|
||||
import { copyToken, pasteToken } from "~/shared/copy-paste/copy-paste";
|
||||
import {
|
||||
copyToken,
|
||||
copyReusableStyleSource,
|
||||
pasteStyleSource,
|
||||
} from "~/shared/copy-paste/copy-paste";
|
||||
import { builderApi } from "~/shared/builder-api";
|
||||
|
||||
// Declare command for this module
|
||||
@@ -105,7 +113,7 @@ const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {
|
||||
// style source may not exist in store which means
|
||||
// temporary generated local stye source was not applied yet
|
||||
const styleSource = styleSources.get(styleSourceId);
|
||||
if (styleSource === undefined || styleSource.type === "local") {
|
||||
if (styleSource?.type !== "token") {
|
||||
return;
|
||||
}
|
||||
const result = executeRuntimeMutation({
|
||||
@@ -171,7 +179,7 @@ const clearStyles = (styleSourceId: StyleSource["id"]) => {
|
||||
};
|
||||
|
||||
type SelectorConfig = {
|
||||
type: "state" | "pseudoElement";
|
||||
type: "state" | "pseudoElement" | "tag";
|
||||
selector: string;
|
||||
label: string;
|
||||
source: "native" | "component" | "custom";
|
||||
@@ -214,18 +222,29 @@ const getComponentStates = ({
|
||||
const allStateSelectors = new Set([...allStates, ...usedSelectors]);
|
||||
|
||||
const toConfig = (selector: string): SelectorConfig => ({
|
||||
type: isPseudoElement(selector) ? "pseudoElement" : "state",
|
||||
label: selector,
|
||||
type: selector.startsWith(" ")
|
||||
? "tag"
|
||||
: isPseudoElement(selector)
|
||||
? "pseudoElement"
|
||||
: "state",
|
||||
label: selector.trimStart(),
|
||||
selector,
|
||||
source: allStates.includes(selector) ? "native" : "custom",
|
||||
});
|
||||
|
||||
const states = Array.from(allStateSelectors)
|
||||
.filter(
|
||||
(state) => !isPseudoElement(state) && !componentStateSelectors.has(state)
|
||||
(state) =>
|
||||
!state.startsWith(" ") &&
|
||||
!isPseudoElement(state) &&
|
||||
!componentStateSelectors.has(state)
|
||||
)
|
||||
.map(toConfig);
|
||||
|
||||
const tagSelectors = Array.from(usedSelectors)
|
||||
.filter((selector) => selector.startsWith(" "))
|
||||
.map(toConfig);
|
||||
|
||||
const pseudoElements = Array.from(allStateSelectors)
|
||||
.filter(isPseudoElement)
|
||||
.map(toConfig);
|
||||
@@ -236,7 +255,12 @@ const getComponentStates = ({
|
||||
source: "component" as const,
|
||||
}));
|
||||
|
||||
return [...states, ...componentStatesConfig, ...pseudoElements];
|
||||
return [
|
||||
...states,
|
||||
...componentStatesConfig,
|
||||
...pseudoElements,
|
||||
...tagSelectors,
|
||||
];
|
||||
};
|
||||
|
||||
const $componentStates = computed(
|
||||
@@ -247,6 +271,7 @@ const $componentStates = computed(
|
||||
$styles,
|
||||
$selectedStyleState,
|
||||
$styleSourceSelections,
|
||||
$temporaryTagStyleId,
|
||||
],
|
||||
(
|
||||
selectedInstance,
|
||||
@@ -254,7 +279,8 @@ const $componentStates = computed(
|
||||
instanceTags,
|
||||
styles,
|
||||
selectedStyleState,
|
||||
styleSourceSelections
|
||||
styleSourceSelections,
|
||||
temporaryTagStyleId
|
||||
) => {
|
||||
if (selectedInstance === undefined) {
|
||||
return;
|
||||
@@ -262,12 +288,16 @@ const $componentStates = computed(
|
||||
const tag = instanceTags.get(selectedInstance.id);
|
||||
const meta = registeredComponentMetas.get(selectedInstance.component);
|
||||
|
||||
const instanceStyleSourceIds = new Set(
|
||||
styleSourceSelections.get(selectedInstance.id)?.values
|
||||
);
|
||||
if (temporaryTagStyleId) {
|
||||
instanceStyleSourceIds.add(temporaryTagStyleId);
|
||||
}
|
||||
return getComponentStates({
|
||||
predefinedStates: pseudoClassesByTag[tag ?? ""] ?? [],
|
||||
componentStates: meta?.states ?? [],
|
||||
instanceStyleSourceIds: new Set(
|
||||
styleSourceSelections.get(selectedInstance.id)?.values
|
||||
),
|
||||
instanceStyleSourceIds,
|
||||
styles: styles.values(),
|
||||
selectedStyleState,
|
||||
});
|
||||
@@ -289,7 +319,12 @@ const convertToInputItem = (
|
||||
): StyleSourceInputItem => {
|
||||
return {
|
||||
id: styleSource.id,
|
||||
label: styleSource.type === "local" ? "Local" : styleSource.name,
|
||||
label:
|
||||
styleSource.type === "local"
|
||||
? "Local"
|
||||
: styleSource.type === "tag"
|
||||
? styleSource.tag
|
||||
: styleSource.name,
|
||||
disabled: false,
|
||||
source: styleSource.type,
|
||||
locked: styleSource.type === "token" && styleSource.locked === true,
|
||||
@@ -297,19 +332,33 @@ const convertToInputItem = (
|
||||
};
|
||||
};
|
||||
|
||||
const $availableStyleSources = computed([$styleSources], (styleSources) => {
|
||||
const availableStylesSources: StyleSourceInputItem[] = [];
|
||||
for (const styleSource of styleSources.values()) {
|
||||
if (styleSource.type === "local") {
|
||||
continue;
|
||||
const $availableStyleSources = computed(
|
||||
[$styleSources, $selectedInstance, $instanceTags],
|
||||
(styleSources, selectedInstance, instanceTags) => {
|
||||
const availableStylesSources: StyleSourceInputItem[] = [];
|
||||
const tag = selectedInstance
|
||||
? instanceTags.get(selectedInstance.id)
|
||||
: undefined;
|
||||
if (tag && isTagStyleTag(tag)) {
|
||||
const id = getTagStyleId(tag);
|
||||
availableStylesSources.push(
|
||||
convertToInputItem(styleSources.get(id) ?? { type: "tag", id, tag }, [])
|
||||
);
|
||||
}
|
||||
availableStylesSources.push(convertToInputItem(styleSource, []));
|
||||
for (const styleSource of styleSources.values()) {
|
||||
if (styleSource.type !== "token") {
|
||||
continue;
|
||||
}
|
||||
availableStylesSources.push(convertToInputItem(styleSource, []));
|
||||
}
|
||||
return availableStylesSources;
|
||||
}
|
||||
return availableStylesSources;
|
||||
});
|
||||
);
|
||||
|
||||
export const StyleSourcesSection = () => {
|
||||
const [inputRef, setInputRef] = useState<HTMLInputElement | null>(null);
|
||||
const selectedInstance = useStore($selectedInstance);
|
||||
const instanceTags = useStore($instanceTags);
|
||||
const componentStates = useStore($componentStates);
|
||||
const availableStyleSources = useStore($availableStyleSources);
|
||||
const selectedInstanceStyleSources = useStore($selectedInstanceStyleSources);
|
||||
@@ -320,6 +369,21 @@ export const StyleSourcesSection = () => {
|
||||
$selectedOrLastStyleSourceSelector
|
||||
);
|
||||
|
||||
const selectedTag = selectedInstance
|
||||
? instanceTags.get(selectedInstance.id)
|
||||
: undefined;
|
||||
useEffect(() => {
|
||||
const temporaryId = $temporaryTagStyleId.get();
|
||||
if (
|
||||
temporaryId &&
|
||||
selectedTag &&
|
||||
temporaryId !== getTagStyleId(selectedTag)
|
||||
) {
|
||||
$temporaryTagStyleId.set(undefined);
|
||||
deselectMatchingStyleSource(temporaryId);
|
||||
}
|
||||
}, [selectedTag]);
|
||||
|
||||
// Subscribe to focusStyleSourceInput command
|
||||
useEffect(() => {
|
||||
const unsubscribe = subscribe("command:focusStyleSourceInput", () => {
|
||||
@@ -360,8 +424,13 @@ export const StyleSourcesSection = () => {
|
||||
selectedItemSelector={selectedOrLastStyleSourceSelector}
|
||||
componentStates={componentStates}
|
||||
onCreateItem={createStyleSource}
|
||||
onSelectAutocompleteItem={({ id }) => {
|
||||
addStyleSourceToInstance(id);
|
||||
onSelectAutocompleteItem={({ id, source }) => {
|
||||
if (source === "tag") {
|
||||
$temporaryTagStyleId.set(id);
|
||||
selectStyleSource(id);
|
||||
} else {
|
||||
addStyleSourceToInstance(id);
|
||||
}
|
||||
}}
|
||||
onDuplicateItem={(id) => {
|
||||
const newId = duplicateStyleSource(id);
|
||||
@@ -370,20 +439,32 @@ export const StyleSourcesSection = () => {
|
||||
}
|
||||
}}
|
||||
onCopyItem={(id) => {
|
||||
copyToken(id).catch(() => {
|
||||
const source = $styleSources.get().get(id);
|
||||
const type =
|
||||
source?.type ?? (getTagFromStyleId(id) ? "tag" : "local");
|
||||
const copy =
|
||||
type === "token"
|
||||
? copyToken(id)
|
||||
: copyReusableStyleSource(id, type);
|
||||
copy.catch(() => {
|
||||
builderApi.toast.error(
|
||||
"Could not prepare the selected content for copying."
|
||||
);
|
||||
});
|
||||
}}
|
||||
onPasteToken={pasteToken}
|
||||
onPasteStyleSource={pasteStyleSource}
|
||||
onConvertToToken={(id) => {
|
||||
convertLocalStyleSourceToToken(id);
|
||||
setEditingItem(id);
|
||||
}}
|
||||
onClearStyles={clearStyles}
|
||||
onDetachItem={(id) => {
|
||||
removeStyleSourceFromInstance(id);
|
||||
if (id === $temporaryTagStyleId.get()) {
|
||||
$temporaryTagStyleId.set(undefined);
|
||||
deselectMatchingStyleSource(id);
|
||||
} else {
|
||||
removeStyleSourceFromInstance(id);
|
||||
}
|
||||
}}
|
||||
onDeleteItem={(id) => {
|
||||
const styleSources = $styleSources.get();
|
||||
@@ -438,6 +519,7 @@ export const StyleSourcesSection = () => {
|
||||
};
|
||||
|
||||
export const __testing__ = {
|
||||
$availableStyleSources,
|
||||
clearStyles,
|
||||
convertLocalStyleSourceToToken,
|
||||
duplicateStyleSource,
|
||||
|
||||
@@ -11,8 +11,6 @@ const accentBackground = cssVar("--background-accent");
|
||||
const instanceBackground = `color-mix(in oklab, ${cssVar(
|
||||
"--background-primary"
|
||||
)} 86%, ${cssVar("--foreground-primary")})`;
|
||||
const tagBackground = rotateBoundedBackgroundHue(accentBackground, 150);
|
||||
const tagForeground = tagBackground;
|
||||
const breakpointBackground = rotateBoundedBackgroundHue(accentBackground, 60);
|
||||
const neutralBackground = `light-dark(
|
||||
${cssVar("--foreground-secondary")},
|
||||
@@ -35,9 +33,9 @@ export const styleSourceColors = {
|
||||
gradient: gradient(styleSourceColor.local.solid),
|
||||
},
|
||||
tag: {
|
||||
background: tagBackground,
|
||||
foreground: tagForeground,
|
||||
gradient: gradient(tagBackground),
|
||||
background: styleSourceColor.tag.background,
|
||||
foreground: styleSourceColor.tag.foreground,
|
||||
gradient: gradient(styleSourceColor.tag.background),
|
||||
},
|
||||
breakpoint: {
|
||||
background: breakpointBackground,
|
||||
|
||||
@@ -37,6 +37,7 @@ export const StyleSourceBadge = styled(Text, {
|
||||
},
|
||||
tag: {
|
||||
backgroundColor: styleSourceColors.tag.background,
|
||||
color: styleSourceColors.tag.foreground,
|
||||
},
|
||||
breakpoint: {
|
||||
backgroundColor: styleSourceColors.breakpoint.background,
|
||||
|
||||
@@ -100,6 +100,10 @@ const StyleSourceContainer = styled(Box, {
|
||||
color: cssVar("--foreground-on-accent"),
|
||||
...menuCssVars({ show: false }),
|
||||
"&:hover": menuCssVars({ show: true }),
|
||||
"&:has(button:focus-visible)": {
|
||||
outline: `1px solid ${cssVar("--border-focus")}`,
|
||||
outlineOffset: -1,
|
||||
},
|
||||
variants: {
|
||||
source: {
|
||||
local: {
|
||||
@@ -112,6 +116,7 @@ const StyleSourceContainer = styled(Box, {
|
||||
[menuTriggerGradientVar]: styleSourceColors.local.gradient,
|
||||
},
|
||||
tag: {
|
||||
color: styleSourceColors.tag.foreground,
|
||||
backgroundColor: styleSourceColors.tag.background,
|
||||
[menuTriggerGradientVar]: styleSourceColors.tag.gradient,
|
||||
},
|
||||
@@ -230,6 +235,8 @@ type StyleSourceControlProps = {
|
||||
onChangeValue: (value: string) => void;
|
||||
onChangeEditing: (isEditing: boolean) => void;
|
||||
onOpenMenu?: () => void;
|
||||
buttonRef?: (element: HTMLButtonElement | null) => void;
|
||||
onArrowToSource?: (direction: "left" | "right") => boolean;
|
||||
};
|
||||
|
||||
export const StyleSourceControl = ({
|
||||
@@ -250,6 +257,8 @@ export const StyleSourceControl = ({
|
||||
onChangeEditing,
|
||||
onSelect,
|
||||
onOpenMenu,
|
||||
buttonRef,
|
||||
onArrowToSource,
|
||||
}: StyleSourceControlProps) => {
|
||||
const showMenu = isEditing === false && isDragging === false;
|
||||
|
||||
@@ -279,7 +288,25 @@ export const StyleSourceControl = ({
|
||||
disabled={disabled || isEditing}
|
||||
isEditing={isEditing}
|
||||
tabIndex={-1}
|
||||
ref={buttonRef}
|
||||
onClick={onSelect}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key.startsWith("Arrow")) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
if (event.key === "ArrowDown" && showMenu && !disabled) {
|
||||
event.preventDefault();
|
||||
onOpenMenu?.();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!event.shiftKey &&
|
||||
(event.key === "ArrowLeft" || event.key === "ArrowRight") &&
|
||||
onArrowToSource?.(event.key === "ArrowLeft" ? "left" : "right")
|
||||
) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
{source === "local" ? (
|
||||
|
||||
+51
@@ -201,3 +201,54 @@ export const TokenMenu: StoryFn<typeof StyleSourceMenuComponent> = () => (
|
||||
states={[]}
|
||||
/>
|
||||
);
|
||||
|
||||
export const TagStyle = () => {
|
||||
const tagStyle: Item = {
|
||||
id: "tag-style-div",
|
||||
label: "div",
|
||||
source: "tag",
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [":hover"],
|
||||
};
|
||||
const token: Item = {
|
||||
id: "card-token",
|
||||
label: "card",
|
||||
source: "token",
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [],
|
||||
};
|
||||
const [value, setValue] = useState<Array<Item>>([tagStyle, token, localItem]);
|
||||
const [selectedItemSelector, setSelectedItemSelector] = useState<
|
||||
undefined | ItemSelector
|
||||
>({ styleSourceId: tagStyle.id });
|
||||
|
||||
return (
|
||||
<Flex
|
||||
css={{
|
||||
width: theme.sizes.sidebarWidth,
|
||||
padding: theme.spacing[5],
|
||||
boxSizing: "content-box",
|
||||
}}
|
||||
>
|
||||
<StyleSourceInputComponent
|
||||
inputRef={() => {}}
|
||||
css={{ width: theme.sizes.sidebarWidth }}
|
||||
items={getItems()}
|
||||
value={value}
|
||||
selectedItemSelector={selectedItemSelector}
|
||||
componentStates={[
|
||||
{ type: "state", selector: ":hover", label: ":hover" },
|
||||
{
|
||||
type: "state",
|
||||
selector: ":focus-visible",
|
||||
label: ":focus-visible",
|
||||
},
|
||||
]}
|
||||
onSelectItem={setSelectedItemSelector}
|
||||
onSort={setValue}
|
||||
/>
|
||||
</Flex>
|
||||
);
|
||||
};
|
||||
+393
-7
@@ -1,18 +1,26 @@
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { copyDesignToken } from "@webstudio-is/project-build/runtime";
|
||||
import { StyleSourceInput } from "./style-source-input";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import {
|
||||
copyDesignToken,
|
||||
copyStyleSourceTransfer,
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import {
|
||||
__testing__ as inputTesting,
|
||||
StyleSourceInput,
|
||||
} from "./style-source-input";
|
||||
import { StyleSourceMenu } from "./style-source-menu";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
test("pastes copied tokens through the token flow and leaves ordinary text to the input", () => {
|
||||
test("pastes copied Tokens and Tag styles while leaving ordinary text to the input", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const onPasteToken = vi.fn();
|
||||
const onPasteStyleSource = vi.fn();
|
||||
const tokenData = copyDesignToken(
|
||||
{
|
||||
assets: new Map(),
|
||||
@@ -25,6 +33,26 @@ test("pastes copied tokens through the token flow and leaves ordinary text to th
|
||||
},
|
||||
{ tokenId: "token" }
|
||||
).data;
|
||||
const tagStyleData = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: new Map(),
|
||||
},
|
||||
{ styleSourceId: "tag-style:button", sourceType: "tag" }
|
||||
).data;
|
||||
const localData = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: new Map(),
|
||||
},
|
||||
{ styleSourceId: "temporary-local", sourceType: "local" }
|
||||
).data;
|
||||
|
||||
try {
|
||||
act(() =>
|
||||
@@ -32,7 +60,7 @@ test("pastes copied tokens through the token flow and leaves ordinary text to th
|
||||
<StyleSourceInput
|
||||
inputRef={() => {}}
|
||||
selectedItemSelector={undefined}
|
||||
onPasteToken={onPasteToken}
|
||||
onPasteStyleSource={onPasteStyleSource}
|
||||
/>
|
||||
)
|
||||
);
|
||||
@@ -50,10 +78,368 @@ test("pastes copied tokens through the token flow and leaves ordinary text to th
|
||||
};
|
||||
|
||||
expect(paste(tokenData).defaultPrevented).toBe(true);
|
||||
expect(onPasteToken).toHaveBeenCalledExactlyOnceWith(tokenData);
|
||||
expect(onPasteStyleSource).toHaveBeenCalledExactlyOnceWith(tokenData);
|
||||
expect(paste(tagStyleData).defaultPrevented).toBe(true);
|
||||
expect(onPasteStyleSource).toHaveBeenLastCalledWith(tagStyleData);
|
||||
expect(paste(localData).defaultPrevented).toBe(true);
|
||||
expect(onPasteStyleSource).toHaveBeenLastCalledWith(localData);
|
||||
expect(paste("Button").defaultPrevented).toBe(false);
|
||||
expect(paste('{"other":"value"}').defaultPrevented).toBe(false);
|
||||
expect(onPasteToken).toHaveBeenCalledTimes(1);
|
||||
expect(onPasteStyleSource).toHaveBeenCalledTimes(3);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
["tag", "tag-style:button", "button"],
|
||||
["local", "temporary-local", "Local"],
|
||||
] as const)(
|
||||
"copies the selected %s source from its menu",
|
||||
(source, id, label) => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const onCopy = vi.fn();
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<StyleSourceMenu
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
selectedItemSelector={undefined}
|
||||
item={{
|
||||
id,
|
||||
label,
|
||||
source,
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [],
|
||||
}}
|
||||
hasStyles
|
||||
states={[]}
|
||||
onCopy={onCopy}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const copy = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="menuitem"]')
|
||||
).find((item) => item.textContent === "Copy");
|
||||
expect(copy).toBeDefined();
|
||||
act(() => copy?.click());
|
||||
expect(onCopy).toHaveBeenCalledExactlyOnceWith(id);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
test("describes Copy and keeps the style source menu width stable", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<StyleSourceMenu
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
selectedItemSelector={undefined}
|
||||
item={{
|
||||
id: "tag-style:button",
|
||||
label: "button",
|
||||
source: "tag",
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [":hover"],
|
||||
}}
|
||||
hasStyles
|
||||
states={[
|
||||
{
|
||||
type: "state",
|
||||
selector: ":hover",
|
||||
label: ":hover",
|
||||
description:
|
||||
"Apply styles while the pointer is over this element.",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
);
|
||||
|
||||
const copy = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="menuitem"]')
|
||||
).find((item) => item.textContent === "Copy")!;
|
||||
act(() => copy.focus());
|
||||
const menu = document.querySelector<HTMLElement>('[role="menu"]')!;
|
||||
const copyDescription = menu.getBoundingClientRect().width;
|
||||
expect(menu.textContent).toContain(
|
||||
"Copy this source’s styles to paste them elsewhere."
|
||||
);
|
||||
|
||||
const hover = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="menuitem"]')
|
||||
).find((item) => item.textContent?.trim() === ":hover")!;
|
||||
act(() => hover.focus());
|
||||
expect(menu.getBoundingClientRect().width).toBe(copyDescription);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
|
||||
test("disables Copy when a source has no declarations", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const onCopy = vi.fn();
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<StyleSourceMenu
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
selectedItemSelector={undefined}
|
||||
item={{
|
||||
id: "tag-style:button",
|
||||
label: "button",
|
||||
source: "tag",
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [":hover"],
|
||||
}}
|
||||
hasStyles={false}
|
||||
states={[]}
|
||||
onCopy={onCopy}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const copy = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="menuitem"]')
|
||||
).find((item) => item.textContent === "Copy")!;
|
||||
expect(copy.getAttribute("aria-disabled")).toBe("true");
|
||||
act(() => copy.click());
|
||||
expect(onCopy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not treat selectors alone as copyable styles", () => {
|
||||
const hasStyles = inputTesting.getHasStylesMap(
|
||||
[
|
||||
{
|
||||
id: "tag-style:button",
|
||||
label: "button",
|
||||
source: "tag",
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [":hover"],
|
||||
},
|
||||
],
|
||||
[]
|
||||
);
|
||||
|
||||
expect(hasStyles.get("tag-style:button")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("allows Copy for styles on inactive states or breakpoints", () => {
|
||||
const hasStyles = inputTesting.getHasStylesMap(
|
||||
[
|
||||
{
|
||||
id: "tag-style:button",
|
||||
label: "button",
|
||||
source: "tag",
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
styleSourceId: "tag-style:button",
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
expect(hasStyles.get("tag-style:button")).toBe(true);
|
||||
});
|
||||
|
||||
test("navigates style sources and restores input focus after Escape", async () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const sources = [
|
||||
{ id: "tag-style:button", label: "button", source: "tag" as const },
|
||||
{ id: "token-one", label: "One", source: "token" as const },
|
||||
{ id: "token-two", label: "Two", source: "token" as const },
|
||||
{ id: "local", label: "Local", source: "local" as const },
|
||||
].map((item) => ({
|
||||
...item,
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [],
|
||||
}));
|
||||
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<StyleSourceInput
|
||||
inputRef={() => {}}
|
||||
selectedItemSelector={undefined}
|
||||
items={sources}
|
||||
value={sources}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
|
||||
const input = container.querySelector<HTMLInputElement>("input")!;
|
||||
const press = (element: Element, key: string) =>
|
||||
element.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })
|
||||
);
|
||||
const sourceButton = (id: string) =>
|
||||
container.querySelector<HTMLElement>(`[data-id="${id}"] button`)!;
|
||||
|
||||
act(() => {
|
||||
input.focus();
|
||||
input.setSelectionRange(0, 0);
|
||||
press(input, "ArrowLeft");
|
||||
});
|
||||
expect(document.activeElement).toBe(sourceButton("token-two"));
|
||||
expect(sourceButton("token-two").matches(":focus-visible")).toBe(true);
|
||||
|
||||
act(() => press(sourceButton("token-two"), "ArrowRight"));
|
||||
expect(document.activeElement).toBe(input);
|
||||
|
||||
act(() => {
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
press(input, "ArrowRight");
|
||||
});
|
||||
expect(document.activeElement).toBe(sourceButton("local"));
|
||||
|
||||
act(() => press(sourceButton("local"), "ArrowLeft"));
|
||||
expect(document.activeElement).toBe(input);
|
||||
|
||||
act(() => press(sourceButton("token-two"), "ArrowDown"));
|
||||
const menu = document.querySelector('[role="menu"]');
|
||||
expect(menu).not.toBeNull();
|
||||
await act(async () => {
|
||||
press(menu!, "Escape");
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(document.querySelector('[role="menu"]')).toBeNull();
|
||||
expect(document.activeElement).toBe(input);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the selected Tag style first in arrow-key autocomplete", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const tagStyle = {
|
||||
id: "tag-style:button",
|
||||
label: "button",
|
||||
source: "tag" as const,
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [],
|
||||
};
|
||||
const token = {
|
||||
id: "token-one",
|
||||
label: "One",
|
||||
source: "token" as const,
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [],
|
||||
};
|
||||
const onSelectAutocompleteItem = vi.fn();
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<StyleSourceInput
|
||||
inputRef={() => {}}
|
||||
selectedItemSelector={undefined}
|
||||
items={[tagStyle, token]}
|
||||
value={[tagStyle]}
|
||||
onSelectAutocompleteItem={onSelectAutocompleteItem}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
|
||||
const input = container.querySelector<HTMLInputElement>("input")!;
|
||||
const press = (key: string, keyCode: number) => {
|
||||
const event = new KeyboardEvent("keydown", {
|
||||
key,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
Object.defineProperty(event, "keyCode", { value: keyCode });
|
||||
input.dispatchEvent(event);
|
||||
};
|
||||
act(() => input.focus());
|
||||
act(() => press("ArrowDown", 40));
|
||||
act(() => press("ArrowDown", 40));
|
||||
act(() => press("Enter", 13));
|
||||
|
||||
expect(onSelectAutocompleteItem).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: tagStyle.id, source: "tag" })
|
||||
);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps menu arrow keys from toggling the outer combobox", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const onOuterKeyDown = vi.fn();
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<div onKeyDown={onOuterKeyDown}>
|
||||
<StyleSourceMenu
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
selectedItemSelector={undefined}
|
||||
item={{
|
||||
id: "token",
|
||||
label: "Token",
|
||||
source: "token",
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [],
|
||||
}}
|
||||
hasStyles
|
||||
states={[]}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
const menu = document.querySelector<HTMLElement>('[role="menu"]')!;
|
||||
act(() =>
|
||||
menu.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "ArrowDown",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(onOuterKeyDown).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
|
||||
+126
-37
@@ -38,6 +38,7 @@ import {
|
||||
Fragment,
|
||||
type ComponentProps,
|
||||
type ForwardRefRenderFunction,
|
||||
type KeyboardEvent,
|
||||
type RefObject,
|
||||
type ReactNode,
|
||||
useRef,
|
||||
@@ -54,8 +55,7 @@ import {
|
||||
import { useSortable } from "./use-sortable";
|
||||
import { matchSorter } from "match-sorter";
|
||||
import { StyleSourceBadge } from "./style-source-badge";
|
||||
import { $computedStyleDeclarations } from "../shared/model";
|
||||
import type { ComputedStyleDecl } from "~/shared/style-object-model";
|
||||
import { $styles } from "~/shared/sync/data-stores";
|
||||
import { StyleSourceMenu, type SelectorConfig } from "./style-source-menu";
|
||||
|
||||
type IntermediateItem = {
|
||||
@@ -102,6 +102,7 @@ type TextFieldBaseWrapperProps<Item extends IntermediateItem> = Omit<
|
||||
hasStyles: boolean;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onReturnToInput: () => void;
|
||||
}) => ReactNode;
|
||||
onChangeItem?: (item: Item) => void;
|
||||
onSort?: (items: Array<Item>) => void;
|
||||
@@ -117,6 +118,7 @@ const StyleSourceControlWithMenu = <Item extends IntermediateItem>({
|
||||
item,
|
||||
hasStyles,
|
||||
renderMenu,
|
||||
onReturnToInput,
|
||||
...props
|
||||
}: Omit<
|
||||
ComponentProps<typeof StyleSourceControl>,
|
||||
@@ -124,11 +126,13 @@ const StyleSourceControlWithMenu = <Item extends IntermediateItem>({
|
||||
> & {
|
||||
item: Item;
|
||||
hasStyles: boolean;
|
||||
onReturnToInput: () => void;
|
||||
renderMenu: (params: {
|
||||
item: Item;
|
||||
hasStyles: boolean;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onReturnToInput: () => void;
|
||||
}) => ReactNode;
|
||||
}) => {
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
@@ -143,6 +147,7 @@ const StyleSourceControlWithMenu = <Item extends IntermediateItem>({
|
||||
hasStyles,
|
||||
open: menuOpen,
|
||||
onOpenChange: setMenuOpen,
|
||||
onReturnToInput,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
@@ -151,20 +156,14 @@ const StyleSourceControlWithMenu = <Item extends IntermediateItem>({
|
||||
// Returns true if style source has defined styles including on the states.
|
||||
const getHasStylesMap = <Item extends IntermediateItem>(
|
||||
styleSourceItems: Array<Item>,
|
||||
computedStyleDeclarations: Array<ComputedStyleDecl>
|
||||
styles: Iterable<{ styleSourceId: string }>
|
||||
) => {
|
||||
const sourceIds = new Set(Array.from(styles, (style) => style.styleSourceId));
|
||||
const map = new Map<Item["id"], boolean>();
|
||||
for (const item of styleSourceItems) {
|
||||
// Style source has styles on states.
|
||||
if (item.states.length > 0) {
|
||||
if (sourceIds.has(item.id)) {
|
||||
map.set(item.id, true);
|
||||
}
|
||||
for (const style of computedStyleDeclarations) {
|
||||
if (item.id === style.source.styleSourceId) {
|
||||
map.set(item.id, true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
};
|
||||
@@ -199,6 +198,7 @@ const TextFieldBase: ForwardRefRenderFunction<
|
||||
onSort,
|
||||
});
|
||||
const internalInputRef = useRef<HTMLInputElement>(null);
|
||||
const sourceButtonRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
|
||||
const { focusWithinProps } = useFocusWithin({
|
||||
onFocusWithin: onFocus,
|
||||
@@ -209,15 +209,53 @@ const TextFieldBase: ForwardRefRenderFunction<
|
||||
internalInputRef.current?.focus();
|
||||
}, [internalInputRef]);
|
||||
|
||||
const computedStyleDeclarations = useStore($computedStyleDeclarations);
|
||||
const styles = useStore($styles);
|
||||
const hasStylesMap = getHasStylesMap(value, styles.values());
|
||||
const focusOrder = [
|
||||
...value.filter((item) => item.source !== "local"),
|
||||
undefined,
|
||||
...value.filter((item) => item.source === "local"),
|
||||
];
|
||||
const focusAdjacent = (id: string | undefined, direction: -1 | 1) => {
|
||||
let index = focusOrder.findIndex((item) => item?.id === id) + direction;
|
||||
while (index >= 0 && index < focusOrder.length) {
|
||||
const item = focusOrder[index];
|
||||
if (item === undefined) {
|
||||
internalInputRef.current?.focus();
|
||||
return true;
|
||||
}
|
||||
const button = sourceButtonRefs.current.get(item.id);
|
||||
if (button && button.disabled === false) {
|
||||
button.focus();
|
||||
return true;
|
||||
}
|
||||
index += direction;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const hasStyles = useCallback(
|
||||
(styleSourceId: string) => {
|
||||
const hasStylesMap = getHasStylesMap(value, computedStyleDeclarations);
|
||||
return hasStylesMap.get(styleSourceId) ?? false;
|
||||
},
|
||||
[value, computedStyleDeclarations]
|
||||
);
|
||||
const handleInputKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
|
||||
const input = internalInputRef.current;
|
||||
if (!event.defaultPrevented && !event.shiftKey && input) {
|
||||
const moveLeft =
|
||||
event.key === "ArrowLeft" &&
|
||||
input.selectionStart === 0 &&
|
||||
input.selectionEnd === 0;
|
||||
const moveRight =
|
||||
event.key === "ArrowRight" &&
|
||||
input.selectionStart === input.value.length &&
|
||||
input.selectionEnd === input.value.length;
|
||||
if (
|
||||
(moveLeft || moveRight) &&
|
||||
focusAdjacent(undefined, moveLeft ? -1 : 1)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
}
|
||||
onKeyDown?.(event);
|
||||
};
|
||||
|
||||
return (
|
||||
<TextFieldContainer
|
||||
@@ -233,7 +271,6 @@ const TextFieldBase: ForwardRefRenderFunction<
|
||||
style={
|
||||
dragItemId ? menuCssVars({ show: false, override: true }) : undefined
|
||||
}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{/* We want input to be the first element in DOM so it receives the focus first */}
|
||||
<InputField
|
||||
@@ -253,6 +290,7 @@ const TextFieldBase: ForwardRefRenderFunction<
|
||||
value={label}
|
||||
onClick={onClick}
|
||||
inputRef={mergeRefs(internalInputRef, inputRef)}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
spellCheck={false}
|
||||
aria-label="New style source input"
|
||||
/>
|
||||
@@ -261,6 +299,7 @@ const TextFieldBase: ForwardRefRenderFunction<
|
||||
key={item.id}
|
||||
item={item}
|
||||
renderMenu={renderMenu}
|
||||
onReturnToInput={() => internalInputRef.current?.focus()}
|
||||
selected={item.id === selectedItemSelector?.styleSourceId}
|
||||
state={
|
||||
item.id === selectedItemSelector?.styleSourceId
|
||||
@@ -279,7 +318,17 @@ const TextFieldBase: ForwardRefRenderFunction<
|
||||
disabled={item.disabled}
|
||||
isDragging={item.id === dragItemId}
|
||||
isEditing={item.id === editingItemId}
|
||||
hasStyles={hasStyles(item.id)}
|
||||
buttonRef={(element) => {
|
||||
if (element) {
|
||||
sourceButtonRefs.current.set(item.id, element);
|
||||
} else {
|
||||
sourceButtonRefs.current.delete(item.id);
|
||||
}
|
||||
}}
|
||||
onArrowToSource={(direction) =>
|
||||
focusAdjacent(item.id, direction === "left" ? -1 : 1)
|
||||
}
|
||||
hasStyles={hasStylesMap.get(item.id) ?? false}
|
||||
source={item.source}
|
||||
locked={item.locked}
|
||||
onChangeEditing={(isEditing) => {
|
||||
@@ -314,7 +363,7 @@ type StyleSourceInputProps<Item extends IntermediateItem> = {
|
||||
onClearStyles?: (id: Item["id"]) => void;
|
||||
onDuplicateItem?: (id: Item["id"]) => void;
|
||||
onCopyItem?: (id: Item["id"]) => void;
|
||||
onPasteToken?: (data: string) => void;
|
||||
onPasteStyleSource?: (data: string) => void;
|
||||
onToggleLockItem?: (id: Item["id"], locked: boolean) => void;
|
||||
onConvertToToken?: (id: Item["id"]) => void;
|
||||
onCreateItem?: (label: string) => void;
|
||||
@@ -340,7 +389,7 @@ const matchOrSuggestToCreate = (
|
||||
const matched = matchSorter(items, search, {
|
||||
keys: [itemToString],
|
||||
});
|
||||
const order: ItemSource[] = ["token"];
|
||||
const order: ItemSource[] = ["tag", "token"];
|
||||
matched.sort((leftItem, rightItem) => {
|
||||
return order.indexOf(leftItem.source) - order.indexOf(rightItem.source);
|
||||
});
|
||||
@@ -349,7 +398,7 @@ const matchOrSuggestToCreate = (
|
||||
itemToString(matched[0]).toLocaleLowerCase() !==
|
||||
search.toLocaleLowerCase().trim()
|
||||
) {
|
||||
matched.unshift({
|
||||
matched.splice(matched[0]?.source === "tag" ? 1 : 0, 0, {
|
||||
id: newItemId,
|
||||
label: search.trim(),
|
||||
disabled: false,
|
||||
@@ -361,7 +410,7 @@ const matchOrSuggestToCreate = (
|
||||
}
|
||||
// skip already added values
|
||||
return matched
|
||||
.filter((item) => item.isAdded === false)
|
||||
.filter((item) => item.isAdded === false || item.source === "tag")
|
||||
.slice(0, maxSuggestedTokens);
|
||||
};
|
||||
|
||||
@@ -381,6 +430,8 @@ export const StyleSourceInput = (
|
||||
) => {
|
||||
const value = props.value ?? [];
|
||||
const [label, setLabel] = useState("");
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const escapePressed = useRef(false);
|
||||
|
||||
const {
|
||||
items,
|
||||
@@ -417,6 +468,9 @@ export const StyleSourceInput = (
|
||||
|
||||
const inputProps = getInputProps({
|
||||
onKeyDown(event) {
|
||||
if (event.key === "Escape") {
|
||||
escapePressed.current = true;
|
||||
}
|
||||
if (
|
||||
event.key === "Backspace" &&
|
||||
label === "" &&
|
||||
@@ -431,6 +485,7 @@ export const StyleSourceInput = (
|
||||
});
|
||||
|
||||
let hasNewTokenItem = false;
|
||||
let hasTagStyleItem = false;
|
||||
let hasGlobalTokenItem = false;
|
||||
|
||||
const states = props.componentStates ?? [];
|
||||
@@ -445,23 +500,35 @@ export const StyleSourceInput = (
|
||||
onPaste={(event) => {
|
||||
const data = event.clipboardData.getData("text/plain");
|
||||
if (
|
||||
props.onPasteToken !== undefined &&
|
||||
parseWebstudioPragma({
|
||||
source: data,
|
||||
syntax: "css",
|
||||
namespace: "token-css",
|
||||
}).owned
|
||||
props.onPasteStyleSource !== undefined &&
|
||||
(
|
||||
["token-css", "tag-style-css", "local-style-css"] as const
|
||||
).some(
|
||||
(namespace) =>
|
||||
parseWebstudioPragma({
|
||||
source: data,
|
||||
syntax: "css",
|
||||
namespace,
|
||||
}).owned
|
||||
)
|
||||
) {
|
||||
event.preventDefault();
|
||||
props.onPasteToken(data);
|
||||
props.onPasteStyleSource(data);
|
||||
}
|
||||
}}
|
||||
inputRef={props.inputRef}
|
||||
inputRef={mergeRefs(inputRef, props.inputRef)}
|
||||
error={props.error}
|
||||
renderMenu={({ item, hasStyles, open, onOpenChange }) => (
|
||||
renderMenu={({
|
||||
item,
|
||||
hasStyles,
|
||||
open,
|
||||
onOpenChange,
|
||||
onReturnToInput,
|
||||
}) => (
|
||||
<StyleSourceMenu
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
onReturnToInput={onReturnToInput}
|
||||
selectedItemSelector={props.selectedItemSelector}
|
||||
item={item}
|
||||
hasStyles={hasStyles}
|
||||
@@ -497,7 +564,21 @@ export const StyleSourceInput = (
|
||||
editingItemId={props.editingItemId}
|
||||
/>
|
||||
</ComboboxAnchor>
|
||||
<ComboboxContent align="start" sideOffset={5}>
|
||||
<ComboboxContent
|
||||
align="start"
|
||||
sideOffset={5}
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
escapePressed.current = false;
|
||||
}}
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (escapePressed.current) {
|
||||
event.preventDefault();
|
||||
escapePressed.current = false;
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ComboboxListbox {...getMenuProps()}>
|
||||
<ComboboxScrollArea>
|
||||
{isOpen &&
|
||||
@@ -529,12 +610,18 @@ export const StyleSourceInput = (
|
||||
}
|
||||
|
||||
let label = null;
|
||||
if (item.source === "tag" && hasTagStyleItem === false) {
|
||||
hasTagStyleItem = true;
|
||||
label = <ComboboxLabel>Tag</ComboboxLabel>;
|
||||
}
|
||||
if (item.source === "token" && hasGlobalTokenItem === false) {
|
||||
hasGlobalTokenItem = true;
|
||||
label = (
|
||||
<>
|
||||
{hasNewTokenItem && <ComboboxSeparator />}
|
||||
<ComboboxLabel>Global tokens</ComboboxLabel>
|
||||
{(hasNewTokenItem || hasTagStyleItem) && (
|
||||
<ComboboxSeparator />
|
||||
)}
|
||||
<ComboboxLabel>Tokens</ComboboxLabel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -562,3 +649,5 @@ export const StyleSourceInput = (
|
||||
</ComboboxRoot>
|
||||
);
|
||||
};
|
||||
|
||||
export const __testing__ = { getHasStylesMap };
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Fragment, useState } from "react";
|
||||
import { Fragment, useRef, useState } from "react";
|
||||
import { tags } from "@webstudio-is/sdk";
|
||||
import {
|
||||
Box,
|
||||
Combobox,
|
||||
@@ -31,7 +32,7 @@ import {
|
||||
} from "./style-source-control";
|
||||
|
||||
export type SelectorConfig = {
|
||||
type: "state" | "pseudoElement";
|
||||
type: "state" | "pseudoElement" | "tag";
|
||||
selector: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
@@ -103,14 +104,17 @@ const MenuTriggerGradient = styled(Box, {
|
||||
const selectorLabels = [
|
||||
"state",
|
||||
"pseudoElement",
|
||||
"tag",
|
||||
] satisfies SelectorConfig["type"][];
|
||||
|
||||
const categoryLabels: Record<SelectorConfig["type"], string> = {
|
||||
state: "States",
|
||||
pseudoElement: "Pseudo elements",
|
||||
tag: "Tag",
|
||||
};
|
||||
|
||||
const menuActionDescriptions = {
|
||||
copy: "Copy this source’s styles to paste them elsewhere.",
|
||||
rename: "Change the name of this token to better describe its purpose.",
|
||||
duplicate: "Create a copy of this token with all its styles.",
|
||||
convertToToken:
|
||||
@@ -131,6 +135,7 @@ const canEditStyleSourceStyles = (item: IntermediateItem) =>
|
||||
const allSelectors = [
|
||||
...Object.keys(pseudoClassDescriptions),
|
||||
...Object.keys(pseudoElementDescriptions),
|
||||
...tags.filter((tag) => tag !== "html"),
|
||||
];
|
||||
|
||||
const getDescription = (selector: string, type: "state" | "pseudoElement") => {
|
||||
@@ -167,27 +172,40 @@ const getSelectorDescription = (selector: string | null | undefined) => {
|
||||
|
||||
const SelectorCombobox = ({
|
||||
existingSelectors,
|
||||
allowDescendants,
|
||||
onSelect,
|
||||
}: {
|
||||
existingSelectors: string[];
|
||||
allowDescendants: boolean;
|
||||
onSelect: (selector: string) => void;
|
||||
}) => {
|
||||
const [value, setValue] = useState("");
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const handleSubmit = (selector: string) => {
|
||||
const validation = validateSelector(selector);
|
||||
let normalizedSelector = selector;
|
||||
let validation = validateSelector(normalizedSelector, { allowDescendants });
|
||||
if (validation.success === false && allowDescendants) {
|
||||
const tagSelector = ` ${selector}`;
|
||||
const tagValidation = validateSelector(tagSelector, { allowDescendants });
|
||||
if (tagValidation.success && tagValidation.type === "tag") {
|
||||
normalizedSelector = tagSelector;
|
||||
validation = tagValidation;
|
||||
}
|
||||
}
|
||||
if (validation.success === false) {
|
||||
setError(validation.error);
|
||||
return;
|
||||
}
|
||||
setError(undefined);
|
||||
onSelect(selector);
|
||||
onSelect(normalizedSelector);
|
||||
setValue("");
|
||||
};
|
||||
|
||||
const availableItems = allSelectors.filter((selector) =>
|
||||
existingSelectors.every((s) => s !== selector)
|
||||
const availableItems = allSelectors.filter(
|
||||
(selector) =>
|
||||
(allowDescendants || tags.includes(selector) === false) &&
|
||||
existingSelectors.every((s) => s.trim() !== selector)
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -233,6 +251,7 @@ const SelectorCombobox = ({
|
||||
type StyleSourceMenuProps = {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onReturnToInput?: () => void;
|
||||
selectedItemSelector: undefined | ItemSelector;
|
||||
item: IntermediateItem;
|
||||
hasStyles: boolean;
|
||||
@@ -252,18 +271,26 @@ type StyleSourceMenuProps = {
|
||||
};
|
||||
|
||||
export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
const availableStates =
|
||||
props.item.source === "tag"
|
||||
? props.states.filter(
|
||||
({ selector }) =>
|
||||
validateSelector(selector, { allowDescendants: false }).success
|
||||
)
|
||||
: props.states;
|
||||
const [highlightedSelector, setHighlightedSelector] = useState<{
|
||||
selector: string;
|
||||
type: "state" | "pseudoElement";
|
||||
type: "state" | "pseudoElement" | "tag";
|
||||
description?: string;
|
||||
}>();
|
||||
const [highlightedAction, setHighlightedAction] = useState<MenuAction>();
|
||||
const escapePressed = useRef(false);
|
||||
const canEditStyles = canEditStyleSourceStyles(props.item);
|
||||
|
||||
// Get description for highlighted or selected item
|
||||
const selectedState = props.selectedItemSelector?.state;
|
||||
const selectedConfig = selectedState
|
||||
? props.states.find((s) => s.selector === selectedState)
|
||||
? availableStates.find((s) => s.selector === selectedState)
|
||||
: undefined;
|
||||
const descriptionSelector =
|
||||
highlightedSelector ??
|
||||
@@ -282,7 +309,12 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
|
||||
const selectorDescription = descriptionSelector
|
||||
? (descriptionSelector.description ??
|
||||
getDescription(descriptionSelector.selector, descriptionSelector.type))
|
||||
(descriptionSelector.type === "tag"
|
||||
? undefined
|
||||
: getDescription(
|
||||
descriptionSelector.selector,
|
||||
descriptionSelector.type
|
||||
)))
|
||||
: undefined;
|
||||
|
||||
// Get source description based on item source
|
||||
@@ -291,7 +323,9 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
? "Style instances without creating a token or override a token locally."
|
||||
: props.item.source === "token"
|
||||
? "Reuse styles across multiple instances by creating a token."
|
||||
: undefined;
|
||||
: props.item.source === "tag"
|
||||
? "Apply styles to every element with this tag."
|
||||
: undefined;
|
||||
|
||||
const description =
|
||||
actionDescription ?? selectorDescription ?? sourceDescription;
|
||||
@@ -305,9 +339,21 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
</MenuTrigger>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
onCloseAutoFocus={(event) => event.preventDefault()}
|
||||
onKeyDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onEscapeKeyDown={() => {
|
||||
escapePressed.current = true;
|
||||
}}
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
if (escapePressed.current) {
|
||||
escapePressed.current = false;
|
||||
queueMicrotask(() => props.onReturnToInput?.());
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
css={{ maxWidth: theme.spacing[26] }}
|
||||
css={{ width: theme.spacing[26] }}
|
||||
>
|
||||
<DropdownMenuLabel>
|
||||
<Flex gap="1" justify="between" align="center">
|
||||
@@ -319,7 +365,7 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
)}
|
||||
</Flex>
|
||||
</DropdownMenuLabel>
|
||||
{props.item.source !== "local" && (
|
||||
{props.item.source === "token" && (
|
||||
<DropdownMenuItem
|
||||
onFocus={() => {
|
||||
setHighlightedSelector(undefined);
|
||||
@@ -330,7 +376,7 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{props.item.source !== "local" && (
|
||||
{props.item.source === "token" && (
|
||||
<DropdownMenuItem
|
||||
onFocus={() => {
|
||||
setHighlightedSelector(undefined);
|
||||
@@ -341,12 +387,15 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
Duplicate
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{props.item.source === "token" && (
|
||||
{(props.item.source === "token" ||
|
||||
props.item.source === "tag" ||
|
||||
props.item.source === "local") && (
|
||||
<DropdownMenuItem
|
||||
onFocus={() => {
|
||||
setHighlightedSelector(undefined);
|
||||
setHighlightedAction(undefined);
|
||||
setHighlightedAction("copy");
|
||||
}}
|
||||
disabled={!props.hasStyles}
|
||||
onSelect={() => props.onCopy?.(props.item.id)}
|
||||
>
|
||||
Copy
|
||||
@@ -388,7 +437,7 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
Clear styles
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{props.item.source !== "local" && (
|
||||
{props.item.source === "token" && (
|
||||
<DropdownMenuItem
|
||||
onFocus={() => {
|
||||
setHighlightedSelector(undefined);
|
||||
@@ -399,7 +448,7 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
Detach
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{props.item.source !== "local" && (
|
||||
{props.item.source === "token" && (
|
||||
<DropdownMenuItem
|
||||
destructive={true}
|
||||
onFocus={() => {
|
||||
@@ -413,7 +462,7 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
)}
|
||||
{canEditStyles &&
|
||||
selectorLabels.map((currentCategory) => {
|
||||
const categoryStates = props.states.filter(
|
||||
const categoryStates = availableStates.filter(
|
||||
({ type }) => type === currentCategory
|
||||
);
|
||||
if (categoryStates.length === 0) {
|
||||
@@ -497,7 +546,10 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
<DropdownMenuLabel>Add more</DropdownMenuLabel>
|
||||
<Box css={{ padding: theme.spacing[4] }}>
|
||||
<SelectorCombobox
|
||||
existingSelectors={props.states.map((state) => state.selector)}
|
||||
existingSelectors={availableStates.map(
|
||||
(state) => state.selector
|
||||
)}
|
||||
allowDescendants={props.item.source !== "tag"}
|
||||
onSelect={(selector) =>
|
||||
props.onAddSelector?.(props.item.id, selector)
|
||||
}
|
||||
|
||||
@@ -60,6 +60,14 @@ export const useSortable = <Item extends { id: string; source: ItemSource }>({
|
||||
if (dropTarget === undefined) {
|
||||
setPlacementIndicator(undefined);
|
||||
} else {
|
||||
if (items[0]?.source === "tag") {
|
||||
const { placement } = dropTarget;
|
||||
placement.indexAdjustment = Math.max(placement.indexAdjustment, 1);
|
||||
placement.closestChildIndex = Math.max(
|
||||
placement.closestChildIndex,
|
||||
1
|
||||
);
|
||||
}
|
||||
// when local style source is last always drop before it
|
||||
if (items.at(-1)?.source === "local") {
|
||||
const lastIndex = items.length - 1;
|
||||
@@ -99,6 +107,10 @@ export const useSortable = <Item extends { id: string; source: ItemSource }>({
|
||||
return false;
|
||||
}
|
||||
|
||||
if (items.find((item) => item.id === itemId)?.source === "tag") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return itemId;
|
||||
},
|
||||
onStart({ data: itemId }) {
|
||||
@@ -134,6 +146,9 @@ export const useSortable = <Item extends { id: string; source: ItemSource }>({
|
||||
if (oldIndex < newIndex) {
|
||||
newIndex = Math.max(0, newIndex - 1);
|
||||
}
|
||||
if (items[0]?.source === "tag") {
|
||||
newIndex = Math.max(1, newIndex);
|
||||
}
|
||||
// when local style source is last always drop before it
|
||||
if (items.at(-1)?.source === "local") {
|
||||
const lastIndex = items.length - 1;
|
||||
|
||||
@@ -102,7 +102,7 @@ export const Loading = ({ state }: { state: LoadingState }) => {
|
||||
<Box
|
||||
css={{
|
||||
position: "absolute",
|
||||
bottom: `calc(50% + ${theme.spacing[10]})`,
|
||||
bottom: `calc(50% + ${theme.spacing[12]})`,
|
||||
left: "50%",
|
||||
display: "flex",
|
||||
transform: "translateX(-50%)",
|
||||
@@ -118,7 +118,6 @@ export const Loading = ({ state }: { state: LoadingState }) => {
|
||||
left: "50%",
|
||||
transform: "translate(-50%, -50%)",
|
||||
background: cssVar("--background-primary"),
|
||||
boxShadow: webstudioBrand.progressShadow,
|
||||
}}
|
||||
indicatorCss={{ background: webstudioBrand.progressGradient }}
|
||||
/>
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { getTagStyleId, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$selectedInstanceOutline,
|
||||
$selectedInstanceOutlines,
|
||||
$selectedInstanceStates,
|
||||
selectInstances,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instances, $styleSourceSelections } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$instances,
|
||||
$styleSourceSelections,
|
||||
$styles,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { subscribeSelected } from "./selected-instance-effects";
|
||||
import { subscribeInstanceSelection } from "./instance-selection-events";
|
||||
import { createCanvasElement } from "./test-utils";
|
||||
@@ -88,7 +95,9 @@ beforeEach(() => {
|
||||
])
|
||||
);
|
||||
$styleSourceSelections.set(new Map());
|
||||
$styles.set(new Map());
|
||||
$allSelectedInstanceSelectors.set([]);
|
||||
$selectedInstanceStates.set(new Set());
|
||||
$selectedInstanceOutline.set(undefined);
|
||||
$selectedInstanceOutlines.set([]);
|
||||
document.body.innerHTML = "";
|
||||
@@ -102,12 +111,68 @@ afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
document.body.innerHTML = "";
|
||||
$instances.set(new Map());
|
||||
$styles.set(new Map());
|
||||
$styleSourceSelections.set(new Map());
|
||||
$allSelectedInstanceSelectors.set([]);
|
||||
$selectedInstanceStates.set(new Set());
|
||||
$selectedInstanceOutline.set(undefined);
|
||||
$selectedInstanceOutlines.set([]);
|
||||
});
|
||||
|
||||
describe("subscribeSelected", () => {
|
||||
test("detects active states defined only by the selected tag style", () => {
|
||||
const button = document.createElement("button");
|
||||
button.disabled = true;
|
||||
button.setAttribute(idAttribute, "box");
|
||||
button.setAttribute(selectorIdAttribute, "box");
|
||||
document.body.appendChild(button);
|
||||
$instances.set(
|
||||
new Map([["box", { ...createInstance("box"), tag: "button" }]])
|
||||
);
|
||||
const declaration: StyleDecl = {
|
||||
styleSourceId: getTagStyleId("button"),
|
||||
breakpointId: "base",
|
||||
state: ":disabled",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
$styles.set(new Map([["button-disabled", declaration]]));
|
||||
unsubscribe = subscribeSelected((callback) => callback());
|
||||
|
||||
selectInstances([["box"]]);
|
||||
|
||||
expect($selectedInstanceStates.get()).toEqual(new Set([":disabled"]));
|
||||
});
|
||||
|
||||
test("does not treat a descendant selector as an active instance state", () => {
|
||||
const div = document.createElement("div");
|
||||
div.setAttribute(idAttribute, "box");
|
||||
div.setAttribute(selectorIdAttribute, "box");
|
||||
document.body.appendChild(div);
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["token"] }]])
|
||||
);
|
||||
$styles.set(
|
||||
new Map([
|
||||
[
|
||||
"token-descendant",
|
||||
{
|
||||
styleSourceId: "token",
|
||||
breakpointId: "base",
|
||||
state: " div",
|
||||
property: "paddingTop",
|
||||
value: { type: "unit", value: 20, unit: "px" },
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
unsubscribe = subscribeSelected((callback) => callback());
|
||||
|
||||
selectInstances([["box"]]);
|
||||
|
||||
expect($selectedInstanceStates.get()).toEqual(new Set());
|
||||
});
|
||||
|
||||
test("creates both outline stores for one selected instance", () => {
|
||||
createCanvasElement({
|
||||
selector: "box,body",
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { shallowEqual } from "shallow-equal";
|
||||
import warnOnce from "warn-once";
|
||||
import type { Instance } from "@webstudio-is/sdk";
|
||||
import { getTagStyleId, type Instance } from "@webstudio-is/sdk";
|
||||
import type { CssProperty, UnitValue } from "@webstudio-is/css-engine";
|
||||
import { isPseudoElement, propertiesData } from "@webstudio-is/css-data";
|
||||
import {
|
||||
isPseudoElement,
|
||||
propertiesData,
|
||||
validateSelector,
|
||||
} from "@webstudio-is/css-data";
|
||||
import { selectorIdAttribute } from "@webstudio-is/react-sdk";
|
||||
import { subscribeWindowResize } from "~/shared/dom-hooks";
|
||||
import {
|
||||
@@ -289,6 +292,7 @@ const subscribeSelectedInstance = (
|
||||
const instanceStyleSourceIds = new Set(
|
||||
$styleSourceSelections.get().get(instanceId)?.values
|
||||
);
|
||||
instanceStyleSourceIds.add(getTagStyleId(element.localName));
|
||||
const styles = $styles.get();
|
||||
for (const styleDecl of styles.values()) {
|
||||
if (
|
||||
@@ -300,6 +304,11 @@ const subscribeSelectedInstance = (
|
||||
}
|
||||
const activeStates = new Set<string>();
|
||||
for (const state of availableStates) {
|
||||
if (
|
||||
validateSelector(state, { allowDescendants: false }).success === false
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
// pseudo classes like :open or :current are not supported in .matches method
|
||||
if (element.matches(state)) {
|
||||
@@ -310,8 +319,12 @@ const subscribeSelectedInstance = (
|
||||
}
|
||||
}
|
||||
|
||||
const selectedStates = $selectedInstanceStates.get();
|
||||
if (
|
||||
!shallowEqual(activeStates.keys(), $selectedInstanceStates.get().keys())
|
||||
activeStates.size !== selectedStates.size ||
|
||||
Array.from(activeStates).some(
|
||||
(state) => selectedStates.has(state) === false
|
||||
)
|
||||
) {
|
||||
$selectedInstanceStates.set(activeStates);
|
||||
}
|
||||
@@ -395,6 +408,7 @@ const subscribeSelectedInstance = (
|
||||
});
|
||||
|
||||
updateObservers();
|
||||
updateStores();
|
||||
|
||||
const unsubscribe$stylesIndex = $stylesIndex.subscribe(update);
|
||||
const unsubscribeSelectedStyleState = $selectedStyleState.subscribe(update);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, test, expect } from "vitest";
|
||||
import type { Instance, StyleDecl } from "@webstudio-is/sdk";
|
||||
import {
|
||||
descendantComponent,
|
||||
getTagStyleId,
|
||||
ROOT_INSTANCE_ID,
|
||||
rootComponent,
|
||||
} from "@webstudio-is/sdk";
|
||||
@@ -13,12 +14,21 @@ import {
|
||||
// polyfill CSS.escape for Node environment
|
||||
import "css.escape";
|
||||
|
||||
import { __testing__ } from "./styles";
|
||||
import { $ephemeralStyles } from "../stores";
|
||||
import {
|
||||
$selectedStyleState,
|
||||
$temporaryTagStyleId,
|
||||
} from "~/shared/nano-states";
|
||||
import { $allSelectedInstanceSelectors } from "~/shared/nano-states/instance-selection";
|
||||
import { $breakpoints, $instances, $styles } from "~/shared/sync/data-stores";
|
||||
import { __testing__, mountStyles } from "./styles";
|
||||
|
||||
const {
|
||||
getEphemeralProperty,
|
||||
getInstanceSelector,
|
||||
getPresetStyleSelector,
|
||||
getStatePreviewSelector,
|
||||
shouldRenderEphemeralTagState,
|
||||
computeDescendantSelectors,
|
||||
computeInstanceStyles,
|
||||
computeEditableCursorRules,
|
||||
@@ -26,6 +36,8 @@ const {
|
||||
toDeclarationParams,
|
||||
toVarValue,
|
||||
renderStateStyles,
|
||||
subscribeStateStyles,
|
||||
subscribeEphemeralStyle,
|
||||
simulateConditionBreakpoints,
|
||||
shouldRenderInBackgroundTask,
|
||||
} = __testing__;
|
||||
@@ -67,6 +79,35 @@ describe("renderStateStyles", () => {
|
||||
expect(sheet.cssText).toBe("");
|
||||
});
|
||||
|
||||
test("preserves Tag-state specificity below instance-state specificity", () => {
|
||||
const sheet = createTestSheet();
|
||||
renderStateStyles({
|
||||
instanceStyles: {
|
||||
instanceId: "button",
|
||||
selectedState: ":hover",
|
||||
breakpoints: [{ id: "base", label: "Base" }],
|
||||
styles: [
|
||||
createStyleDecl({
|
||||
styleSourceId: getTagStyleId("button"),
|
||||
state: ":hover",
|
||||
}),
|
||||
createStyleDecl({
|
||||
styleSourceId: "local",
|
||||
state: ":hover",
|
||||
}),
|
||||
],
|
||||
},
|
||||
sheet,
|
||||
transformValue: mockTransformValue,
|
||||
toStyleValue: mockToStyleValue,
|
||||
});
|
||||
|
||||
expect(sheet.cssText).toContain(
|
||||
':where([data-ws-id="button"]):is(button, button:hover)'
|
||||
);
|
||||
expect(sheet.cssText).toContain('[data-ws-id="button"]:is(*, :hover)');
|
||||
});
|
||||
|
||||
describe("pseudo-elements keep their selector", () => {
|
||||
test("::before styles apply to ::before selector", () => {
|
||||
const sheet = createTestSheet();
|
||||
@@ -147,7 +188,8 @@ describe("renderStateStyles", () => {
|
||||
transformValue: mockTransformValue,
|
||||
toStyleValue: mockToStyleValue,
|
||||
});
|
||||
expect(sheet.cssText).not.toContain(":hover");
|
||||
expect(sheet.cssText).not.toContain('[data-ws-id="button"]:hover');
|
||||
expect(sheet.cssText).toContain(":is(*, :hover)");
|
||||
expect(sheet.cssText).toContain("background-color: blue");
|
||||
});
|
||||
|
||||
@@ -164,7 +206,8 @@ describe("renderStateStyles", () => {
|
||||
transformValue: mockTransformValue,
|
||||
toStyleValue: mockToStyleValue,
|
||||
});
|
||||
expect(sheet.cssText).not.toContain(":focus");
|
||||
expect(sheet.cssText).not.toContain('[data-ws-id="input"]:focus');
|
||||
expect(sheet.cssText).toContain(":is(*, :focus)");
|
||||
});
|
||||
|
||||
test(":active styles apply without :active selector", () => {
|
||||
@@ -180,10 +223,62 @@ describe("renderStateStyles", () => {
|
||||
transformValue: mockTransformValue,
|
||||
toStyleValue: mockToStyleValue,
|
||||
});
|
||||
expect(sheet.cssText).not.toContain(":active");
|
||||
expect(sheet.cssText).not.toContain('[data-ws-id="button"]:active');
|
||||
expect(sheet.cssText).toContain(":is(*, :active)");
|
||||
});
|
||||
});
|
||||
|
||||
test("descendant tag styles preview on the matching tag", () => {
|
||||
const sheet = createTestSheet();
|
||||
renderStateStyles({
|
||||
instanceStyles: {
|
||||
instanceId: "box",
|
||||
selectedState: " h1",
|
||||
breakpoints: [{ id: "base", label: "Base" }],
|
||||
styles: [createStyleDecl()],
|
||||
},
|
||||
sheet,
|
||||
transformValue: mockTransformValue,
|
||||
toStyleValue: mockToStyleValue,
|
||||
});
|
||||
expect(sheet.cssText).toContain('[data-ws-id="box"] h1');
|
||||
});
|
||||
|
||||
test("Tag preview selectors stay below instance selectors at every breakpoint", () => {
|
||||
const sheet = createTestSheet();
|
||||
const tagStyleId = getTagStyleId("button");
|
||||
renderStateStyles({
|
||||
instanceStyles: {
|
||||
instanceId: "button",
|
||||
selectedState: ":hover",
|
||||
breakpoints: [
|
||||
{ id: "base", label: "Base" },
|
||||
{ id: "mobile", label: "Mobile" },
|
||||
],
|
||||
styles: [
|
||||
createStyleDecl({
|
||||
styleSourceId: tagStyleId,
|
||||
breakpointId: "mobile",
|
||||
state: ":hover",
|
||||
value: { type: "keyword", value: "red" },
|
||||
}),
|
||||
createStyleDecl({
|
||||
styleSourceId: "local",
|
||||
breakpointId: "base",
|
||||
state: ":hover",
|
||||
value: { type: "keyword", value: "blue" },
|
||||
}),
|
||||
],
|
||||
},
|
||||
sheet,
|
||||
transformValue: mockTransformValue,
|
||||
toStyleValue: mockToStyleValue,
|
||||
});
|
||||
|
||||
expect(sheet.cssText).toContain(':where([data-ws-id="button"])');
|
||||
expect(sheet.cssText).toContain('[data-ws-id="button"]');
|
||||
});
|
||||
|
||||
test("creates nesting rule with correct instance selector", () => {
|
||||
const sheet = createTestSheet();
|
||||
renderStateStyles({
|
||||
@@ -464,6 +559,78 @@ describe("computeInstanceStyles", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("previews Tag state styles before instance styles", () => {
|
||||
const tagStyleId = getTagStyleId("button");
|
||||
const result = computeInstanceStyles({
|
||||
selectedInstance: { ...createInstance("button"), tag: "button" },
|
||||
selectedStyleState: ":hover",
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSourceSelections: new Map([["button", { values: ["local"] }]]),
|
||||
temporaryTagStyleId: tagStyleId,
|
||||
styles: new Map([
|
||||
[
|
||||
"local",
|
||||
createStyleDecl({
|
||||
styleSourceId: "local",
|
||||
state: ":hover",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "blue" },
|
||||
}),
|
||||
],
|
||||
[
|
||||
"tag",
|
||||
createStyleDecl({
|
||||
styleSourceId: tagStyleId,
|
||||
state: ":hover",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
}),
|
||||
],
|
||||
]),
|
||||
});
|
||||
|
||||
expect(result?.styles.map((styleDecl) => styleDecl.styleSourceId)).toEqual([
|
||||
tagStyleId,
|
||||
"local",
|
||||
]);
|
||||
});
|
||||
|
||||
test("includes matching Tag state styles without a temporary chip", () => {
|
||||
const tagStyleId = getTagStyleId("button");
|
||||
const result = computeInstanceStyles({
|
||||
selectedInstance: createInstance("button"),
|
||||
selectedStyleState: ":hover",
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSourceSelections: new Map([["button", { values: ["local"] }]]),
|
||||
instanceTag: "button",
|
||||
styles: new Map([
|
||||
[
|
||||
"local",
|
||||
createStyleDecl({
|
||||
styleSourceId: "local",
|
||||
state: ":hover",
|
||||
property: "paddingTop",
|
||||
value: { type: "unit", unit: "px", value: 8 },
|
||||
}),
|
||||
],
|
||||
[
|
||||
"tag",
|
||||
createStyleDecl({
|
||||
styleSourceId: tagStyleId,
|
||||
state: ":hover",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
}),
|
||||
],
|
||||
]),
|
||||
});
|
||||
|
||||
expect(result?.styles.map((styleDecl) => styleDecl.styleSourceId)).toEqual([
|
||||
tagStyleId,
|
||||
"local",
|
||||
]);
|
||||
});
|
||||
|
||||
test("includes styles from multiple style sources", () => {
|
||||
const result = computeInstanceStyles({
|
||||
selectedInstance: createInstance("box"),
|
||||
@@ -688,8 +855,27 @@ describe("getInstanceSelector", () => {
|
||||
});
|
||||
|
||||
describe("getPresetStyleSelector", () => {
|
||||
test("returns :root for rootComponent", () => {
|
||||
expect(getPresetStyleSelector(rootComponent, "div")).toBe(":root");
|
||||
test("keeps root preset below tag style specificity", () => {
|
||||
expect(getPresetStyleSelector(rootComponent, "div")).toBe(":where(:root)");
|
||||
});
|
||||
|
||||
test("html Tag style overrides the root preset in the canvas cascade", () => {
|
||||
const preset = document.createElement("style");
|
||||
const tagStyle = document.createElement("style");
|
||||
preset.textContent = `${getPresetStyleSelector(rootComponent, "html")} { --root-preset-test: red; }`;
|
||||
tagStyle.textContent = "html { --root-preset-test: blue; }";
|
||||
document.head.appendChild(preset);
|
||||
document.head.appendChild(tagStyle);
|
||||
try {
|
||||
expect(
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--root-preset-test")
|
||||
.trim()
|
||||
).toBe("blue");
|
||||
} finally {
|
||||
preset.remove();
|
||||
tagStyle.remove();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns :where selector for regular component", () => {
|
||||
@@ -711,6 +897,118 @@ describe("getPresetStyleSelector", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldRenderEphemeralTagState", () => {
|
||||
test("does not let an ephemeral Tag state override an instance declaration", () => {
|
||||
const tagStyleId = getTagStyleId("button");
|
||||
const declaration = createStyleDecl({
|
||||
styleSourceId: tagStyleId,
|
||||
state: ":hover",
|
||||
property: "color",
|
||||
});
|
||||
|
||||
expect(
|
||||
shouldRenderEphemeralTagState(declaration, true, {
|
||||
name: "overwritten",
|
||||
styleSourceId: tagStyleId,
|
||||
})
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRenderEphemeralTagState(declaration, true, {
|
||||
name: "local",
|
||||
styleSourceId: "local",
|
||||
})
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRenderEphemeralTagState(declaration, true, {
|
||||
name: "remote",
|
||||
styleSourceId: tagStyleId,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStatePreviewSelector", () => {
|
||||
test("keeps descendant and pseudo-element selectors on live edits", () => {
|
||||
expect(getStatePreviewSelector(" h1")).toBe(" h1");
|
||||
expect(getStatePreviewSelector("::before")).toBe("::before");
|
||||
});
|
||||
|
||||
test("previews pseudo-classes without requiring interaction", () => {
|
||||
expect(getStatePreviewSelector(":hover")).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
test("ephemeral Tag state edits update and clean up the selected preview", () => {
|
||||
const previous = {
|
||||
instances: $instances.get(),
|
||||
breakpoints: $breakpoints.get(),
|
||||
styles: $styles.get(),
|
||||
temporaryTagStyleId: $temporaryTagStyleId.get(),
|
||||
selectedStyleState: $selectedStyleState.get(),
|
||||
selections: $allSelectedInstanceSelectors.get(),
|
||||
};
|
||||
const tagStyleId = getTagStyleId("p");
|
||||
const instance: Instance = {
|
||||
type: "instance",
|
||||
id: "ephemeral-tag-test",
|
||||
component: "Box",
|
||||
tag: "p",
|
||||
children: [],
|
||||
};
|
||||
mountStyles();
|
||||
$instances.set(new Map([[instance.id, instance]]));
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "Base" }]]));
|
||||
$styles.set(new Map());
|
||||
$temporaryTagStyleId.set(tagStyleId);
|
||||
$allSelectedInstanceSelectors.set([[instance.id]]);
|
||||
$selectedStyleState.set(":hover");
|
||||
const unsubscribeState = subscribeStateStyles();
|
||||
const unsubscribeEphemeral = subscribeEphemeralStyle();
|
||||
const declaration = createStyleDecl({
|
||||
styleSourceId: tagStyleId,
|
||||
state: ":hover",
|
||||
});
|
||||
try {
|
||||
$ephemeralStyles.set([declaration]);
|
||||
const property = getEphemeralProperty(declaration);
|
||||
expect(document.documentElement.style.getPropertyValue(property)).toBe(
|
||||
"red"
|
||||
);
|
||||
expect(
|
||||
document.querySelector('style[data-webstudio="state-styles"]')
|
||||
?.textContent
|
||||
).toContain("var(");
|
||||
|
||||
$ephemeralStyles.set([]);
|
||||
expect(document.documentElement.style.getPropertyValue(property)).toBe("");
|
||||
expect(
|
||||
document.querySelector('style[data-webstudio="state-styles"]')
|
||||
?.textContent
|
||||
).not.toContain("var(");
|
||||
|
||||
$selectedStyleState.set(" h1");
|
||||
const descendantDeclaration = createStyleDecl({
|
||||
state: " h1",
|
||||
property: "paddingTop",
|
||||
});
|
||||
$ephemeralStyles.set([descendantDeclaration]);
|
||||
expect(
|
||||
document.querySelector('style[data-webstudio="state-styles"]')
|
||||
?.textContent
|
||||
).toContain('[data-ws-id="ephemeral-tag-test"] h1');
|
||||
} finally {
|
||||
$ephemeralStyles.set([]);
|
||||
unsubscribeEphemeral();
|
||||
unsubscribeState();
|
||||
$allSelectedInstanceSelectors.set(previous.selections);
|
||||
$selectedStyleState.set(previous.selectedStyleState);
|
||||
$temporaryTagStyleId.set(previous.temporaryTagStyleId);
|
||||
$instances.set(previous.instances);
|
||||
$styles.set(previous.styles);
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
}
|
||||
});
|
||||
|
||||
describe("toVarValue", () => {
|
||||
test("returns var type with escaped property name", () => {
|
||||
const result = toVarValue(
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type Instance,
|
||||
ROOT_INSTANCE_ID,
|
||||
getStyleDeclKey,
|
||||
getTagFromStyleId,
|
||||
descendantComponent,
|
||||
rootComponent,
|
||||
type Breakpoint,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
type StyleSourceSelection,
|
||||
createImageValueTransformer,
|
||||
addFontRules,
|
||||
getTagStyleId,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { inflatedAttribute, idAttribute } from "@webstudio-is/react-sdk";
|
||||
import { INFLATE_PADDING } from "~/canvas/inflator";
|
||||
@@ -31,6 +33,7 @@ import {
|
||||
$registeredComponentMetas,
|
||||
$selectedBreakpoint,
|
||||
$selectedStyleState,
|
||||
$temporaryTagStyleId,
|
||||
assetBaseUrl,
|
||||
} from "~/shared/nano-states";
|
||||
import { $assets } from "~/shared/sync/data-stores";
|
||||
@@ -39,6 +42,7 @@ import {
|
||||
$instances,
|
||||
$props,
|
||||
$styleSourceSelections,
|
||||
$styleSources,
|
||||
$styles,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { setDifference } from "~/shared/shim";
|
||||
@@ -54,7 +58,10 @@ import {
|
||||
type InstanceSelector,
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import { getAllElementsByInstanceSelector } from "~/shared/dom-utils";
|
||||
import { createComputedStyleDeclStore } from "~/builder/features/style-panel/shared/model";
|
||||
import {
|
||||
$instanceTags,
|
||||
createComputedStyleDeclStore,
|
||||
} from "~/builder/features/style-panel/shared/model";
|
||||
import { cssVar, declareCssVar } from "@webstudio-is/design-system";
|
||||
|
||||
const userSheet = createRegularStyleSheet({ name: "user-styles" });
|
||||
@@ -64,6 +71,7 @@ const fontsAndDefaultsSheet = createRegularStyleSheet({
|
||||
name: "fonts-and-defaults",
|
||||
});
|
||||
const presetSheet = createRegularStyleSheet({ name: "preset-styles" });
|
||||
const tagStyleSheet = createRegularStyleSheet({ name: "tag-style-styles" });
|
||||
|
||||
/**
|
||||
* maintain order of rendered stylesheets
|
||||
@@ -72,6 +80,7 @@ const presetSheet = createRegularStyleSheet({ name: "preset-styles" });
|
||||
export const mountStyles = () => {
|
||||
fontsAndDefaultsSheet.render();
|
||||
presetSheet.render();
|
||||
tagStyleSheet.render();
|
||||
userSheet.render();
|
||||
stateSheet.render();
|
||||
helpersSheet.render();
|
||||
@@ -397,11 +406,11 @@ const getInstanceSelector = (instanceId: string) =>
|
||||
|
||||
/**
|
||||
* Convert component and tag to preset CSS selector.
|
||||
* rootComponent maps to ":root", others use :where() for low specificity.
|
||||
* rootComponent maps to :where(:root), others use :where() for low specificity.
|
||||
*/
|
||||
const getPresetStyleSelector = (component: string, tag: string) =>
|
||||
component === rootComponent
|
||||
? ":root"
|
||||
? ":where(:root)"
|
||||
: `${tag}:where([data-ws-component="${component}"])`;
|
||||
|
||||
const $descendantSelectors = computed(
|
||||
@@ -522,6 +531,73 @@ export const subscribeStyles = () => {
|
||||
renderUserSheetInTheNextFrame();
|
||||
});
|
||||
|
||||
const unsubscribeTagStyles = computed(
|
||||
[
|
||||
$styleSources,
|
||||
$styles,
|
||||
$breakpoints,
|
||||
$selectedBreakpoint,
|
||||
$transformValue,
|
||||
$ephemeralStyles,
|
||||
],
|
||||
(
|
||||
styleSources,
|
||||
styles,
|
||||
breakpoints,
|
||||
selectedBreakpoint,
|
||||
transformValue,
|
||||
ephemeralStyles
|
||||
) => ({
|
||||
styleSources,
|
||||
styles,
|
||||
breakpoints,
|
||||
selectedBreakpoint,
|
||||
transformValue,
|
||||
ephemeralStyles,
|
||||
})
|
||||
).subscribe(
|
||||
({
|
||||
styleSources,
|
||||
styles,
|
||||
breakpoints,
|
||||
selectedBreakpoint,
|
||||
transformValue,
|
||||
ephemeralStyles,
|
||||
}) => {
|
||||
tagStyleSheet.clear();
|
||||
tagStyleSheet.setTransformer(transformValue);
|
||||
const mediaRules = simulateConditionBreakpoints({
|
||||
breakpoints: breakpoints.values(),
|
||||
selectedBreakpoint,
|
||||
});
|
||||
for (const [id, options] of mediaRules) {
|
||||
tagStyleSheet.addMediaRule(id, options);
|
||||
}
|
||||
const tagStyles = new Map<string, string>();
|
||||
for (const source of styleSources.values()) {
|
||||
if (source.type === "tag") {
|
||||
tagStyles.set(source.id, source.tag);
|
||||
tagStyleSheet.addNestingRule(source.tag);
|
||||
}
|
||||
}
|
||||
for (const styleDecl of [...styles.values(), ...ephemeralStyles]) {
|
||||
const tag =
|
||||
tagStyles.get(styleDecl.styleSourceId) ??
|
||||
(styleSources.has(styleDecl.styleSourceId)
|
||||
? undefined
|
||||
: getTagFromStyleId(styleDecl.styleSourceId));
|
||||
if (tag === undefined) {
|
||||
continue;
|
||||
}
|
||||
tagStyleSheet.addNestingRule(tag).setDeclaration({
|
||||
...toDeclarationParams(styleDecl),
|
||||
value: styleDecl.value,
|
||||
});
|
||||
}
|
||||
tagStyleSheet.render();
|
||||
}
|
||||
);
|
||||
|
||||
// add/delete declarations in mixins
|
||||
let prevStylesSet = new Set<StyleDecl>();
|
||||
let prevTransformValue: undefined | TransformValue;
|
||||
@@ -543,10 +619,16 @@ export const subscribeStyles = () => {
|
||||
prevStylesSet = nextPrevStylesSet;
|
||||
// delete before adding declarations by the same key
|
||||
for (const styleDecl of deletedStyles) {
|
||||
if ($styleSources.get().get(styleDecl.styleSourceId)?.type === "tag") {
|
||||
continue;
|
||||
}
|
||||
const rule = userSheet.addMixinRule(styleDecl.styleSourceId);
|
||||
rule.deleteDeclaration(toDeclarationParams(styleDecl));
|
||||
}
|
||||
for (const styleDecl of addedStyles) {
|
||||
if ($styleSources.get().get(styleDecl.styleSourceId)?.type === "tag") {
|
||||
continue;
|
||||
}
|
||||
const rule = userSheet.addMixinRule(styleDecl.styleSourceId);
|
||||
rule.setDeclaration({
|
||||
...toDeclarationParams(styleDecl),
|
||||
@@ -595,6 +677,7 @@ export const subscribeStyles = () => {
|
||||
unsubscribeBreakpoints();
|
||||
unsubscribeStyles();
|
||||
unsubscribeStyleSourceSelections();
|
||||
unsubscribeTagStyles();
|
||||
unsubscribeDescendantSelectors();
|
||||
unsubscribeTransformValue();
|
||||
cancelScheduledRender();
|
||||
@@ -666,29 +749,45 @@ const computeInstanceStyles = ({
|
||||
selectedStyleState,
|
||||
breakpoints,
|
||||
styleSourceSelections,
|
||||
temporaryTagStyleId,
|
||||
instanceTag,
|
||||
styles,
|
||||
}: {
|
||||
selectedInstance: Instance | undefined;
|
||||
selectedStyleState: string | undefined;
|
||||
breakpoints: Map<string, Breakpoint>;
|
||||
styleSourceSelections: Map<string, { values: string[] }>;
|
||||
temporaryTagStyleId?: string;
|
||||
instanceTag?: string;
|
||||
styles: Map<string, StyleDecl>;
|
||||
}) => {
|
||||
if (selectedInstance === undefined || selectedStyleState === undefined) {
|
||||
return;
|
||||
}
|
||||
const styleSources = new Set(
|
||||
styleSourceSelections.get(selectedInstance.id)?.values
|
||||
const styleSourceOrder = new Map(
|
||||
styleSourceSelections
|
||||
.get(selectedInstance.id)
|
||||
?.values.map((id, index) => [id, index + 1] as const)
|
||||
);
|
||||
if (temporaryTagStyleId) {
|
||||
styleSourceOrder.set(temporaryTagStyleId, 0);
|
||||
} else if (instanceTag) {
|
||||
styleSourceOrder.set(getTagStyleId(instanceTag), 0);
|
||||
}
|
||||
const instanceStyles: StyleDecl[] = [];
|
||||
for (const styleDecl of styles.values()) {
|
||||
if (
|
||||
styleDecl.state === selectedStyleState &&
|
||||
styleSources.has(styleDecl.styleSourceId)
|
||||
styleSourceOrder.has(styleDecl.styleSourceId)
|
||||
) {
|
||||
instanceStyles.push(styleDecl);
|
||||
}
|
||||
}
|
||||
instanceStyles.sort(
|
||||
(a, b) =>
|
||||
styleSourceOrder.get(a.styleSourceId)! -
|
||||
styleSourceOrder.get(b.styleSourceId)!
|
||||
);
|
||||
return {
|
||||
instanceId: selectedInstance.id,
|
||||
selectedState: selectedStyleState,
|
||||
@@ -703,6 +802,8 @@ const $instanceStyles = computed(
|
||||
$selectedStyleState,
|
||||
$breakpoints,
|
||||
$styleSourceSelections,
|
||||
$temporaryTagStyleId,
|
||||
$instanceTags,
|
||||
$styles,
|
||||
],
|
||||
(
|
||||
@@ -710,6 +811,8 @@ const $instanceStyles = computed(
|
||||
selectedStyleState,
|
||||
breakpoints,
|
||||
styleSourceSelections,
|
||||
temporaryTagStyleId,
|
||||
instanceTags,
|
||||
styles
|
||||
) =>
|
||||
computeInstanceStyles({
|
||||
@@ -717,6 +820,10 @@ const $instanceStyles = computed(
|
||||
selectedStyleState,
|
||||
breakpoints,
|
||||
styleSourceSelections,
|
||||
temporaryTagStyleId,
|
||||
instanceTag: selectedInstance
|
||||
? instanceTags.get(selectedInstance.id)
|
||||
: undefined,
|
||||
styles,
|
||||
})
|
||||
);
|
||||
@@ -726,9 +833,40 @@ const $instanceStyles = computed(
|
||||
*
|
||||
* For pseudo-classes like :hover, render without state so users can preview
|
||||
* the styles without triggering the state.
|
||||
* For pseudo-elements like ::before, keep the selector so styles apply
|
||||
* to the pseudo-element, not the parent.
|
||||
* For pseudo-elements and descendant tags, keep the selector so styles apply
|
||||
* to the matching element, not the parent.
|
||||
*/
|
||||
const getStatePreviewSelector = (state: string) =>
|
||||
isPseudoElement(state) || state.startsWith(" ") ? state : "";
|
||||
|
||||
const shouldSimulateState = (state: string) =>
|
||||
(state.startsWith(":") && isPseudoElement(state) === false) ||
|
||||
state.startsWith("[");
|
||||
|
||||
const getTagStatePreviewSelector = (
|
||||
selector: string,
|
||||
tag: string,
|
||||
state: string
|
||||
) =>
|
||||
shouldSimulateState(state)
|
||||
? `:where(${selector}):is(${tag}, ${tag}${state})`
|
||||
: `:where(${selector})${tag}${getStatePreviewSelector(state)}`;
|
||||
|
||||
const getInstanceStatePreviewSelector = (selector: string, state: string) =>
|
||||
shouldSimulateState(state)
|
||||
? `${selector}:is(*, ${state})`
|
||||
: `${selector}${getStatePreviewSelector(state)}`;
|
||||
|
||||
const shouldRenderEphemeralTagState = (
|
||||
styleDecl: StyleDecl,
|
||||
isTagStyle: boolean,
|
||||
source: { name: string; styleSourceId?: string }
|
||||
) =>
|
||||
isTagStyle === false ||
|
||||
(source.name !== "overwritten" &&
|
||||
(source.styleSourceId === undefined ||
|
||||
source.styleSourceId === styleDecl.styleSourceId));
|
||||
|
||||
const renderStateStyles = ({
|
||||
instanceStyles,
|
||||
sheet,
|
||||
@@ -753,12 +891,15 @@ const renderStateStyles = ({
|
||||
sheet.addMediaRule(breakpoint.id, breakpoint);
|
||||
}
|
||||
const selector = `[${idAttribute}="${instanceId}"]`;
|
||||
const rule = sheet.addNestingRule(selector);
|
||||
const stateSelector = isPseudoElement(selectedState) ? selectedState : "";
|
||||
for (const styleDecl of styles) {
|
||||
const tag = getTagFromStyleId(styleDecl.styleSourceId);
|
||||
const previewSelector = tag
|
||||
? getTagStatePreviewSelector(selector, tag, selectedState)
|
||||
: getInstanceStatePreviewSelector(selector, selectedState);
|
||||
const rule = sheet.addNestingRule(previewSelector);
|
||||
rule.setDeclaration({
|
||||
breakpoint: styleDecl.breakpointId,
|
||||
selector: stateSelector,
|
||||
selector: "",
|
||||
property: styleDecl.property,
|
||||
value: toStyleValue(styleDecl, transformValue),
|
||||
});
|
||||
@@ -817,6 +958,13 @@ const subscribeEphemeralStyle = () => {
|
||||
userSheet.setTransformer($transformValue.get());
|
||||
userSheet.render();
|
||||
appliedEphemeralDeclarations.clear();
|
||||
renderStateStyles({
|
||||
instanceStyles: $instanceStyles.get(),
|
||||
sheet: stateSheet,
|
||||
transformValue: $transformValue.get(),
|
||||
toStyleValue: (styleDecl, transformValue) =>
|
||||
toVarValue(styleDecl, transformValue),
|
||||
});
|
||||
}
|
||||
|
||||
// add ephemeral styles
|
||||
@@ -826,6 +974,8 @@ const subscribeEphemeralStyle = () => {
|
||||
const rule = userSheet.addNestingRule(selector);
|
||||
let ephemeralSheetUpdated = false;
|
||||
for (const styleDecl of ephemeralStyles) {
|
||||
const tag = getTagFromStyleId(styleDecl.styleSourceId);
|
||||
const isTagStyle = tag !== undefined;
|
||||
// update custom property
|
||||
document.documentElement.style.setProperty(
|
||||
getEphemeralProperty(styleDecl),
|
||||
@@ -847,8 +997,6 @@ const subscribeEphemeralStyle = () => {
|
||||
if (appliedEphemeralDeclarations.has(styleDeclKey) === false) {
|
||||
ephemeralSheetUpdated = true;
|
||||
|
||||
const mixinRule = userSheet.addMixinRule(styleDecl.styleSourceId);
|
||||
|
||||
// Use the actual style value as a fallback (non-ephemeral); see the "Lazy" comment above.
|
||||
const computedStyleDecl = createComputedStyleDeclStore(
|
||||
hyphenateProperty(styleDecl.property)
|
||||
@@ -860,26 +1008,32 @@ const subscribeEphemeralStyle = () => {
|
||||
computedStyleDecl.cascadedValue
|
||||
);
|
||||
|
||||
mixinRule.setDeclaration({
|
||||
...toDeclarationParams(styleDecl),
|
||||
value,
|
||||
});
|
||||
|
||||
rule.addMixin(styleDecl.styleSourceId);
|
||||
if (!isTagStyle) {
|
||||
const mixinRule = userSheet.addMixinRule(styleDecl.styleSourceId);
|
||||
mixinRule.setDeclaration({
|
||||
...toDeclarationParams(styleDecl),
|
||||
value,
|
||||
});
|
||||
rule.addMixin(styleDecl.styleSourceId);
|
||||
}
|
||||
|
||||
// When editing state styles (e.g., :hover), also render var() in stateSheet
|
||||
// so ephemeral updates are visible in the state preview
|
||||
if (styleDecl.state !== undefined) {
|
||||
const stateRule = stateSheet.addNestingRule(selector);
|
||||
// For pseudo-elements (::before, ::after), keep the selector so styles
|
||||
// apply to the pseudo-element. For pseudo-classes (:hover, :focus),
|
||||
// render without state so users can preview without triggering the state.
|
||||
const stateSelector = isPseudoElement(styleDecl.state)
|
||||
? styleDecl.state
|
||||
: "";
|
||||
if (
|
||||
styleDecl.state !== undefined &&
|
||||
shouldRenderEphemeralTagState(
|
||||
styleDecl,
|
||||
isTagStyle,
|
||||
computedStyleDecl.source
|
||||
)
|
||||
) {
|
||||
const previewSelector = tag
|
||||
? getTagStatePreviewSelector(selector, tag, styleDecl.state)
|
||||
: getInstanceStatePreviewSelector(selector, styleDecl.state);
|
||||
const stateRule = stateSheet.addNestingRule(previewSelector);
|
||||
stateRule.setDeclaration({
|
||||
breakpoint: styleDecl.breakpointId,
|
||||
selector: stateSelector,
|
||||
selector: "",
|
||||
property: styleDecl.property,
|
||||
value,
|
||||
});
|
||||
@@ -900,6 +1054,8 @@ export const __testing__ = {
|
||||
getEphemeralProperty,
|
||||
getInstanceSelector,
|
||||
getPresetStyleSelector,
|
||||
getStatePreviewSelector,
|
||||
shouldRenderEphemeralTagState,
|
||||
computeDescendantSelectors,
|
||||
computeInstanceStyles,
|
||||
computeEditableCursorRules,
|
||||
@@ -907,6 +1063,8 @@ export const __testing__ = {
|
||||
toDeclarationParams,
|
||||
toVarValue,
|
||||
renderStateStyles,
|
||||
subscribeStateStyles,
|
||||
subscribeEphemeralStyle,
|
||||
simulateConditionBreakpoints,
|
||||
shouldRenderInBackgroundTask,
|
||||
};
|
||||
@@ -1354,6 +1354,7 @@ describe("api router permits", () => {
|
||||
pages: createDefaultPages({ rootInstanceId: "root" }),
|
||||
breakpoints: [],
|
||||
styles: [],
|
||||
styleSources: [],
|
||||
styleSourceSelections: [],
|
||||
dataSources: [],
|
||||
props: [],
|
||||
|
||||
@@ -625,6 +625,9 @@ const canPublishBuildCss = async (build: CompactBuild, assets: Asset[]) => {
|
||||
)
|
||||
.map((style) => [getStyleDeclKey(style), style])
|
||||
),
|
||||
styleSources: new Map(
|
||||
build.styleSources.map((source) => [source.id, source])
|
||||
),
|
||||
styleSourceSelections: new Map(
|
||||
build.styleSourceSelections.map((selection) => [
|
||||
selection.instanceId,
|
||||
|
||||
@@ -16,7 +16,11 @@ 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 {
|
||||
styleSource,
|
||||
copyTokenData,
|
||||
copyReusableStyleSourceData,
|
||||
} from "./plugin-style-source";
|
||||
import { builderApi } from "../builder-api";
|
||||
import { readClipboardText } from "../clipboard";
|
||||
import { $selectedInstance } from "../nano-states";
|
||||
@@ -330,7 +334,7 @@ export const initCopyPaste = ({ signal }: { signal: AbortSignal }) => {
|
||||
initPlugins({
|
||||
plugins: [
|
||||
variableClipboard,
|
||||
token,
|
||||
styleSource,
|
||||
pageText,
|
||||
instanceJson,
|
||||
instanceText,
|
||||
@@ -473,8 +477,13 @@ export const copyInstance = () => {
|
||||
export const copyToken = async (tokenId: string) =>
|
||||
writeClipboardText(copyTokenData(tokenId));
|
||||
|
||||
export const pasteToken = async (data: string) => {
|
||||
const result = await token.onPaste?.(data);
|
||||
export const copyReusableStyleSource = async (
|
||||
styleSourceId: string,
|
||||
sourceType: "tag" | "local"
|
||||
) => writeClipboardText(copyReusableStyleSourceData(styleSourceId, sourceType));
|
||||
|
||||
export const pasteStyleSource = async (data: string) => {
|
||||
const result = await styleSource.onPaste?.(data);
|
||||
if (result !== undefined) {
|
||||
reportPasteResult(result);
|
||||
}
|
||||
|
||||
+42
-15
@@ -1,5 +1,11 @@
|
||||
import { copyDesignToken } from "@webstudio-is/project-build/runtime";
|
||||
import { parseTokenTransferData } from "@webstudio-is/project-build/transfer";
|
||||
import {
|
||||
copyDesignToken,
|
||||
copyStyleSourceTransfer,
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import {
|
||||
parseReusableStyleSourceTransferData,
|
||||
parseTokenTransferData,
|
||||
} from "@webstudio-is/project-build/transfer";
|
||||
import { $project } from "~/shared/sync/data-stores";
|
||||
import { $selectedInstance } from "~/shared/nano-states";
|
||||
import {
|
||||
@@ -16,24 +22,49 @@ export const copyTokenData = (tokenId: string) =>
|
||||
sourceOrigin: window.location.origin,
|
||||
}).data;
|
||||
|
||||
export const token: Plugin = {
|
||||
name: "token",
|
||||
export const copyReusableStyleSourceData = (
|
||||
styleSourceId: string,
|
||||
sourceType: "tag" | "local"
|
||||
) =>
|
||||
copyStyleSourceTransfer(getWebstudioData(), {
|
||||
styleSourceId,
|
||||
sourceType,
|
||||
sourceOrigin: window.location.origin,
|
||||
}).data;
|
||||
|
||||
export const styleSource: Plugin = {
|
||||
name: "style-source",
|
||||
mimeType: "text/plain",
|
||||
onPaste: async (data) => {
|
||||
const parsed = parseTokenTransferData(data);
|
||||
const token = parseTokenTransferData(data);
|
||||
const reusable = token.owned
|
||||
? undefined
|
||||
: parseReusableStyleSourceTransferData(data);
|
||||
const parsed = token.owned ? token : reusable!;
|
||||
const sourceType = reusable?.valid
|
||||
? reusable.data.fragment.styleSources[0]?.type
|
||||
: undefined;
|
||||
const cannotPaste = reusable?.owned
|
||||
? "Style source cannot be pasted here"
|
||||
: "Token cannot be pasted here";
|
||||
if (parsed.owned === false) {
|
||||
return pasteIgnored;
|
||||
}
|
||||
if (parsed.valid === false) {
|
||||
return { success: false, error: "Invalid token data" };
|
||||
return {
|
||||
success: false,
|
||||
error: reusable?.owned
|
||||
? "Invalid style source data"
|
||||
: "Invalid token data",
|
||||
};
|
||||
}
|
||||
const projectId = $project.get()?.id;
|
||||
const instanceId = $selectedInstance.get()?.id;
|
||||
if (projectId === undefined) {
|
||||
return { success: false, error: "Project is unavailable" };
|
||||
}
|
||||
if (instanceId === undefined) {
|
||||
return { success: false, error: "Token cannot be pasted here" };
|
||||
if (sourceType !== "tag" && instanceId === undefined) {
|
||||
return { success: false, error: cannotPaste };
|
||||
}
|
||||
try {
|
||||
const transfer = await transferFragmentAssets({
|
||||
@@ -53,17 +84,13 @@ export const token: Plugin = {
|
||||
}
|
||||
const result = executeRuntimeMutation({
|
||||
id: "designTokens.paste",
|
||||
input: {
|
||||
instanceId,
|
||||
data,
|
||||
assetIds: [...transfer.assetIds],
|
||||
},
|
||||
input: { instanceId, data, assetIds: [...transfer.assetIds] },
|
||||
});
|
||||
return result === undefined
|
||||
? { success: false, error: "Token cannot be pasted here" }
|
||||
? { success: false, error: cannotPaste }
|
||||
: pasteHandled;
|
||||
} catch {
|
||||
return { success: false, error: "Token cannot be pasted here" };
|
||||
return { success: false, error: cannotPaste };
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -16,6 +16,7 @@ import { toast, type Placement } from "@webstudio-is/design-system";
|
||||
import {
|
||||
createId,
|
||||
getHtmlTagsFromProps,
|
||||
getTagFromStyleId,
|
||||
type AssetType,
|
||||
type Instance,
|
||||
type Prop,
|
||||
@@ -72,9 +73,11 @@ export const $selectedStyleSources = atom(
|
||||
new Map<Instance["id"], StyleSource["id"]>()
|
||||
);
|
||||
export const $selectedStyleState = atom<StyleDecl["state"]>();
|
||||
export const $temporaryTagStyleId = atom<string | undefined>(undefined);
|
||||
// reset style state whenever selected instance change
|
||||
onSet($selectedInstanceSelector, () => {
|
||||
$selectedStyleState.set(undefined);
|
||||
$temporaryTagStyleId.set(undefined);
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -178,8 +181,8 @@ export const $selectedInstanceRenderState = atom<
|
||||
>("notMounted");
|
||||
|
||||
export const $selectedInstanceStatesByStyleSourceId = computed(
|
||||
[$styles, $styleSourceSelections, $selectedInstance],
|
||||
(styles, styleSourceSelections, selectedInstance) => {
|
||||
[$styles, $styleSourceSelections, $selectedInstance, $temporaryTagStyleId],
|
||||
(styles, styleSourceSelections, selectedInstance, temporaryTagStyleId) => {
|
||||
const statesByStyleSourceId = new Map<StyleSource["id"], string[]>();
|
||||
if (selectedInstance === undefined) {
|
||||
return statesByStyleSourceId;
|
||||
@@ -187,6 +190,9 @@ export const $selectedInstanceStatesByStyleSourceId = computed(
|
||||
const styleSourceIds = new Set(
|
||||
styleSourceSelections.get(selectedInstance.id)?.values
|
||||
);
|
||||
if (temporaryTagStyleId) {
|
||||
styleSourceIds.add(temporaryTagStyleId);
|
||||
}
|
||||
for (const styleDecl of styles.values()) {
|
||||
if (
|
||||
styleDecl.state === undefined ||
|
||||
@@ -208,12 +214,34 @@ export const $selectedInstanceStatesByStyleSourceId = computed(
|
||||
);
|
||||
|
||||
export const $selectedInstanceStyleSources = computed(
|
||||
[$styleSourceSelections, $styleSources, $selectedInstance],
|
||||
(styleSourceSelections, styleSources, selectedInstance) => {
|
||||
[
|
||||
$styleSourceSelections,
|
||||
$styleSources,
|
||||
$selectedInstance,
|
||||
$temporaryTagStyleId,
|
||||
],
|
||||
(
|
||||
styleSourceSelections,
|
||||
styleSources,
|
||||
selectedInstance,
|
||||
temporaryTagStyleId
|
||||
) => {
|
||||
const selectedInstanceStyleSources: StyleSource[] = [];
|
||||
if (selectedInstance === undefined) {
|
||||
return selectedInstanceStyleSources;
|
||||
}
|
||||
const tag = temporaryTagStyleId
|
||||
? getTagFromStyleId(temporaryTagStyleId)
|
||||
: undefined;
|
||||
if (tag && temporaryTagStyleId) {
|
||||
selectedInstanceStyleSources.push(
|
||||
styleSources.get(temporaryTagStyleId) ?? {
|
||||
type: "tag",
|
||||
id: temporaryTagStyleId,
|
||||
tag,
|
||||
}
|
||||
);
|
||||
}
|
||||
const styleSourceIds =
|
||||
styleSourceSelections.get(selectedInstance.id)?.values ?? [];
|
||||
let hasLocal = false;
|
||||
|
||||
@@ -327,7 +327,7 @@ export const SectionMarketplace = () => {
|
||||
|
||||
{approval.status === "UNLISTED" && (
|
||||
<Grid gap={2} css={sectionSpacing}>
|
||||
<CheckboxAndLabel>
|
||||
<CheckboxAndLabel css={{ alignItems: "flex-start" }}>
|
||||
<Checkbox
|
||||
checked={isConfirmed}
|
||||
id={ids.isConfirmed}
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type Instance,
|
||||
type StyleDecl,
|
||||
getStyleDeclKey,
|
||||
getTagStyleId,
|
||||
} from "@webstudio-is/sdk";
|
||||
import {
|
||||
createTemplateComponentFixture,
|
||||
@@ -104,6 +105,7 @@ const createModel = ({
|
||||
}
|
||||
return {
|
||||
styles,
|
||||
tagStyleIds: new Map(),
|
||||
styleSourceSelections,
|
||||
presetStyles,
|
||||
instanceTags,
|
||||
@@ -1077,6 +1079,83 @@ test("user styles are more specific than preset styles", () => {
|
||||
).toEqual({ type: "keyword", value: "red" });
|
||||
});
|
||||
|
||||
test("tag token provides the source for an unstyled matching element", () => {
|
||||
const model = createModel({
|
||||
css: "",
|
||||
jsx: <Box ws:id="box" ws:tag="p" />,
|
||||
});
|
||||
const id = getTagStyleId("p");
|
||||
const declaration: StyleDecl = {
|
||||
styleSourceId: id,
|
||||
breakpointId: "base",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
model.tagStyleIds.set("p", id);
|
||||
model.styles.set(getStyleDeclKey(declaration), declaration);
|
||||
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["box"],
|
||||
property: "color",
|
||||
}).source
|
||||
).toMatchObject({ styleSourceId: id, instanceId: "box" });
|
||||
});
|
||||
|
||||
test("selected tag token remains the source when an instance overrides it", () => {
|
||||
const model = createModel({
|
||||
css: "local { color: blue; }",
|
||||
jsx: <Box ws:id="box" ws:tag="p" class="local" />,
|
||||
});
|
||||
const id = getTagStyleId("p");
|
||||
const declaration: StyleDecl = {
|
||||
styleSourceId: id,
|
||||
breakpointId: "base",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
model.tagStyleIds.set("p", id);
|
||||
model.styles.set(getStyleDeclKey(declaration), declaration);
|
||||
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["box"],
|
||||
styleSourceId: id,
|
||||
property: "color",
|
||||
}).source
|
||||
).toMatchObject({ name: "overwritten", styleSourceId: id });
|
||||
});
|
||||
|
||||
test("base instance style wins over responsive tag style", () => {
|
||||
const model = createModel({
|
||||
css: "local { color: blue; }",
|
||||
jsx: <Box ws:id="box" ws:tag="p" class="local" />,
|
||||
matchingBreakpoints: ["base", "small"],
|
||||
});
|
||||
const id = getTagStyleId("p");
|
||||
const declaration: StyleDecl = {
|
||||
styleSourceId: id,
|
||||
breakpointId: "small",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
model.tagStyleIds.set("p", id);
|
||||
model.styles.set(getStyleDeclKey(declaration), declaration);
|
||||
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["box"],
|
||||
property: "color",
|
||||
})
|
||||
).toMatchObject({
|
||||
usedValue: { type: "keyword", value: "blue" },
|
||||
source: { styleSourceId: "local" },
|
||||
});
|
||||
});
|
||||
|
||||
test("preset styles are more specific than browser styles", () => {
|
||||
// @layer browser { body { display: block } }
|
||||
// @layer preset { body { display: flex } }
|
||||
|
||||
@@ -73,6 +73,7 @@ export type StyleValueSource = {
|
||||
export type StyleObjectModel = {
|
||||
styles: Styles;
|
||||
styleSourceSelections: StyleSourceSelections;
|
||||
tagStyleIds: Map<string, StyleDecl["styleSourceId"]>;
|
||||
// component:tag:state:property
|
||||
presetStyles: Map<string, StyleValue>;
|
||||
instanceTags: Map<Instance["id"], HtmlTags>;
|
||||
@@ -135,6 +136,7 @@ const getCascadedValue = ({
|
||||
const {
|
||||
styles,
|
||||
styleSourceSelections,
|
||||
tagStyleIds,
|
||||
presetStyles,
|
||||
instanceTags,
|
||||
instanceComponents,
|
||||
@@ -144,6 +146,7 @@ const getCascadedValue = ({
|
||||
const tag = instanceTags.get(instanceId);
|
||||
const component = instanceComponents.get(instanceId);
|
||||
let selectedIndex = -1;
|
||||
let selectedTagStyleSource: StyleValueSource | undefined;
|
||||
// store the source of latest value
|
||||
let source: StyleValueSource = { name: "default" };
|
||||
|
||||
@@ -200,8 +203,44 @@ const getCascadedValue = ({
|
||||
|
||||
// user styles
|
||||
const styleSourceIds = styleSourceSelections.get(instanceId)?.values ?? [];
|
||||
const tagStyleId = tag ? tagStyleIds.get(tag) : undefined;
|
||||
selectedStyleSourceId ??= styleSourceIds.at(-1);
|
||||
// Within each state, resolve all Tag breakpoints before instance styles.
|
||||
// Instance selectors then win over Tag selectors across breakpoints.
|
||||
for (const state of states) {
|
||||
if (tagStyleId) {
|
||||
for (const breakpointId of matchingBreakpoints) {
|
||||
const key = getStyleDeclKey({
|
||||
styleSourceId: tagStyleId,
|
||||
breakpointId,
|
||||
state,
|
||||
property: camelCaseProperty(property),
|
||||
});
|
||||
const styleDecl = styles.get(key);
|
||||
if (tagStyleId === selectedStyleSourceId && state === selectedState) {
|
||||
selectedIndex = styleDecl ? declaredValues.length : -1;
|
||||
selectedTagStyleSource = styleDecl
|
||||
? {
|
||||
name: "remote",
|
||||
instanceId,
|
||||
styleSourceId: tagStyleId,
|
||||
state,
|
||||
breakpointId,
|
||||
}
|
||||
: undefined;
|
||||
}
|
||||
if (styleDecl) {
|
||||
source = {
|
||||
name: "remote",
|
||||
instanceId,
|
||||
styleSourceId: tagStyleId,
|
||||
state,
|
||||
breakpointId,
|
||||
};
|
||||
declaredValues.push(styleDecl.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const breakpointId of matchingBreakpoints) {
|
||||
for (const styleSourceId of styleSourceIds) {
|
||||
const key = getStyleDeclKey({
|
||||
@@ -236,6 +275,9 @@ const getCascadedValue = ({
|
||||
// when reset or unselected (-1) take last declared value
|
||||
const cascadedValue = declaredValues.at(selectedIndex);
|
||||
if (cascadedValue) {
|
||||
if (selectedStyleSourceId === tagStyleId && selectedTagStyleSource) {
|
||||
source = selectedTagStyleSource;
|
||||
}
|
||||
if (selectedIndex > -1) {
|
||||
// local when selected value is latest declared
|
||||
if (selectedIndex === declaredValues.length - 1) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
$selectedInstanceOutlines,
|
||||
$selectedInstanceSelector,
|
||||
$selectedPageId,
|
||||
$temporaryTagStyleId,
|
||||
selectInstance,
|
||||
selectInstances,
|
||||
} from "../nano-states";
|
||||
@@ -372,6 +373,18 @@ describe("createObjectPool", () => {
|
||||
expect($resourcesState.get()).toBe("settled");
|
||||
});
|
||||
|
||||
test("syncs temporary Tag style selection to the canvas", () => {
|
||||
const objectPool = createObjectPool();
|
||||
|
||||
objectPool.applyTransaction({
|
||||
id: "select-tag-style",
|
||||
object: "temporaryTagStyleId",
|
||||
payload: "tag-style:button",
|
||||
});
|
||||
|
||||
expect($temporaryTagStyleId.get()).toBe("tag-style:button");
|
||||
});
|
||||
|
||||
test("syncs selected instance outlines for builder canvas overlay", () => {
|
||||
const objectPool = createObjectPool();
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
$toastErrors,
|
||||
$selectedStyleSources,
|
||||
$selectedStyleState,
|
||||
$temporaryTagStyleId,
|
||||
$dataSourceVariables,
|
||||
$dragAndDropState,
|
||||
$selectedInstanceStates,
|
||||
@@ -368,6 +369,7 @@ export const createObjectPool = () => {
|
||||
new NanostoresSyncObject("toastErrors", $toastErrors),
|
||||
new NanostoresSyncObject("selectedStyleSources", $selectedStyleSources),
|
||||
new NanostoresSyncObject("selectedStyleState", $selectedStyleState),
|
||||
new NanostoresSyncObject("temporaryTagStyleId", $temporaryTagStyleId),
|
||||
new NanostoresSyncObject("dragAndDropState", $dragAndDropState),
|
||||
new NanostoresSyncObject("ephemeralStyles", $ephemeralStyles),
|
||||
new NanostoresSyncObject("selectedInstanceStates", $selectedInstanceStates),
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
@@ -22,6 +22,7 @@
|
||||
* [🧱 CSS variables](university/foundations/css-variables.md)
|
||||
* [🖌️ Design tokens](university/foundations/design-tokens.md)
|
||||
* [🎨 Style panel](university/foundations/style-panel.md)
|
||||
* [Tag styles](university/foundations/tag-styles.md)
|
||||
* [🎯 States and selectors](university/foundations/states-and-selectors.md)
|
||||
* [🔡 Variables](university/foundations/variables.md)
|
||||
* [➕ Expression editor](university/foundations/expression-editor.md)
|
||||
|
||||
@@ -155,12 +155,13 @@ The Style Panel is located to the right of the canvas, and you can use it to cus
|
||||
<img src="../../.gitbook/assets/style-panel-light.png" alt="Style panel showing style sources, layout, grid child, and spacing controls" width="240">
|
||||
</picture>
|
||||
|
||||
There are three methods for adding styles:
|
||||
There are four methods for adding styles:
|
||||
|
||||
1. Local - By default, the Local icon is active, meaning any styles you apply to that instance are for that instance only. The dot in the middle of the Local icon indicates that it has styles, whereas no dot indicates that there are no styles applied, making it easy to identify which ones have styles applied.
|
||||
|
||||
2. [CSS variables](css-variables.md) - Instead of pasting in your colors, sizes, and other styles, you can create a variable for each style and access the variables in each input field. For example, you can define a variable called "color-primary," and in your border color field, you can enter the variable name instead of the color itself.
|
||||
3. [Tokens](design-tokens.md) - These enable reusing groupings of styles across your site. You can either create a new Token and apply styles to it or start with Local and convert it to a Token. Tokens are typically comprised of CSS variables and one-off styles.
|
||||
4. [Tag styles](tag-styles.md) - Set styles for every instance of an HTML tag, such as `h1` or `button`.
|
||||
|
||||
### Label colors
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ A Webstudio **Token** is a reusable style source that can contain multiple
|
||||
declarations and states. [Craft](../craft.md) calls it a **composite Token** to
|
||||
distinguish it from individual values stored in CSS variables.
|
||||
|
||||
[Tag styles](tag-styles.md) are a separate source for styles that apply to every instance of an HTML tag. Tokens apply only where you attach them.
|
||||
|
||||
The Design Tokens Community Group also uses _design token_ for values in its
|
||||
portable data format. Webstudio imports that format and represents its values
|
||||
as CSS variables or Webstudio Tokens according to their type and intended use.
|
||||
|
||||
@@ -50,9 +50,11 @@ You can type any valid CSS pseudo-class into the Style Sources dropdown. If it's
|
||||
{% hint style="info" %}
|
||||
Custom states can target descendants while staying scoped to the selected instance. For example, `:hover .button` targets descendants with the [custom class](custom-classes-and-attributes.md) `button` while the selected instance is hovered, and `:hover > .icon` targets only direct children with the custom class `icon`.
|
||||
|
||||
You can also select a descendant tag in a Local source or Token. For example, `p` targets paragraphs inside that instance. A [Tag style](tag-styles.md) targets one tag across the site instead.
|
||||
|
||||
Prefer [CSS variables for parent-child interactions](css-variables.md#parent-child-interactions). They keep each property on the child that uses it, can coordinate several children from one parent state, and do not couple the interaction to descendant classes or structure. Use a descendant custom state when the interaction specifically requires selector-based targeting.
|
||||
|
||||
Start the selector with a pseudo-class, pseudo-element, or attribute selector for the selected instance. You can then use a descendant (` `) or child (`>`) combinator. Selector lists, selectors that start with a type, class, or ID, and sibling combinators (`+` and `~`) are rejected because they can target elements outside the selected instance.
|
||||
Start a custom state with a pseudo-class, pseudo-element, or attribute selector for the selected instance. You can then use a descendant (` `) or child (`>`) combinator. A tag name on its own is treated as a descendant selector. Selector lists, class or ID selectors at the start, and sibling combinators (`+` and `~`) are rejected because they can target elements outside the selected instance.
|
||||
{% endhint %}
|
||||
|
||||
## Pseudo-elements
|
||||
|
||||
@@ -13,10 +13,14 @@ The Style Panel is on the right side of the builder. It exposes every CSS proper
|
||||
|
||||
## Style sources
|
||||
|
||||
At the top of the Style Panel is the **style source bar**, which determines where styles are saved and how reusable they are. There are two types of style sources:
|
||||
At the top of the Style Panel is the **style source bar**, which determines where styles are saved and how reusable they are. There are three types of style sources:
|
||||
|
||||
- **Local** — styles apply only to this instance. See [Design tokens](design-tokens.md) for the full explanation of Local vs. Tokens.
|
||||
|
||||
- **Tokens** — reusable style groups shared across multiple instances. See [Design tokens](design-tokens.md).
|
||||
- **Tag styles** — site-wide styles for an HTML tag, such as `h1` or `button`. See [Tag styles](tag-styles.md).
|
||||
|
||||
To reuse Local styles on another instance, open the Local source menu and choose **Copy**, then select the destination instance and paste. Webstudio merges the copied styles into that instance's Local source. Pasted values replace matching properties, states, and breakpoints; other Local styles remain.
|
||||
|
||||
[CSS variables](css-variables.md) are not a style source — they are named values (e.g. `--color-brand`) defined on any instance in the Advanced section and referenced inside style inputs across the site.
|
||||
|
||||
@@ -218,6 +222,7 @@ site supports before relying on them.
|
||||
## Related
|
||||
|
||||
- [Design tokens](design-tokens.md) – Local styles, tokens, and how they work together
|
||||
- [Tag styles](tag-styles.md) – Set site-wide styles for HTML tags
|
||||
- [CSS variables](css-variables.md) – Named values used inside style inputs
|
||||
- [Label colors](anatomy-of-the-webstudio-builder.md#label-colors) – What the blue, orange, and gray labels mean
|
||||
- [States and selectors](states-and-selectors.md) – Style hover, focus, and other states
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
description: Set site-wide styles for HTML tags such as div, h1, and button.
|
||||
---
|
||||
|
||||
# Tag styles
|
||||
|
||||
**Tag styles** let you change the default appearance of an HTML tag across your site. For example, set the color of `h1` once to update every `h1` element. Tag styles extend Webstudio's preset styles for that tag.
|
||||
|
||||
## Add a Tag style
|
||||
|
||||
1. Select an instance on the canvas, such as a `div`.
|
||||
2. Open the **Style sources** field at the top of the Style panel.
|
||||
3. Select `div` under **Tag style**. Its source appears first in the field.
|
||||
4. Select that source and set a style. The Tag style is saved when you add its first style.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="../../.gitbook/assets/tag-style-source-dark.png">
|
||||
<img src="../../.gitbook/assets/tag-style-source-light.png" alt="Style sources field with the div Tag style selected before a card Token and the Local source" width="240">
|
||||
</picture>
|
||||
|
||||
The source appears only while you work on the selected instance. If you select another instance and return, open the field to add it again. The saved style remains in the project and continues to affect every matching tag. Only the Tag style for the selected instance's HTML tag is offered. The Global root is the `html` tag and can also have a Tag style.
|
||||
|
||||
## Style a state
|
||||
|
||||
Open the Tag style's menu and choose a state such as `:hover` or `:focus-visible`. Set styles while that state is selected. Select the state again to return to the tag's base styles.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="../../.gitbook/assets/tag-style-states-dark.png">
|
||||
<img src="../../.gitbook/assets/tag-style-states-light.png" alt="div Tag style menu with Copy above hover and focus-visible states" width="240">
|
||||
</picture>
|
||||
|
||||
A Tag style targets its tag and state across the site. To style a descendant within one element instead, use a [custom state or selector](states-and-selectors.md#custom-states) on a Token or Local source.
|
||||
|
||||
## Copy and paste
|
||||
|
||||
Open a Tag style's menu and choose **Copy**. Paste into the **Style sources** field in another project, or use the usual paste shortcut. Webstudio merges the copied styles into the Tag style for the same tag. Pasted values replace existing values for the same property, state, and breakpoint; other styles remain. No new Token is created.
|
||||
|
||||
## How Tag styles combine with other styles
|
||||
|
||||
The Tag style source stays first in the Style sources field. Tokens follow it, and Local is last. CSS specificity and source order determine which declaration applies when several sources set the same property. Hover a property label to see its source under **Value comes from**.
|
||||
|
||||
Tag styles are separate from [Tokens](design-tokens.md). A Token applies to instances where you attach it; a Tag style applies to its HTML tag throughout the site without attaching it to an instance.
|
||||
|
||||
## Related
|
||||
|
||||
- [Style panel](style-panel.md) – Find and edit style sources
|
||||
- [States and selectors](states-and-selectors.md) – Style hover, focus, and descendants
|
||||
- [Design tokens](design-tokens.md) – Reuse styles on chosen instances
|
||||
@@ -62,10 +62,12 @@ While the server is running, stdout is reserved for MCP JSON-RPC messages. Do no
|
||||
|
||||
## One-Shot Tool Calls
|
||||
|
||||
### Token transfer
|
||||
### Style source transfer
|
||||
|
||||
Use `copy-design-token` with `tokenId` to get a transfer payload. Pass that payload as `data` to `paste-design-token` in the target project. Set `instanceId` to attach the new token to an instance; without it, paste creates the token without attaching it. Each paste creates the next numbered copy. Image and font assets transfer when both projects use the same Webstudio origin.
|
||||
|
||||
The same commands transfer all three style source types. Call `copy-design-token` with `styleSourceId` and `sourceType` set to `token`, `tag`, or `local`. The older `tokenId` input still copies a Token. Pass the returned `data` to `paste-design-token`; the payload identifies its source type. A Tag style merges into the matching global tag. A Local style merges into the Local source of the supplied `instanceId`, creating that source if needed. Pasted declarations replace matching properties, states, and breakpoints; other styles remain.
|
||||
|
||||
### Native Form actions
|
||||
|
||||
A native Form (`ResourceForm`) selects Resources through a data source. Create
|
||||
@@ -445,6 +447,7 @@ terms, agents can:
|
||||
- Bind props to expressions, resources, actions, and runtime system values.
|
||||
- Read, add, update, delete, and replace local styles.
|
||||
- Update selected style-source styles.
|
||||
- List and edit global Tag styles.
|
||||
- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.
|
||||
- List, define, rename, delete, and rewrite CSS variables.
|
||||
- List, create, update, and delete static data variables.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"bundleVersion": "bundle-1sh9iaz",
|
||||
"bundleVersion": "bundle-1u9ug3c",
|
||||
"build": {
|
||||
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
|
||||
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"bundleVersion": "bundle-1sh9iaz",
|
||||
"bundleVersion": "bundle-1u9ug3c",
|
||||
"build": {
|
||||
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
|
||||
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"bundleVersion": "bundle-1sh9iaz",
|
||||
"bundleVersion": "bundle-1u9ug3c",
|
||||
"build": {
|
||||
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
|
||||
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"bundleVersion": "bundle-1sh9iaz",
|
||||
"bundleVersion": "bundle-1u9ug3c",
|
||||
"build": {
|
||||
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
|
||||
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"bundleVersion": "bundle-1sh9iaz",
|
||||
"bundleVersion": "bundle-1u9ug3c",
|
||||
"build": {
|
||||
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
|
||||
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"bundleVersion": "bundle-1sh9iaz",
|
||||
"bundleVersion": "bundle-1u9ug3c",
|
||||
"build": {
|
||||
"id": "823cc69d-b2ed-418b-823c-2efc717319cd",
|
||||
"projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"bundleVersion": "bundle-1sh9iaz",
|
||||
"bundleVersion": "bundle-1u9ug3c",
|
||||
"build": {
|
||||
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
|
||||
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"bundleVersion": "bundle-1sh9iaz",
|
||||
"bundleVersion": "bundle-1u9ug3c",
|
||||
"build": {
|
||||
"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32",
|
||||
"projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type Asset,
|
||||
type AssetFolder,
|
||||
type Page,
|
||||
type StyleSource,
|
||||
} from "@webstudio-is/sdk";
|
||||
import {
|
||||
fontAssetFixtureFiles,
|
||||
@@ -95,9 +96,7 @@ export type EvaluationProject = {
|
||||
minWidth?: number;
|
||||
maxWidth?: number;
|
||||
}>;
|
||||
styleSources: Array<
|
||||
{ type: "token"; id: string; name: string } | { type: "local"; id: string }
|
||||
>;
|
||||
styleSources: StyleSource[];
|
||||
styleSourceSelections: Array<{ instanceId: string; values: string[] }>;
|
||||
styles: EvaluationStyle[];
|
||||
};
|
||||
|
||||
+90
-6
@@ -1,7 +1,15 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { copyDesignToken } from "@webstudio-is/project-build/runtime";
|
||||
import { getStyleDeclKey, type Asset, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import { prepareMcpTokenPasteData } from "./mcp-token-transfer";
|
||||
import {
|
||||
copyDesignToken,
|
||||
copyStyleSourceTransfer,
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import {
|
||||
getStyleDeclKey,
|
||||
getTagStyleId,
|
||||
type Asset,
|
||||
type StyleDecl,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { prepareMcpStyleSourcePasteData } from "./mcp-style-source-transfer";
|
||||
|
||||
const image: Asset = {
|
||||
id: "source-image",
|
||||
@@ -33,9 +41,85 @@ const data = copyDesignToken(
|
||||
{ tokenId: "token", sourceOrigin: "https://builder.example.com" }
|
||||
).data;
|
||||
|
||||
const tagId = getTagStyleId("button");
|
||||
const tagStyle = { ...style, styleSourceId: tagId };
|
||||
const tagData = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map([[image.id, image]]),
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSources: new Map([[tagId, { type: "tag", id: tagId, tag: "button" }]]),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: new Map([[getStyleDeclKey(tagStyle), tagStyle]]),
|
||||
},
|
||||
{
|
||||
styleSourceId: tagId,
|
||||
sourceType: "tag",
|
||||
sourceOrigin: "https://builder.example.com",
|
||||
}
|
||||
).data;
|
||||
|
||||
const localId = "local-source";
|
||||
const localStyle = { ...style, styleSourceId: localId };
|
||||
const localData = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map([[image.id, image]]),
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSources: new Map([[localId, { type: "local", id: localId }]]),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: new Map([[getStyleDeclKey(localStyle), localStyle]]),
|
||||
},
|
||||
{
|
||||
styleSourceId: localId,
|
||||
sourceType: "local",
|
||||
sourceOrigin: "https://builder.example.com",
|
||||
}
|
||||
).data;
|
||||
|
||||
test("MCP paste transfers Local style assets", async () => {
|
||||
const prepared = await prepareMcpStyleSourcePasteData({
|
||||
data: localData,
|
||||
projectOrigin: "https://builder.example.com",
|
||||
dryRun: false,
|
||||
download: async (url) => ({
|
||||
ok: true,
|
||||
url: url.href,
|
||||
arrayBuffer: async () => new ArrayBuffer(3),
|
||||
}),
|
||||
upload: async () => [{ ...image, id: "target-image", projectId: "target" }],
|
||||
refreshAssets: async () => {},
|
||||
});
|
||||
expect(prepared).toEqual([
|
||||
[
|
||||
"https://builder.example.com/cgi/image/image.png?format=raw",
|
||||
"target-image",
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
test("MCP paste transfers Tag style assets", async () => {
|
||||
const prepared = await prepareMcpStyleSourcePasteData({
|
||||
data: tagData,
|
||||
projectOrigin: "https://builder.example.com",
|
||||
dryRun: false,
|
||||
download: async (url) => ({
|
||||
ok: true,
|
||||
url: url.href,
|
||||
arrayBuffer: async () => new ArrayBuffer(3),
|
||||
}),
|
||||
upload: async () => [{ ...image, id: "target-image", projectId: "target" }],
|
||||
refreshAssets: async () => {},
|
||||
});
|
||||
expect(prepared).toEqual([
|
||||
[
|
||||
"https://builder.example.com/cgi/image/image.png?format=raw",
|
||||
"target-image",
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
test("MCP paste transfers token assets before passing data to the runtime", async () => {
|
||||
const steps: string[] = [];
|
||||
const prepared = await prepareMcpTokenPasteData({
|
||||
const prepared = await prepareMcpStyleSourcePasteData({
|
||||
data,
|
||||
projectOrigin: "https://builder.example.com",
|
||||
dryRun: false,
|
||||
@@ -71,7 +155,7 @@ test("MCP paste transfers token assets before passing data to the runtime", asyn
|
||||
test("MCP dry runs do not upload token assets", async () => {
|
||||
let requested = false;
|
||||
await expect(
|
||||
prepareMcpTokenPasteData({
|
||||
prepareMcpStyleSourcePasteData({
|
||||
data,
|
||||
projectOrigin: "https://builder.example.com",
|
||||
dryRun: true,
|
||||
@@ -94,7 +178,7 @@ test("MCP dry runs do not upload token assets", async () => {
|
||||
test("MCP paste rejects assets from another origin before downloading", async () => {
|
||||
let requested = false;
|
||||
await expect(
|
||||
prepareMcpTokenPasteData({
|
||||
prepareMcpStyleSourcePasteData({
|
||||
data,
|
||||
projectOrigin: "https://another-builder.example.com",
|
||||
dryRun: false,
|
||||
+25
-6
@@ -1,8 +1,11 @@
|
||||
import { importFragmentAssets } from "@webstudio-is/project-build/runtime";
|
||||
import { parseTokenTransferData } from "@webstudio-is/project-build/transfer";
|
||||
import {
|
||||
parseReusableStyleSourceTransferData,
|
||||
parseTokenTransferData,
|
||||
} from "@webstudio-is/project-build/transfer";
|
||||
import { getAssetUrl, type Asset } from "@webstudio-is/sdk";
|
||||
|
||||
export const prepareMcpTokenPasteData = async ({
|
||||
export const prepareMcpStyleSourcePasteData = async ({
|
||||
data,
|
||||
projectOrigin,
|
||||
dryRun,
|
||||
@@ -21,7 +24,11 @@ export const prepareMcpTokenPasteData = async ({
|
||||
) => Promise<Asset[]>;
|
||||
refreshAssets: () => Promise<unknown>;
|
||||
}) => {
|
||||
const parsed = parseTokenTransferData(data);
|
||||
const token = parseTokenTransferData(data);
|
||||
const parsed = token.owned
|
||||
? token
|
||||
: parseReusableStyleSourceTransferData(data);
|
||||
const isToken = token.owned;
|
||||
if (parsed.valid === false || parsed.data.fragment.assets.length === 0) {
|
||||
return [];
|
||||
}
|
||||
@@ -29,7 +36,11 @@ export const prepareMcpTokenPasteData = async ({
|
||||
throw new Error("Asset transfer is unavailable in dry-run mode");
|
||||
}
|
||||
if (parsed.data.sourceOrigin !== projectOrigin) {
|
||||
throw new Error("Token assets must come from this Webstudio origin");
|
||||
throw new Error(
|
||||
isToken
|
||||
? "Token assets must come from this Webstudio origin"
|
||||
: "Style source assets must come from this Webstudio origin"
|
||||
);
|
||||
}
|
||||
const transfer = await importFragmentAssets(
|
||||
[parsed.data.fragment],
|
||||
@@ -41,7 +52,11 @@ export const prepareMcpTokenPasteData = async ({
|
||||
response.ok === false ||
|
||||
new URL(response.url).origin !== projectOrigin
|
||||
) {
|
||||
throw new Error("Token asset could not be downloaded");
|
||||
throw new Error(
|
||||
isToken
|
||||
? "Token asset could not be downloaded"
|
||||
: "Style source asset could not be downloaded"
|
||||
);
|
||||
}
|
||||
const uploaded = await upload(
|
||||
asset,
|
||||
@@ -50,7 +65,11 @@ export const prepareMcpTokenPasteData = async ({
|
||||
);
|
||||
const imported = uploaded.find((item) => item.type === asset.type);
|
||||
if (imported === undefined) {
|
||||
throw new Error("Token asset could not be uploaded");
|
||||
throw new Error(
|
||||
isToken
|
||||
? "Token asset could not be uploaded"
|
||||
: "Style source asset could not be uploaded"
|
||||
);
|
||||
}
|
||||
importedAssets.set(asset.id, imported);
|
||||
}
|
||||
@@ -61,7 +61,7 @@ import {
|
||||
getPagePath,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { matchPathnameRoutes } from "@webstudio-is/wsauth";
|
||||
import { prepareMcpTokenPasteData } from "./mcp-token-transfer";
|
||||
import { prepareMcpStyleSourcePasteData } from "./mcp-style-source-transfer";
|
||||
import { fontMetaUpdate } from "@webstudio-is/fonts";
|
||||
import { resolveApiConnection } from "../api-connection";
|
||||
import {
|
||||
@@ -2155,7 +2155,7 @@ const createCliMcpHost = async ({
|
||||
) {
|
||||
operationInput = {
|
||||
...operationInput,
|
||||
assetIds: await prepareMcpTokenPasteData({
|
||||
assetIds: await prepareMcpStyleSourcePasteData({
|
||||
data: operationInput.data,
|
||||
projectOrigin,
|
||||
dryRun: dryRun === true,
|
||||
|
||||
@@ -149,8 +149,8 @@ test("prints compact mcp tool summaries as json by default", () => {
|
||||
inputSchema,
|
||||
})
|
||||
);
|
||||
// Includes Form simulation, custom response headers, screenshot, and token transfer schemas.
|
||||
expect(JSON.stringify(handshakePayload).length).toBeLessThan(224_000);
|
||||
// Includes Form simulation, custom response headers, screenshot, and all three style source transfer schemas.
|
||||
expect(JSON.stringify(handshakePayload).length).toBeLessThan(224_500);
|
||||
const screenshotTool = expectedTools.find(
|
||||
({ name }) => name === "screenshot"
|
||||
);
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
// Edit markdown files in src/docs instead.
|
||||
export const cliDocs = {
|
||||
"api-use-cases":
|
||||
'# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nest
Line truncated
|
||||
'# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nest
Line truncated
|
||||
"manual-api":
|
||||
'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## Search project data\n\nRun `webstudio search-project \'{"query":"known value"}\'` to search all Builder\nnamespaces in the local project session. Narrow it with\n`{"query":"Brand","namespaces":["styleSources","styles"]}` when only specific\nnamespaces are relevant. Results contain the current value, stable match id,\nnamespace path, owning entity, resolved references, and affected pages.\n\nValues in recognized credential fields are excluded and reported in\n`excludedSensitiveValueCount`.\n\nThe command synchronizes its required Builder namespaces, then searches locally\nand returns only matches. Namespace filters limit values matched; related\nnamespaces may still supply route and reference context, and synchronization is\nunchanged. This reduces data sent to the model, not project synchronization. It\nsearches asset metadata, not asset binaries or document contents.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\nAn Editor link with API access can patch text and editable props inside a\nContent Block. The server checks the complete batch before saving it. Pages,\nassets, component structure, and design changes still require Builder access.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand M
Line truncated
|
||||
"manual-llm":
|
||||
'# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call m
Line truncated
|
||||
"manual-mcp":
|
||||
'# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\n### Token transfer\n\nUse `copy-design-token` with `tokenId` to get a transfer payload. Pass that payload as `data` to `paste-design-token` in the target project. Set `instanceId` to attach the new token to an instance; without it, paste creates the token without attaching it. Each paste creates the next numbered copy. Image and font assets transfer when both projects use the same Webstudio origin.\n\n### Native Form actions\n\nA native Form (`ResourceForm`) selects Resources through a data source. Create\nthe Resource with `scopeInstanceId` on the Form or an ancestor and\n`exposeAsDataSource:true`; use the returned `dataSourceId` in the Form\'s `action`\nJSON array with `update-props`. Scope it to the Form when the request needs\n`formData`. Do not bind a resource prop or set `exposeAsDataSource:false` for a\nnative Form action. The selected Resource runs on submission unless page\ncontent also reads it.\n\n### Server-side Form simulation\n\n`forms.simulate-submission` evaluates a saved Form using synthetic string fields\nand the same trusted Builder server Form handler used by Builder Preview. Supply\nthe saved Form instance ID and page path. The server uses this project\'s\npublisher origin. It can trigger the Form\'s configured HTTP and Email Resources, so verify\nevery destination and recipient first. For dynamic checkbox or multiple-select fields,\npass `arrayNames` to preserve an empty oLine truncated
|
||||
'# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\n### Style source transfer\n\nUse `copy-design-token` with `tokenId` to get a transfer payload. Pass that payload as `data` to `paste-design-token` in the target project. Set `instanceId` to attach the new token to an instance; without it, paste creates the token without attaching it. Each paste creates the next numbered copy. Image and font assets transfer when both projects use the same Webstudio origin.\n\nThe same commands transfer all three style source types. Call `copy-design-token` with `styleSourceId` and `sourceType` set to `token`, `tag`, or `local`. The older `tokenId` input still copies a Token. Pass the returned `data` to `paste-design-token`; the payload identifies its source type. A Tag style merges into the matching global tag. A Local style merges into the Local source of the supplied `instanceId`, creating that source if needed. Pasted declarations replace matching properties, states, and breakpoints; other styles remain.\n\n### Native Form actions\n\nA native Form (`ResourceForm`) selects Resources through a data source. Create\nthe Resource with `scopeInstanceId` on the Form or an ancestor and\n`exposeAsDataSource:true`; use the returned `dataSourceId` in the Form\'s `action`\nJSON array with `update-props`. Scope it to the Form when the request needs\n`formData`. Do not bind a resource prop or set `exposeAsDataSource:false` for a\nnative Form action. The selected Resource rLine truncated
|
||||
"mcp-startup-epilogue":
|
||||
'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in exactly one direct `ws:block-template` child. A missing or second template container makes the block invalid. Templates themselves are protected; an editor\'s inserted copy becomes editable Content Block body content. Verify this structure before handoff.\n\nFor an MDX-backed Content Block, use the dedicated content-source tools instead of generic prop mutations: connect, switch, inspect, edit, update frontmatter, reload, or disconnect the source. Confirm before replacing existing Body content. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep template styles. A mismatched child structure replaces defaults, an explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live when matching templates are added later. Preserve invalid source and unresolved names, inspect all diagnostics, and reload before retrying a revision conflict. A frontmatter update replaces the complete property map; preserve fields the user did not ask to remove. Store frontmatter images as exact `$ref` objects; bind editable Image sources to `.src` with explicit `binding.mode:"readwrite"` and alt properties to the Asset `.description` with `mode:"read"`. Omitting the source mode leaves the image visible but not replaceable in Content mode. Only exact direct frontmatter bindings may use `mode:"readwrite"`. After a template rename or deletion, use `migrate-content-block-template-refe
Line truncated
|
||||
"mcp-vision":
|
||||
|
||||
@@ -658,6 +658,29 @@ Commands:
|
||||
|
||||
- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}
|
||||
|
||||
## Read global Tag styles
|
||||
|
||||
Commands:
|
||||
|
||||
- MCP tool: list-tag-styles {}
|
||||
- MCP tool: list-tag-styles {"tag":"button","verbose":true}
|
||||
|
||||
Notes:
|
||||
|
||||
- Tag styles apply across the project without being attached to an instance. Use `list-tag-styles` to read them; `get-styles` lists attached sources.
|
||||
- `list-design-tokens` does not include Tag styles.
|
||||
|
||||
## Update a global Tag style
|
||||
|
||||
Commands:
|
||||
|
||||
- MCP tool: update-selected-styles {"updates":[{"instanceId":"<buttonInstanceId>","styleSourceId":"tag-style:button","property":"color","value":{"type":"keyword","value":"red"}}]}
|
||||
|
||||
Notes:
|
||||
|
||||
- Use `tag-style:<tag>` to create or edit a Tag style. The first update creates its style source; no instance attachment is saved.
|
||||
- Use `delete-selected-styles` with the same `instanceId`, `styleSourceId`, and `property` to remove a declaration.
|
||||
|
||||
## Update local styles
|
||||
|
||||
Commands:
|
||||
|
||||
@@ -35,10 +35,12 @@ While the server is running, stdout is reserved for MCP JSON-RPC messages. Do no
|
||||
|
||||
## One-Shot Tool Calls
|
||||
|
||||
### Token transfer
|
||||
### Style source transfer
|
||||
|
||||
Use `copy-design-token` with `tokenId` to get a transfer payload. Pass that payload as `data` to `paste-design-token` in the target project. Set `instanceId` to attach the new token to an instance; without it, paste creates the token without attaching it. Each paste creates the next numbered copy. Image and font assets transfer when both projects use the same Webstudio origin.
|
||||
|
||||
The same commands transfer all three style source types. Call `copy-design-token` with `styleSourceId` and `sourceType` set to `token`, `tag`, or `local`. The older `tokenId` input still copies a Token. Pass the returned `data` to `paste-design-token`; the payload identifies its source type. A Tag style merges into the matching global tag. A Local style merges into the Local source of the supplied `instanceId`, creating that source if needed. Pasted declarations replace matching properties, states, and breakpoints; other styles remain.
|
||||
|
||||
### Native Form actions
|
||||
|
||||
A native Form (`ResourceForm`) selects Resources through a data source. Create
|
||||
@@ -418,6 +420,7 @@ terms, agents can:
|
||||
- Bind props to expressions, resources, actions, and runtime system values.
|
||||
- Read, add, update, delete, and replace local styles.
|
||||
- Update selected style-source styles.
|
||||
- List and edit global Tag styles.
|
||||
- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.
|
||||
- List, define, rename, delete, and rewrite CSS variables.
|
||||
- List, create, update, and delete static data variables.
|
||||
|
||||
@@ -1656,6 +1656,11 @@ export const createManagedFormResourceFetch = ({ request, context, projectDomain
|
||||
.filter(({ instanceId }) => renderedIds.has(instanceId))
|
||||
.flatMap(({ values }) => values)
|
||||
);
|
||||
for (const source of publishedStyleSources.values()) {
|
||||
if (source.type === "tag") {
|
||||
styleSourceIds.add(source.id);
|
||||
}
|
||||
}
|
||||
const pageStyles = Array.from(publishedStyles.values()).filter(
|
||||
({ styleSourceId }) => styleSourceIds.has(styleSourceId)
|
||||
);
|
||||
@@ -1712,6 +1717,7 @@ export const createManagedFormResourceFetch = ({ request, context, projectDomain
|
||||
assets,
|
||||
breakpoints: publishedBreakpoints,
|
||||
styles: publishableStyles,
|
||||
styleSources: publishedStyleSources,
|
||||
styleSourceSelections: publishedStyleSourceSelections,
|
||||
// pass only used metas to not generate unused preset styles
|
||||
componentMetas: usedMetas,
|
||||
|
||||
@@ -34,6 +34,35 @@ describe("validateSelector", () => {
|
||||
expect(validateSelector(selector).success).toBe(true);
|
||||
});
|
||||
|
||||
test.each([" p", " button:hover", " a[aria-current=page]"])(
|
||||
"accepts one descendant tag and its states: %s",
|
||||
(selector) => {
|
||||
expect(validateSelector(selector)).toMatchObject({
|
||||
success: true,
|
||||
type: "tag",
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
test.each([" p strong", " .card", " #card", " p + span"])(
|
||||
"rejects unsupported descendant tag selectors: %s",
|
||||
(selector) => {
|
||||
expect(validateSelector(selector).success).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
test("limits a tag token to states of its own tag", () => {
|
||||
expect(
|
||||
validateSelector(":hover", { allowDescendants: false }).success
|
||||
).toBe(true);
|
||||
expect(validateSelector(" p", { allowDescendants: false }).success).toBe(
|
||||
false
|
||||
);
|
||||
expect(
|
||||
validateSelector(":hover p", { allowDescendants: false }).success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test.each([
|
||||
":not-a-real-state:hover",
|
||||
":hover:not-a-real-state",
|
||||
|
||||
@@ -4,7 +4,10 @@ import { pseudoClasses } from "./__generated__/pseudo-classes";
|
||||
|
||||
export type SelectorValidationResult =
|
||||
| { success: false; error: string }
|
||||
| { success: true; type: "pseudo-class" | "pseudo-element" | "attribute" };
|
||||
| {
|
||||
success: true;
|
||||
type: "pseudo-class" | "pseudo-element" | "attribute" | "tag";
|
||||
};
|
||||
|
||||
/**
|
||||
* Validates an open CSS state suffix scoped to the current element.
|
||||
@@ -18,14 +21,21 @@ export type SelectorValidationResult =
|
||||
* @returns SelectorValidationResult with success status and type or error message
|
||||
*/
|
||||
export const validateSelector = (
|
||||
selector: string
|
||||
selector: string,
|
||||
{ allowDescendants = true }: { allowDescendants?: boolean } = {}
|
||||
): SelectorValidationResult => {
|
||||
if (!selector || selector.trim() === "") {
|
||||
return { success: false, error: "Selector cannot be empty" };
|
||||
}
|
||||
|
||||
// Must start with a colon or bracket
|
||||
if (!selector.startsWith(":") && !selector.startsWith("[")) {
|
||||
// A leading space marks a descendant tag selector. The CSS engine appends
|
||||
// state strings directly to the styled element's selector.
|
||||
const isTagSelector = selector.startsWith(" ");
|
||||
if (
|
||||
!isTagSelector &&
|
||||
!selector.startsWith(":") &&
|
||||
!selector.startsWith("[")
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
@@ -49,19 +59,42 @@ export const validateSelector = (
|
||||
const firstCombinatorIndex = selectorNodes.findIndex(
|
||||
(node) => node.type === "Combinator"
|
||||
);
|
||||
if (
|
||||
allowDescendants === false &&
|
||||
(isTagSelector || firstCombinatorIndex !== -1)
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Selector must be one state scoped to the current element",
|
||||
};
|
||||
}
|
||||
const stateNodes = selectorNodes.slice(
|
||||
0,
|
||||
firstCombinatorIndex === -1 ? undefined : firstCombinatorIndex
|
||||
);
|
||||
const hasValidTagStart =
|
||||
isTagSelector &&
|
||||
firstCombinatorIndex === -1 &&
|
||||
stateNodes[0]?.type === "TypeSelector" &&
|
||||
stateNodes
|
||||
.slice(1)
|
||||
.every(
|
||||
(node) =>
|
||||
node.type === "PseudoClassSelector" ||
|
||||
node.type === "PseudoElementSelector" ||
|
||||
node.type === "AttributeSelector"
|
||||
);
|
||||
if (
|
||||
parsedSelector?.type !== "Selector" ||
|
||||
stateNodes.length === 0 ||
|
||||
stateNodes.some(
|
||||
(node) =>
|
||||
node.type !== "PseudoClassSelector" &&
|
||||
node.type !== "PseudoElementSelector" &&
|
||||
node.type !== "AttributeSelector"
|
||||
) ||
|
||||
(!hasValidTagStart &&
|
||||
stateNodes.some(
|
||||
(node) =>
|
||||
node.type !== "PseudoClassSelector" &&
|
||||
node.type !== "PseudoElementSelector" &&
|
||||
node.type !== "AttributeSelector"
|
||||
)) ||
|
||||
(isTagSelector && !hasValidTagStart) ||
|
||||
selectorNodes.some(
|
||||
(node) =>
|
||||
node.type === "Combinator" && node.name !== " " && node.name !== ">"
|
||||
@@ -116,7 +149,7 @@ export const validateSelector = (
|
||||
// Validate that the pseudo-element actually exists
|
||||
// Some pseudo-elements are functional (e.g., ::part(), ::slotted())
|
||||
// The list includes both "part" and "part()" variants
|
||||
return { success: true, type: "pseudo-element" };
|
||||
return { success: true, type: isTagSelector ? "tag" : "pseudo-element" };
|
||||
}
|
||||
|
||||
if (pseudoClassNames.length > 0) {
|
||||
@@ -127,11 +160,15 @@ export const validateSelector = (
|
||||
) {
|
||||
return { success: true, type: "pseudo-element" };
|
||||
}
|
||||
return { success: true, type: "pseudo-class" };
|
||||
return { success: true, type: isTagSelector ? "tag" : "pseudo-class" };
|
||||
}
|
||||
|
||||
if (foundAttribute) {
|
||||
return { success: true, type: "attribute" };
|
||||
return { success: true, type: isTagSelector ? "tag" : "attribute" };
|
||||
}
|
||||
|
||||
if (isTagSelector) {
|
||||
return { success: true, type: "tag" };
|
||||
}
|
||||
|
||||
// If we get here, something unexpected happened
|
||||
|
||||
@@ -13,5 +13,4 @@ export const webstudioBrand = {
|
||||
].join(", "),
|
||||
progressGradient:
|
||||
"linear-gradient(90deg, #39fbbb00 0%, #39fbbb 20%, #4a4efa 40.03%, #e63cfe 60.02%, #ffae3c 80.04%, #ffae3c00 100%)",
|
||||
progressShadow: "0 0 32px #4a4efa80",
|
||||
} as const;
|
||||
@@ -0,0 +1,54 @@
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { Checkbox, CheckboxAndLabel } from "./checkbox";
|
||||
import { Label } from "./label";
|
||||
|
||||
let root: Root | undefined;
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
root = undefined;
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
test("consent checkboxes keep their size beside wrapped labels", () => {
|
||||
const container = document.createElement("div");
|
||||
container.style.width = "220px";
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root?.render(
|
||||
<>
|
||||
{[false, true].map((checked) => (
|
||||
<CheckboxAndLabel
|
||||
key={String(checked)}
|
||||
css={{ alignItems: "flex-start" }}
|
||||
>
|
||||
<Checkbox checked={checked} aria-label={String(checked)} />
|
||||
<Label css={{ flexShrink: 1 }}>
|
||||
I understand that by submitting, this project will become
|
||||
available in a public marketplace.
|
||||
</Label>
|
||||
</CheckboxAndLabel>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
const checkboxes = [
|
||||
...container.querySelectorAll<HTMLButtonElement>("button"),
|
||||
];
|
||||
expect(checkboxes).toHaveLength(2);
|
||||
for (const checkbox of checkboxes) {
|
||||
const { width, height, top } = checkbox.getBoundingClientRect();
|
||||
const rowTop = checkbox.parentElement?.getBoundingClientRect().top;
|
||||
expect({ width, height }).toEqual({ width: 14, height: 14 });
|
||||
expect(top).toBe(rowTop);
|
||||
}
|
||||
});
|
||||
@@ -79,3 +79,25 @@ export const Checkbox = () => {
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const MarketplaceConsent = () => (
|
||||
<StorySection title="Marketplace consent">
|
||||
<StoryGrid css={{ width: 220 }}>
|
||||
{[false, true].map((checked) => (
|
||||
<CheckboxAndLabel
|
||||
key={String(checked)}
|
||||
css={{ alignItems: "flex-start" }}
|
||||
>
|
||||
<CheckboxComponent
|
||||
checked={checked}
|
||||
aria-label={checked ? "Checked consent" : "Unchecked consent"}
|
||||
/>
|
||||
<Label css={{ flexShrink: 1 }}>
|
||||
I understand that by submitting, this project will become available
|
||||
in a public marketplace.
|
||||
</Label>
|
||||
</CheckboxAndLabel>
|
||||
))}
|
||||
</StoryGrid>
|
||||
</StorySection>
|
||||
);
|
||||
@@ -12,8 +12,10 @@ import { cssVar } from "../css-var";
|
||||
const checkboxStyle = css({
|
||||
all: "unset", // reset <button>
|
||||
|
||||
width: theme.spacing[7],
|
||||
height: theme.spacing[7],
|
||||
boxSizing: "border-box",
|
||||
width: theme.spacing[8],
|
||||
height: theme.spacing[8],
|
||||
flexShrink: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
|
||||
@@ -9,6 +9,10 @@ export const getSelectedItemBackground = (background: string) => `light-dark(
|
||||
color-mix(in oklab, ${cssVar("--background-accent")} 20%, ${background})
|
||||
)`;
|
||||
|
||||
export const toggleGroupBackground = `color-mix(in oklab, ${cssVar(
|
||||
"--background-primary"
|
||||
)} 96%, ${cssVar("--foreground-primary")})`;
|
||||
|
||||
export const selectedItemBackground = getSelectedItemBackground(
|
||||
cssVar("--background-primary")
|
||||
);
|
||||
|
||||
@@ -6,7 +6,14 @@ export default {
|
||||
title: "Label",
|
||||
};
|
||||
|
||||
const colors = ["default", "preset", "local", "overwritten", "remote"] as const;
|
||||
const colors = [
|
||||
"default",
|
||||
"preset",
|
||||
"tag",
|
||||
"local",
|
||||
"overwritten",
|
||||
"remote",
|
||||
] as const;
|
||||
|
||||
const LabelStory = () => (
|
||||
<>
|
||||
|
||||
@@ -22,6 +22,7 @@ const withInteractionOverlay = (background: string) =>
|
||||
export const labelColors = [
|
||||
"default",
|
||||
"preset",
|
||||
"tag",
|
||||
"local",
|
||||
"overwritten",
|
||||
"remote",
|
||||
@@ -79,6 +80,13 @@ const StyledLabel = styled(RadixLabel, {
|
||||
background: withInteractionOverlay(presetBackground),
|
||||
},
|
||||
},
|
||||
tag: {
|
||||
backgroundColor: styleSourceColor.tag.background,
|
||||
color: styleSourceColor.tag.foreground,
|
||||
"&:hover": {
|
||||
background: withInteractionOverlay(styleSourceColor.tag.background),
|
||||
},
|
||||
},
|
||||
local: {
|
||||
backgroundColor: styleSourceColor.local.background,
|
||||
color: styleSourceColor.local.foreground,
|
||||
|
||||
@@ -28,6 +28,12 @@ const colors = {
|
||||
backgroundHover: withInteractionOverlay(presetBackground),
|
||||
icon: cssVar("--foreground-primary"),
|
||||
},
|
||||
tag: {
|
||||
border: styleSourceColor.tag.border,
|
||||
background: styleSourceColor.tag.background,
|
||||
backgroundHover: withInteractionOverlay(styleSourceColor.tag.background),
|
||||
icon: styleSourceColor.tag.foreground,
|
||||
},
|
||||
local: {
|
||||
border: styleSourceColor.local.border,
|
||||
background: styleSourceColor.local.background,
|
||||
@@ -95,6 +101,7 @@ const style = css({
|
||||
color: {
|
||||
default: perColorStyle("default"),
|
||||
preset: perColorStyle("preset"),
|
||||
tag: perColorStyle("tag"),
|
||||
local: perColorStyle("local"),
|
||||
overwritten: perColorStyle("overwritten"),
|
||||
remote: perColorStyle("remote"),
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import "../colors/colors.css";
|
||||
import { Box } from "./box";
|
||||
import { Select } from "./select";
|
||||
|
||||
let root: Root | undefined;
|
||||
const previousColorScheme =
|
||||
document.documentElement.getAttribute("data-color-scheme");
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
root = undefined;
|
||||
document.body.innerHTML = "";
|
||||
if (previousColorScheme === null) {
|
||||
document.documentElement.removeAttribute("data-color-scheme");
|
||||
} else {
|
||||
document.documentElement.setAttribute(
|
||||
"data-color-scheme",
|
||||
previousColorScheme
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["light", "dark"] as const)(
|
||||
"Select descriptions wrap inside narrow menus in %s mode",
|
||||
async (colorScheme) => {
|
||||
document.documentElement.dataset.colorScheme = colorScheme;
|
||||
const container = document.createElement("div");
|
||||
container.style.width = "180px";
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root?.render(
|
||||
<Select
|
||||
fullWidth
|
||||
options={["block", "flex"]}
|
||||
value="block"
|
||||
getDescription={(option) => (
|
||||
<Box css={{ width: "176px" }}>
|
||||
{option === "block"
|
||||
? "Displays an element as a block-level element."
|
||||
: "Displays an element as a flexible container."}
|
||||
</Box>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
const trigger =
|
||||
container.querySelector<HTMLButtonElement>('[role="combobox"]');
|
||||
expect(trigger).not.toBeNull();
|
||||
await act(async () => await userEvent.click(trigger!));
|
||||
|
||||
const description = document.querySelector<HTMLElement>(
|
||||
'[data-select-description="content"]'
|
||||
);
|
||||
const activeDescription = description?.lastElementChild as HTMLElement;
|
||||
expect(description).not.toBeNull();
|
||||
expect(activeDescription).not.toBeNull();
|
||||
expect(activeDescription.scrollWidth).toBeLessThanOrEqual(
|
||||
activeDescription.clientWidth
|
||||
);
|
||||
expect(activeDescription.scrollHeight).toBeLessThanOrEqual(
|
||||
activeDescription.clientHeight
|
||||
);
|
||||
expect(activeDescription.clientHeight).toBeGreaterThan(
|
||||
Number.parseFloat(getComputedStyle(activeDescription).lineHeight)
|
||||
);
|
||||
}
|
||||
);
|
||||
@@ -5,6 +5,8 @@ import { Select as SelectComponent, type SelectOption } from "./select";
|
||||
import { Flex } from "./flex";
|
||||
import { Text } from "./text";
|
||||
import { StorySection } from "./storybook";
|
||||
import { Box } from "./box";
|
||||
import { theme } from "../stitches.config";
|
||||
|
||||
export default {
|
||||
title: "Select",
|
||||
@@ -148,6 +150,38 @@ export const WithItemHighlight = () => {
|
||||
);
|
||||
};
|
||||
|
||||
const displayDescriptions = {
|
||||
block: "Displays an element as a block-level element.",
|
||||
flex: "Displays an element as a flexible container.",
|
||||
};
|
||||
|
||||
export const NarrowDescription = () => {
|
||||
const [display, setDisplay] =
|
||||
useState<keyof typeof displayDescriptions>("block");
|
||||
|
||||
return (
|
||||
<StorySection title="Narrow description">
|
||||
<Flex css={{ width: 180 }}>
|
||||
<SelectComponent
|
||||
fullWidth
|
||||
options={
|
||||
Object.keys(displayDescriptions) as Array<
|
||||
keyof typeof displayDescriptions
|
||||
>
|
||||
}
|
||||
value={display}
|
||||
onChange={setDisplay}
|
||||
getDescription={(option) => (
|
||||
<Box css={{ width: theme.spacing[26] }}>
|
||||
{displayDescriptions[option]}
|
||||
</Box>
|
||||
)}
|
||||
/>
|
||||
</Flex>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const ControlledOpen = () => {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
|
||||
@@ -121,6 +121,7 @@ export const SelectItemDescription = ({
|
||||
data-select-description="content"
|
||||
css={{
|
||||
display: "grid",
|
||||
"& > * > *": { maxWidth: "100%" },
|
||||
}}
|
||||
hint
|
||||
>
|
||||
|
||||
@@ -24,8 +24,14 @@ const accentBackground = cssVar("--background-accent");
|
||||
const accentForeground = cssVar("--foreground-accent");
|
||||
|
||||
// Style-source states are a component domain, not information, warning, or
|
||||
// error intent. Their palette is derived from the theme accent locally.
|
||||
// error intent. Tag styles share the global Slot color; the other source
|
||||
// colors derive from the theme accent.
|
||||
export const styleSourceColor = {
|
||||
tag: {
|
||||
background: cssVar("--background-accent-secondary"),
|
||||
border: cssVar("--background-accent-secondary"),
|
||||
foreground: cssVar("--foreground-on-accent-secondary"),
|
||||
},
|
||||
local: createStyleSourceColor(accentBackground, accentForeground),
|
||||
overwritten: createStyleSourceColor(
|
||||
rotateBoundedBackgroundHue(accentBackground, 100),
|
||||
|
||||
@@ -101,6 +101,7 @@ import {
|
||||
parseBuildPatchTransactions,
|
||||
parseBuilderUrl,
|
||||
pasteDesignToken,
|
||||
pasteStyleSource,
|
||||
toLocalProjectBundle,
|
||||
uploadAsset,
|
||||
uploadAssets,
|
||||
@@ -172,6 +173,46 @@ const apiParams = {
|
||||
projectId: "project-id",
|
||||
};
|
||||
|
||||
test("normalizes Token and Tag paste results in pasteStyleSource", async () => {
|
||||
const fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify([{ result: { data: { tokenId: "token" } } }]),
|
||||
{
|
||||
headers: { "content-type": "application/json" },
|
||||
}
|
||||
)
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify([
|
||||
{ result: { data: { styleSourceId: "tag-style:p" } } },
|
||||
]),
|
||||
{ headers: { "content-type": "application/json" } }
|
||||
)
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify([{ result: { data: { tokenId: "legacy" } } }]),
|
||||
{
|
||||
headers: { "content-type": "application/json" },
|
||||
}
|
||||
)
|
||||
);
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
|
||||
await expect(
|
||||
pasteStyleSource({ ...apiParams, data: "token-data" })
|
||||
).resolves.toEqual({ styleSourceId: "token" });
|
||||
await expect(
|
||||
pasteStyleSource({ ...apiParams, data: "tag-data" })
|
||||
).resolves.toEqual({ styleSourceId: "tag-style:p" });
|
||||
await expect(
|
||||
pasteDesignToken({ ...apiParams, data: "token-data" })
|
||||
).resolves.toEqual({ tokenId: "legacy" });
|
||||
});
|
||||
|
||||
test("re-exports builder URL parsing from protocol", () => {
|
||||
expect(
|
||||
parseBuilderUrl(
|
||||
|
||||
@@ -2169,6 +2169,10 @@ export const listDesignTokens = projectQueryInput<
|
||||
}
|
||||
>("list-design-tokens");
|
||||
|
||||
export const listTagStyles = projectQueryInput<
|
||||
AuthProjectParams & PaginatedQueryInput & { tag?: string }
|
||||
>("list-tag-styles");
|
||||
|
||||
const queryCopyDesignToken = projectQueryInput<
|
||||
AuthProjectParams & { tokenId: string; sourceOrigin?: string },
|
||||
{ data: string }
|
||||
@@ -2183,11 +2187,48 @@ export const copyDesignToken = (
|
||||
params.sourceOrigin ?? parseBuilderUrl(params.origin).sourceOrigin,
|
||||
});
|
||||
|
||||
const queryCopyStyleSource = projectQueryInput<
|
||||
AuthProjectParams & {
|
||||
styleSourceId: string;
|
||||
sourceType: "token" | "tag" | "local";
|
||||
sourceOrigin?: string;
|
||||
},
|
||||
{ data: string }
|
||||
>("copy-design-token");
|
||||
|
||||
export const copyStyleSource = (
|
||||
params: AuthProjectParams & {
|
||||
styleSourceId: string;
|
||||
sourceType: "token" | "tag" | "local";
|
||||
sourceOrigin?: string;
|
||||
}
|
||||
) =>
|
||||
queryCopyStyleSource({
|
||||
...params,
|
||||
sourceOrigin:
|
||||
params.sourceOrigin ?? parseBuilderUrl(params.origin).sourceOrigin,
|
||||
});
|
||||
|
||||
export const pasteDesignToken = projectMutationInput<
|
||||
AuthProjectParams & { data: string; instanceId?: string },
|
||||
{ tokenId: string }
|
||||
>("paste-design-token");
|
||||
|
||||
const queryPasteStyleSource = projectMutationInput<
|
||||
AuthProjectParams & { data: string; instanceId?: string },
|
||||
{ styleSourceId: string } | { tokenId: string }
|
||||
>("paste-design-token");
|
||||
|
||||
export const pasteStyleSource = async (
|
||||
params: AuthProjectParams & { data: string; instanceId?: string }
|
||||
) => {
|
||||
const result = await queryPasteStyleSource(params);
|
||||
return {
|
||||
styleSourceId:
|
||||
"styleSourceId" in result ? result.styleSourceId : result.tokenId,
|
||||
};
|
||||
};
|
||||
|
||||
type DesignTokenStyleInput = {
|
||||
property: string;
|
||||
value: unknown;
|
||||
|
||||
+343
-18
@@ -11234,6 +11234,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -14500,6 +14516,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -17777,6 +17809,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -21043,6 +21091,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -27218,6 +27282,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -30692,6 +30772,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -33506,7 +33602,7 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
source: {
|
||||
type: "string",
|
||||
enum: ["local", "token"],
|
||||
enum: ["local", "token", "tag"],
|
||||
},
|
||||
},
|
||||
required: [
|
||||
@@ -45290,6 +45386,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -48635,6 +48747,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -55610,6 +55738,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -61572,6 +61716,22 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
required: ["type", "id", "name"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
const: "tag",
|
||||
},
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["type", "id", "tag"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -68962,7 +69122,7 @@ export const runtimeOperationContractData = [
|
||||
},
|
||||
source: {
|
||||
type: "string",
|
||||
enum: ["local", "token"],
|
||||
enum: ["local", "token", "tag"],
|
||||
},
|
||||
valueType: {
|
||||
type: "string",
|
||||
@@ -69513,23 +69673,174 @@ export const runtimeOperationContractData = [
|
||||
invalidatesNamespaces: [],
|
||||
retryOnConflict: false,
|
||||
},
|
||||
{
|
||||
id: "tagStyles.list",
|
||||
command: "list-tag-styles",
|
||||
client: "listTagStyles",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
cursor: {
|
||||
type: "string",
|
||||
},
|
||||
limit: {
|
||||
type: "integer",
|
||||
minimum: 1,
|
||||
maximum: 200,
|
||||
},
|
||||
verbose: {
|
||||
description:
|
||||
"Expand the same result with complete records and diagnostics. Omit for compact output.",
|
||||
type: "boolean",
|
||||
},
|
||||
},
|
||||
required: [],
|
||||
},
|
||||
outputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
tagStyles: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "object",
|
||||
properties: {
|
||||
id: {
|
||||
type: "string",
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
},
|
||||
declarationCount: {
|
||||
type: "integer",
|
||||
minimum: -9007199254740991,
|
||||
maximum: 9007199254740991,
|
||||
},
|
||||
declarations: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "object",
|
||||
properties: {
|
||||
property: {
|
||||
type: "string",
|
||||
},
|
||||
value: {
|
||||
type: "object",
|
||||
properties: {
|
||||
type: {
|
||||
type: "string",
|
||||
description: "CSS value kind",
|
||||
},
|
||||
hidden: {
|
||||
type: "boolean",
|
||||
},
|
||||
},
|
||||
required: ["type"],
|
||||
additionalProperties: {},
|
||||
},
|
||||
breakpoint: {
|
||||
type: "string",
|
||||
},
|
||||
state: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["property", "value", "breakpoint"],
|
||||
additionalProperties: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ["id", "tag", "declarationCount"],
|
||||
additionalProperties: {},
|
||||
},
|
||||
},
|
||||
detail: {
|
||||
type: "string",
|
||||
enum: ["compact", "verbose"],
|
||||
},
|
||||
total: {
|
||||
type: "integer",
|
||||
minimum: 0,
|
||||
maximum: 9007199254740991,
|
||||
},
|
||||
returnedCount: {
|
||||
type: "integer",
|
||||
minimum: 0,
|
||||
maximum: 9007199254740991,
|
||||
},
|
||||
nextCursor: {
|
||||
anyOf: [
|
||||
{
|
||||
type: "string",
|
||||
},
|
||||
{
|
||||
type: "null",
|
||||
},
|
||||
],
|
||||
},
|
||||
filters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
additionalProperties: {},
|
||||
required: [],
|
||||
},
|
||||
},
|
||||
required: [
|
||||
"tagStyles",
|
||||
"detail",
|
||||
"total",
|
||||
"returnedCount",
|
||||
"nextCursor",
|
||||
"filters",
|
||||
],
|
||||
additionalProperties: {},
|
||||
},
|
||||
readNamespaces: ["styleSources", "styles"],
|
||||
writeNamespaces: [],
|
||||
invalidatesNamespaces: [],
|
||||
retryOnConflict: false,
|
||||
},
|
||||
{
|
||||
id: "designTokens.copy",
|
||||
command: "copy-design-token",
|
||||
client: "copyDesignToken",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
tokenId: {
|
||||
type: "string",
|
||||
anyOf: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
tokenId: {
|
||||
type: "string",
|
||||
},
|
||||
sourceOrigin: {
|
||||
type: "string",
|
||||
format: "uri",
|
||||
},
|
||||
},
|
||||
required: ["tokenId"],
|
||||
},
|
||||
sourceOrigin: {
|
||||
type: "string",
|
||||
format: "uri",
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
styleSourceId: {
|
||||
type: "string",
|
||||
},
|
||||
sourceType: {
|
||||
type: "string",
|
||||
enum: ["token", "tag", "local"],
|
||||
},
|
||||
sourceOrigin: {
|
||||
type: "string",
|
||||
format: "uri",
|
||||
},
|
||||
},
|
||||
required: ["styleSourceId", "sourceType"],
|
||||
},
|
||||
},
|
||||
required: ["tokenId"],
|
||||
],
|
||||
},
|
||||
outputSchema: {
|
||||
type: "object",
|
||||
@@ -69587,14 +69898,28 @@ export const runtimeOperationContractData = [
|
||||
required: ["data"],
|
||||
},
|
||||
outputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
tokenId: {
|
||||
type: "string",
|
||||
anyOf: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
tokenId: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["tokenId"],
|
||||
additionalProperties: {},
|
||||
},
|
||||
},
|
||||
required: ["tokenId"],
|
||||
additionalProperties: {},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
styleSourceId: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["styleSourceId"],
|
||||
additionalProperties: {},
|
||||
},
|
||||
],
|
||||
},
|
||||
readNamespaces: [
|
||||
"assets",
|
||||
|
||||
@@ -898,7 +898,12 @@ describe("project session mcp adapter", () => {
|
||||
"copy-design-token",
|
||||
"paste-design-token",
|
||||
]);
|
||||
expect(tokenTools[0]?.inputSchema.required).toContain("tokenId");
|
||||
expect(tokenTools[0]?.inputSchema).toMatchObject({
|
||||
anyOf: expect.arrayContaining([
|
||||
expect.objectContaining({ required: ["tokenId"] }),
|
||||
expect.objectContaining({ required: ["styleSourceId", "sourceType"] }),
|
||||
]),
|
||||
});
|
||||
expect(tokenTools[1]?.inputSchema.required).toContain("data");
|
||||
const responseHeaderTools = listProjectSessionMcpTools(
|
||||
runtimeOperationContracts
|
||||
|
||||
@@ -4587,8 +4587,13 @@ const capabilityAreas = [
|
||||
goal: "Read and change styles, design tokens, CSS variables, and breakpoints.",
|
||||
tools: [
|
||||
"get-styles",
|
||||
"list-tag-styles",
|
||||
"copy-design-token",
|
||||
"paste-design-token",
|
||||
"update-styles",
|
||||
"delete-styles",
|
||||
"update-selected-styles",
|
||||
"delete-selected-styles",
|
||||
"replace-styles",
|
||||
"list-design-tokens",
|
||||
"create-design-token",
|
||||
@@ -7305,6 +7310,9 @@ const workflowOnlyGuideToolNames = new Set([
|
||||
]);
|
||||
const designSystemGuideToolNames = new Set([
|
||||
"list-design-tokens",
|
||||
"list-tag-styles",
|
||||
"copy-design-token",
|
||||
"paste-design-token",
|
||||
"attach-design-token",
|
||||
"update-design-token-styles",
|
||||
]);
|
||||
|
||||
@@ -218,6 +218,7 @@ export const builderRuntimeCutoverManifests = [
|
||||
family: "style-reads",
|
||||
operationIds: [
|
||||
"styles.getDeclarations",
|
||||
"tagStyles.list",
|
||||
"designTokens.list",
|
||||
"designTokens.copy",
|
||||
] as const,
|
||||
@@ -226,6 +227,7 @@ export const builderRuntimeCutoverManifests = [
|
||||
"appRouter.api.designTokens",
|
||||
"Builder token menu",
|
||||
"MCP/CLI token transfer",
|
||||
"MCP/CLI Tag style discovery",
|
||||
] as const,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,6 +1,28 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { copyDesignToken } from "../token-transfer";
|
||||
import { parseTokenTransferData, serializeTokenCss } from "./token-css";
|
||||
import {
|
||||
parseTagStyleTransferData,
|
||||
parseTokenTransferData,
|
||||
serializeTokenCss,
|
||||
} from "./token-css";
|
||||
|
||||
test("Tag style clipboard data accepts only a supported tag and its CSS selector", () => {
|
||||
expect(
|
||||
parseTagStyleTransferData(
|
||||
'/* @webstudio/tag-style-css/v1 "not-a-tag" */\n.ws-tag-style { color: red; }'
|
||||
).valid
|
||||
).toBe(false);
|
||||
expect(
|
||||
parseTagStyleTransferData(
|
||||
'/* @webstudio/tag-style-css/v1 "button" */\n.ws-token { color: red; }'
|
||||
).valid
|
||||
).toBe(false);
|
||||
expect(
|
||||
parseTagStyleTransferData(
|
||||
'/* @webstudio/tag-style-css/v1 "button" */\n.ws-tag-style p { color: red; }'
|
||||
).valid
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("reads a CSS token with variables, states, breakpoints, images, and fonts", () => {
|
||||
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
extractCssCustomProperties,
|
||||
parseCss,
|
||||
parseMediaQuery,
|
||||
validateSelector,
|
||||
} from "@webstudio-is/css-data";
|
||||
import {
|
||||
createRegularStyleSheet,
|
||||
@@ -16,6 +17,8 @@ import {
|
||||
} from "@webstudio-is/fonts";
|
||||
import {
|
||||
getAssetUrl,
|
||||
getTagStyleId,
|
||||
isTagStyleTag,
|
||||
type Asset,
|
||||
type Breakpoint,
|
||||
type WebstudioFragment,
|
||||
@@ -38,12 +41,24 @@ export type TokenTransferData = {
|
||||
sourceOrigin?: string;
|
||||
};
|
||||
|
||||
export const serializeTokenCss = (data: TokenTransferData): string => {
|
||||
type TransferKind = "token" | "tag" | "local";
|
||||
|
||||
const transferFormat = (kind: TransferKind) =>
|
||||
kind === "token"
|
||||
? { namespace: "token-css", selector: ".ws-token" }
|
||||
: kind === "tag"
|
||||
? { namespace: "tag-style-css", selector: ".ws-tag-style" }
|
||||
: { namespace: "local-style-css", selector: ".ws-local" };
|
||||
|
||||
export const serializeTokenCss = (
|
||||
data: TokenTransferData,
|
||||
kind: TransferKind = "token"
|
||||
): string => {
|
||||
const { fragment, sourceOrigin } = data;
|
||||
const token = fragment.styleSources.find(
|
||||
(source) => source.id === data.tokenId
|
||||
);
|
||||
if (token?.type !== "token") {
|
||||
if (token?.type !== kind) {
|
||||
throw new Error("Invalid token data");
|
||||
}
|
||||
const sheet = createRegularStyleSheet({ element: new FakeStyleElement() });
|
||||
@@ -96,15 +111,23 @@ export const serializeTokenCss = (data: TokenTransferData): string => {
|
||||
});
|
||||
}
|
||||
sheet.addNestingRule(":root").applyMixins([rootId]);
|
||||
sheet.addNestingRule(".ws-token").applyMixins([data.tokenId]);
|
||||
sheet
|
||||
.addNestingRule(transferFormat(kind).selector)
|
||||
.applyMixins([data.tokenId]);
|
||||
const fonts = fragment.assets.filter((asset) => asset.type === "font");
|
||||
for (const face of getFontFaces(fonts, {
|
||||
assetBaseUrl: sourceOrigin ? `${sourceOrigin}/cgi/asset/` : "/cgi/asset/",
|
||||
})) {
|
||||
sheet.addFontFaceRule(face);
|
||||
}
|
||||
const name = JSON.stringify(token.name).replaceAll("*/", "*\\/");
|
||||
return `/* @webstudio/token-css/v1 ${name} */\n${sheet.cssText}`;
|
||||
const name = JSON.stringify(
|
||||
token.type === "token"
|
||||
? token.name
|
||||
: token.type === "tag"
|
||||
? token.tag
|
||||
: "local"
|
||||
).replaceAll("*/", "*\\/");
|
||||
return `/* @webstudio/${transferFormat(kind).namespace}/v1 ${name} */\n${sheet.cssText}`;
|
||||
};
|
||||
|
||||
type ParsedTokenCss =
|
||||
@@ -163,18 +186,24 @@ const assetFromUrl = (
|
||||
return { ...common, type, format, meta: { width: 0, height: 0 } };
|
||||
};
|
||||
|
||||
export const parseTokenTransferData = (source: string): ParsedTokenCss => {
|
||||
const parseStyleSourceTransferData = (
|
||||
source: string,
|
||||
kind: TransferKind
|
||||
): ParsedTokenCss => {
|
||||
const format = transferFormat(kind);
|
||||
const pragma = parseWebstudioPragma({
|
||||
source,
|
||||
syntax: "css",
|
||||
namespace: "token-css",
|
||||
namespace: format.namespace,
|
||||
});
|
||||
if (pragma.valid === false) {
|
||||
return pragma;
|
||||
}
|
||||
if (
|
||||
pragma.version !== "v1" ||
|
||||
pragma.value === undefined ||
|
||||
typeof pragma.value !== "string" ||
|
||||
(kind === "tag" && !isTagStyleTag(pragma.value)) ||
|
||||
(kind === "local" && pragma.value !== "local") ||
|
||||
source.slice(0, pragma.start).trim() !== ""
|
||||
) {
|
||||
return { owned: true, valid: false };
|
||||
@@ -212,7 +241,7 @@ export const parseTokenTransferData = (source: string): ParsedTokenCss => {
|
||||
(item) =>
|
||||
item.type === "Selector" &&
|
||||
item.children.first?.type === "ClassSelector" &&
|
||||
item.children.first.name === "ws-token"
|
||||
item.children.first.name === format.selector.slice(1)
|
||||
);
|
||||
return node.block !== null && (rootSelector || tokenSelector);
|
||||
}
|
||||
@@ -297,7 +326,7 @@ export const parseTokenTransferData = (source: string): ParsedTokenCss => {
|
||||
const name =
|
||||
selector.children.first?.type === "PseudoClassSelector"
|
||||
? ":root"
|
||||
: ".ws-token";
|
||||
: format.selector;
|
||||
return {
|
||||
name,
|
||||
state: cssTree.generate(selector).slice(name.length) || undefined,
|
||||
@@ -307,7 +336,13 @@ export const parseTokenTransferData = (source: string): ParsedTokenCss => {
|
||||
if (
|
||||
parsed.errors.length > 0 ||
|
||||
parsed.styles.some(
|
||||
(style) => style.selector === ":root" && !style.property.startsWith("--")
|
||||
(style) =>
|
||||
(style.selector === ":root" && !style.property.startsWith("--")) ||
|
||||
(kind === "tag" &&
|
||||
style.selector !== ":root" &&
|
||||
style.state !== undefined &&
|
||||
validateSelector(style.state, { allowDescendants: false }).success ===
|
||||
false)
|
||||
)
|
||||
) {
|
||||
return { owned: true, valid: false };
|
||||
@@ -399,6 +434,7 @@ export const parseTokenTransferData = (source: string): ParsedTokenCss => {
|
||||
sourceOrigin = url.origin;
|
||||
}
|
||||
}
|
||||
const tagStyleId = kind === "tag" ? getTagStyleId(pragma.value) : tokenId;
|
||||
const fragment: WebstudioFragment = {
|
||||
children: [],
|
||||
instances: [],
|
||||
@@ -406,7 +442,13 @@ export const parseTokenTransferData = (source: string): ParsedTokenCss => {
|
||||
dataSources: [],
|
||||
resources: [],
|
||||
styleSourceSelections: [],
|
||||
styleSources: [{ type: "token", id: tokenId, name: pragma.value }],
|
||||
styleSources: [
|
||||
kind === "token"
|
||||
? { type: "token", id: tokenId, name: pragma.value }
|
||||
: kind === "tag"
|
||||
? { type: "tag", id: tagStyleId, tag: pragma.value }
|
||||
: { type: "local", id: tokenId },
|
||||
],
|
||||
styles,
|
||||
breakpoints: [...breakpoints.values()],
|
||||
assets: [...assets.values()],
|
||||
@@ -414,6 +456,34 @@ export const parseTokenTransferData = (source: string): ParsedTokenCss => {
|
||||
return {
|
||||
owned: true,
|
||||
valid: true,
|
||||
data: { tokenId, fragment, sourceOrigin },
|
||||
data: {
|
||||
tokenId: tagStyleId,
|
||||
fragment: {
|
||||
...fragment,
|
||||
styles:
|
||||
kind === "token"
|
||||
? fragment.styles
|
||||
: fragment.styles.map((style) =>
|
||||
style.styleSourceId === tokenId
|
||||
? { ...style, styleSourceId: tagStyleId }
|
||||
: style
|
||||
),
|
||||
},
|
||||
sourceOrigin,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const parseTokenTransferData = (source: string) =>
|
||||
parseStyleSourceTransferData(source, "token");
|
||||
|
||||
export const parseTagStyleTransferData = (source: string) =>
|
||||
parseStyleSourceTransferData(source, "tag");
|
||||
|
||||
export const parseLocalStyleTransferData = (source: string) =>
|
||||
parseStyleSourceTransferData(source, "local");
|
||||
|
||||
export const parseReusableStyleSourceTransferData = (source: string) => {
|
||||
const tagStyle = parseTagStyleTransferData(source);
|
||||
return tagStyle.owned ? tagStyle : parseLocalStyleTransferData(source);
|
||||
};
|
||||
@@ -333,6 +333,9 @@ const createStyleSource = (
|
||||
name: id,
|
||||
};
|
||||
}
|
||||
if (type === "tag") {
|
||||
return { type, id, tag: "div" };
|
||||
}
|
||||
return {
|
||||
type,
|
||||
id,
|
||||
|
||||
@@ -164,7 +164,7 @@ const declaration = looseObject({
|
||||
value: styleValue,
|
||||
breakpoint: id,
|
||||
state: z.string().optional(),
|
||||
source: z.enum(["local", "token"]),
|
||||
source: z.enum(["local", "token", "tag"]),
|
||||
});
|
||||
const declarationSummary = declaration.omit({ value: true }).extend({
|
||||
valueType: z.string(),
|
||||
@@ -177,6 +177,21 @@ const token = looseObject({
|
||||
styles: z.record(z.string(), styleValue).optional(),
|
||||
usageCount: z.number().int().optional(),
|
||||
});
|
||||
const tagStyle = looseObject({
|
||||
id,
|
||||
tag: z.string(),
|
||||
declarationCount: z.number().int(),
|
||||
declarations: z
|
||||
.array(
|
||||
looseObject({
|
||||
property: z.string(),
|
||||
value: styleValue,
|
||||
breakpoint: id,
|
||||
state: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
const cssVariable = looseObject({
|
||||
name: z.string(),
|
||||
value: z.string(),
|
||||
@@ -659,8 +674,15 @@ export const runtimeOutputSchemas = {
|
||||
"styles.deleteSelectedDeclarations": styleKeysResult,
|
||||
"styles.replaceValues": styleKeysResult,
|
||||
"designTokens.list": looseObject({ tokens: z.array(token), ...outputPage }),
|
||||
"tagStyles.list": looseObject({
|
||||
tagStyles: z.array(tagStyle),
|
||||
...outputPage,
|
||||
}),
|
||||
"designTokens.copy": looseObject({ data: z.string() }),
|
||||
"designTokens.paste": looseObject({ tokenId: id }),
|
||||
"designTokens.paste": z.union([
|
||||
looseObject({ tokenId: id }),
|
||||
looseObject({ styleSourceId: id }),
|
||||
]),
|
||||
"designTokens.create": looseObject({ tokenIds: stringArray }),
|
||||
"designTokens.import": looseObject({
|
||||
plan: z.array(designTokenImportPlanEntrySchema),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
coreMetas,
|
||||
getStyleDeclKey,
|
||||
getTagStyleId,
|
||||
getInputJsonSchemaMetadata,
|
||||
ROOT_INSTANCE_ID,
|
||||
rootComponent,
|
||||
@@ -90,6 +91,7 @@ const paginatedReadOperationIds = [
|
||||
"instances.listTexts",
|
||||
"styles.getDeclarations",
|
||||
"designTokens.list",
|
||||
"tagStyles.list",
|
||||
"cssVariables.list",
|
||||
"variables.list",
|
||||
"resources.list",
|
||||
@@ -320,6 +322,35 @@ test.each(paginatedReadOperationIds)(
|
||||
}
|
||||
);
|
||||
|
||||
test("lists global Tag styles through the runtime command", () => {
|
||||
const id = getTagStyleId("h1");
|
||||
const declaration: StyleDecl = {
|
||||
styleSourceId: id,
|
||||
breakpointId: "base",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
const result = executeBuilderRuntimeOperation({
|
||||
id: "tagStyles.list",
|
||||
state: {
|
||||
styleSources: new Map([[id, { id, type: "tag", tag: "h1" }]]),
|
||||
styles: new Map([[getStyleDeclKey(declaration), declaration]]),
|
||||
},
|
||||
input: { tag: "h1", verbose: true },
|
||||
context,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
tagStyles: [
|
||||
{
|
||||
id,
|
||||
tag: "h1",
|
||||
declarationCount: 1,
|
||||
declarations: [{ property: "color", breakpoint: "base" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const getMutationResult = (operation: unknown): unknown => {
|
||||
expect(operation).toHaveProperty("result");
|
||||
return (operation as { result: unknown }).result;
|
||||
@@ -2905,6 +2936,12 @@ describe("builder runtime registry", () => {
|
||||
"styles.deleteDeclarations",
|
||||
{ deletions: [{ instanceId: "heading", property: "color" }] },
|
||||
],
|
||||
[
|
||||
"designTokens.paste",
|
||||
{
|
||||
data: '/* @webstudio/tag-style-css/v1 "h1" */\n.ws-tag-style { color: red; }',
|
||||
},
|
||||
],
|
||||
[
|
||||
"designTokens.create",
|
||||
{
|
||||
|
||||
@@ -473,6 +473,10 @@ const designTokenListInput = z.object({
|
||||
sort: z.enum(["name", "usage"]).optional(),
|
||||
...paginatedOutputInputSchema.shape,
|
||||
});
|
||||
const tagStyleListInput = z.object({
|
||||
tag: z.string().optional(),
|
||||
...paginatedOutputInputSchema.shape,
|
||||
});
|
||||
const cssVariableListInput = z.object({
|
||||
filter: z.string().optional(),
|
||||
withUsage: z.boolean().optional(),
|
||||
@@ -1851,12 +1855,19 @@ export const builderRuntimeOperations = [
|
||||
designTokenListInput,
|
||||
({ state, input }) => styles.listDesignTokens(state, input)
|
||||
),
|
||||
runtimeOperation(
|
||||
"tagStyles.list",
|
||||
api("list-tag-styles", "listTagStyles"),
|
||||
readContract(["styleSources", "styles"]),
|
||||
tagStyleListInput,
|
||||
({ state, input }) => styles.listTagStyles(state, input)
|
||||
),
|
||||
runtimeOperation(
|
||||
"designTokens.copy",
|
||||
api("copy-design-token", "copyDesignToken"),
|
||||
readContract(["assets", "breakpoints", ...styleNamespaces]),
|
||||
tokenTransfer.copyDesignTokenInput,
|
||||
({ state, input }) => tokenTransfer.copyDesignToken(state, input)
|
||||
({ state, input }) => tokenTransfer.copyStyleSourceTransfer(state, input)
|
||||
),
|
||||
runtimeOperation(
|
||||
"designTokens.paste",
|
||||
@@ -1877,7 +1888,7 @@ export const builderRuntimeOperations = [
|
||||
}),
|
||||
tokenTransfer.pasteDesignTokenInput,
|
||||
({ state, input, context }) =>
|
||||
tokenTransfer.pasteDesignToken(state, input, context)
|
||||
tokenTransfer.pasteStyleSourceTransfer(state, input, context)
|
||||
),
|
||||
runtimeOperation(
|
||||
"designTokens.create",
|
||||
|
||||
@@ -348,10 +348,9 @@ export const insertStyleSources = ({
|
||||
};
|
||||
|
||||
for (const styleSource of fragmentStyleSources) {
|
||||
if (styleSource.type === "local") {
|
||||
if (styleSource.type !== "token") {
|
||||
continue;
|
||||
}
|
||||
styleSource.type satisfies "token";
|
||||
|
||||
const originalFragmentTokenId = styleSource.id;
|
||||
const referencedTokenId = referencedTokenIds?.get(originalFragmentTokenId);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
type Breakpoint,
|
||||
getStyleDeclKey,
|
||||
getTagStyleId,
|
||||
ROOT_INSTANCE_ID,
|
||||
type Instance,
|
||||
type Prop,
|
||||
@@ -51,6 +52,7 @@ import {
|
||||
getReferencedCssVariables,
|
||||
getStyleSourceInsertionIndex,
|
||||
getStyleDeclarations,
|
||||
listTagStyles,
|
||||
getUnusedCssVariableNames,
|
||||
performCssVariableRename,
|
||||
renameCssVariable,
|
||||
@@ -1591,6 +1593,119 @@ describe("runtime style operations", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("editing a tag token creates a global source without attaching it", () => {
|
||||
const id = getTagStyleId("button");
|
||||
const mutation = updateSelectedStyleDeclarations(
|
||||
{
|
||||
breakpoints: runtimeBreakpoints,
|
||||
instances: toMap([instance("button-instance")]),
|
||||
styles: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
},
|
||||
{
|
||||
updates: [
|
||||
{
|
||||
instanceId: "button-instance",
|
||||
styleSourceId: id,
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
state: ":hover",
|
||||
},
|
||||
],
|
||||
}
|
||||
);
|
||||
|
||||
expect(mutation.payload).toContainEqual({
|
||||
namespace: "styleSources",
|
||||
patches: [
|
||||
{
|
||||
op: "add",
|
||||
path: [id],
|
||||
value: { type: "tag", id, tag: "button" },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(mutation.payload).toContainEqual({
|
||||
namespace: "styles",
|
||||
patches: [
|
||||
expect.objectContaining({
|
||||
path: [`${id}:desktop:color::hover`],
|
||||
value: expect.objectContaining({
|
||||
styleSourceId: id,
|
||||
state: ":hover",
|
||||
}),
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(
|
||||
mutation.payload.some(
|
||||
(change) => change.namespace === "styleSourceSelections"
|
||||
)
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("editing the html Tag style from Global root creates a global source", () => {
|
||||
const id = getTagStyleId("html");
|
||||
const mutation = updateSelectedStyleDeclarations(
|
||||
{
|
||||
breakpoints: runtimeBreakpoints,
|
||||
instances: new Map(),
|
||||
styles: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
},
|
||||
{
|
||||
updates: [
|
||||
{
|
||||
instanceId: ROOT_INSTANCE_ID,
|
||||
styleSourceId: id,
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
},
|
||||
],
|
||||
}
|
||||
);
|
||||
|
||||
expect(mutation.payload).toContainEqual({
|
||||
namespace: "styleSources",
|
||||
patches: [
|
||||
{ op: "add", path: [id], value: { type: "tag", id, tag: "html" } },
|
||||
],
|
||||
});
|
||||
expect(
|
||||
mutation.payload.some(
|
||||
(change) => change.namespace === "styleSourceSelections"
|
||||
)
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects a descendant selector on a tag token", () => {
|
||||
const id = getTagStyleId("button");
|
||||
expect(() =>
|
||||
updateSelectedStyleDeclarations(
|
||||
{
|
||||
breakpoints: runtimeBreakpoints,
|
||||
instances: toMap([instance("button-instance")]),
|
||||
styles: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
},
|
||||
{
|
||||
updates: [
|
||||
{
|
||||
instanceId: "button-instance",
|
||||
styleSourceId: id,
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
state: " p",
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
test("renames, locks, and deletes style sources", () => {
|
||||
const styleSources = sources([token("token", "Primary")]);
|
||||
|
||||
@@ -2029,6 +2144,47 @@ describe("serializeDesignTokens", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("lists global Tag styles separately from design tokens", () => {
|
||||
const divId = getTagStyleId("div");
|
||||
const buttonId = getTagStyleId("button");
|
||||
const declaration: StyleDecl = {
|
||||
styleSourceId: divId,
|
||||
breakpointId: "base",
|
||||
property: "color",
|
||||
state: ":hover",
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
const state = {
|
||||
styleSources: new Map<string, StyleSource>([
|
||||
[divId, { type: "tag", id: divId, tag: "div" }],
|
||||
[buttonId, { type: "tag", id: buttonId, tag: "button" }],
|
||||
["token", { type: "token", id: "token", name: "Primary" }],
|
||||
]),
|
||||
styles: new Map([[getStyleDeclKey(declaration), declaration]]),
|
||||
};
|
||||
expect(listTagStyles(state).tagStyles).toEqual([
|
||||
{ id: buttonId, tag: "button", declarationCount: 0 },
|
||||
{ id: divId, tag: "div", declarationCount: 1 },
|
||||
]);
|
||||
expect(listTagStyles(state, { tag: "div", verbose: true }).tagStyles).toEqual(
|
||||
[
|
||||
{
|
||||
id: divId,
|
||||
tag: "div",
|
||||
declarationCount: 1,
|
||||
declarations: [
|
||||
{
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
breakpoint: "base",
|
||||
state: ":hover",
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test("expands style values without changing pagination or filters", () => {
|
||||
const largeValue = {
|
||||
type: "unparsed" as const,
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import {
|
||||
createId,
|
||||
getStyleDeclKey,
|
||||
getTagFromStyleId,
|
||||
ROOT_INSTANCE_ID,
|
||||
styleDecl as styleDeclSchema,
|
||||
type Breakpoint,
|
||||
@@ -128,6 +129,59 @@ export const serializeDesignTokens = ({
|
||||
return { tokens: items, ...pagination };
|
||||
};
|
||||
|
||||
export const listTagStyles = (
|
||||
state: Pick<BuilderState, "styles" | "styleSources">,
|
||||
input: PaginatedOutputInput & { tag?: string } = {}
|
||||
) => {
|
||||
if (state.styles === undefined || state.styleSources === undefined) {
|
||||
return throwBuilderRuntimeError(
|
||||
"BAD_REQUEST",
|
||||
"Style namespaces are missing"
|
||||
);
|
||||
}
|
||||
const declarationsBySource = new Map<string, StyleDecl[]>();
|
||||
for (const declaration of state.styles.values()) {
|
||||
const declarations =
|
||||
declarationsBySource.get(declaration.styleSourceId) ?? [];
|
||||
declarations.push(declaration);
|
||||
declarationsBySource.set(declaration.styleSourceId, declarations);
|
||||
}
|
||||
const tagStyles = Array.from(state.styleSources.values())
|
||||
.filter((source) => source.type === "tag")
|
||||
.filter((source) => input.tag === undefined || source.tag === input.tag)
|
||||
.sort((left, right) => left.tag.localeCompare(right.tag))
|
||||
.map((source) => {
|
||||
const declarations = declarationsBySource.get(source.id) ?? [];
|
||||
return projectOutput({
|
||||
input,
|
||||
compact: {
|
||||
id: source.id,
|
||||
tag: source.tag,
|
||||
declarationCount: declarations.length,
|
||||
},
|
||||
expanded: () => ({
|
||||
declarations: declarations.map(
|
||||
({ property, value, breakpointId, state }) => ({
|
||||
property,
|
||||
value,
|
||||
breakpoint: breakpointId,
|
||||
state,
|
||||
})
|
||||
),
|
||||
}),
|
||||
});
|
||||
});
|
||||
const { items, ...pagination } = paginateOutput({
|
||||
items: tagStyles,
|
||||
cursor: input.cursor,
|
||||
limit: input.limit,
|
||||
filters: { tag: input.tag },
|
||||
verbose: input.verbose,
|
||||
invalidCursorMessage: "Invalid Tag style cursor",
|
||||
});
|
||||
return { tagStyles: items, ...pagination };
|
||||
};
|
||||
|
||||
const getRequiredStyleState = (
|
||||
state: Pick<BuilderState, "styles" | "styleSources" | "styleSourceSelections">
|
||||
) => {
|
||||
@@ -2236,7 +2290,11 @@ export const deleteStyleSources = (
|
||||
) => {
|
||||
const styleState = getRequiredStyleState(state);
|
||||
for (const styleSourceId of input.styleSourceIds) {
|
||||
if (styleState.styleSources.has(styleSourceId) === false) {
|
||||
const source = styleState.styleSources.get(styleSourceId);
|
||||
if (source === undefined) {
|
||||
return throwBuilderRuntimeError("NOT_FOUND", "Style source not found");
|
||||
}
|
||||
if (source.type === "tag") {
|
||||
return throwBuilderRuntimeError("NOT_FOUND", "Style source not found");
|
||||
}
|
||||
}
|
||||
@@ -2458,7 +2516,7 @@ export const duplicateStyleSource = (
|
||||
if (styleSource === undefined) {
|
||||
return throwBuilderRuntimeError("NOT_FOUND", "Style source not found");
|
||||
}
|
||||
if (styleSource.type === "local") {
|
||||
if (styleSource.type !== "token") {
|
||||
return throwBuilderRuntimeError(
|
||||
"BAD_REQUEST",
|
||||
"Local style sources cannot be duplicated. Convert the local style source to a design token first."
|
||||
@@ -3138,33 +3196,36 @@ export const createSelectedStyleDeclarationUpdatePayload = ({
|
||||
nextStyleSourceIds.add(update.styleSource.id);
|
||||
}
|
||||
|
||||
const selection = styleSourceSelectionByInstanceId.get(update.instanceId);
|
||||
const hasPendingSelection =
|
||||
selection === undefined &&
|
||||
nextSelectionValuesByInstanceId.has(update.instanceId);
|
||||
const selectionValues =
|
||||
nextSelectionValuesByInstanceId.get(update.instanceId) ?? [];
|
||||
if (selectionValues.includes(update.styleSourceId) === false) {
|
||||
styleSelectionPatches.push(
|
||||
selection === undefined && hasPendingSelection === false
|
||||
? {
|
||||
op: "add" as const,
|
||||
path: [update.instanceId],
|
||||
value: {
|
||||
instanceId: update.instanceId,
|
||||
values: [update.styleSourceId],
|
||||
},
|
||||
}
|
||||
: {
|
||||
op: "add" as const,
|
||||
path: [update.instanceId, "values", selectionValues.length],
|
||||
value: update.styleSourceId,
|
||||
}
|
||||
);
|
||||
nextSelectionValuesByInstanceId.set(update.instanceId, [
|
||||
...selectionValues,
|
||||
update.styleSourceId,
|
||||
]);
|
||||
// Tag styles render globally and never enter instance selections.
|
||||
if (update.styleSource.type !== "tag") {
|
||||
const selection = styleSourceSelectionByInstanceId.get(update.instanceId);
|
||||
const hasPendingSelection =
|
||||
selection === undefined &&
|
||||
nextSelectionValuesByInstanceId.has(update.instanceId);
|
||||
const selectionValues =
|
||||
nextSelectionValuesByInstanceId.get(update.instanceId) ?? [];
|
||||
if (selectionValues.includes(update.styleSourceId) === false) {
|
||||
styleSelectionPatches.push(
|
||||
selection === undefined && hasPendingSelection === false
|
||||
? {
|
||||
op: "add" as const,
|
||||
path: [update.instanceId],
|
||||
value: {
|
||||
instanceId: update.instanceId,
|
||||
values: [update.styleSourceId],
|
||||
},
|
||||
}
|
||||
: {
|
||||
op: "add" as const,
|
||||
path: [update.instanceId, "values", selectionValues.length],
|
||||
value: update.styleSourceId,
|
||||
}
|
||||
);
|
||||
nextSelectionValuesByInstanceId.set(update.instanceId, [
|
||||
...selectionValues,
|
||||
update.styleSourceId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
for (const styleDecl of createStyleDeclsFromInput({
|
||||
@@ -3415,10 +3476,30 @@ export const updateSelectedStyleDeclarations = (
|
||||
input.updates.map((update) => update.instanceId)
|
||||
);
|
||||
const updates = input.updates.map((update) => {
|
||||
const styleSource = styleState.styleSources.get(update.styleSourceId);
|
||||
if (styleSource === undefined) {
|
||||
const existingSource = styleState.styleSources.get(update.styleSourceId);
|
||||
const tag = getTagFromStyleId(update.styleSourceId);
|
||||
if (existingSource === undefined && tag === undefined) {
|
||||
return throwBuilderRuntimeError("NOT_FOUND", "Style source not found");
|
||||
}
|
||||
if (existingSource && tag && existingSource.type !== "tag") {
|
||||
return throwBuilderRuntimeError("CONFLICT", "Tag style id is in use");
|
||||
}
|
||||
const styleSource: StyleSource = existingSource ?? {
|
||||
type: "tag",
|
||||
id: update.styleSourceId,
|
||||
tag: tag!,
|
||||
};
|
||||
if (
|
||||
styleSource.type === "tag" &&
|
||||
update.state !== undefined &&
|
||||
validateSelector(update.state, { allowDescendants: false }).success ===
|
||||
false
|
||||
) {
|
||||
return throwBuilderRuntimeError(
|
||||
"BAD_REQUEST",
|
||||
"Selector must be one state scoped to the current element"
|
||||
);
|
||||
}
|
||||
if (isStyleSourceLocked(styleSource)) {
|
||||
return throwBuilderRuntimeError("BAD_REQUEST", "Style source is locked");
|
||||
}
|
||||
|
||||
@@ -2,12 +2,21 @@ import { expect, test } from "vitest";
|
||||
import { parseCssValue } from "@webstudio-is/css-data";
|
||||
import {
|
||||
getStyleDeclKey,
|
||||
getTagStyleId,
|
||||
ROOT_INSTANCE_ID,
|
||||
type Asset,
|
||||
type StyleDecl,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { copyDesignToken, pasteDesignToken } from "./token-transfer";
|
||||
import { parseTokenTransferData } from "./data-formats/token-css";
|
||||
import {
|
||||
copyDesignToken,
|
||||
copyStyleSourceTransfer,
|
||||
pasteDesignToken,
|
||||
pasteStyleSourceTransfer,
|
||||
} from "./token-transfer";
|
||||
import {
|
||||
parseTagStyleTransferData,
|
||||
parseTokenTransferData,
|
||||
} from "./data-formats/token-css";
|
||||
import { remapFragmentAssets } from "./fragment";
|
||||
import { applyBuilderPatchTransactions } from "../state/patch";
|
||||
|
||||
@@ -31,6 +40,286 @@ const styleMap = (declarations: StyleDecl[]) =>
|
||||
])
|
||||
);
|
||||
|
||||
test("pastes Tag styles into the matching tag and overwrites only matching declarations", () => {
|
||||
const id = getTagStyleId("button");
|
||||
const hover = { ...style(id, "base", "color", "red"), state: ":hover" };
|
||||
const copied = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([
|
||||
["base", { id: "base", label: "Base" }],
|
||||
["mobile", { id: "mobile", label: "Mobile", maxWidth: 600 }],
|
||||
]),
|
||||
styleSources: new Map([[id, { type: "tag", id, tag: "button" }]]),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: styleMap([
|
||||
hover,
|
||||
style(id, "base", "paddingTop", "8px"),
|
||||
style(id, "mobile", "color", "orange"),
|
||||
]),
|
||||
},
|
||||
{ styleSourceId: id, sourceType: "tag" }
|
||||
);
|
||||
const parsed = parseTagStyleTransferData(copied.data);
|
||||
expect(parsed.valid).toBe(true);
|
||||
const target = {
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([
|
||||
["target-base", { id: "target-base", label: "Base" }],
|
||||
[
|
||||
"target-mobile",
|
||||
{ id: "target-mobile", label: "Mobile", maxWidth: 600 },
|
||||
],
|
||||
]),
|
||||
styleSources: new Map([[id, { type: "tag" as const, id, tag: "button" }]]),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: styleMap([
|
||||
{ ...style(id, "target-base", "color", "blue"), state: ":hover" },
|
||||
style(id, "target-base", "marginTop", "4px"),
|
||||
style(id, "target-mobile", "color", "blue"),
|
||||
style(getTagStyleId("h1"), "target-base", "color", "green"),
|
||||
]),
|
||||
};
|
||||
const mutation = pasteStyleSourceTransfer(target, { data: copied.data });
|
||||
expect(mutation.result).toEqual({ styleSourceId: id });
|
||||
const pasted = applyBuilderPatchTransactions(target, [
|
||||
{ id: "paste", payload: mutation.payload },
|
||||
]).state;
|
||||
expect(
|
||||
pasted.styles!.get(`${id}:target-base:color::hover`)?.value
|
||||
).toMatchObject({ value: "red" });
|
||||
expect(
|
||||
pasted.styles!.get(`${id}:target-base:paddingTop:`)?.value
|
||||
).toMatchObject({ type: "unit", unit: "px", value: 8 });
|
||||
expect(pasted.styles!.get(`${id}:target-mobile:color:`)?.value).toMatchObject(
|
||||
{
|
||||
value: "orange",
|
||||
}
|
||||
);
|
||||
expect(
|
||||
pasted.styles!.get(`${id}:target-base:marginTop:`)?.value
|
||||
).toMatchObject({ value: "4px" });
|
||||
expect(
|
||||
pasted.styles!.get(`${getTagStyleId("h1")}:target-base:color:`)?.value
|
||||
).toMatchObject({ value: "green" });
|
||||
});
|
||||
|
||||
test("copies a Tag style before it has any saved declarations", () => {
|
||||
const copied = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: new Map(),
|
||||
},
|
||||
{ styleSourceId: getTagStyleId("div"), sourceType: "tag" }
|
||||
);
|
||||
const parsed = parseTagStyleTransferData(copied.data);
|
||||
expect(parsed.valid).toBe(true);
|
||||
if (parsed.valid) {
|
||||
expect(parsed.data.fragment.styleSources).toEqual([
|
||||
{ type: "tag", id: getTagStyleId("div"), tag: "div" },
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
test("creates the matching Tag style on paste without attaching it to an instance", () => {
|
||||
const id = getTagStyleId("h1");
|
||||
const copied = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSources: new Map([[id, { type: "tag", id, tag: "h1" }]]),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: styleMap([style(id, "base", "color", "red")]),
|
||||
},
|
||||
{ styleSourceId: id, sourceType: "tag" }
|
||||
);
|
||||
const target = {
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([
|
||||
["target-base", { id: "target-base", label: "Base" }],
|
||||
]),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: new Map(),
|
||||
};
|
||||
const mutation = pasteStyleSourceTransfer(target, { data: copied.data });
|
||||
const pasted = applyBuilderPatchTransactions(target, [
|
||||
{ id: "paste", payload: mutation.payload },
|
||||
]).state;
|
||||
expect(pasted.styleSources?.get(id)).toEqual({
|
||||
type: "tag",
|
||||
id,
|
||||
tag: "h1",
|
||||
});
|
||||
expect(pasted.styles?.get(`${id}:target-base:color:`)?.value).toMatchObject({
|
||||
value: "red",
|
||||
});
|
||||
expect(pasted.styleSourceSelections?.size).toBe(0);
|
||||
});
|
||||
|
||||
test("pastes Local styles into the selected instance and overwrites matching declarations", () => {
|
||||
const copied = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSources: new Map([
|
||||
["source-local", { type: "local", id: "source-local" }],
|
||||
]),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: styleMap([
|
||||
{ ...style("source-local", "base", "color", "red"), state: ":hover" },
|
||||
style("source-local", "base", "paddingTop", "8px"),
|
||||
]),
|
||||
},
|
||||
{ styleSourceId: "source-local", sourceType: "local" }
|
||||
);
|
||||
const target = {
|
||||
assets: new Map(),
|
||||
instances: new Map([
|
||||
[
|
||||
"box",
|
||||
{
|
||||
type: "instance" as const,
|
||||
id: "box",
|
||||
component: "Box",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
]),
|
||||
breakpoints: new Map([
|
||||
["target-base", { id: "target-base", label: "Base" }],
|
||||
]),
|
||||
styleSources: new Map([
|
||||
["target-local", { type: "local" as const, id: "target-local" }],
|
||||
]),
|
||||
styleSourceSelections: new Map([
|
||||
["box", { instanceId: "box", values: ["target-local"] }],
|
||||
]),
|
||||
styles: styleMap([
|
||||
{
|
||||
...style("target-local", "target-base", "color", "blue"),
|
||||
state: ":hover",
|
||||
},
|
||||
style("target-local", "target-base", "marginTop", "4px"),
|
||||
]),
|
||||
};
|
||||
const mutation = pasteStyleSourceTransfer(target, {
|
||||
data: copied.data,
|
||||
instanceId: "box",
|
||||
});
|
||||
expect(mutation.result).toEqual({ styleSourceId: "target-local" });
|
||||
const pasted = applyBuilderPatchTransactions(target, [
|
||||
{ id: "paste", payload: mutation.payload },
|
||||
]).state;
|
||||
expect(
|
||||
pasted.styles?.get("target-local:target-base:color::hover")?.value
|
||||
).toMatchObject({ value: "red" });
|
||||
expect(
|
||||
pasted.styles?.get("target-local:target-base:paddingTop:")?.value
|
||||
).toMatchObject({ type: "unit", unit: "px", value: 8 });
|
||||
expect(
|
||||
pasted.styles?.get("target-local:target-base:marginTop:")?.value
|
||||
).toMatchObject({ value: "4px" });
|
||||
expect(pasted.styleSourceSelections?.get("box")?.values).toEqual([
|
||||
"target-local",
|
||||
]);
|
||||
});
|
||||
|
||||
test("creates one Local source when pasting into an instance without one", () => {
|
||||
const copied = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: new Map(),
|
||||
},
|
||||
{ styleSourceId: "temporary-local", sourceType: "local" }
|
||||
);
|
||||
const target = {
|
||||
assets: new Map(),
|
||||
instances: new Map([
|
||||
[
|
||||
"box",
|
||||
{
|
||||
type: "instance" as const,
|
||||
id: "box",
|
||||
component: "Box",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
]),
|
||||
breakpoints: new Map([
|
||||
["target-base", { id: "target-base", label: "Base" }],
|
||||
]),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: new Map(),
|
||||
};
|
||||
const mutation = pasteStyleSourceTransfer(
|
||||
target,
|
||||
{ data: copied.data, instanceId: "box" },
|
||||
{ createId: () => "new-local" }
|
||||
);
|
||||
expect(mutation.result).toEqual({ styleSourceId: "new-local" });
|
||||
const pasted = applyBuilderPatchTransactions(target, [
|
||||
{ id: "paste", payload: mutation.payload },
|
||||
]).state;
|
||||
expect(pasted.styleSources?.get("new-local")).toEqual({
|
||||
type: "local",
|
||||
id: "new-local",
|
||||
});
|
||||
expect(pasted.styleSourceSelections?.get("box")?.values).toEqual([
|
||||
"new-local",
|
||||
]);
|
||||
});
|
||||
|
||||
test("pastes Local styles into Global root without creating two Local sources", () => {
|
||||
const copied = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSources: new Map([
|
||||
["source-local", { type: "local", id: "source-local" }],
|
||||
]),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: styleMap([style("source-local", "base", "color", "red")]),
|
||||
},
|
||||
{ styleSourceId: "source-local", sourceType: "local" }
|
||||
);
|
||||
const target = {
|
||||
assets: new Map(),
|
||||
instances: new Map(),
|
||||
breakpoints: new Map([
|
||||
["target-base", { id: "target-base", label: "Base" }],
|
||||
]),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: new Map(),
|
||||
};
|
||||
const mutation = pasteStyleSourceTransfer(
|
||||
target,
|
||||
{ data: copied.data, instanceId: ROOT_INSTANCE_ID },
|
||||
{ createId: () => "root-local" }
|
||||
);
|
||||
const pasted = applyBuilderPatchTransactions(target, [
|
||||
{ id: "paste", payload: mutation.payload },
|
||||
]).state;
|
||||
expect(pasted.styleSourceSelections?.get(ROOT_INSTANCE_ID)?.values).toEqual([
|
||||
"root-local",
|
||||
]);
|
||||
expect(pasted.styleSources?.get("root-local")).toEqual({
|
||||
type: "local",
|
||||
id: "root-local",
|
||||
});
|
||||
expect(
|
||||
pasted.styles?.get("root-local:target-base:color:")?.value
|
||||
).toMatchObject({ value: "red" });
|
||||
});
|
||||
|
||||
test("copies a token with breakpoint styles and transitive root CSS variables", () => {
|
||||
const source = {
|
||||
assets: new Map(),
|
||||
@@ -54,7 +343,10 @@ test("copies a token with breakpoint styles and transitive root CSS variables",
|
||||
style("root", "base", "--unrelated", "black"),
|
||||
]),
|
||||
};
|
||||
const copied = copyDesignToken(source, { tokenId: "token" });
|
||||
const copied = copyStyleSourceTransfer(source, {
|
||||
styleSourceId: "token",
|
||||
sourceType: "token",
|
||||
});
|
||||
expect(copied.data.startsWith('/* @webstudio/token-css/v1 "Button" */')).toBe(
|
||||
true
|
||||
);
|
||||
@@ -175,6 +467,133 @@ test("copies a token with breakpoint styles and transitive root CSS variables",
|
||||
);
|
||||
});
|
||||
|
||||
test("copies html Tag variables below attached Global root variables", () => {
|
||||
const htmlTagStyleId = getTagStyleId("html");
|
||||
const source = {
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSources: new Map([
|
||||
["token", { type: "token" as const, id: "token", name: "Card" }],
|
||||
[
|
||||
htmlTagStyleId,
|
||||
{ type: "tag" as const, id: htmlTagStyleId, tag: "html" },
|
||||
],
|
||||
["root", { type: "local" as const, id: "root" }],
|
||||
]),
|
||||
styleSourceSelections: new Map([
|
||||
[ROOT_INSTANCE_ID, { instanceId: ROOT_INSTANCE_ID, values: ["root"] }],
|
||||
]),
|
||||
styles: styleMap([
|
||||
style("token", "base", "color", "var(--brand)"),
|
||||
style("token", "base", "paddingTop", "var(--space)"),
|
||||
style(htmlTagStyleId, "base", "--brand", "red"),
|
||||
style(htmlTagStyleId, "base", "--space", "8px"),
|
||||
style("root", "base", "--brand", "blue"),
|
||||
]),
|
||||
};
|
||||
|
||||
const copied = copyStyleSourceTransfer(source, {
|
||||
styleSourceId: "token",
|
||||
sourceType: "token",
|
||||
});
|
||||
const parsed = parseTokenTransferData(copied.data);
|
||||
|
||||
expect(parsed.valid).toBe(true);
|
||||
if (parsed.valid) {
|
||||
expect(
|
||||
parsed.data.fragment.styles.map((item) => [item.property, item.value])
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
["--brand", expect.objectContaining({ value: "blue" })],
|
||||
["--space", expect.objectContaining({ value: 8 })],
|
||||
])
|
||||
);
|
||||
expect(
|
||||
parsed.data.fragment.styles
|
||||
.filter((item) => item.property === "--brand")
|
||||
.map((item) => item.value)
|
||||
).toEqual([expect.objectContaining({ value: "blue" })]);
|
||||
}
|
||||
});
|
||||
|
||||
test("copies html Tag variables referenced by another Tag style", () => {
|
||||
const htmlTagStyleId = getTagStyleId("html");
|
||||
const tagStyleId = getTagStyleId("h1");
|
||||
const copied = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSources: new Map([
|
||||
[
|
||||
htmlTagStyleId,
|
||||
{ type: "tag" as const, id: htmlTagStyleId, tag: "html" },
|
||||
],
|
||||
[tagStyleId, { type: "tag" as const, id: tagStyleId, tag: "h1" }],
|
||||
]),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: styleMap([
|
||||
style(tagStyleId, "base", "color", "var(--brand)"),
|
||||
style(htmlTagStyleId, "base", "--brand", "red"),
|
||||
]),
|
||||
},
|
||||
{ styleSourceId: tagStyleId, sourceType: "tag" }
|
||||
);
|
||||
const parsed = parseTagStyleTransferData(copied.data);
|
||||
|
||||
expect(parsed.valid).toBe(true);
|
||||
if (parsed.valid) {
|
||||
expect(parsed.data.fragment.styles).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
property: "--brand",
|
||||
value: expect.objectContaining({ value: "red" }),
|
||||
}),
|
||||
])
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("does not copy html Tag variables a second time as root dependencies", () => {
|
||||
const htmlTagStyleId = getTagStyleId("html");
|
||||
const copied = copyStyleSourceTransfer(
|
||||
{
|
||||
assets: new Map(),
|
||||
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
|
||||
styleSources: new Map([
|
||||
[
|
||||
htmlTagStyleId,
|
||||
{ type: "tag" as const, id: htmlTagStyleId, tag: "html" },
|
||||
],
|
||||
]),
|
||||
styleSourceSelections: new Map(),
|
||||
styles: styleMap([
|
||||
style(htmlTagStyleId, "base", "--brand", "red"),
|
||||
style(htmlTagStyleId, "base", "color", "var(--brand)"),
|
||||
]),
|
||||
},
|
||||
{ styleSourceId: htmlTagStyleId, sourceType: "tag" }
|
||||
);
|
||||
const parsed = parseTagStyleTransferData(copied.data);
|
||||
|
||||
expect(parsed.valid).toBe(true);
|
||||
if (parsed.valid) {
|
||||
expect(
|
||||
parsed.data.fragment.styles.filter((item) => item.property === "--brand")
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
parsed.data.fragment.styles.map((item) => [
|
||||
item.styleSourceId,
|
||||
item.property,
|
||||
])
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
[htmlTagStyleId, "--brand"],
|
||||
[htmlTagStyleId, "color"],
|
||||
])
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("copies the winning root variable when root sources overlap", () => {
|
||||
const copied = copyDesignToken(
|
||||
{
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { toValue } from "@webstudio-is/css-engine";
|
||||
import {
|
||||
createId,
|
||||
getTagFromStyleId,
|
||||
getTagStyleId,
|
||||
getStyleDeclKey,
|
||||
ROOT_INSTANCE_ID,
|
||||
type Asset,
|
||||
@@ -21,6 +23,7 @@ import { remapFragmentAssets } from "./fragment";
|
||||
import {
|
||||
collectCssVariableReferences,
|
||||
createStyleSourceSelectionAttachPayload,
|
||||
getLocalStyleSourceId,
|
||||
} from "./styles";
|
||||
import {
|
||||
getUniqueNameWithSuffix,
|
||||
@@ -28,6 +31,9 @@ import {
|
||||
traverseStyleValue,
|
||||
} from "./style-utils";
|
||||
import {
|
||||
parseTagStyleTransferData,
|
||||
parseLocalStyleTransferData,
|
||||
parseReusableStyleSourceTransferData,
|
||||
parseTokenTransferData,
|
||||
serializeTokenCss,
|
||||
} from "./data-formats/token-css";
|
||||
@@ -55,10 +61,14 @@ const requireTokenState = (state: TokenState) => {
|
||||
return state as Required<TokenState>;
|
||||
};
|
||||
|
||||
export const copyDesignTokenInput = z.object({
|
||||
tokenId: z.string(),
|
||||
sourceOrigin: z.string().url().optional(),
|
||||
});
|
||||
export const copyDesignTokenInput = z.union([
|
||||
z.object({ tokenId: z.string(), sourceOrigin: z.string().url().optional() }),
|
||||
z.object({
|
||||
styleSourceId: z.string(),
|
||||
sourceType: z.enum(["token", "tag", "local"]),
|
||||
sourceOrigin: z.string().url().optional(),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const pasteDesignTokenInput = z.object({
|
||||
data: z.string(),
|
||||
@@ -88,24 +98,36 @@ const rewriteVariableReferences = (
|
||||
return rewritten;
|
||||
};
|
||||
|
||||
export const copyDesignToken = (
|
||||
const copyStyleSource = (
|
||||
state: TokenState,
|
||||
input: z.infer<typeof copyDesignTokenInput>
|
||||
input: { sourceId: string; sourceOrigin?: string },
|
||||
kind: "token" | "tag" | "local"
|
||||
) => {
|
||||
const { assets, breakpoints, styleSources, styleSourceSelections, styles } =
|
||||
requireTokenState(state);
|
||||
const token = styleSources.get(input.tokenId);
|
||||
if (token?.type !== "token") {
|
||||
return throwBuilderRuntimeError("NOT_FOUND", "Design token not found");
|
||||
const tag = kind === "tag" ? getTagFromStyleId(input.sourceId) : undefined;
|
||||
const source =
|
||||
styleSources.get(input.sourceId) ??
|
||||
(tag
|
||||
? { type: "tag" as const, id: input.sourceId, tag }
|
||||
: kind === "local"
|
||||
? { type: "local" as const, id: input.sourceId }
|
||||
: undefined);
|
||||
if (source?.type !== kind) {
|
||||
return throwBuilderRuntimeError(
|
||||
"NOT_FOUND",
|
||||
kind === "token" ? "Design token not found" : "Style source not found"
|
||||
);
|
||||
}
|
||||
const tokenStyles = Array.from(styles.values()).filter(
|
||||
(style) => style.styleSourceId === token.id
|
||||
);
|
||||
const rootSourceOrder = new Map(
|
||||
styleSourceSelections
|
||||
.get(ROOT_INSTANCE_ID)
|
||||
?.values.map((id, index) => [id, index] as const)
|
||||
(style) => style.styleSourceId === source.id
|
||||
);
|
||||
const rootSourceOrder = new Map([[getTagStyleId("html"), -1]]);
|
||||
for (const [index, id] of (
|
||||
styleSourceSelections.get(ROOT_INSTANCE_ID)?.values ?? []
|
||||
).entries()) {
|
||||
rootSourceOrder.set(id, index);
|
||||
}
|
||||
const rootStylesByKey = new Map<string, StyleDecl>();
|
||||
for (const style of styles.values()) {
|
||||
if (
|
||||
@@ -141,9 +163,13 @@ export const copyDesignToken = (
|
||||
}
|
||||
}
|
||||
const variableStyles = rootStyles
|
||||
.filter((style) => referencedNames.has(style.property))
|
||||
.filter(
|
||||
(style) =>
|
||||
referencedNames.has(style.property) &&
|
||||
(kind === "token" || style.styleSourceId !== source.id)
|
||||
)
|
||||
.map((style) =>
|
||||
style.styleSourceId === token.id
|
||||
style.styleSourceId === source.id
|
||||
? { ...style, styleSourceId: ROOT_INSTANCE_ID }
|
||||
: style
|
||||
);
|
||||
@@ -172,7 +198,7 @@ export const copyDesignToken = (
|
||||
dataSources: [],
|
||||
resources: [],
|
||||
styleSourceSelections: [],
|
||||
styleSources: [token],
|
||||
styleSources: [source],
|
||||
styles: copiedStyles,
|
||||
breakpoints: copiedBreakpoints,
|
||||
assets: Array.from(assets.values()).filter((asset) =>
|
||||
@@ -181,33 +207,85 @@ export const copyDesignToken = (
|
||||
};
|
||||
for (const assetId of usedAssets.keys()) {
|
||||
if (assets.has(assetId) === false) {
|
||||
return throwBuilderRuntimeError("NOT_FOUND", "Token asset is missing");
|
||||
return throwBuilderRuntimeError(
|
||||
"NOT_FOUND",
|
||||
kind === "token"
|
||||
? "Token asset is missing"
|
||||
: "Style source asset is missing"
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
data: serializeTokenCss({
|
||||
tokenId: token.id,
|
||||
fragment,
|
||||
sourceOrigin: input.sourceOrigin,
|
||||
}),
|
||||
data: serializeTokenCss(
|
||||
{
|
||||
tokenId: source.id,
|
||||
fragment,
|
||||
sourceOrigin: input.sourceOrigin,
|
||||
},
|
||||
kind
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
export const pasteDesignToken = (
|
||||
export const copyDesignToken = (
|
||||
state: TokenState,
|
||||
input: { tokenId: string; sourceOrigin?: string }
|
||||
) =>
|
||||
copyStyleSource(
|
||||
state,
|
||||
{ sourceId: input.tokenId, sourceOrigin: input.sourceOrigin },
|
||||
"token"
|
||||
);
|
||||
|
||||
export const copyStyleSourceTransfer = (
|
||||
state: TokenState,
|
||||
input: z.infer<typeof copyDesignTokenInput>
|
||||
) =>
|
||||
"tokenId" in input
|
||||
? copyDesignToken(state, input)
|
||||
: copyStyleSource(
|
||||
state,
|
||||
{ sourceId: input.styleSourceId, sourceOrigin: input.sourceOrigin },
|
||||
input.sourceType
|
||||
);
|
||||
|
||||
const pasteStyleSource = (
|
||||
state: TokenState,
|
||||
input: z.infer<typeof pasteDesignTokenInput>,
|
||||
kind: "token" | "tag" | "local",
|
||||
context: { createId: () => string } = { createId: () => createId("nano") }
|
||||
) => {
|
||||
const target = requireTokenState(state);
|
||||
const parsed = parseTokenTransferData(input.data);
|
||||
const parsed =
|
||||
kind === "token"
|
||||
? parseTokenTransferData(input.data)
|
||||
: kind === "tag"
|
||||
? parseTagStyleTransferData(input.data)
|
||||
: parseLocalStyleTransferData(input.data);
|
||||
if (parsed.valid === false) {
|
||||
return throwBuilderRuntimeError("INVALID_INPUT", "Invalid token data");
|
||||
return throwBuilderRuntimeError(
|
||||
"INVALID_INPUT",
|
||||
kind === "token" ? "Invalid token data" : "Invalid style source data"
|
||||
);
|
||||
}
|
||||
const { tokenId } = parsed.data;
|
||||
let { fragment } = parsed.data;
|
||||
const sourceToken = fragment.styleSources[0];
|
||||
if (sourceToken?.type !== "token") {
|
||||
return throwBuilderRuntimeError("INVALID_INPUT", "Invalid token data");
|
||||
if (sourceToken?.type !== kind) {
|
||||
return throwBuilderRuntimeError(
|
||||
"INVALID_INPUT",
|
||||
kind === "token" ? "Invalid token data" : "Invalid style source data"
|
||||
);
|
||||
}
|
||||
if (kind === "local" && input.instanceId === undefined) {
|
||||
return throwBuilderRuntimeError("BAD_REQUEST", "Instance not found");
|
||||
}
|
||||
if (
|
||||
kind === "tag" &&
|
||||
target.styleSources.get(tokenId) !== undefined &&
|
||||
target.styleSources.get(tokenId)?.type !== "tag"
|
||||
) {
|
||||
return throwBuilderRuntimeError("CONFLICT", "Tag style id is in use");
|
||||
}
|
||||
if (fragment.assets.length > 0) {
|
||||
const assetIds = new Map(input.assetIds ?? []);
|
||||
@@ -215,12 +293,19 @@ export const pasteDesignToken = (
|
||||
for (const source of fragment.assets) {
|
||||
const imported = target.assets.get(assetIds.get(source.id) ?? source.id);
|
||||
if (imported === undefined) {
|
||||
return throwBuilderRuntimeError("NOT_FOUND", "Token asset is missing");
|
||||
return throwBuilderRuntimeError(
|
||||
"NOT_FOUND",
|
||||
kind === "token"
|
||||
? "Token asset is missing"
|
||||
: "Style source asset is missing"
|
||||
);
|
||||
}
|
||||
if (source.type !== imported.type) {
|
||||
return throwBuilderRuntimeError(
|
||||
"INVALID_INPUT",
|
||||
"Token asset type changed"
|
||||
kind === "token"
|
||||
? "Token asset type changed"
|
||||
: "Style source asset type changed"
|
||||
);
|
||||
}
|
||||
importedAssets.set(source.id, imported);
|
||||
@@ -268,6 +353,15 @@ export const pasteDesignToken = (
|
||||
(id) => target.styleSources.get(id)?.type === "local"
|
||||
);
|
||||
const rootSourceId = sourceId ?? context.createId();
|
||||
const localSourceId =
|
||||
kind === "local"
|
||||
? getLocalStyleSourceId({
|
||||
styleSources: target.styleSources,
|
||||
styleSourceSelection: target.styleSourceSelections.get(
|
||||
input.instanceId!
|
||||
),
|
||||
})
|
||||
: undefined;
|
||||
const incomingVariables = fragment.styles.filter(
|
||||
(style) => style.styleSourceId !== tokenId
|
||||
);
|
||||
@@ -320,16 +414,27 @@ export const pasteDesignToken = (
|
||||
source.type === "token" ? [source.name] : []
|
||||
)
|
||||
);
|
||||
const newTokenId = context.createId();
|
||||
const newToken = {
|
||||
...sourceToken,
|
||||
id: newTokenId,
|
||||
name: createCopyName(
|
||||
sourceToken.name,
|
||||
(name) => tokenNames.has(name),
|
||||
true
|
||||
),
|
||||
};
|
||||
const newTokenId =
|
||||
kind === "token"
|
||||
? context.createId()
|
||||
: kind === "local"
|
||||
? (localSourceId ??
|
||||
(input.instanceId === ROOT_INSTANCE_ID
|
||||
? rootSourceId
|
||||
: context.createId()))
|
||||
: tokenId;
|
||||
const newToken =
|
||||
sourceToken.type === "token"
|
||||
? {
|
||||
...sourceToken,
|
||||
id: newTokenId,
|
||||
name: createCopyName(
|
||||
sourceToken.name,
|
||||
(name) => tokenNames.has(name),
|
||||
true
|
||||
),
|
||||
}
|
||||
: { ...sourceToken, id: newTokenId };
|
||||
const variablePatches: BuilderPatchChange["patches"] = [];
|
||||
const tokenPatches: BuilderPatchChange["patches"] = [];
|
||||
for (const style of mappedStyles) {
|
||||
@@ -341,7 +446,11 @@ export const pasteDesignToken = (
|
||||
};
|
||||
const key = getStyleDeclKey(mapped);
|
||||
if (style.styleSourceId === tokenId) {
|
||||
tokenPatches.push({ op: "add", path: [key], value: mapped });
|
||||
tokenPatches.push({
|
||||
op: kind !== "token" && target.styles.has(key) ? "replace" : "add",
|
||||
path: [key],
|
||||
value: mapped,
|
||||
});
|
||||
} else if (target.styles.has(key) === false) {
|
||||
variablePatches.push({ op: "add", path: [key], value: mapped });
|
||||
}
|
||||
@@ -355,39 +464,72 @@ export const pasteDesignToken = (
|
||||
value: { type: "local", id: rootSourceId } satisfies StyleSource,
|
||||
});
|
||||
}
|
||||
sourcePatches.push({
|
||||
op: "add",
|
||||
path: [newTokenId],
|
||||
value: newToken,
|
||||
});
|
||||
if (
|
||||
target.styleSources.has(newTokenId) === false &&
|
||||
(!needsRootSource || newTokenId !== rootSourceId)
|
||||
) {
|
||||
sourcePatches.push({ op: "add", path: [newTokenId], value: newToken });
|
||||
}
|
||||
const stylePatches = [...variablePatches, ...tokenPatches];
|
||||
const payload: BuilderPatchChange[] = [];
|
||||
if (breakpointPatches.length > 0) {
|
||||
payload.push({ namespace: "breakpoints", patches: breakpointPatches });
|
||||
}
|
||||
payload.push({ namespace: "styleSources", patches: sourcePatches });
|
||||
if (sourcePatches.length > 0) {
|
||||
payload.push({ namespace: "styleSources", patches: sourcePatches });
|
||||
}
|
||||
if (stylePatches.length > 0) {
|
||||
payload.push({ namespace: "styles", patches: stylePatches });
|
||||
}
|
||||
const selectionPatches: BuilderPatchChange["patches"] = [];
|
||||
if (needsRootSource) {
|
||||
selectionPatches.push(
|
||||
selection === undefined
|
||||
? {
|
||||
op: "add",
|
||||
path: [ROOT_INSTANCE_ID],
|
||||
value: { instanceId: ROOT_INSTANCE_ID, values: [rootSourceId] },
|
||||
}
|
||||
: {
|
||||
op: "add",
|
||||
path: [ROOT_INSTANCE_ID, "values", selection.values.length],
|
||||
value: rootSourceId,
|
||||
}
|
||||
);
|
||||
}
|
||||
if (
|
||||
kind === "local" &&
|
||||
localSourceId === undefined &&
|
||||
!(input.instanceId === ROOT_INSTANCE_ID && needsRootSource)
|
||||
) {
|
||||
const destinationSelection = target.styleSourceSelections.get(
|
||||
input.instanceId!
|
||||
);
|
||||
selectionPatches.push(
|
||||
destinationSelection === undefined
|
||||
? {
|
||||
op: "add",
|
||||
path: [input.instanceId!],
|
||||
value: { instanceId: input.instanceId!, values: [newTokenId] },
|
||||
}
|
||||
: {
|
||||
op: "add",
|
||||
path: [
|
||||
input.instanceId!,
|
||||
"values",
|
||||
destinationSelection.values.length,
|
||||
],
|
||||
value: newTokenId,
|
||||
}
|
||||
);
|
||||
}
|
||||
if (selectionPatches.length > 0) {
|
||||
payload.push({
|
||||
namespace: "styleSourceSelections",
|
||||
patches: [
|
||||
selection === undefined
|
||||
? {
|
||||
op: "add",
|
||||
path: [ROOT_INSTANCE_ID],
|
||||
value: { instanceId: ROOT_INSTANCE_ID, values: [rootSourceId] },
|
||||
}
|
||||
: {
|
||||
op: "add",
|
||||
path: [ROOT_INSTANCE_ID, "values", selection.values.length],
|
||||
value: rootSourceId,
|
||||
},
|
||||
],
|
||||
patches: selectionPatches,
|
||||
});
|
||||
}
|
||||
if (input.instanceId !== undefined) {
|
||||
if (kind === "token" && input.instanceId !== undefined) {
|
||||
const selections = new Map(target.styleSourceSelections);
|
||||
if (needsRootSource) {
|
||||
selections.set(ROOT_INSTANCE_ID, {
|
||||
@@ -406,7 +548,7 @@ export const pasteDesignToken = (
|
||||
}
|
||||
return createRuntimeMutation({
|
||||
payload,
|
||||
result: { tokenId: newTokenId },
|
||||
result: { styleSourceId: newTokenId },
|
||||
invalidatesNamespaces: [
|
||||
"breakpoints",
|
||||
"styleSources",
|
||||
@@ -415,3 +557,36 @@ export const pasteDesignToken = (
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
export const pasteDesignToken = (
|
||||
state: TokenState,
|
||||
input: z.infer<typeof pasteDesignTokenInput>,
|
||||
context?: { createId: () => string }
|
||||
) => {
|
||||
const mutation = pasteStyleSource(state, input, "token", context);
|
||||
return { ...mutation, result: { tokenId: mutation.result.styleSourceId } };
|
||||
};
|
||||
|
||||
export const pasteStyleSourceTransfer = (
|
||||
state: TokenState,
|
||||
input: z.infer<typeof pasteDesignTokenInput>,
|
||||
context?: { createId: () => string }
|
||||
) => {
|
||||
const reusable = parseReusableStyleSourceTransferData(input.data);
|
||||
if (reusable.owned) {
|
||||
const kind = reusable.valid
|
||||
? reusable.data.fragment.styleSources[0]?.type
|
||||
: undefined;
|
||||
const mutation = pasteStyleSource(
|
||||
state,
|
||||
input,
|
||||
kind === "local" ? "local" : "tag",
|
||||
context
|
||||
);
|
||||
return {
|
||||
...mutation,
|
||||
result: { styleSourceId: mutation.result.styleSourceId },
|
||||
};
|
||||
}
|
||||
return pasteDesignToken(state, input, context);
|
||||
};
|
||||
@@ -480,12 +480,28 @@ const curatedPublicApiOperationDocumentation = [
|
||||
description: "List style declarations",
|
||||
examples: ["webstudio get-styles --instance instance-id --json"],
|
||||
},
|
||||
{
|
||||
command: "list-tag-styles",
|
||||
description: "List global Tag styles and their declarations",
|
||||
examples: [
|
||||
"MCP tool: list-tag-styles {}",
|
||||
'MCP tool: list-tag-styles {"tag":"button","verbose":true}',
|
||||
],
|
||||
},
|
||||
{
|
||||
command: "update-styles",
|
||||
description: "Create or update local style declarations",
|
||||
requiredOptions: ["input", "json"],
|
||||
examples: ["webstudio update-styles --input styles.json --json"],
|
||||
},
|
||||
{
|
||||
command: "update-selected-styles",
|
||||
description:
|
||||
"Create or update selected style-source declarations. Use tag-style:<tag> to create or edit a global Tag style.",
|
||||
examples: [
|
||||
'MCP tool: update-selected-styles {"updates":[{"instanceId":"instance-id","styleSourceId":"tag-style:button","property":"color","value":{"type":"keyword","value":"red"}}]}',
|
||||
],
|
||||
},
|
||||
{
|
||||
command: "delete-styles",
|
||||
description: "Delete local style declarations",
|
||||
|
||||
@@ -241,6 +241,7 @@ export const generateStories = async ({
|
||||
assets: new Map(),
|
||||
breakpoints,
|
||||
styles: new Map(data.styles.map((item) => [getStyleDeclKey(item), item])),
|
||||
styleSources: new Map(data.styleSources.map((item) => [item.id, item])),
|
||||
styleSourceSelections: new Map(
|
||||
data.styleSourceSelections.map((item) => [item.instanceId, item])
|
||||
),
|
||||
|
||||
@@ -9,6 +9,7 @@ import { generateCss, type CssConfig } from "./css";
|
||||
import type { Breakpoint } from "./schema/breakpoints";
|
||||
import type { Asset } from "./schema/assets";
|
||||
import { rootComponent } from "./core-metas";
|
||||
import { getTagStyleId } from "./schema/style-sources";
|
||||
|
||||
const Body = createTemplateComponentFixture("Body");
|
||||
const Box = createTemplateComponentFixture("Box");
|
||||
@@ -29,6 +30,81 @@ const generateAllCss = (config: Omit<CssConfig, "atomic">) => {
|
||||
return { cssText, atomicCssText, classes, atomicClasses };
|
||||
};
|
||||
|
||||
test("renders an unattached tag token before instance styles", () => {
|
||||
const data = renderData(
|
||||
<Box
|
||||
ws:id="box"
|
||||
ws:style={css`
|
||||
color: blue;
|
||||
`}
|
||||
/>
|
||||
);
|
||||
const id = getTagStyleId("p");
|
||||
const declaration = {
|
||||
styleSourceId: id,
|
||||
breakpointId: "base",
|
||||
property: "color" as const,
|
||||
value: { type: "keyword" as const, value: "red" },
|
||||
};
|
||||
const hoverDeclaration = {
|
||||
...declaration,
|
||||
state: ":hover",
|
||||
};
|
||||
const { cssText, atomicCssText } = generateAllCss({
|
||||
...data,
|
||||
breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),
|
||||
styleSources: new Map([
|
||||
...data.styleSources,
|
||||
[id, { type: "tag" as const, id, tag: "p" }],
|
||||
]),
|
||||
styles: new Map([
|
||||
...data.styles,
|
||||
["tag-color", declaration],
|
||||
["tag-hover-color", hoverDeclaration],
|
||||
]),
|
||||
componentMetas: new Map(),
|
||||
assetBaseUrl: "/",
|
||||
});
|
||||
|
||||
expect(cssText).toContain("p {\n color: red\n }");
|
||||
expect(atomicCssText).toContain("p {\n color: red\n }");
|
||||
expect(cssText).toContain("p:hover");
|
||||
expect(atomicCssText).toContain("p:hover");
|
||||
expect(cssText.indexOf("p {")).toBeLessThan(cssText.indexOf("color: blue"));
|
||||
});
|
||||
|
||||
test("renders a tag selector inside an attached token as a descendant", () => {
|
||||
const data = renderData(<Box ws:id="box" />);
|
||||
const { cssText, atomicCssText } = generateAllCss({
|
||||
...data,
|
||||
styleSources: new Map([
|
||||
...data.styleSources,
|
||||
["token", { type: "token" as const, id: "token", name: "Token" }],
|
||||
]),
|
||||
styleSourceSelections: new Map([
|
||||
["box", { instanceId: "box", values: ["token"] }],
|
||||
]),
|
||||
styles: new Map([
|
||||
[
|
||||
"token-descendant",
|
||||
{
|
||||
styleSourceId: "token",
|
||||
breakpointId: "base",
|
||||
state: " p",
|
||||
property: "color",
|
||||
value: { type: "keyword" as const, value: "red" },
|
||||
},
|
||||
],
|
||||
]),
|
||||
breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),
|
||||
componentMetas: new Map(),
|
||||
assetBaseUrl: "/",
|
||||
});
|
||||
|
||||
expect(cssText).toContain(".w-box p");
|
||||
expect(atomicCssText).toMatch(/\.c[a-z0-9]+ p/);
|
||||
});
|
||||
|
||||
test("generates distinct upright and italic variable font faces", () => {
|
||||
const variableFontAsset = (style: "normal" | "italic"): Asset => ({
|
||||
id: style,
|
||||
|
||||
+19
-3
@@ -13,6 +13,7 @@ import type { Props } from "./schema/props";
|
||||
import type { Breakpoints } from "./schema/breakpoints";
|
||||
import type { Styles } from "./schema/styles";
|
||||
import type { StyleSourceSelections } from "./schema/style-source-selections";
|
||||
import type { StyleSources } from "./schema/style-sources";
|
||||
import type { WsComponentMeta } from "./schema/component-meta";
|
||||
import { createScope } from "./scope";
|
||||
import {
|
||||
@@ -50,6 +51,7 @@ export type CssConfig = {
|
||||
props: Props;
|
||||
breakpoints: Breakpoints;
|
||||
styles: Styles;
|
||||
styleSources: StyleSources;
|
||||
styleSourceSelections: StyleSourceSelections;
|
||||
componentMetas: Map<string, WsComponentMeta>;
|
||||
assetBaseUrl: string;
|
||||
@@ -90,6 +92,7 @@ export const generateCss = ({
|
||||
props,
|
||||
breakpoints,
|
||||
styles,
|
||||
styleSources,
|
||||
styleSourceSelections,
|
||||
componentMetas,
|
||||
assetBaseUrl,
|
||||
@@ -97,6 +100,7 @@ export const generateCss = ({
|
||||
}: CssConfig) => {
|
||||
const fontSheet = createRegularStyleSheet({ name: "ssr" });
|
||||
const presetSheet = createRegularStyleSheet({ name: "ssr" });
|
||||
const tagStyleSheet = createRegularStyleSheet({ name: "ssr" });
|
||||
const userSheet = createRegularStyleSheet({ name: "ssr" });
|
||||
|
||||
addFontRules({ sheet: fontSheet, assets, assetBaseUrl });
|
||||
@@ -153,6 +157,7 @@ export const generateCss = ({
|
||||
}
|
||||
|
||||
for (const breakpoint of breakpoints.values()) {
|
||||
tagStyleSheet.addMediaRule(breakpoint.id, breakpoint);
|
||||
userSheet.addMediaRule(breakpoint.id, breakpoint);
|
||||
}
|
||||
|
||||
@@ -160,9 +165,12 @@ export const generateCss = ({
|
||||
assetBaseUrl,
|
||||
});
|
||||
userSheet.setTransformer(imageValueTransformer);
|
||||
tagStyleSheet.setTransformer(imageValueTransformer);
|
||||
|
||||
for (const styleDecl of styles.values()) {
|
||||
const rule = userSheet.addMixinRule(styleDecl.styleSourceId);
|
||||
const styleSource = styleSources.get(styleDecl.styleSourceId);
|
||||
const sheet = styleSource?.type === "tag" ? tagStyleSheet : userSheet;
|
||||
const rule = sheet.addMixinRule(styleDecl.styleSourceId);
|
||||
rule.setDeclaration({
|
||||
breakpoint: styleDecl.breakpointId,
|
||||
selector: styleDecl.state ?? "",
|
||||
@@ -171,6 +179,12 @@ export const generateCss = ({
|
||||
});
|
||||
}
|
||||
|
||||
for (const source of styleSources.values()) {
|
||||
if (source.type === "tag") {
|
||||
tagStyleSheet.addNestingRule(source.tag).applyMixins([source.id]);
|
||||
}
|
||||
}
|
||||
|
||||
const classes = new Map<Instance["id"], string[]>();
|
||||
const parentIdByInstanceId = new Map<Instance["id"], Instance["id"]>();
|
||||
for (const instance of instances.values()) {
|
||||
@@ -243,6 +257,8 @@ export const generateCss = ({
|
||||
"@media all ",
|
||||
"@layer presets "
|
||||
);
|
||||
const tagStyleCss = tagStyleSheet.cssText;
|
||||
const tagStyleCssPrefix = tagStyleCss ? `${tagStyleCss}\n` : "";
|
||||
|
||||
if (atomic) {
|
||||
const { cssText } = generateAtomic(userSheet, {
|
||||
@@ -251,12 +267,12 @@ export const generateCss = ({
|
||||
classes,
|
||||
});
|
||||
return {
|
||||
cssText: `${fontCss}${presetCss}\n${cssText}`,
|
||||
cssText: `${fontCss}${presetCss}\n${tagStyleCssPrefix}${cssText}`,
|
||||
classes,
|
||||
};
|
||||
}
|
||||
return {
|
||||
cssText: `${fontCss}${presetCss}\n${userSheet.cssText}`,
|
||||
cssText: `${fontCss}${presetCss}\n${tagStyleCssPrefix}${userSheet.cssText}`,
|
||||
classes,
|
||||
};
|
||||
};
|
||||
@@ -1,7 +1,17 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { styleSource } from "./style-sources";
|
||||
import { getTagFromStyleId, getTagStyleId, styleSource } from "./style-sources";
|
||||
|
||||
describe("StyleSource", () => {
|
||||
test("accepts an html Tag style for Global root", () => {
|
||||
const id = getTagStyleId("html");
|
||||
expect(id).toBe("tag-style:html");
|
||||
expect(getTagFromStyleId(id)).toBe("html");
|
||||
expect(styleSource.parse({ type: "tag", id, tag: "html" })).toEqual({
|
||||
type: "tag",
|
||||
id,
|
||||
tag: "html",
|
||||
});
|
||||
});
|
||||
test("parses unlocked tokens without locked field", () => {
|
||||
expect(
|
||||
styleSource.parse({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { tags } from "../__generated__/tags";
|
||||
|
||||
const styleSourceId = z.string();
|
||||
|
||||
@@ -11,12 +12,38 @@ const styleSourceToken = z.object({
|
||||
|
||||
export type StyleSourceToken = z.infer<typeof styleSourceToken>;
|
||||
|
||||
export const getTagStyleId = (tag: string) => `tag-style:${tag}`;
|
||||
|
||||
export const isTagStyleTag = (tag: string) => tags.includes(tag);
|
||||
|
||||
export const getTagFromStyleId = (id: string) => {
|
||||
if (id.startsWith("tag-style:") === false) {
|
||||
return;
|
||||
}
|
||||
const tag = id.slice("tag-style:".length);
|
||||
return isTagStyleTag(tag) ? tag : undefined;
|
||||
};
|
||||
|
||||
const styleSourceTagStyle = z
|
||||
.object({
|
||||
type: z.literal("tag"),
|
||||
id: styleSourceId,
|
||||
tag: z.string().refine(isTagStyleTag),
|
||||
})
|
||||
.refine((source) => source.id === getTagStyleId(source.tag));
|
||||
|
||||
export type StyleSourceTagStyle = z.infer<typeof styleSourceTagStyle>;
|
||||
|
||||
const styleSourceLocal = z.object({
|
||||
type: z.literal("local"),
|
||||
id: styleSourceId,
|
||||
});
|
||||
|
||||
export const styleSource = z.union([styleSourceToken, styleSourceLocal]);
|
||||
export const styleSource = z.union([
|
||||
styleSourceToken,
|
||||
styleSourceTagStyle,
|
||||
styleSourceLocal,
|
||||
]);
|
||||
|
||||
export type StyleSource = z.infer<typeof styleSource>;
|
||||
|
||||
|
||||
Reference in new issue
Block a user