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.

refactor: render html attributes for all components (#5163)

Bogdan Chadkin6fa88d9711e4
diff --git a/apps/builder/app/builder/features/ai/ai-fetch-result.ts b/apps/builder/app/builder/features/ai/ai-fetch-result.ts
index d91ee8c188..faa8772efa 100644
--- a/apps/builder/app/builder/features/ai/ai-fetch-result.ts
+++ b/apps/builder/app/builder/features/ai/ai-fetch-result.ts
@@ -285,6 +285,7 @@ const $jsx = computed(
const jsx = generateJsxElement({
scope,
+ metas,
instance,
props,
dataSources,
@@ -292,6 +293,7 @@ const $jsx = computed(
indexesWithinAncestors,
children: generateJsxChildren({
scope,
+ metas,
children: instance.children,
instances,
props,
diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
index cabd0ab5a6..c9efa87e37 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -36,6 +36,7 @@ import {
selectorIdAttribute,
type AnyComponent,
textContentAttribute,
+ standardAttributesToReactProps,
} from "@webstudio-is/react-sdk";
import { rawTheme } from "@webstudio-is/design-system";
import {
@@ -285,13 +286,23 @@ const useInstanceProps = (instanceSelector: InstanceSelector) => {
$propValuesByInstanceSelectorWithMemoryProps,
$instances,
$indexesWithinAncestors,
+ $registeredComponentMetas,
],
- (propValuesByInstanceSelector, instances, indexesWithinAncestors) => {
+ (
+ propValuesByInstanceSelector,
+ instances,
+ indexesWithinAncestors,
+ metas
+ ) => {
const instancePropsObject: Record<Prop["name"], unknown> = {};
- const tag = instances.get(instanceId)?.tag;
+ const instance = instances.get(instanceId);
+ const tag = instance?.tag;
if (tag !== undefined) {
instancePropsObject[tagProperty] = tag;
}
+ const hasTags =
+ Object.keys(metas.get(instance?.component ?? "")?.presetStyle ?? {})
+ .length > 0;
const index = indexesWithinAncestors.get(instanceId);
if (index !== undefined) {
instancePropsObject[indexProperty] = index.toString();
@@ -299,7 +310,12 @@ const useInstanceProps = (instanceSelector: InstanceSelector) => {
const instanceProps = propValuesByInstanceSelector.get(instanceKey);
if (instanceProps) {
for (const [name, value] of instanceProps) {
- instancePropsObject[name] = value;
+ if (hasTags) {
+ const reactName = standardAttributesToReactProps[name] ?? name;
+ instancePropsObject[reactName] = value;
+ } else {
+ instancePropsObject[name] = value;
+ }
}
}
return instancePropsObject;
diff --git a/packages/html-data/bin/aria.ts b/packages/html-data/bin/aria.ts
index 82bd8c8f85..69086723cd 100644
--- a/packages/html-data/bin/aria.ts
+++ b/packages/html-data/bin/aria.ts
@@ -1,11 +1,4 @@
import { aria } from "aria-query";
-import {
- findTags,
- getAttr,
- getTextContent,
- loadPage,
- parseHtml,
-} from "./crawler";
import { mkdir, writeFile } from "node:fs/promises";
import {
createScope,
@@ -16,6 +9,13 @@ import {
type Props,
} from "@webstudio-is/sdk";
import { generateWebstudioComponent } from "@webstudio-is/react-sdk";
+import {
+ findTags,
+ getAttr,
+ getTextContent,
+ loadPage,
+ parseHtml,
+} from "./crawler";
type Attribute = {
name: string;
@@ -45,7 +45,14 @@ for (let index = 0; index < terms.length; index += 1) {
descriptions.set(term, detail);
}
-const attributes: Attribute[] = [];
+const attributes: Attribute[] = [
+ {
+ name: "role",
+ description:
+ "Defines an explicit role for an element for use by assistive technologies.",
+ type: "string",
+ },
+];
for (const [name, meta] of aria.entries()) {
const attribute: Attribute = {
name,
diff --git a/packages/html-data/bin/attributes.ts b/packages/html-data/bin/attributes.ts
index 6564f6d89d..0affab6984 100644
--- a/packages/html-data/bin/attributes.ts
+++ b/packages/html-data/bin/attributes.ts
@@ -15,6 +15,9 @@ import {
loadHtmlIndices,
parseHtml,
} from "./crawler";
+import { possibleStandardNames } from "./possible-standard-names";
+
+const validHtmlAttributes = new Set<string>();
type Attribute = {
name: string;
@@ -110,6 +113,7 @@ for (const row of rows) {
) {
type = "number";
}
+ validHtmlAttributes.add(attribute);
for (let tag of tags) {
tag = tag.toLowerCase().trim();
if (/custom elements/i.test(tag)) {
@@ -251,3 +255,29 @@ await writeFile(
metas: new Map(),
}) + "export { Page }"
);
+
+// react does not have this one
+possibleStandardNames["dirname"] = "dirName";
+const standardAttributesToReactProps: Record<string, string> = {};
+const reactPropsToStandardAttributes: Record<string, string> = {};
+for (const [htmlAttribute, reactProperty] of Object.entries(
+ possibleStandardNames
+)) {
+ if (
+ validHtmlAttributes.has(htmlAttribute) &&
+ htmlAttribute !== reactProperty
+ ) {
+ standardAttributesToReactProps[htmlAttribute] = reactProperty;
+ reactPropsToStandardAttributes[reactProperty] = htmlAttribute;
+ }
+}
+
+let standardAttributesContent = "";
+standardAttributesContent += `export const standardAttributesToReactProps: Record<string, string> = ${JSON.stringify(standardAttributesToReactProps, null, 2)};\n\n`;
+standardAttributesContent += `export const reactPropsToStandardAttributes: Record<string, string> = ${JSON.stringify(reactPropsToStandardAttributes, null, 2)};\n`;
+
+await mkdir("../react-sdk/src/__generated__", { recursive: true });
+await writeFile(
+ "../react-sdk/src/__generated__/standard-attributes.ts",
+ standardAttributesContent
+);
diff --git a/packages/react-sdk/src/standard-attributes.ts b/packages/html-data/bin/possible-standard-names.ts
similarity index 98%
rename from packages/react-sdk/src/standard-attributes.ts
rename to packages/html-data/bin/possible-standard-names.ts
index efe8a347b9..2ca71a7b74 100644
--- a/packages/react-sdk/src/standard-attributes.ts
+++ b/packages/html-data/bin/possible-standard-names.ts
@@ -5,12 +5,10 @@
* LICENSE file in the root directory of this source tree.
*/
-// https://github.com/facebook/react/blob/6377903074d4b3a2de48c4da91783a5af9fc5237/packages/react-dom-bindings/src/shared/possibleStandardNames.js
-
// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
-export const standardAttributesToReactProps: Record<string, string> = {
+export const possibleStandardNames: Record<string, string> = {
// HTML
accept: "accept",
acceptcharset: "acceptCharset",
@@ -506,6 +504,4 @@ export const standardAttributesToReactProps: Record<string, string> = {
ychannelselector: "yChannelSelector",
z: "z",
zoomandpan: "zoomAndPan",
- // added by us
- dirname: "dirName",
};
diff --git a/packages/html-data/package.json b/packages/html-data/package.json
index daf0cd31d6..54bfef5234 100644
--- a/packages/html-data/package.json
+++ b/packages/html-data/package.json
@@ -8,7 +8,7 @@
"scripts": {
"typecheck": "tsc",
"build:elements": "tsx --conditions=webstudio ./bin/elements.ts && prettier --write ./src/__generated__",
- "build:attributes": "tsx --conditions=webstudio ./bin/attributes.ts && prettier --write ./src/__generated__",
+ "build:attributes": "tsx --conditions=webstudio ./bin/attributes.ts && prettier --write ./src/__generated__ ../react-sdk/src/__generated__",
"build:aria": "tsx --conditions=webstudio ./bin/aria.ts && prettier --write ./src/__generated__"
},
"devDependencies": {
diff --git a/packages/html-data/src/__generated__/aria-jsx-test.tsx b/packages/html-data/src/__generated__/aria-jsx-test.tsx
index 533c78d065..a2a1f7aa81 100644
--- a/packages/html-data/src/__generated__/aria-jsx-test.tsx
+++ b/packages/html-data/src/__generated__/aria-jsx-test.tsx
@@ -1,6 +1,7 @@
const Page = () => {
return (
<div
+ role={""}
aria-activedescendant={""}
aria-atomic={true}
aria-autocomplete={"inline"}
diff --git a/packages/html-data/src/__generated__/aria.ts b/packages/html-data/src/__generated__/aria.ts
index 983aadfdb7..a940a38b17 100644
--- a/packages/html-data/src/__generated__/aria.ts
+++ b/packages/html-data/src/__generated__/aria.ts
@@ -6,6 +6,12 @@ type Attribute = {
};
export const ariaAttributes: Attribute[] = [
+ {
+ name: "role",
+ description:
+ "Defines an explicit role for an element for use by assistive technologies.",
+ type: "string",
+ },
{
name: "aria-activedescendant",
description:
diff --git a/packages/react-sdk/src/__generated__/standard-attributes.ts b/packages/react-sdk/src/__generated__/standard-attributes.ts
new file mode 100644
index 0000000000..bae2c1e79c
--- /dev/null
+++ b/packages/react-sdk/src/__generated__/standard-attributes.ts
@@ -0,0 +1,105 @@
+export const standardAttributesToReactProps: Record<string, string> = {
+ "accept-charset": "acceptCharset",
+ accesskey: "accessKey",
+ allowfullscreen: "allowFullScreen",
+ autocapitalize: "autoCapitalize",
+ autocomplete: "autoComplete",
+ autocorrect: "autoCorrect",
+ autofocus: "autoFocus",
+ autoplay: "autoPlay",
+ charset: "charSet",
+ class: "className",
+ colspan: "colSpan",
+ contenteditable: "contentEditable",
+ crossorigin: "crossOrigin",
+ datetime: "dateTime",
+ enctype: "encType",
+ enterkeyhint: "enterKeyHint",
+ fetchpriority: "fetchPriority",
+ for: "htmlFor",
+ formmethod: "formMethod",
+ formaction: "formAction",
+ formenctype: "formEncType",
+ formnovalidate: "formNoValidate",
+ formtarget: "formTarget",
+ hreflang: "hrefLang",
+ "http-equiv": "httpEquiv",
+ imagesizes: "imageSizes",
+ imagesrcset: "imageSrcSet",
+ inputmode: "inputMode",
+ itemid: "itemID",
+ itemprop: "itemProp",
+ itemref: "itemRef",
+ itemscope: "itemScope",
+ itemtype: "itemType",
+ maxlength: "maxLength",
+ minlength: "minLength",
+ nomodule: "noModule",
+ novalidate: "noValidate",
+ playsinline: "playsInline",
+ readonly: "readOnly",
+ referrerpolicy: "referrerPolicy",
+ rowspan: "rowSpan",
+ spellcheck: "spellCheck",
+ srcdoc: "srcDoc",
+ srclang: "srcLang",
+ srcset: "srcSet",
+ tabindex: "tabIndex",
+ usemap: "useMap",
+ popovertarget: "popoverTarget",
+ popovertargetaction: "popoverTargetAction",
+ dirname: "dirName",
+};
+
+export const reactPropsToStandardAttributes: Record<string, string> = {
+ acceptCharset: "accept-charset",
+ accessKey: "accesskey",
+ allowFullScreen: "allowfullscreen",
+ autoCapitalize: "autocapitalize",
+ autoComplete: "autocomplete",
+ autoCorrect: "autocorrect",
+ autoFocus: "autofocus",
+ autoPlay: "autoplay",
+ charSet: "charset",
+ className: "class",
+ colSpan: "colspan",
+ contentEditable: "contenteditable",
+ crossOrigin: "crossorigin",
+ dateTime: "datetime",
+ encType: "enctype",
+ enterKeyHint: "enterkeyhint",
+ fetchPriority: "fetchpriority",
+ htmlFor: "for",
+ formMethod: "formmethod",
+ formAction: "formaction",
+ formEncType: "formenctype",
+ formNoValidate: "formnovalidate",
+ formTarget: "formtarget",
+ hrefLang: "hreflang",
+ httpEquiv: "http-equiv",
+ imageSizes: "imagesizes",
+ imageSrcSet: "imagesrcset",
+ inputMode: "inputmode",
+ itemID: "itemid",
+ itemProp: "itemprop",
+ itemRef: "itemref",
+ itemScope: "itemscope",
+ itemType: "itemtype",
+ maxLength: "maxlength",
+ minLength: "minlength",
+ noModule: "nomodule",
+ noValidate: "novalidate",
+ playsInline: "playsinline",
+ readOnly: "readonly",
+ referrerPolicy: "referrerpolicy",
+ rowSpan: "rowspan",
+ spellCheck: "spellcheck",
+ srcDoc: "srcdoc",
+ srcLang: "srclang",
+ srcSet: "srcset",
+ tabIndex: "tabindex",
+ useMap: "usemap",
+ popoverTarget: "popovertarget",
+ popoverTargetAction: "popovertargetaction",
+ dirName: "dirname",
+};
diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsx
index 1c49919284..677bd100f7 100644
--- a/packages/react-sdk/src/component-generator.test.tsx
+++ b/packages/react-sdk/src/component-generator.test.tsx
@@ -83,6 +83,7 @@ test("generate jsx element with children and without them", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "body" }],
...renderData(<$.Body ws:id="body">Children</$.Body>),
})
@@ -100,6 +101,7 @@ test("generate jsx element with children and without them", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "image" }],
...renderData(<$.Image ws:id="image"></$.Image>),
})
@@ -119,6 +121,7 @@ test("generate jsx element with namespaces components", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "body" }],
...renderData(<library.Body ws:id="body"></library.Body>),
})
@@ -134,6 +137,7 @@ test("generate jsx element with namespaces components", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "image" }],
...renderData(<library.Image ws:id="image"></library.Image>),
})
@@ -152,6 +156,7 @@ test("generate jsx element with literal props", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "body" }],
...renderData(<$.Body ws:id="body" string="string" number={0}></$.Body>),
})
@@ -169,6 +174,7 @@ test("generate jsx element with literal props", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "image" }],
...renderData(
<$.Image
@@ -195,6 +201,7 @@ test("ignore asset and page props", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "box" }],
...renderData(
<$.Box
@@ -220,6 +227,7 @@ test("generate jsx element with data sources and action", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "box" }],
...renderData(
<$.Box
@@ -251,6 +259,7 @@ test("generate jsx element with condition based on show prop", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "box" }],
...renderData(<$.Box ws:id="box" data-ws-show={true}></$.Box>),
})
@@ -266,6 +275,7 @@ test("generate jsx element with condition based on show prop", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "box" }],
...renderData(<$.Box ws:id="box" data-ws-show={false}></$.Box>),
})
@@ -276,6 +286,7 @@ test("generate jsx element with condition based on show prop", () => {
scope: createScope(),
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
+ metas: new Map(),
children: [{ type: "id", value: "box" }],
...renderData(
<$.Box ws:id="box" data-ws-show={expression`${condition}`}></$.Box>
@@ -296,6 +307,7 @@ test("generate jsx children with text", () => {
expect(
generateJsxChildren({
scope: createScope(),
+ metas: new Map(),
children: [
{ type: "text", value: "Some\ntext" },
{ type: "text", value: 'Escaped "text"' },
@@ -322,6 +334,7 @@ test("exclude text placeholders", () => {
expect(
generateJsxChildren({
scope: createScope(),
+ metas: new Map(),
children: [
{ type: "text", value: "Text" },
{ type: "text", value: "Placeholder text", placeholder: true },
@@ -346,6 +359,7 @@ test("generate jsx children with expression", () => {
expect(
generateJsxChildren({
scope: createScope(),
+ metas: new Map(),
children: [
{ type: "expression", value: "'Hello ' + $ws$dataSource$var" },
],
@@ -376,6 +390,7 @@ test("generate jsx children with nested instances", () => {
expect(
generateJsxChildren({
scope: createScope(),
+ metas: new Map(),
children: [{ type: "id", value: "form" }],
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
@@ -404,6 +419,7 @@ test("deduplicate base and namespaced components with same short name", () => {
expect(
generateJsxChildren({
scope: createScope(),
+ metas: new Map(),
children: [
{ type: "id", value: "button1" },
{ type: "id", value: "button2" },
@@ -431,6 +447,7 @@ test("generate collection component as map", () => {
expect(
generateJsxChildren({
scope: createScope(),
+ metas: new Map(),
children: [{ type: "id", value: "list" }],
usedDataSources: new Map(),
indexesWithinAncestors: new Map(),
@@ -1396,7 +1413,7 @@ test("convert attributes to react compatible when render ws:element", () => {
);
});
-test("ignore props similar to standard attributes on react components", () => {
+test("convert attributes to react compatible when render components with tags", () => {
expect(
generateWebstudioComponent({
classesMap: new Map(),
@@ -1404,7 +1421,7 @@ test("ignore props similar to standard attributes on react components", () => {
name: "Page",
rootInstanceId: "bodyId",
parameters: [],
- metas: new Map(),
+ metas: new Map([["Box", { icon: "", presetStyle: { div: [] } }]]),
...renderData(
<$.Body ws:id="bodyId">
<$.Box class="my-class" for="my-id" autocomplete="off"></$.Box>
@@ -1417,6 +1434,41 @@ test("ignore props similar to standard attributes on react components", () => {
const Page = () => {
return <Body>
<Box
+ htmlFor={"my-id"}
+ autoComplete={"off"}
+ className={\`\${"my-class"}\`} />
+ </Body>
+ }
+ `)
+ )
+ );
+});
+
+test("ignore props similar to standard attributes on react components without tags", () => {
+ expect(
+ generateWebstudioComponent({
+ classesMap: new Map(),
+ scope: createScope(),
+ name: "Page",
+ rootInstanceId: "bodyId",
+ parameters: [],
+ metas: new Map([["HeadSlot", { icon: "" }]]),
+ ...renderData(
+ <$.Body ws:id="bodyId">
+ <$.HeadSlot
+ class="my-class"
+ for="my-id"
+ autocomplete="off"
+ ></$.HeadSlot>
+ </$.Body>
+ ),
+ })
+ ).toEqual(
+ validateJSX(
+ clear(`
+ const Page = () => {
+ return <Body>
+ <HeadSlot
class={"my-class"}
for={"my-id"}
autocomplete={"off"} />
diff --git a/packages/react-sdk/src/component-generator.ts b/packages/react-sdk/src/component-generator.ts
index cc287c94d0..9462c2e1ad 100644
--- a/packages/react-sdk/src/component-generator.ts
+++ b/packages/react-sdk/src/component-generator.ts
@@ -23,7 +23,7 @@ import {
} from "@webstudio-is/sdk";
import { indexProperty, tagProperty } from "@webstudio-is/sdk/runtime";
import { isAttributeNameSafe, showAttribute } from "./props";
-import { standardAttributesToReactProps } from "./standard-attributes";
+import { standardAttributesToReactProps } from "./__generated__/standard-attributes";
/**
* (arg1) => {
@@ -144,6 +144,7 @@ const generatePropValue = ({
export const generateJsxElement = ({
context = "jsx",
scope,
+ metas,
instance,
props,
dataSources,
@@ -154,6 +155,7 @@ export const generateJsxElement = ({
}: {
context?: "expression" | "jsx";
scope: Scope;
+ metas: Map<Instance["component"], WsComponentMeta>;
instance: Instance;
props: Props;
dataSources: DataSources;
@@ -168,6 +170,9 @@ export const generateJsxElement = ({
return "";
}
+ const hasTags =
+ Object.keys(metas.get(instance.component)?.presetStyle ?? {}).length > 0;
+
let generatedProps = "";
const index = indexesWithinAncestors.get(instance.id);
@@ -199,7 +204,7 @@ export const generateJsxElement = ({
continue;
}
let name = prop.name;
- if (instance.component === elementComponent) {
+ if (instance.component === elementComponent || hasTags) {
name = standardAttributesToReactProps[prop.name] ?? prop.name;
}
@@ -327,6 +332,7 @@ export const generateJsxElement = ({
export const generateJsxChildren = ({
scope,
+ metas,
children,
instances,
props,
@@ -337,6 +343,7 @@ export const generateJsxChildren = ({
excludePlaceholders,
}: {
scope: Scope;
+ metas: Map<Instance["component"], WsComponentMeta>;
children: Instance["children"];
instances: Instances;
props: Props;
@@ -379,6 +386,7 @@ export const generateJsxChildren = ({
generatedChildren += generateJsxElement({
context: "jsx",
scope,
+ metas,
instance,
props,
dataSources,
@@ -388,6 +396,7 @@ export const generateJsxChildren = ({
children: generateJsxChildren({
classesMap,
scope,
+ metas,
children: instance.children,
instances,
props,
@@ -437,6 +446,7 @@ export const generateWebstudioComponent = ({
generatedJsx = generateJsxElement({
context: "expression",
scope,
+ metas,
instance,
props,
dataSources,
@@ -445,6 +455,7 @@ export const generateWebstudioComponent = ({
classesMap,
children: generateJsxChildren({
scope,
+ metas,
children: instance.children,
instances,
props,
diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.ts
index b3ace3ac91..3479812fba 100644
--- a/packages/react-sdk/src/index.ts
+++ b/packages/react-sdk/src/index.ts
@@ -8,3 +8,4 @@ export {
generateJsxElement,
generateJsxChildren,
} from "./component-generator";
+export * from "./__generated__/standard-attributes";