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.

feat: Add helper functions for Tailwind support: shorthand expansion and variable substitution (#2371)

Ivan Starkov333f167c481a
diff --git a/packages/css-data/LICENSE-3RD-PARTY b/packages/css-data/LICENSE-3RD-PARTY
new file mode 100644
index 0000000000..b62fd2e3e9
--- /dev/null
+++ b/packages/css-data/LICENSE-3RD-PARTY
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) 2021 Dany Castillo
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/packages/css-data/bin/property-value-descriptions.ts b/packages/css-data/bin/property-value-descriptions.ts
index e7456d0146..4c03e2fafd 100755
--- a/packages/css-data/bin/property-value-descriptions.ts
+++ b/packages/css-data/bin/property-value-descriptions.ts
@@ -127,7 +127,7 @@ for (let i = 0; i < newPropertiesNames.length; ) {
}
properties.forEach((name, index) => {
- propertiesGenerated[name] = descriptions[index]
+ propertiesGenerated[name] = (descriptions[index] ?? "")
.replace(new RegExp(`^\`?${name}\`?:`), "")
.trim();
});
@@ -251,7 +251,7 @@ for (let i = 0; i < newDeclarationsDescriptionsEntries.length; ) {
batch.forEach((value, index) => {
const [descriptionKey, decl] = value;
- const description = descriptions[index]
+ const description = (descriptions[index] ?? "")
.replace(new RegExp(`^\`${decl}\` -`), "")
.trim();
if (descriptionKey.endsWith(":{color}")) {
@@ -341,7 +341,7 @@ async function generate(message: string): Promise<string | [number, string]> {
const completion = (await response.json()) as CreateChatCompletionResponse;
- const content = completion.choices[0].message?.content.trim() || "";
+ const content = completion.choices[0]?.message?.content.trim() || "";
if (content === "") {
return [404, "No response"];
diff --git a/packages/css-data/src/parse-css-value.ts b/packages/css-data/src/parse-css-value.ts
index e2803d4969..fb7cc7a9de 100644
--- a/packages/css-data/src/parse-css-value.ts
+++ b/packages/css-data/src/parse-css-value.ts
@@ -129,7 +129,7 @@ export const parseCssValue = (
if (index > -1) {
return {
type: "keyword",
- value: values[index],
+ value: values[index]!,
};
}
}
diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.ts
index a748396f4f..32b2a1c02e 100644
--- a/packages/css-data/src/parse-css.test.ts
+++ b/packages/css-data/src/parse-css.test.ts
@@ -55,7 +55,7 @@ describe("Parse CSS", () => {
});
test("parses unsupported shorthand values", () => {
- expect(parseCss(`.test { padding: 4px }`).test[0]).toMatchInlineSnapshot(`
+ expect(parseCss(`.test { padding: 4px }`).test?.[0]).toMatchInlineSnapshot(`
{
"property": "padding",
"value": {
diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.ts
index 5d318e3d45..e54c6a4e0f 100644
--- a/packages/css-data/src/parse-css.ts
+++ b/packages/css-data/src/parse-css.ts
@@ -108,8 +108,9 @@ export const parseCss = function cssToWS(css: string) {
try {
StyleValue.parse(value);
selectors.forEach((selector) => {
- if (Array.isArray(styles[selector])) {
- styles[selector].push({
+ const selectors = styles[selector];
+ if (Array.isArray(selectors)) {
+ selectors.push({
property,
value,
});
diff --git a/packages/css-data/src/property-parsers/box-shadow.ts b/packages/css-data/src/property-parsers/box-shadow.ts
index 97931b0a43..e80a4b8da3 100644
--- a/packages/css-data/src/property-parsers/box-shadow.ts
+++ b/packages/css-data/src/property-parsers/box-shadow.ts
@@ -74,6 +74,10 @@ export const parseBoxShadow = (
for (let index = 0; index < layer.length; index++) {
const item = layer[index];
+ if (item === undefined) {
+ throw new Error(`Layer at index ${index} is undefined`);
+ }
+
if (item.type === "Identifier") {
shadow.push({
type: "keyword",
diff --git a/packages/css-data/src/tailwind-parser/shorthand.test.ts b/packages/css-data/src/tailwind-parser/shorthand.test.ts
new file mode 100644
index 0000000000..6aa611e24c
--- /dev/null
+++ b/packages/css-data/src/tailwind-parser/shorthand.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from "@jest/globals";
+import { expandTailwindShorthand } from "./shorthand"; // Import the function
+
+describe("expandTailwindShorthand", () => {
+ test("expand mx-4 to mr-4 ml-4", () => {
+ expect(expandTailwindShorthand("mx-4")).toBe("mr-4 ml-4");
+ });
+
+ test("expand flex-initial to grow-0 shrink basis-auto", () => {
+ expect(expandTailwindShorthand("flex-initial")).toBe(
+ "grow-0 shrink basis-auto"
+ );
+ });
+
+ test("return the original class if not a shorthand", () => {
+ expect(expandTailwindShorthand("bg-red-500")).toBe("bg-red-500");
+ });
+
+ test("handle classes without a modifier", () => {
+ expect(expandTailwindShorthand("none")).toBe("grow-0 shrink-0 basis-auto");
+ });
+
+ test("handle dynamic values", () => {
+ expect(expandTailwindShorthand("flex-1")).toBe("grow shrink basis-[0%]");
+ });
+
+ test("expand inset-x-4 to right-4 left-4", () => {
+ expect(expandTailwindShorthand("inset-x-4")).toBe("right-4 left-4");
+ });
+});
diff --git a/packages/css-data/src/tailwind-parser/shorthand.ts b/packages/css-data/src/tailwind-parser/shorthand.ts
new file mode 100644
index 0000000000..0475c8d518
--- /dev/null
+++ b/packages/css-data/src/tailwind-parser/shorthand.ts
@@ -0,0 +1,78 @@
+export const expandShorthand = (property: string) => {};
+
+/**
+ * Expands shorthand CSS properties into their long-form equivalents.
+ * For example, 'mx' is expanded to 'mr' (margin-right) and 'ml' (margin-left).
+ **/
+export const expandTailwindShorthand = (classname: string) => {
+ let expanded = conflictingClassGroups[classname];
+
+ if (expanded) {
+ return expanded.join(" ");
+ }
+
+ const parts = classname.split("-");
+ const modifier = parts.pop();
+ const base = parts.join("-");
+
+ expanded = conflictingClassGroups[base];
+
+ if (expanded) {
+ return expanded.map((cls) => `${cls}-${modifier}`).join(" ");
+ }
+
+ return classname;
+};
+
+/**
+ * A little bit changed tailwind-merge
+ * conflictingClassGroups https://github.com/dcastil/tailwind-merge/blob/fb1fc1f9d106f2184e24949e6e6d1a67904706fa/src/lib/default-config.ts#L1716
+ *
+ * Attributions
+ * MIT License
+ * Copyright (c) 2021 Dany Castillo
+ **/
+const conflictingClassGroups: Record<string, string[]> = {
+ overflow: ["overflow-x", "overflow-y"],
+ overscroll: ["overscroll-x", "overscroll-y"],
+ inset: ["top", "right", "bottom", "left"],
+ "inset-x": ["right", "left"],
+ "inset-y": ["top", "bottom"],
+
+ "flex-initial": ["grow-0", "shrink", "basis-auto"], // 0 1 auto
+ "flex-auto": ["grow", "shrink", "basis-auto"], // 1 1 auto
+ none: ["grow-0", "shrink-0", "basis-auto"], // 0 0 auto,
+ "flex-1": ["grow", "shrink", "basis-[0%]"], // 1 1 0%,
+
+ gap: ["gap-x", "gap-y"],
+
+ p: ["pt", "pr", "pb", "pl"],
+ px: ["pr", "pl"],
+ py: ["pt", "pb"],
+ m: ["mt", "mr", "mb", "ml"],
+ mx: ["mr", "ml"],
+ my: ["mt", "mb"],
+
+ rounded: ["rounded-tl", "rounded-tr", "rounded-br", "rounded-bl"],
+ "rounded-t": ["rounded-tl", "rounded-tr"],
+ "rounded-r": ["rounded-tr", "rounded-br"],
+ "rounded-b": ["rounded-br", "rounded-bl"],
+ "rounded-l": ["rounded-tl", "rounded-bl"],
+
+ "border-spacing": ["border-spacing-x", "border-spacing-y"],
+
+ "border-w": ["border-w-t", "border-w-r", "border-w-b", "border-w-l"],
+ "border-w-x": ["border-w-r", "border-w-l"],
+ "border-w-y": ["border-w-t", "border-w-b"],
+ /*
+ We are supporting shorthand for border-color
+ "border-color": [
+ "border-color-t",
+ "border-color-r",
+ "border-color-b",
+ "border-color-l",
+ ],
+ "border-color-x": ["border-color-r", "border-color-l"],
+ "border-color-y": ["border-color-t", "border-color-b"],
+ */
+};
diff --git a/packages/css-data/src/tailwind-parser/substitute.test.ts b/packages/css-data/src/tailwind-parser/substitute.test.ts
new file mode 100644
index 0000000000..929672d322
--- /dev/null
+++ b/packages/css-data/src/tailwind-parser/substitute.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, test, jest } from "@jest/globals";
+
+import { substituteVariables } from "./substitute"; // Import the function
+
+const cssPreflight = `
+*,
+::before,
+::after {
+ --var-a: rgba(111, 111, 111, 0.5);
+ --var-b: rgba(222, 222, 222, 0.5);
+}
+`;
+
+describe("expandTailwindShorthand", () => {
+ test("resolve simple variable", () => {
+ const css = `
+ ${cssPreflight}
+ .class {
+ color: var(--var-a);
+ }
+ `;
+
+ expect(substituteVariables(css)).toMatchInlineSnapshot(
+ `".class{color:rgba(111,111,111,0.5)}"`
+ );
+ });
+
+ test("substitute latest defined variable value", () => {
+ const css = `
+ ${cssPreflight}
+ .class {
+ color: var(--var-a);
+ }
+ .vars {
+ --var-a: rgba(222, 222, 222, 1);
+ }
+ `;
+
+ expect(substituteVariables(css)).toMatchInlineSnapshot(
+ `".class{color:rgba(222,222,222,1)}"`
+ );
+ });
+
+ test("support variable fallback", () => {
+ const css = `
+ ${cssPreflight}
+ .class {
+ color: var(--var-not-exists, rgba(123, 123, 123, 0.1));
+ }
+ `;
+
+ expect(substituteVariables(css)).toMatchInlineSnapshot(
+ `".class{color:rgba(123,123,123,0.1)}"`
+ );
+ });
+
+ test("resolve variables inside functions", () => {
+ const css = `
+ ${cssPreflight}
+ .class {
+ background: linear-gradient(var(--var-a), var(--var-b));
+ }
+ `;
+ expect(substituteVariables(css)).toMatchInlineSnapshot(
+ `".class{background:linear-gradient(rgba(111,111,111,0.5),rgba(222,222,222,0.5))}"`
+ );
+ });
+
+ test("resolve nested dependencies", () => {
+ const css = `
+ ${cssPreflight}
+ .class {
+ --var-c: var(--var-a), var(--var-b);
+ background: linear-gradient(var(--var-c));
+ }
+ `;
+ expect(substituteVariables(css)).toMatchInlineSnapshot(
+ `".class{background:linear-gradient(rgba(111,111,111,0.5),rgba(222,222,222,0.5))}"`
+ );
+ });
+
+ test("warn if variable is not defined and omits property and empty selectors", () => {
+ const css = `
+ ${cssPreflight}
+ .class {
+ --var-c: var(--var-not-existed), var(--var-b);
+ background: linear-gradient(var(--var-c));
+ }
+ `;
+ const warn = jest.fn();
+
+ expect(substituteVariables(css, warn)).toMatchInlineSnapshot(`""`);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledWith(
+ true,
+ 'Variable var(--var-not-existed) cannot be resolved for property "background:linear-gradient(var(--var-not-existed),rgba(222,222,222,0.5))" in selector ".class"'
+ );
+ });
+
+ test("work with media queries", () => {
+ const css = `
+ ${cssPreflight}
+ @media (min-width: 640px) {
+ .sm\\:shadow-md {
+ --var-c: var(--var-a), var(--var-b);
+ background: linear-gradient(var(--var-c));
+ }
+ `;
+ expect(substituteVariables(css)).toMatchInlineSnapshot(
+ `"@media (min-width:640px){.sm\\:shadow-md{background:linear-gradient(rgba(111,111,111,0.5),rgba(222,222,222,0.5))}}"`
+ );
+ });
+
+ test("don't respect non * and class selectors i.e. ::backdrop", () => {
+ const css = `
+ ${cssPreflight}
+ ::backdrop {
+ --var-a: rgba(2, 2, 2, 0.5);
+ }
+ .class {
+ color: var(--var-a);
+ }
+ `;
+
+ expect(substituteVariables(css)).toMatchInlineSnapshot(
+ `".class{color:rgba(111,111,111,0.5)}"`
+ );
+ });
+});
diff --git a/packages/css-data/src/tailwind-parser/substitute.ts b/packages/css-data/src/tailwind-parser/substitute.ts
new file mode 100644
index 0000000000..d7e4bae2b9
--- /dev/null
+++ b/packages/css-data/src/tailwind-parser/substitute.ts
@@ -0,0 +1,157 @@
+import * as csstree from "css-tree";
+import warnOnce from "warn-once";
+
+/**
+ * Resolves CSS variables by replacing their references with actual values.
+ * Transforms `.class { --property: 1px; margin: var(--property); }` into `.class { margin: 1px; }`.
+ **/
+export const substituteVariables = (css: string, warn = warnOnce) => {
+ const ast = csstree.parse(css);
+
+ // Cleanup
+ csstree.walk(ast, {
+ enter(node, item, list) {
+ // Remove selectors not startings with * or .
+ if (node.type === "Rule") {
+ const selectors = csstree.generate(node.prelude);
+ if (
+ selectors.startsWith("*") === false &&
+ selectors.startsWith(".") === false
+ ) {
+ list.remove(item);
+ }
+ }
+ },
+ });
+
+ const rawProperties: Record<string, string> = {};
+
+ // Extract all variables and remove them
+ csstree.walk(ast, {
+ enter: (node, item, list) => {
+ if (node.type === "Declaration" && node.property.startsWith("--")) {
+ const propertyName = node.property.trim();
+ const propertValue = csstree.generate(node.value);
+ rawProperties[propertyName] = propertValue;
+ list.remove(item);
+ }
+ },
+ });
+
+ /**
+ * Iteratively resolve CSS variables within custom properties.
+ * Custom properties treat variables as strings, making direct resolution impossible.
+ * We perform multiple iterations to substitute these variables with their actual values.
+ *
+ * Example:
+ * Initial: .class { --var: var(--margin-y) var(--margin-x); margin: var(--var); }
+ * Iteration 1: .class { margin: var(--margin-y) var(--margin-x); }
+ * Iteration 2: .class { margin: 1px 2px; }
+ */
+ const MAX_NESTED_DEPENDENCIES_DEPTH = 5;
+ for (let depth = 0; depth !== MAX_NESTED_DEPENDENCIES_DEPTH; ++depth) {
+ csstree.walk(ast, {
+ enter: (node, item, list) => {
+ if (node.type === "Function") {
+ const functionName = node.name;
+ if (functionName !== "var") {
+ return;
+ }
+
+ const firstArgument = node.children.first;
+
+ if (firstArgument === null) {
+ throw new Error("Should never happen");
+ }
+
+ const propertyName = csstree.generate(firstArgument).trim();
+ const propertyValue = rawProperties[propertyName];
+ const fallbackArg =
+ node.children.last === node.children.first
+ ? null
+ : node.children.last;
+
+ const fallback =
+ fallbackArg !== null ? csstree.generate(fallbackArg).trim() : null;
+
+ if (propertyValue) {
+ const astVariable = csstree.parse(propertyValue, {
+ context: "value",
+ });
+
+ if ("children" in astVariable && astVariable.children !== null) {
+ list.replace(item, astVariable.children);
+ return;
+ }
+ }
+
+ if (fallback) {
+ const astVariable = csstree.parse(fallback, {
+ context: "value",
+ });
+
+ if ("children" in astVariable && astVariable.children !== null) {
+ list.replace(item, astVariable.children);
+ return;
+ }
+ }
+ }
+ },
+ });
+ }
+
+ let lastKnownRule: csstree.Rule | undefined = undefined;
+
+ csstree.walk(ast, {
+ enter: (node, item, list) => {
+ if (node.type === "Rule") {
+ lastKnownRule = node;
+ }
+
+ if (node.type === "Declaration") {
+ let hasVariables = false;
+ csstree.walk(node.value, {
+ enter: (childNode) => {
+ if (childNode.type === "Function") {
+ const funcName = childNode.name;
+
+ if (funcName === "var") {
+ warn(
+ true,
+ `Variable ${csstree.generate(
+ childNode
+ )} cannot be resolved for property "${csstree.generate(
+ node
+ )}" in selector "${
+ lastKnownRule !== undefined
+ ? csstree.generate(lastKnownRule.prelude)
+ : "unknown"
+ }"`
+ );
+ hasVariables = true;
+ }
+ }
+ },
+ });
+
+ if (hasVariables) {
+ // Remove declaration if it still contains variables
+ list.remove(item);
+ }
+ }
+ },
+ });
+
+ // Cleanup empty rules
+ csstree.walk(ast, {
+ enter: (node, item, list) => {
+ if (node.type === "Rule") {
+ if (node.block.children.isEmpty) {
+ list.remove(item);
+ }
+ }
+ },
+ });
+
+ return csstree.generate(ast);
+};
diff --git a/packages/css-data/tsconfig.json b/packages/css-data/tsconfig.json
index d2e5040f8f..7d0603b2c2 100644
--- a/packages/css-data/tsconfig.json
+++ b/packages/css-data/tsconfig.json
@@ -1,3 +1,6 @@
{
- "extends": "@webstudio-is/tsconfig/base.json"
+ "extends": "@webstudio-is/tsconfig/base.json",
+ "compilerOptions": {
+ "noUncheckedIndexedAccess": true
+ }
}
diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.ts
index f9233a9225..222aae980c 100644
--- a/packages/css-engine/src/core/to-value.ts
+++ b/packages/css-engine/src/core/to-value.ts
@@ -7,7 +7,8 @@ export type TransformValue = (styleValue: StyleValue) => undefined | StyleValue;
const fallbackTransform: TransformValue = (styleValue) => {
if (styleValue.type === "fontFamily") {
const firstFontFamily = styleValue.value[0];
- const fallbacks = SYSTEM_FONTS.get(firstFontFamily);
+
+ const fallbacks = SYSTEM_FONTS.get(firstFontFamily ?? "Arial");
const fontFamily: string[] = [...styleValue.value];
if (Array.isArray(fallbacks)) {
fontFamily.push(...fallbacks);