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
fix: Scaffold projects with attribute aliases (#6300)
Oleg Isonenc9618de88bb1
diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsxindex e87e1b186d..3e00280030 100644--- a/packages/react-sdk/src/component-generator.test.tsx+++ b/packages/react-sdk/src/component-generator.test.tsx@@ -1,6 +1,7 @@import { API, type Snapshot } from "typescript/unstable/sync";import { afterAll, beforeAll, expect, test } from "vitest";import stripIndent from "strip-indent";+import { standardAttributesToReactProps } from "@webstudio-is/content-engine/jsx-attributes";import {createScope,elementComponent,@@ -726,6 +727,100 @@ test("add classes", () => {);});+test("merges class aliases when generating jsx", () => {+ const data = renderData(<$.Body ws:id="body" className="standard"></$.Body>);+ data.props.set("duplicate-class", {+ id: "duplicate-class",+ instanceId: "body",+ name: "class",+ type: "string",+ value: "replacement",+ });+ data.props.set("legacy-class-name", {+ id: "legacy-class-name",+ instanceId: "body",+ name: "className",+ type: "string",+ value: "legacy",+ });++ expect(+ generateWebstudioComponent({+ classesMap: new Map([["body", ["atomic"]]]),+ scope: createScope(),+ name: "Page",+ rootInstanceId: "body",+ parameters: [],+ metas: new Map(),+ ...data,+ })+ ).toEqual(+ validateJSX(+ clear(`+ const Page = () => {+ return <Body+ className={\`atomic \${"replacement"} \${"legacy"}\`} />+ }+ `)+ )+ );+});++test.each(+ Object.entries(standardAttributesToReactProps).filter(+ ([standardName, jsxName]) =>+ standardName !== "class" && standardName !== jsxName+ )+)(+ "keeps the last value when %s and %s map to the same JSX prop",+ (standardName, jsxName) => {+ const generate = (attributes: [name: string, value: string][]) => {+ const data = renderData(<$.Body ws:id="body"></$.Body>);+ const instance = data.instances.get("body");+ if (instance === undefined) {+ throw new Error("Expected Body instance");+ }+ data.instances.set("body", { ...instance, tag: "div" });+ for (const [index, [name, value]] of attributes.entries()) {+ data.props.set(`${index}-${name}`, {+ id: `${index}-${name}`,+ instanceId: "body",+ name,+ type: "string",+ value,+ });+ }+ return generateJsxChildren({+ scope: createScope(),+ usedDataSources: new Map(),+ indexesWithinAncestors: new Map(),+ metas: new Map(),+ children: [{ type: "id", value: "body" }],+ ...data,+ });+ };+ const expected = (value: string) =>+ clear(`+ <Body+ data-ws-tag="div"+ ${jsxName}={"${value}"} />+ `);++ expect(+ generate([+ [standardName, "standard"],+ [jsxName, "jsx"],+ ])+ ).toBe(expected("jsx"));+ expect(+ generate([+ [jsxName, "jsx"],+ [standardName, "standard"],+ ])+ ).toBe(expected("standard"));+ }+);+test("add bind classes and merge classes", () => {const hasClass2 = new Variable("variableName", false);expect(diff --git a/packages/react-sdk/src/component-generator.ts b/packages/react-sdk/src/component-generator.tsindex 9380bcbbc8..ed60d3e3be 100644--- a/packages/react-sdk/src/component-generator.ts+++ b/packages/react-sdk/src/component-generator.ts@@ -25,10 +25,7 @@ import {} from "@webstudio-is/sdk";import { transpileExpression } from "@webstudio-is/expression";import { indexProperty, tagProperty } from "@webstudio-is/sdk/runtime";-import {- getJsxPropName,- mapAttributeNames,-} from "@webstudio-is/content-engine/jsx-attributes";+import { getJsxPropName } from "@webstudio-is/content-engine/jsx-attributes";import { isAttributeNameSafe, showAttribute } from "./props";import { generateCollectionIterationCode } from "./collection-utils";@@ -213,20 +210,7 @@ export const generateJsxElement = ({let collectionDataValue: undefined | string;let collectionItemValue: undefined | string;let collectionItemKeyValue: undefined | string;- let classNameValue: undefined | string;- // Older projects can contain duplicate props after an asset-derived prop was- // persisted alongside the authored prop. Keep the last value for a prop- // name so malformed data cannot produce duplicate JSX attributes.- const instanceProps = Array.from(- Array.from(props.values())- .filter((prop) => prop.instanceId === instance.id)- .reduce((uniqueProps, prop) => {- uniqueProps.set(prop.name, prop);- return uniqueProps;- }, new Map<string, Prop>())- .values()- );- const instancePropNames = new Set(instanceProps.map((prop) => prop.name));+ const classNameValues: string[] = [];const projectedResourceProps = new Map<string, unknown>();const componentPropNames = new Set(Object.keys(meta?.props ?? {}));const acceptsHtmlAttributes =@@ -239,16 +223,34 @@ export const generateJsxElement = ({componentPropNames,acceptsHtmlAttributes,});- const generatedPropNames = new Map(- mapAttributeNames({- attributes: instanceProps.filter(({ name }) => isAttributeNameSafe(name)),- direction: "instance-to-jsx",- componentPropNames,- acceptsHtmlAttributes,- }).map(({ id, name }) => [id, name])- );+ // Older projects can contain duplicate props or both standard and React+ // aliases. Keep the last prop for each generated JSX name. Class aliases are+ // composable, so keep the last value for each alias and merge them below.+ const propsByGeneratedName = new Map<string, Prop>();+ const classProps = new Map<string, Prop>();+ for (const prop of props.values()) {+ if (+ prop.instanceId !== instance.id ||+ isAttributeNameSafe(prop.name) === false+ ) {+ continue;+ }+ const name = getGeneratedPropName(prop.name);+ if (name === "className") {+ classProps.set(prop.name, prop);+ continue;+ }+ propsByGeneratedName.set(name, prop);+ }+ const generatedPropNames = new Set([+ ...propsByGeneratedName.keys(),+ ...(classProps.size > 0 ? ["className"] : []),+ ]);- for (const prop of instanceProps) {+ for (const [name, prop] of [+ ...propsByGeneratedName,+ ...Array.from(classProps.values(), (prop) => ["className", prop] as const),+ ]) {const propValue = generatePropValue({scope,prop,@@ -256,27 +258,22 @@ export const generateJsxElement = ({usedDataSources,});- if (isAttributeNameSafe(prop.name) === false) {- continue;- }-if (prop.type === "resource") {const propMeta = meta?.props?.[prop.name];const resource = resources?.get(prop.value);if (propMeta?.type === "resource" && resource !== undefined) {- for (const name of propMeta.generatedProps ?? []) {+ for (const propName of propMeta.generatedProps ?? []) {+ const generatedPropName = getGeneratedPropName(propName);if (- instancePropNames.has(name) === false &&- isAttributeNameSafe(name)+ generatedPropNames.has(generatedPropName) === false &&+ isAttributeNameSafe(propName)) {- projectedResourceProps.set(name, resource[name]);+ projectedResourceProps.set(generatedPropName, resource[propName]);}}}}- const name = generatedPropNames.get(prop.id) ?? prop.name;-// show prop controls conditional rendering and need to be handled separatelyif (prop.name === showAttribute) {// prevent generating unnecessary condition@@ -306,7 +303,7 @@ export const generateJsxElement = ({// Merge atomic classes with the JSX className produced by the shared// instance-to-JSX property adapter.if (name === "className" && propValue !== undefined) {- classNameValue = propValue;+ classNameValues.push(propValue);continue;}if (propValue !== undefined) {@@ -314,15 +311,14 @@ export const generateJsxElement = ({}}- for (const [propName, value] of projectedResourceProps) {- const name = getGeneratedPropName(propName);+ for (const [name, value] of projectedResourceProps) {generatedProps += `\n${name}={${JSON.stringify(value)}}`;}const classMapArray = classesMap?.get(instance.id);- if (classMapArray || classNameValue) {+ if (classMapArray || classNameValues.length > 0) {let classNameTemplate = classMapArray ? classMapArray.join(" ") : "";- if (classNameValue) {+ for (const classNameValue of classNameValues) {if (classNameTemplate) {classNameTemplate += " ";}