Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

experimental: support copying root styles from marketplace (#4193)

Bogdan Chadkince475d467767
diff --git a/apps/builder/app/shared/instance-utils.test.ts b/apps/builder/app/shared/instance-utils.test.tsx
similarity index 96%
rename from apps/builder/app/shared/instance-utils.test.ts
rename to apps/builder/app/shared/instance-utils.test.tsx
index bcfd14297f..301f94ced6 100644
--- a/apps/builder/app/shared/instance-utils.test.ts
+++ b/apps/builder/app/shared/instance-utils.test.tsx
@@ -5,6 +5,10 @@ import {
collectionComponent,
type WsComponentMeta,
} from "@webstudio-is/react-sdk";
+import type { Project } from "@webstudio-is/project";
+import { createDefaultPages } from "@webstudio-is/project-build";
+import { $, renderJsx } from "@webstudio-is/sdk/testing";
+import { parseCss } from "@webstudio-is/css-data";
import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";
import type {
Asset,
@@ -16,10 +20,13 @@ import type {
Resource,
StyleDecl,
StyleDeclKey,
+ Styles,
StyleSource,
+ StyleSources,
+ StyleSourceSelections,
WebstudioData,
} from "@webstudio-is/sdk";
-import { encodeDataSourceVariable } from "@webstudio-is/sdk";
+import { encodeDataSourceVariable, getStyleDeclKey } from "@webstudio-is/sdk";
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
import {
computeInstancesConstraints,
@@ -50,8 +57,7 @@ import {
$resources,
} from "./nano-states";
import { registerContainers } from "./sync";
-import type { Project } from "@webstudio-is/project";
-import { createDefaultPages } from "@webstudio-is/project-build";
+import { mapGroupBy } from "./shim";
enableMapSet();
registerContainers();
@@ -3165,6 +3171,101 @@ describe("insert webstudio fragment copy", () => {
availableDataSources: new Set(),
});
expect(data.instances.size).toEqual(4);
- expect(newInstanceIds.size).toEqual(4);
+ expect(newInstanceIds.size).toEqual(5);
+ });
+});
+
+describe("support copy paste of :root styles", () => {
+ const css = (strings: TemplateStringsArray, ...values: string[]) => {
+ let cssString = "";
+ strings.forEach((string, index) => {
+ cssString += string + (values[index] ?? "");
+ });
+ const styleSourceSelections: StyleSourceSelections = new Map();
+ const styleSources: StyleSources = new Map();
+ const styles: Styles = new Map();
+ const parsed = mapGroupBy(
+ parseCss(cssString),
+ (parsedStyleDecl) => parsedStyleDecl.selector
+ );
+ for (const [selector, parsedStyles] of parsed) {
+ const [instanceId, styleSourceId] = selector.split("__");
+ styleSourceSelections.set(instanceId, {
+ instanceId: instanceId,
+ values: [styleSourceId],
+ });
+ styleSources.set(styleSourceId, { id: styleSourceId, type: "local" });
+ for (const { property, value } of parsedStyles) {
+ const styleDecl: StyleDecl = {
+ breakpointId: "baseId",
+ styleSourceId,
+ property,
+ value,
+ };
+ styles.set(getStyleDeclKey(styleDecl), styleDecl);
+ }
+ }
+ return { styleSourceSelections, styleSources, styles };
+ };
+
+ test("should add :root local styles", () => {
+ const oldProject = getWebstudioDataStub({
+ ...renderJsx(<$.Body ws:id="oldProjectBodyId"></$.Body>),
+ ...css`
+ :root__oldprojectlocalid {
+ color: red;
+ }
+ `,
+ });
+ const newProject = getWebstudioDataStub();
+ const fragment = extractWebstudioFragment(oldProject, ":root");
+ insertWebstudioFragmentCopy({
+ data: newProject,
+ fragment,
+ availableDataSources: new Set(),
+ });
+ const [newStyleSourceId] = newProject.styleSources.keys();
+ expect(newProject).toEqual(
+ expect.objectContaining(css`
+ :root__${newStyleSourceId} {
+ color: red;
+ }
+ `)
+ );
+ });
+
+ test("should merge :root local styles", () => {
+ const oldProject = getWebstudioDataStub({
+ ...renderJsx(<$.Body ws:id="oldProjectBodyId"></$.Body>),
+ ...css`
+ :root__oldprojectlocalid {
+ color: red;
+ }
+ `,
+ });
+ const newProject = getWebstudioDataStub({
+ ...renderJsx(<$.Body ws:id="oldProjectBodyId"></$.Body>),
+ ...css`
+ :root__newprojectlocalid {
+ font-size: medium;
+ }
+ `,
+ });
+ const fragment = extractWebstudioFragment(oldProject, ":root");
+ insertWebstudioFragmentCopy({
+ data: newProject,
+ fragment,
+ availableDataSources: new Set(),
+ });
+ expect({
+ styleSourceSelections: newProject.styleSourceSelections,
+ styleSources: newProject.styleSources,
+ styles: newProject.styles,
+ }).toEqual(css`
+ :root__newprojectlocalid {
+ font-size: medium;
+ color: red;
+ }
+ `);
});
});
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index f5f1467922..b71787bfe7 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -1326,6 +1326,8 @@ export const insertWebstudioFragmentCopy = ({
for (const instanceId of fragmentInstanceIds) {
newInstanceIds.set(instanceId, nanoid());
}
+ fragmentInstanceIds.add(ROOT_INSTANCE_ID);
+ newInstanceIds.set(ROOT_INSTANCE_ID, ROOT_INSTANCE_ID);
const availableFragmentDataSources = new Set(availableDataSources);
const newResourceIds = new Map<Resource["id"], Resource["id"]>();
@@ -1482,46 +1484,55 @@ export const insertWebstudioFragmentCopy = ({
// insert local styles with new ids
- const instanceStyleSourceIds = new Set<StyleSource["id"]>();
- for (const styleSourceSelection of fragment.styleSourceSelections) {
- if (fragmentInstanceIds.has(styleSourceSelection.instanceId) === false) {
- continue;
- }
- for (const styleSourceId of styleSourceSelection.values) {
- instanceStyleSourceIds.add(styleSourceId);
+ const newLocalStyleSources = new Map();
+ for (const styleSource of fragment.styleSources) {
+ if (styleSource.type === "local") {
+ newLocalStyleSources.set(styleSource.id, styleSource);
}
}
+
const newLocalStyleSourceIds = new Map<
StyleSource["id"],
StyleSource["id"]
>();
- for (const styleSource of fragment.styleSources) {
- if (
- styleSource.type === "local" &&
- instanceStyleSourceIds.has(styleSource.id)
- ) {
- const newId = nanoid();
- newLocalStyleSourceIds.set(styleSource.id, newId);
- styleSources.set(newId, { ...styleSource, id: newId });
- }
- }
- for (const styleSourceSelection of fragment.styleSourceSelections) {
- const { instanceId, values } = styleSourceSelection;
+ for (const { instanceId, values } of fragment.styleSourceSelections) {
if (fragmentInstanceIds.has(instanceId) === false) {
continue;
}
+
+ const existingStyleSourceIds =
+ styleSourceSelections.get(instanceId)?.values ?? [];
+ let existingLocalStyleSource;
+ for (const styleSourceId of existingStyleSourceIds) {
+ const styleSource = styleSources.get(styleSourceId);
+ if (styleSource?.type === "local") {
+ existingLocalStyleSource = styleSource;
+ }
+ }
+ const newStyleSourceIds = [];
+ for (let styleSourceId of values) {
+ const newLocalStyleSource = newLocalStyleSources.get(styleSourceId);
+ if (newLocalStyleSource) {
+ if (existingLocalStyleSource) {
+ // write local styles into existing local style source
+ styleSourceId = existingLocalStyleSource.id;
+ } else {
+ // create new local styles
+ const newId = nanoid();
+ styleSources.set(newId, { ...newLocalStyleSource, id: newId });
+ styleSourceId = newId;
+ }
+ newLocalStyleSourceIds.set(newLocalStyleSource.id, styleSourceId);
+ }
+ newStyleSourceIds.push(styleSourceId);
+ }
const newInstanceId = newInstanceIds.get(instanceId) ?? instanceId;
styleSourceSelections.set(newInstanceId, {
instanceId: newInstanceId,
- values: values.map(
- (styleSourceId) =>
- newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId
- ),
+ values: newStyleSourceIds,
});
- for (const styleSourceId of styleSourceSelection.values) {
- instanceStyleSourceIds.add(styleSourceId);
- }
}
+
for (const styleDecl of fragment.styles) {
const { breakpointId, styleSourceId } = styleDecl;
if (newLocalStyleSourceIds.has(styleDecl.styleSourceId)) {
diff --git a/apps/builder/app/shared/page-utils.ts b/apps/builder/app/shared/page-utils.ts
index cfc57d47ce..fe4f1d6889 100644
--- a/apps/builder/app/shared/page-utils.ts
+++ b/apps/builder/app/shared/page-utils.ts
@@ -10,6 +10,7 @@ import {
type Page,
type Pages,
type WebstudioData,
+ ROOT_INSTANCE_ID,
} from "@webstudio-is/sdk";
import {
extractWebstudioFragment,
@@ -94,10 +95,16 @@ export const insertPageCopyMutable = ({
if (page === undefined) {
return;
}
- const fragment = extractWebstudioFragment(source.data, page.rootInstanceId);
+ // copy paste project :root
+ insertWebstudioFragmentCopy({
+ data: target.data,
+ fragment: extractWebstudioFragment(source.data, ROOT_INSTANCE_ID),
+ availableDataSources: new Set(),
+ });
+ // copy paste page body
const { newInstanceIds, newDataSourceIds } = insertWebstudioFragmentCopy({
data: target.data,
- fragment,
+ fragment: extractWebstudioFragment(source.data, page.rootInstanceId),
availableDataSources: new Set(),
});
const newPageId = nanoid();
diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.ts
index cf64fb8ca4..3ecb30fdb8 100644
--- a/packages/css-data/src/parse-css.test.ts
+++ b/packages/css-data/src/parse-css.test.ts
@@ -194,6 +194,17 @@ describe("Parse CSS", () => {
]);
});
+ test("parse first pseudo class as selector", () => {
+ expect(parseCss(`:first-pseudo:my-state { color: #ff0000 }`)).toEqual([
+ {
+ selector: ":first-pseudo",
+ state: ":my-state",
+ property: "color",
+ value: { alpha: 1, b: 0, g: 0, r: 255, type: "rgb" },
+ },
+ ]);
+ });
+
test("parse pseudo element", () => {
expect(parseCss(`input::placeholder { color: #ff0000 }`)).toEqual([
{
diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.ts
index 1f739e6bcc..9efb238c11 100644
--- a/packages/css-data/src/parse-css.ts
+++ b/packages/css-data/src/parse-css.ts
@@ -173,34 +173,40 @@ export const parseCss = (css: string, options: ParserOptions = {}) => {
}
const selectors: Selector[] = [];
- csstree.walk(this.rule.prelude, (node, item) => {
- if (node.type !== "ClassSelector" && node.type !== "TypeSelector") {
- return;
- }
- // We don't support nesting yet.
- if (
- (item?.prev && item.prev.data.type === "Combinator") ||
- (item?.next && item.next.data.type === "Combinator")
- ) {
- return;
- }
-
- if (item?.next && item.next.data.type === "PseudoElementSelector") {
- selectors.push({
- name: node.name,
- state: `::${item.next.data.name}`,
- });
- } else if (item?.next && item.next.data.type === "PseudoClassSelector") {
- selectors.push({
- name: node.name,
- state: `:${item.next.data.name}`,
- });
- } else {
- selectors.push({
- name: node.name,
- });
+ if (this.rule.prelude.type === "SelectorList") {
+ for (const selector of this.rule.prelude.children) {
+ if (selector.type !== "Selector" || selector.children.size > 2) {
+ continue;
+ }
+ const [nameNode, stateNode] = selector.children;
+ let name;
+ if (
+ nameNode.type === "ClassSelector" ||
+ nameNode.type === "TypeSelector"
+ ) {
+ name = nameNode.name;
+ } else if (nameNode.type === "PseudoClassSelector") {
+ name = `:${nameNode.name}`;
+ } else {
+ continue;
+ }
+ if (stateNode?.type === "PseudoClassSelector") {
+ selectors.push({
+ name,
+ state: `:${stateNode.name}`,
+ });
+ } else if (stateNode?.type === "PseudoElementSelector") {
+ selectors.push({
+ name,
+ state: `::${stateNode.name}`,
+ });
+ } else {
+ selectors.push({
+ name,
+ });
+ }
}
- });
+ }
const stringValue = csstree.generate(node.value);
diff --git a/packages/sdk/src/instances-utils.test.tsx b/packages/sdk/src/instances-utils.test.tsx
index 87d4232036..1bd40e21e3 100644
--- a/packages/sdk/src/instances-utils.test.tsx
+++ b/packages/sdk/src/instances-utils.test.tsx
@@ -37,6 +37,14 @@ test("find all tree instances excluding slot descendants", () => {
).toEqual(new Set(["box1", "slot", "box2"]));
});
+test("include not existing/virtual instance", () => {
+ const { instances } = renderJsx(<$.Body ws:id="1"></$.Body>);
+ expect(findTreeInstanceIds(instances, ":root")).toEqual(new Set([":root"]));
+ expect(
+ findTreeInstanceIdsExcludingSlotDescendants(instances, ":root")
+ ).toEqual(new Set([":root"]));
+});
+
test("extract short name and namespace from component name", () => {
expect(parseComponentName("Box")).toEqual([undefined, "Box"]);
expect(parseComponentName("radix:Box")).toEqual(["radix", "Box"]);
diff --git a/packages/sdk/src/instances-utils.ts b/packages/sdk/src/instances-utils.ts
index 568fab04ca..35ed3085f7 100644
--- a/packages/sdk/src/instances-utils.ts
+++ b/packages/sdk/src/instances-utils.ts
@@ -26,7 +26,7 @@ export const findTreeInstanceIds = (
instances: Instances,
rootInstanceId: Instance["id"]
) => {
- const ids = new Set<Instance["id"]>();
+ const ids = new Set<Instance["id"]>([rootInstanceId]);
traverseInstances(instances, rootInstanceId, (instance) => {
ids.add(instance.id);
});
@@ -37,7 +37,7 @@ export const findTreeInstanceIdsExcludingSlotDescendants = (
instances: Instances,
rootInstanceId: Instance["id"]
) => {
- const ids = new Set<Instance["id"]>();
+ const ids = new Set<Instance["id"]>([rootInstanceId]);
traverseInstances(instances, rootInstanceId, (instance) => {
ids.add(instance.id);
if (instance.component === "Slot") {