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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
experimental: Paste from webflow 3 (#3482)
Oleg Isonen04b878bf4120
diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow.ts b/apps/builder/app/shared/copy-paste/plugin-webflow.tsdeleted file mode 100644index 6a0645fe63..0000000000--- a/apps/builder/app/shared/copy-paste/plugin-webflow.ts+++ /dev/null@@ -1,426 +0,0 @@-import { nanoid } from "nanoid";-import type { Instance, WebstudioFragment } from "@webstudio-is/sdk";-import {- computeInstancesConstraints,- findClosestDroppableTarget,- insertTemplateData,-} from "../instance-utils";-import {- $breakpoints,- $instances,- $registeredComponentMetas,- $selectedInstanceSelector,- $selectedPage,-} from "../nano-states";-import { z } from "zod";-import { isBaseBreakpoint } from "../breakpoints";-import { parseCss } from "@webstudio-is/css-data";-import { isFeatureEnabled } from "@webstudio-is/feature-flags";--export const mimeType = "application/json";--// A list of Webflow component names that need to be mapped.-const componentMappers = {- Block(wfNode: WfElementNode) {- if (wfNode.type === "Block") {- return wfNode.data?.text ? "Text" : "Box";- }- return wfNode.type;- },- Section(wfNode: WfElementNode) {- if (wfNode.type === "Section") {- return "Box";- }- return wfNode.type;- },- RichText(wfNode: WfElementNode) {- if (wfNode.type === "RichText") {- return "Box";- }- return wfNode.type;- },- Strong(wfNode: WfElementNode) {- if (wfNode.type === "Strong") {- return "Bold";- }- return wfNode.type;- },- Emphasized(wfNode: WfElementNode) {- if (wfNode.type === "Emphasized") {- return "Italic";- }- return wfNode.type;- },- BlockContainer(wfNode: WfElementNode) {- if (wfNode.type === "BlockContainer") {- return "Box";- }- return wfNode.type;- },- Layout(wfNode: WfElementNode) {- if (wfNode.type === "Layout") {- return "Box";- }- return wfNode.type;- },- Cell(wfNode: WfElementNode) {- if (wfNode.type === "Cell") {- return "Box";- }- return wfNode.type;- },- VFlex(wfNode: WfElementNode) {- if (wfNode.type === "VFlex") {- return "Box";- }- return wfNode.type;- },- HFlex(wfNode: WfElementNode) {- if (wfNode.type === "HFlex") {- return "Box";- }- return wfNode.type;- },-};--const WfBaseNode = z.object({- _id: z.string(),- tag: z.string(),- children: z.array(z.string()),- classes: z.array(z.string()),- data: z.object({}).optional(),-});--const WfTextNode = z.object({- _id: z.string(),- v: z.string(),- text: z.boolean(),-});--const WfElementNode = z.union([- WfBaseNode.extend({ type: z.enum(["Heading"]) }),- WfBaseNode.extend({- type: z.enum(["Block"]),- data: z.object({ text: z.boolean().optional() }).optional(),- }),- WfBaseNode.extend({ type: z.enum(["List"]) }),- WfBaseNode.extend({ type: z.enum(["ListItem"]) }),- WfBaseNode.extend({- type: z.enum(["Link"]),- data: z.object({- link: z.object({- url: z.string(),- target: z.string().optional(),- }),- }),- }),- WfBaseNode.extend({ type: z.enum(["Paragraph"]) }),- WfBaseNode.extend({ type: z.enum(["Blockquote"]) }),- WfBaseNode.extend({ type: z.enum(["RichText"]) }),- WfBaseNode.extend({ type: z.enum(["Strong"]) }),- WfBaseNode.extend({ type: z.enum(["Emphasized"]) }),- WfBaseNode.extend({ type: z.enum(["Superscript"]) }),- WfBaseNode.extend({ type: z.enum(["Subscript"]) }),- WfBaseNode.extend({ type: z.enum(["Section"]) }),- WfBaseNode.extend({ type: z.enum(["BlockContainer"]) }),- WfBaseNode.extend({ type: z.enum(["Layout"]) }),- WfBaseNode.extend({ type: z.enum(["Cell"]) }),- WfBaseNode.extend({ type: z.enum(["VFlex"]) }),- WfBaseNode.extend({ type: z.enum(["HFlex"]) }),-]);-type WfElementNode = z.infer<typeof WfElementNode>;--const WfNode = z.union([WfElementNode, WfTextNode]);-type WfNode = z.infer<typeof WfNode>;--const WfStyle = z.object({- _id: z.string(),- type: z.enum(["class"]),- name: z.string(),- styleLess: z.string(),- //comb: z.string(),- //namespace: z.string(),- //variants: z.object(),- //children: z.array(z.string()),- //createdBy: z.string(),- //origin: z.null(),- //selector: z.null(),-});--type WfStyle = z.infer<typeof WfStyle>;--const WfData = z.object({- type: z.literal("@webflow/XscpData"),- payload: z.object({- nodes: z.array(WfNode),- styles: z.array(WfStyle),- }),-});-type WfData = z.infer<typeof WfData>;--const addStyles = (- wfNodes: Map<WfNode["_id"], WfNode>,- wfStyles: Map<WfStyle["_id"], WfStyle>,- added: Map<WfNode["_id"], Instance["id"]>,- fragment: WebstudioFragment-) => {- for (const wfNode of wfNodes.values()) {- if ("text" in wfNode) {- continue;- }- for (const classId of wfNode.classes) {- const style = wfStyles.get(classId);- if (style === undefined) {- continue;- }- const styleSourceId = nanoid();- fragment.styleSources.push({- type: "token",- id: styleSourceId,- name: style.name,- });- const instanceId = added.get(wfNode._id);- if (instanceId === undefined) {- console.error("No instance id found - should never happen");- continue;- }-- fragment.styleSourceSelections.push({- instanceId,- values: [styleSourceId],- });-- const breakpointId = Array.from($breakpoints.get().values()).find(- isBaseBreakpoint- )?.id;- if (breakpointId === undefined) {- console.error("No base breakpoint found - should never happen");- continue;- }- const styles = parseCss(`.styles {${style.styleLess}}`).styles ?? [];- for (const style of styles) {- fragment.styles.push({- styleSourceId,- breakpointId,- property: style.property,- value: style.value,- });- }- }- }-};--const addInstance = (- wfNode: WfNode,- added: Map<WfNode["_id"], Instance["id"]>,- wfNodes: Map<WfNode["_id"], WfNode>,- fragment: WebstudioFragment-) => {- if (added.get(wfNode._id) || "text" in wfNode) {- return;- }-- const children: Instance["children"] = [];- const instanceId = nanoid();-- for (const wfChildId of wfNode.children) {- const wfChildNode = wfNodes.get(wfChildId);- if (wfChildNode === undefined) {- continue;- }- if ("text" in wfChildNode) {- children.push({- type: "text",- value: wfChildNode.v,- });- added.set(wfChildId, instanceId);- continue;- }-- const childInstanceId = addInstance(wfChildNode, added, wfNodes, fragment);- if (childInstanceId !== undefined) {- children.push({- type: "id",- value: childInstanceId,- });- }- }-- const component =- wfNode.type in componentMappers- ? componentMappers[wfNode.type as keyof typeof componentMappers](wfNode)- : wfNode.type;-- fragment.instances.push({- id: instanceId,- type: "instance",- component,- children,- });- added.set(wfNode._id, instanceId);-- return instanceId;-};--// Converting Webflow attributes and data to Webstudio props.-const propertyMappers = {- Link(wfNode: WfNode, instanceId: Instance["id"]) {- if ("type" in wfNode === false || wfNode.type !== "Link") {- return [];- }- const data = wfNode.data;- const props: WebstudioFragment["props"] = [];-- if (data.link.url) {- props.push({- type: "string",- id: nanoid(),- instanceId,- name: "href",- value: data.link.url,- });- }- if (data.link.target) {- props.push({- type: "string",- id: nanoid(),- instanceId,- name: "target",- value: data.link.target,- });- }- return props;- },-};--const addProperties = (- wfNodes: Map<WfNode["_id"], WfNode>,- added: Map<WfNode["_id"], Instance["id"]>,- fragment: WebstudioFragment-) => {- for (const wfNode of wfNodes.values()) {- if ("text" in wfNode) {- continue;- }- const instanceId = added.get(wfNode._id);- if (instanceId === undefined) {- console.error("No instance id found - should never happen");- continue;- }- // Webflow nodes always come with a tag.- // We support tag only for instances like Heading, not all of them.- // @todo decide what to do about other instances.- if ("tag" in wfNode) {- fragment.props.push({- type: "string",- id: nanoid(),- instanceId,- name: "tag",- value: wfNode.tag,- });- }- if (wfNode.type in propertyMappers) {- const props = propertyMappers[- wfNode.type as keyof typeof propertyMappers- ](wfNode, instanceId);- fragment.props.push(...props);- }- }-};--const toWebstudioFragment = (wfData: WfData) => {- const fragment: WebstudioFragment = {- children: [],- instances: [],- props: [],- breakpoints: [],- styles: [],- styleSources: [],- styleSourceSelections: [],- dataSources: [],- resources: [],- assets: [],- };-- const wfNodes = new Map<WfNode["_id"], WfNode>(- wfData.payload.nodes.map((node: WfNode) => [node._id, node])- );- const wfStyles = new Map<WfStyle["_id"], WfStyle>(- wfData.payload.styles.map((style: WfStyle) => [style._id, style])- );- const added = new Map<WfNode["_id"], Instance["id"]>();- for (const wfNode of wfNodes.values()) {- addInstance(wfNode, added, wfNodes, fragment);- }- addStyles(wfNodes, wfStyles, added, fragment);- addProperties(wfNodes, added, fragment);- // First node should be always the root node in theory, if not- // we need to find a node that is not a child of any other node.- const rootWfNode = wfData.payload.nodes[0];- const rootInstanceId = added.get(rootWfNode._id);- if (rootInstanceId === undefined) {- console.error("No root instance id found - should never happen");- return fragment;- }- fragment.children = [- {- type: "id",- value: rootInstanceId,- },- ];- return fragment;-};--const parse = (clipboardData: string) => {- try {- const data = JSON.parse(clipboardData);- const result = WfData.safeParse(data);- if (result.success) {- return result.data;- }- throw result.error.message;- } catch (error) {- console.error(error);- }-};--export const onPaste = (clipboardData: string): boolean => {- if (isFeatureEnabled("pasteFromWebflow") === false) {- return false;- }- const wfData = parse(clipboardData);- if (wfData === undefined) {- return false;- }- const data = toWebstudioFragment(wfData);- const selectedPage = $selectedPage.get();- if (data === undefined || selectedPage === undefined) {- return false;- }- const metas = $registeredComponentMetas.get();- const newInstances = new Map(- data.instances.map((instance) => [instance.id, instance])- );- const rootInstanceIds = data.children- .filter((child) => child.type === "id")- .map((child) => child.value);- // paste to the root if nothing is selected- const instanceSelector = $selectedInstanceSelector.get() ?? [- selectedPage.rootInstanceId,- ];- const dropTarget = findClosestDroppableTarget(- metas,- $instances.get(),- instanceSelector,- computeInstancesConstraints(metas, newInstances, rootInstanceIds)- );- if (dropTarget === undefined) {- return false;- }- insertTemplateData(data, dropTarget);- return true;-};--export const __testing__ = {- toWebstudioFragment,-};diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/instances-properties.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/instances-properties.tsnew file mode 100644index 0000000000..94fd124aba--- /dev/null+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/instances-properties.ts@@ -0,0 +1,266 @@+import { nanoid } from "nanoid";+import type { Instance, Prop, WebstudioFragment } from "@webstudio-is/sdk";+import type { WfElementNode, WfNode } from "./schema";++const mapComponentAndProperties = (+ wfNode: WfElementNode,+ instanceId: Instance["id"]+) => {+ const props: Array<Prop> = [];+ const component = wfNode.type;++ switch (component) {+ case "Heading":+ case "List":+ case "ListItem":+ case "Paragraph":+ case "Superscript":+ case "Subscript":+ case "Blockquote": {+ return { component, props };+ }+ case "Block": {+ const component = wfNode.data?.text ? "Text" : "Box";+ return { component, props };+ }+ case "Link": {+ const data = wfNode.data;++ if (data.link.url) {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "href",+ value: data.link.url,+ });+ }+ if (data.link.target) {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "target",+ value: data.link.target,+ });+ }+ return { component, props };+ }+ case "Section": {+ const component = "Box";+ return { component, props };+ }+ case "RichText": {+ const component = "Box";+ return { component, props };+ }+ case "Strong": {+ const component = "Bold";+ return { component, props };+ }+ case "Emphasized": {+ const component = "Italic";+ return { component, props };+ }+ case "BlockContainer": {+ const component = "Box";+ return { component, props };+ }+ case "Layout": {+ const component = "Box";+ return { component, props };+ }+ case "Cell": {+ const component = "Box";+ return { component, props };+ }+ case "VFlex": {+ const component = "Box";+ return { component, props };+ }+ case "HFlex": {+ const component = "Box";+ return { component, props };+ }+ case "Grid": {+ const component = "Box";+ return { component, props };+ }+ case "Row": {+ const component = "Box";+ return { component, props };+ }+ case "Column": {+ const component = "Box";+ return { component, props };+ }+ case "CodeBlock": {+ const component = "CodeText";+ const data = wfNode.data;++ if (data.language) {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "lang",+ value: data.language,+ });+ }++ if (data.code) {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "code",+ value: data.code,+ });+ }+ return { component, props };+ }+ case "Image": {+ const data = wfNode.data;++ if (+ data.attr.alt &&+ // This is how they tell it when alt comes from image meta during publishing+ data.attr.alt !== "__wf_reserved_inherit" &&+ // This is how they tell it to use alt="", which is our default anyways+ data.attr.alt !== "__wf_reserved_decorative"+ ) {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "alt",+ value: data.attr.alt,+ });+ }++ if (data.attr.loading === "eager" || data.attr.loading === "lazy") {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "loading",+ value: data.attr.loading,+ });+ }++ if (data.attr.width && data.attr.width !== "auto") {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "width",+ value: data.attr.width,+ });+ }++ if (data.attr.height && data.attr.height !== "auto") {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "height",+ value: data.attr.height,+ });+ }+ if (data.attr.src) {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "src",+ value: data.attr.src,+ });+ }+ return { component, props };+ }+ }++ component satisfies never;+};++const addAttributes = (+ wfNode: WfElementNode,+ instanceId: Instance["id"],+ props: Array<Prop>+) => {+ if ("tag" in wfNode) {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: "tag",+ value: wfNode.tag,+ });+ }++ if (wfNode.data?.xattr) {+ for (const attribute of wfNode.data.xattr) {+ props.push({+ type: "string",+ id: nanoid(),+ instanceId,+ name: attribute.name,+ value: attribute.value,+ });+ }+ }+};++export const addInstanceAndProperties = (+ wfNode: WfNode,+ added: Map<WfNode["_id"], Instance["id"]>,+ wfNodes: Map<WfNode["_id"], WfNode>,+ fragment: WebstudioFragment+) => {+ if (added.get(wfNode._id) || "text" in wfNode || "type" in wfNode === false) {+ return;+ }+ const children: Instance["children"] = [];+ const instanceId = nanoid();+ for (const wfChildId of wfNode.children) {+ const wfChildNode = wfNodes.get(wfChildId);+ if (wfChildNode === undefined) {+ continue;+ }+ if ("text" in wfChildNode) {+ children.push({+ type: "text",+ value: wfChildNode.v,+ });+ added.set(wfChildId, instanceId);+ continue;+ }++ const childInstanceId = addInstanceAndProperties(+ wfChildNode,+ added,+ wfNodes,+ fragment+ );+ if (childInstanceId !== undefined) {+ children.push({+ type: "id",+ value: childInstanceId,+ });+ }+ }++ const { component, props } = mapComponentAndProperties(wfNode, instanceId);++ fragment.instances.push({+ id: instanceId,+ type: "instance",+ component,+ children,+ });+ added.set(wfNode._id, instanceId);+ addAttributes(wfNode, instanceId, props);+ fragment.props.push(...props);++ return instanceId;+};diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow.test.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tssimilarity index 66%rename from apps/builder/app/shared/copy-paste/plugin-webflow.test.tsrename to apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsindex 8ef96e2cf4..923f26d580 100644--- a/apps/builder/app/shared/copy-paste/plugin-webflow.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.ts@@ -1,6 +1,6 @@-import { test, expect } from "@jest/globals";+import { test, expect, describe } from "@jest/globals";import { __testing__ } from "./plugin-webflow";-import { $breakpoints } from "../nano-states";+import { $breakpoints } from "../../nano-states";const { toWebstudioFragment } = __testing__;@@ -100,22 +100,22 @@ test("Link Block, Button, Text Link", () => {type: "string",id: expect.not.stringMatching("id"),instanceId: expect.not.stringMatching("instanceId"),- name: "tag",- value: "a",+ name: "href",+ value: "https://webstudio.is",},{type: "string",id: expect.not.stringMatching("id"),instanceId: expect.not.stringMatching("instanceId"),- name: "href",- value: "https://webstudio.is",+ name: "target",+ value: "_blank",},{type: "string",id: expect.not.stringMatching("id"),instanceId: expect.not.stringMatching("instanceId"),- name: "target",- value: "_blank",+ name: "tag",+ value: "a",},]);});@@ -638,18 +638,6 @@ test("Quick Stack", () => {"91782272-bf55-194d-ce85-9ddc69c51def","91782272-bf55-194d-ce85-9ddc69c51df0",],- data: {- style: {- base: {- main: {- noPseudo: {- gridTemplateColumns: "1fr 1fr",- gridTemplateRows: "auto",- },- },- },- },- },},{_id: "91782272-bf55-194d-ce85-9ddc69c51def",@@ -695,56 +683,332 @@ test("Quick Stack", () => {]);});-test("Basic styles with a class", () => {+test("Grid", () => {const fragment = toWebstudioFragment({type: "@webflow/XscpData",payload: {nodes: [{- _id: "97d91be2-3bba-d340-0f13-a84e975b7497",- type: "Heading",- tag: "h1",- classes: [- "2891ad3d-89de-2434-bedd-51ef56dff4c4",- "a7bff598-b719-1edb-067b-a90a54d68605",+ _id: "25ffefdf-c015-5edd-7673-933b41a25328",+ type: "Grid",+ tag: "div",+ classes: [],+ children: [],+ },+ ],+ styles: [],+ },+ });++ expect(fragment.instances).toEqual([+ {+ id: expect.not.stringMatching("instanceId"),+ type: "instance",+ component: "Box",+ children: [],+ },+ ]);+});++test("Columns", () => {+ const fragment = toWebstudioFragment({+ type: "@webflow/XscpData",+ payload: {+ nodes: [+ {+ _id: "08fb88d6-f6ec-5169-f4d4-8dac98df2b58",+ type: "Row",+ tag: "div",+ classes: [],+ children: [+ "08fb88d6-f6ec-5169-f4d4-8dac98df2b59",+ "08fb88d6-f6ec-5169-f4d4-8dac98df2b5a",],- children: ["97d91be2-3bba-d340-0f13-a84e975b7498"],},{- _id: "97d91be2-3bba-d340-0f13-a84e975b7498",- text: true,- v: "Turtle in the sea",+ _id: "08fb88d6-f6ec-5169-f4d4-8dac98df2b59",+ type: "Column",+ tag: "div",+ classes: [],+ children: [],+ },+ {+ _id: "08fb88d6-f6ec-5169-f4d4-8dac98df2b5a",+ type: "Column",+ tag: "div",+ classes: [],+ children: [],},],- styles: [+ styles: [],+ },+ });++ expect(fragment.instances).toEqual([+ {+ id: expect.not.stringMatching("instanceId"),+ type: "instance",+ component: "Box",+ children: [],+ },+ {+ id: expect.not.stringMatching("instanceId"),+ type: "instance",+ component: "Box",+ children: [],+ },+ {+ id: expect.not.stringMatching("instanceId"),+ type: "instance",+ component: "Box",+ children: [+ { type: "id", value: expect.not.stringMatching("instanceId") },+ { type: "id", value: expect.not.stringMatching("instanceId") },+ ],+ },+ ]);+});++test("Image", () => {+ const fragment = toWebstudioFragment({+ type: "@webflow/XscpData",+ payload: {+ nodes: [{- _id: "a7bff598-b719-1edb-067b-a90a54d68605",- type: "class",- name: "Heading",- styleLess: "color: hsla(0, 80.00%, 47.78%, 1.00);",+ _id: "3c0b6a7a-830f-4b4a-48c5-4215f9c9389a",+ type: "Image",+ tag: "img",+ classes: [],+ children: [],+ data: {+ attr: {+ src: "https://uploads-ssl.webflow.com/6640ea3496ea68a4a4e3efcf/665dd9f1927826d5caad6ed4_Screenshot%202024-05-29%20at%2023.10.33.png",+ loading: "eager",+ width: "200",+ height: "auto",+ alt: "Test",+ },+ },},],+ styles: [],},});- expect(fragment.styleSources).toEqual([++ expect(fragment.instances).toEqual([{- type: "token",- id: expect.not.stringMatching("styleSourceId"),- name: "Heading",+ id: expect.not.stringMatching("instanceId"),+ type: "instance",+ component: "Image",+ children: [],},]);- expect(fragment.styleSourceSelections).toEqual([++ expect(fragment.props).toEqual([{- instanceId: expect.not.stringMatching("instanceId"),- values: [expect.not.stringMatching("styleSourceId")],+ type: "string",+ id: expect.not.stringMatching("instanceId"),+ instanceId: expect.not.stringMatching("id"),+ name: "alt",+ value: "Test",+ },+ {+ type: "string",+ id: expect.not.stringMatching("instanceId"),+ instanceId: expect.not.stringMatching("id"),+ name: "loading",+ value: "eager",+ },+ {+ type: "string",+ id: expect.not.stringMatching("instanceId"),+ instanceId: expect.not.stringMatching("id"),+ name: "width",+ value: "200",+ },+ {+ type: "string",+ id: expect.not.stringMatching("instanceId"),+ instanceId: expect.not.stringMatching("id"),+ name: "src",+ value: expect.not.stringMatching("src"),+ },+ {+ type: "string",+ id: expect.not.stringMatching("instanceId"),+ instanceId: expect.not.stringMatching("id"),+ name: "tag",+ value: "img",},]);- expect(fragment.styles).toEqual([+});++describe("Custom attributes", () => {+ const fragment = toWebstudioFragment({+ type: "@webflow/XscpData",+ payload: {+ nodes: [+ {+ _id: "249f235e-91b6-bd0f-bc42-00993479e637",+ type: "Heading",+ tag: "h1",+ classes: [],+ children: [],+ data: {+ xattr: [+ {+ name: "at",+ value: "b",+ },+ ],+ },+ },+ ],+ styles: [],+ },+ });+ expect(fragment.props).toEqual([{- styleSourceId: expect.not.stringMatching("styleSourceId"),- breakpointId: "0",- property: "color",- value: { type: "rgb", alpha: 1, r: 219, g: 24, b: 24 },+ type: "string",+ id: expect.not.stringMatching("id"),+ instanceId: expect.not.stringMatching("instanceId"),+ name: "tag",+ value: "h1",+ },+ {+ type: "string",+ id: expect.not.stringMatching("id"),+ instanceId: expect.not.stringMatching("instanceId"),+ name: "at",+ value: "b",},]);});++describe("Styles", () => {+ test("Single class", () => {+ const fragment = toWebstudioFragment({+ type: "@webflow/XscpData",+ payload: {+ nodes: [+ {+ _id: "97d91be2-3bba-d340-0f13-a84e975b7497",+ type: "Heading",+ tag: "h1",+ classes: ["a7bff598-b719-1edb-067b-a90a54d68605"],+ children: [],+ },+ ],+ styles: [+ {+ _id: "a7bff598-b719-1edb-067b-a90a54d68605",+ type: "class",+ name: "Heading",+ styleLess: "color: hsla(0, 80.00%, 47.78%, 1.00);",+ },+ ],+ },+ });+ expect(fragment.styleSources).toEqual([+ {+ type: "token",+ id: expect.not.stringMatching("styleSourceId"),+ name: "Heading",+ },+ ]);+ expect(fragment.styleSourceSelections).toEqual([+ {+ instanceId: expect.not.stringMatching("instanceId"),+ values: [expect.not.stringMatching("styleSourceId")],+ },+ ]);+ expect(fragment.styles).toEqual([+ {+ styleSourceId: expect.not.stringMatching("styleSourceId"),+ breakpointId: "0",+ property: "color",+ value: { type: "rgb", alpha: 1, r: 219, g: 24, b: 24 },+ },+ ]);+ });++ test("Combo class", () => {+ const fragment = toWebstudioFragment({+ type: "@webflow/XscpData",+ payload: {+ nodes: [+ {+ _id: "5f7ab979-89b3-c705-6ab9-35f77dfb209f",+ type: "Link",+ tag: "a",+ classes: [+ "194e7d07-469d-6ffa-3925-1f51bdad7e44",+ "194e7d07-469d-6ffa-3925-1f51bdad7e46",+ ],+ children: [],+ data: {+ link: {+ url: "#",+ },+ },+ },+ ],+ styles: [+ {+ _id: "194e7d07-469d-6ffa-3925-1f51bdad7e44",+ type: "class",+ name: "button",+ styleLess: "text-align: center;",+ children: ["194e7d07-469d-6ffa-3925-1f51bdad7e46"],+ },+ {+ _id: "194e7d07-469d-6ffa-3925-1f51bdad7e46",+ type: "class",+ name: "is-secondary",+ comb: "&",+ styleLess: "background-color: transparent; ",+ createdBy: "6075409192d886a671499223",+ },+ ],+ },+ });+ expect(fragment.styleSources).toEqual([+ {+ type: "token",+ id: expect.not.stringMatching("styleSourceId"),+ name: "button",+ },+ {+ type: "token",+ id: expect.not.stringMatching("styleSourceId"),+ name: "is-secondary",+ },+ ]);+ expect(fragment.styleSourceSelections).toEqual([+ {+ instanceId: expect.not.stringMatching("instanceId"),+ values: [+ expect.not.stringMatching("styleSourceId"),+ expect.not.stringMatching("styleSourceId"),+ ],+ },+ ]);+ expect(fragment.styles).toEqual([+ {+ styleSourceId: expect.not.stringMatching("styleSourceId"),+ breakpointId: "0",+ property: "textAlign",+ value: { type: "keyword", value: "center" },+ },+ {+ styleSourceId: expect.not.stringMatching("styleSourceId"),+ breakpointId: "0",+ property: "backgroundColor",+ value: {+ type: "keyword",+ value: "transparent",+ },+ },+ ]);+ });+});diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.tsnew file mode 100644index 0000000000..023945f9ce--- /dev/null+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts@@ -0,0 +1,117 @@+import type { Instance, WebstudioFragment } from "@webstudio-is/sdk";+import {+ computeInstancesConstraints,+ findClosestDroppableTarget,+ insertTemplateData,+} from "../../instance-utils";+import {+ $instances,+ $registeredComponentMetas,+ $selectedInstanceSelector,+ $selectedPage,+} from "../../nano-states";+import { isFeatureEnabled } from "@webstudio-is/feature-flags";+import { WfData, WfNode, WfStyle } from "./schema";+import { addInstanceAndProperties } from "./instances-properties";+import { addStyles } from "./styles";++export const mimeType = "application/json";++const toWebstudioFragment = (wfData: WfData) => {+ const fragment: WebstudioFragment = {+ children: [],+ instances: [],+ props: [],+ breakpoints: [],+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ dataSources: [],+ resources: [],+ assets: [],+ };++ const wfNodes = new Map<WfNode["_id"], WfNode>();+ for (const node of wfData.payload.nodes) {+ if ("type" in node || "text" in node) {+ wfNodes.set(node._id, node);+ }+ }+ const wfStyles = new Map<WfStyle["_id"], WfStyle>(+ wfData.payload.styles.map((style: WfStyle) => [style._id, style])+ );+ const added = new Map<WfNode["_id"], Instance["id"]>();+ for (const wfNode of wfNodes.values()) {+ addInstanceAndProperties(wfNode, added, wfNodes, fragment);+ }+ addStyles(wfNodes, wfStyles, added, fragment);+ // First node should be always the root node in theory, if not+ // we need to find a node that is not a child of any other node.+ const rootWfNode = wfData.payload.nodes[0];+ const rootInstanceId = added.get(rootWfNode._id);+ if (rootInstanceId === undefined) {+ console.error(`No root instance id found for node ${rootWfNode._id}`);+ return fragment;+ }+ fragment.children = [+ {+ type: "id",+ value: rootInstanceId,+ },+ ];+ return fragment;+};++const parse = (clipboardData: string) => {+ try {+ const data = JSON.parse(clipboardData);+ const result = WfData.safeParse(data);+ if (result.success) {+ return result.data;+ }+ throw result.error.message;+ } catch (error) {+ console.error(error);+ }+};++export const onPaste = (clipboardData: string): boolean => {+ if (isFeatureEnabled("pasteFromWebflow") === false) {+ return false;+ }+ const wfData = parse(clipboardData);+ if (wfData === undefined) {+ return false;+ }+ const fragment = toWebstudioFragment(wfData);+ const selectedPage = $selectedPage.get();+ if (fragment.instances.length === 0 || selectedPage === undefined) {+ return false;+ }+ const metas = $registeredComponentMetas.get();+ const newInstances = new Map(+ fragment.instances.map((instance) => [instance.id, instance])+ );+ const rootInstanceIds = fragment.children+ .filter((child) => child.type === "id")+ .map((child) => child.value);+ // paste to the root if nothing is selected+ const instanceSelector = $selectedInstanceSelector.get() ?? [+ selectedPage.rootInstanceId,+ ];+ const dropTarget = findClosestDroppableTarget(+ metas,+ $instances.get(),+ instanceSelector,+ computeInstancesConstraints(metas, newInstances, rootInstanceIds)+ );+ if (dropTarget === undefined) {+ return false;+ }+ insertTemplateData(fragment, dropTarget);+ return true;+};++export const __testing__ = {+ toWebstudioFragment,+};diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/schema.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/schema.tsnew file mode 100644index 0000000000..f976f739ed--- /dev/null+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/schema.ts@@ -0,0 +1,103 @@+import { z } from "zod";++const WfNodeData = z.object({+ xattr: z.array(z.object({ name: z.string(), value: z.string() })).optional(),+});++const WfBaseNode = z.object({+ _id: z.string(),+ tag: z.string(),+ children: z.array(z.string()),+ classes: z.array(z.string()),+ data: WfNodeData.optional(),+});++const WfTextNode = z.object({+ _id: z.string(),+ v: z.string(),+ text: z.boolean(),+});++export const WfElementNode = z.union([+ WfBaseNode.extend({ type: z.enum(["Heading"]) }),+ WfBaseNode.extend({+ type: z.enum(["Block"]),+ data: WfNodeData.extend({ text: z.boolean().optional() }).optional(),+ }),+ WfBaseNode.extend({ type: z.enum(["List"]) }),+ WfBaseNode.extend({ type: z.enum(["ListItem"]) }),+ WfBaseNode.extend({+ type: z.enum(["Link"]),+ data: WfNodeData.extend({+ link: z.object({+ url: z.string(),+ target: z.string().optional(),+ }),+ }),+ }),+ WfBaseNode.extend({ type: z.enum(["Paragraph"]) }),+ WfBaseNode.extend({ type: z.enum(["Blockquote"]) }),+ WfBaseNode.extend({ type: z.enum(["RichText"]) }),+ WfBaseNode.extend({ type: z.enum(["Strong"]) }),+ WfBaseNode.extend({ type: z.enum(["Emphasized"]) }),+ WfBaseNode.extend({ type: z.enum(["Superscript"]) }),+ WfBaseNode.extend({ type: z.enum(["Subscript"]) }),+ WfBaseNode.extend({ type: z.enum(["Section"]) }),+ WfBaseNode.extend({ type: z.enum(["BlockContainer"]) }),+ WfBaseNode.extend({ type: z.enum(["Layout"]) }),+ WfBaseNode.extend({ type: z.enum(["Cell"]) }),+ WfBaseNode.extend({ type: z.enum(["VFlex"]) }),+ WfBaseNode.extend({ type: z.enum(["HFlex"]) }),+ WfBaseNode.extend({ type: z.enum(["Grid"]) }),+ WfBaseNode.extend({ type: z.enum(["Row"]) }),+ WfBaseNode.extend({ type: z.enum(["Column"]) }),+ WfBaseNode.extend({+ type: z.enum(["CodeBlock"]),+ data: WfNodeData.extend({+ language: z.string().optional(),+ code: z.string(),+ }),+ }),+ WfBaseNode.extend({+ type: z.enum(["Image"]),+ data: WfNodeData.extend({+ attr: z.object({+ alt: z.string(),+ loading: z.enum(["lazy", "eager", "auto"]),+ src: z.string(),+ width: z.string(),+ height: z.string(),+ }),+ }),+ }),+]);+export type WfElementNode = z.infer<typeof WfElementNode>;++export const WfNode = z.union([WfElementNode, WfTextNode]);+export type WfNode = z.infer<typeof WfNode>;++export const WfStyle = z.object({+ _id: z.string(),+ type: z.enum(["class"]),+ name: z.string(),+ styleLess: z.string(),+ fake: z.boolean().optional(),+ comb: z.string().optional(),+ namespace: z.string().optional(),+ variants: z.object({}).optional(),+ children: z.array(z.string()).optional(),+ createdBy: z.string().optional(),+ origin: z.null().optional(),+ selector: z.null().optional(),+});+export type WfStyle = z.infer<typeof WfStyle>;++export const WfData = z.object({+ type: z.literal("@webflow/XscpData"),+ payload: z.object({+ // Using WfBaseNode here just so we can skip a node with unknown node.type.+ nodes: z.array(z.union([WfNode, WfBaseNode])),+ styles: z.array(WfStyle),+ }),+});+export type WfData = z.infer<typeof WfData>;diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/styles.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/styles.tsnew file mode 100644index 0000000000..5401fe3424--- /dev/null+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/styles.ts@@ -0,0 +1,69 @@+import type { Instance, WebstudioFragment } from "@webstudio-is/sdk";+import type { WfNode, WfStyle } from "./schema";+import { nanoid } from "nanoid";+import { $breakpoints } from "~/shared/nano-states";+import { isBaseBreakpoint } from "~/shared/breakpoints";+import { parseCss } from "@webstudio-is/css-data";++export const addStyles = (+ wfNodes: Map<WfNode["_id"], WfNode>,+ wfStyles: Map<WfStyle["_id"], WfStyle>,+ added: Map<WfNode["_id"], Instance["id"]>,+ fragment: WebstudioFragment+) => {+ for (const wfNode of wfNodes.values()) {+ if ("text" in wfNode) {+ continue;+ }+ for (const classId of wfNode.classes) {+ const style = wfStyles.get(classId);+ if (style === undefined) {+ continue;+ }+ const styleSourceId = nanoid();+ fragment.styleSources.push({+ type: "token",+ id: styleSourceId,+ name: style.name,+ });+ const instanceId = added.get(wfNode._id);+ if (instanceId === undefined) {+ console.error(`No instance id found for node ${wfNode._id}`);+ continue;+ }++ let styleSourceSelection = fragment.styleSourceSelections.find(+ (selection) => selection.instanceId === instanceId+ );+ if (styleSourceSelection === undefined) {+ styleSourceSelection = { instanceId, values: [] };+ fragment.styleSourceSelections.push(styleSourceSelection);+ }+ styleSourceSelection.values.push(styleSourceId);++ const breakpointId = Array.from($breakpoints.get().values()).find(+ isBaseBreakpoint+ )?.id;+ if (breakpointId === undefined) {+ console.error("No base breakpoint found - should never happen");+ continue;+ }+ try {+ const styles = parseCss(`.styles {${style.styleLess}}`).styles ?? [];+ for (const style of styles) {+ fragment.styles.push({+ styleSourceId,+ breakpointId,+ property: style.property,+ value: style.value,+ });+ if (style.value.type === "invalid") {+ console.error("Invalid style value", style);+ }+ }+ } catch (error) {+ console.error("Failed to parse style", error, style.styleLess);+ }+ }+ }+};diff --git a/apps/builder/app/shared/copy-paste/use-copy-paste.ts b/apps/builder/app/shared/copy-paste/use-copy-paste.tsindex 676a66f4de..303615fe4b 100644--- a/apps/builder/app/shared/copy-paste/use-copy-paste.ts+++ b/apps/builder/app/shared/copy-paste/use-copy-paste.ts@@ -3,7 +3,7 @@ import { initCopyPaste } from "./init-copy-paste";import * as instance from "./plugin-instance";import * as embedTemplate from "./plugin-embed-template";import * as markdown from "./plugin-markdown";-import * as webflow from "./plugin-webflow";+import * as webflow from "./plugin-webflow/plugin-webflow";export const useCopyPaste = () => {useEffect(() => {diff --git a/packages/css-data/src/parse-css-value.ts b/packages/css-data/src/parse-css-value.tsindex 08c3c6d8fe..d41f28851e 100644--- a/packages/css-data/src/parse-css-value.ts+++ b/packages/css-data/src/parse-css-value.ts@@ -11,6 +11,7 @@ import {import { keywordValues } from "./__generated__/keyword-values";import { units } from "./__generated__/units";import { parseFilter, parseShadow, parseTransition } from "./property-parsers";+import { camelCase } from "change-case";export const cssTryParseValue = (input: string) => {try {@@ -131,9 +132,14 @@ export const parseCssValue = (}if (first?.type === "Identifier") {- const values = keywordValues[- property as keyof typeof keywordValues- ] as ReadonlyArray<string>;+ const values =+ keywordValues[camelCase(property) as keyof typeof keywordValues];+ if (values === undefined) {+ return {+ type: "invalid",+ value: "",+ };+ }const lettersRegex = /[^a-zA-Z]+/g;const searchValues = values.map((value) =>value.replace(lettersRegex, "").toLowerCase()diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.tsindex 32b2a1c02e..992058da98 100644--- a/packages/css-data/src/parse-css.test.ts+++ b/packages/css-data/src/parse-css.test.ts@@ -2,6 +2,22 @@ import { describe, expect, test } from "@jest/globals";import { parseCss } from "./parse-css";describe("Parse CSS", () => {+ test("longhand property name with keyword value", () => {+ expect(parseCss(`.test { background-color: red }`)).toMatchInlineSnapshot(`+ {+ "test": [+ {+ "property": "backgroundColor",+ "value": {+ "type": "keyword",+ "value": "red",+ },+ },+ ],+ }+ `);+ });+test("one class selector rules", () => {expect(parseCss(`.test { color: #ff0000 }`)).toMatchInlineSnapshot(`{diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.tsindex 17c16ccf68..d8baee9df8 100644--- a/packages/css-data/src/parse-css.ts+++ b/packages/css-data/src/parse-css.ts@@ -49,7 +49,7 @@ const parseCssValue = (];}- if (!value) {+ if (value === undefined || value === "") {return [property, { type: "invalid", value: "" }];}@@ -120,19 +120,7 @@ export const parseCss = (css: string) => {}});} catch (error) {- if (process.env.NODE_ENV !== "production") {- // eslint-disable-next-line no-console- console.warn(- true,- `Declaration parsing for \`${selectors.join(", ")}.${- node.property- }: ${stringValue}\` failed:\n\n${JSON.stringify(- parsedCss,- null,- 2- )}`- );- }+ console.error("Bad CSS declaration", error, parsedCss);}});