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: support custom properties (#3047)
Bogdan Chadkinbeb34382243f
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex 07f2d65b67..27bfac6be4 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -697,7 +697,8 @@ const traverseStyleValue = (value.type === "invalid" ||value.type === "unset" ||value.type === "rgb" ||- value.type === "function"+ value.type === "function" ||+ value.type === "guaranteedInvalid") {callback(value);return;diff --git a/apps/builder/app/shared/style-object-model.test.ts b/apps/builder/app/shared/style-object-model.test.tsindex f45b1b0722..19f9472208 100644--- a/apps/builder/app/shared/style-object-model.test.ts+++ b/apps/builder/app/shared/style-object-model.test.ts@@ -302,3 +302,259 @@ test("in root color property currentcolor is initial", () => {getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue).toEqual({ type: "keyword", value: "black" });});++test("support custom properties", () => {+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "--my-property",+ value: { type: "keyword", value: "blue" },+ },+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "color",+ value: { type: "var", value: "--my-property", fallbacks: [] },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ };+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "--my-property" })+ .usedValue+ ).toEqual({ type: "keyword", value: "blue" });+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue+ ).toEqual({ type: "keyword", value: "blue" });+});++test("use fallback value when custom property does not exist", () => {+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "color",+ value: {+ type: "var",+ value: "--my-property",+ fallbacks: [{ type: "keyword", value: "red" }],+ },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ };+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue+ ).toEqual({ type: "keyword", value: "red" });+});++test("use initial value when custom property does not exist", () => {+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "color",+ value: { type: "var", value: "--my-property", fallbacks: [] },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ };+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue+ ).toEqual({ type: "keyword", value: "black" });+});++test("use inherited value when custom property does not exist", () => {+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "keyword", value: "fit-content" },+ },+ {+ breakpointId: "base",+ styleSourceId: "boxLocal",+ property: "color",+ value: { type: "var", value: "--my-property", fallbacks: [] },+ },+ {+ breakpointId: "base",+ styleSourceId: "boxLocal",+ property: "width",+ value: { type: "var", value: "--my-property", fallbacks: [] },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([+ ["body", ["bodyLocal"]],+ ["box", ["boxLocal"]],+ ]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["box", "body"],+ };+ // inherited property use inherited value+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue+ ).toEqual({ type: "keyword", value: "red" });+ // not inherited property use initial value+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "width" }).usedValue+ ).toEqual({ type: "keyword", value: "auto" });+});++test("inherit custom property", () => {+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "level1Local",+ property: "--my-property",+ value: { type: "keyword", value: "blue" },+ },+ {+ breakpointId: "base",+ styleSourceId: "level3Local",+ property: "color",+ value: { type: "var", value: "--my-property", fallbacks: [] },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([+ ["level3", ["level3Local"]],+ ["level2", ["level2Local"]],+ ["level1", ["level1Local"]],+ ]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["level3", "level2", "level1"],+ };+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "--my-property" })+ .usedValue+ ).toEqual({ type: "keyword", value: "blue" });+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue+ ).toEqual({ type: "keyword", value: "blue" });+});++test("resolve dependency cycles in custom properties", () => {+ // .body { --color: red; }+ // .box { --color: var(--another); --another: var(--color); background-color: var(--color) }+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "--color",+ value: { type: "keyword", value: "red" },+ },+ {+ breakpointId: "base",+ styleSourceId: "boxLocal",+ property: "--color",+ value: { type: "var", value: "--another", fallbacks: [] },+ },+ {+ breakpointId: "base",+ styleSourceId: "boxLocal",+ property: "--another",+ value: { type: "var", value: "--color", fallbacks: [] },+ },+ {+ breakpointId: "base",+ styleSourceId: "boxLocal",+ property: "color",+ value: { type: "var", value: "--color", fallbacks: [] },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([+ ["body", ["bodyLocal"]],+ ["box", ["boxLocal"]],+ ]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["box", "body"],+ };+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue+ ).toEqual({ type: "keyword", value: "black" });+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "--color" })+ .usedValue+ ).toEqual({ type: "invalid", value: "" });+});++test("resolve non-cyclic references in custom properties", () => {+ // .body { --color: red; --another: var(--color); }+ // .box { --color: var(--another); background-color: var(--color) }+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "--color",+ value: { type: "keyword", value: "red" },+ },+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "--another",+ value: { type: "var", value: "--color", fallbacks: [] },+ },+ {+ breakpointId: "base",+ styleSourceId: "boxLocal",+ property: "--color",+ value: { type: "var", value: "--another", fallbacks: [] },+ },+ // same custom property name is defined in parent+ {+ breakpointId: "base",+ styleSourceId: "boxLocal",+ property: "color",+ value: { type: "var", value: "--color", fallbacks: [] },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([+ ["body", ["bodyLocal"]],+ ["box", ["boxLocal"]],+ ]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["box", "body"],+ };+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue+ ).toEqual({ type: "keyword", value: "red" });+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "--color" })+ .usedValue+ ).toEqual({ type: "keyword", value: "red" });+});diff --git a/apps/builder/app/shared/style-object-model.ts b/apps/builder/app/shared/style-object-model.tsindex 099036f59d..b8844ece19 100644--- a/apps/builder/app/shared/style-object-model.ts+++ b/apps/builder/app/shared/style-object-model.ts@@ -42,7 +42,7 @@ export type StyleSelector = {instanceSelector: InstanceSelector;};-type Style = Map<StyleDecl["property"], StyleDecl>;+type Style = Map<string, StyleDecl>;/*** model contains all data and cache of computed styles@@ -53,8 +53,6 @@ export type StyleObjectModel = {styleByStyleSourceId: Map<StyleSource["id"], Style>;};-type Property = keyof typeof properties;-const getCascadedValue = ({model,instanceId,@@ -62,7 +60,7 @@ const getCascadedValue = ({}: {model: StyleObjectModel;instanceId: Instance["id"];- property: Property;+ property: string;}) => {// https://drafts.csswg.org/css-cascade-5/#declaredconst declaredValues = [];@@ -85,12 +83,22 @@ const getCascadedValue = ({const matchKeyword = (styleValue: undefined | StyleValue, keyword: string) =>styleValue?.type === "keyword" && styleValue.value.toLowerCase() === keyword;+/**+ * stable invalid values to support caching+ */+const guaranteedInvalidValue: StyleValue = { type: "guaranteedInvalid" };+const invalidValue: StyleValue = { type: "invalid", value: "" };++const customPropertyData = {+ inherited: true,+ initial: guaranteedInvalidValue,+};+/*** follow value processing specification* https://drafts.csswg.org/css-cascade-5/#value-stages** @todo- * - custom property* - html* - preset* - cascaded@@ -103,29 +111,47 @@ export const getComputedStyleDecl = ({model,styleSelector,property,+ customPropertiesGraph = new Map(),}: {model: StyleObjectModel;styleSelector: StyleSelector;- property: Property;+ property: string;+ /**+ * for internal use only+ */+ customPropertiesGraph?: Map<Instance["id"], Set<string>>;}): {+ computedValue: StyleValue;usedValue: StyleValue;} => {const { instanceSelector } = styleSelector;- const propertyData = properties[property];+ const isCustomProperty = property.startsWith("--");+ const propertyData = isCustomProperty+ ? customPropertyData+ : properties[property as keyof typeof properties];const inherited = propertyData.inherited;- const initialValue = propertyData.initial;+ const initialValue: StyleValue = propertyData.initial;let computedValue: StyleValue = initialValue;// start computing from the root- for (const instanceId of Array.from(instanceSelector).reverse()) {+ for (let index = instanceSelector.length - 1; index >= 0; index -= 1) {+ const instanceId = instanceSelector[index];+ let usedCustomProperties = customPropertiesGraph.get(instanceId);+ if (usedCustomProperties === undefined) {+ usedCustomProperties = new Set();+ customPropertiesGraph.set(instanceId, usedCustomProperties);+ }+// https://drafts.csswg.org/css-cascade-5/#inheritingconst inheritedValue: StyleValue = computedValue;// https://drafts.csswg.org/css-cascade-5/#cascadedconst { cascadedValue } = getCascadedValue({ model, instanceId, property });+ // resolve specified value// https://drafts.csswg.org/css-cascade-5/#specified- let specifiedValue: StyleValue;+ let specifiedValue: StyleValue = initialValue;+// explicit defaulting// https://drafts.csswg.org/css-cascade-5/#defaulting-keywordsif (matchKeyword(cascadedValue, "initial")) {@@ -155,6 +181,41 @@ export const getComputedStyleDecl = ({// https://drafts.csswg.org/css-cascade-5/#computedcomputedValue = specifiedValue;++ if (computedValue.type === "var") {+ const customProperty = computedValue.value;+ // https://www.w3.org/TR/css-variables-1/#cycles+ if (usedCustomProperties.has(customProperty)) {+ computedValue = invalidValue;+ break;+ }+ usedCustomProperties.add(customProperty);++ const fallback = computedValue.fallbacks.at(0);+ const customPropertyValue = getComputedStyleDecl({+ model,+ styleSelector: {+ ...styleSelector,+ // resolve custom properties on instance they are defined+ // instead of where they are accessed+ instanceSelector: instanceSelector.slice(index),+ },+ property: customProperty,+ customPropertiesGraph,+ });+ computedValue = customPropertyValue.computedValue;+ // https://www.w3.org/TR/css-variables-1/#invalid-variables+ if (+ computedValue.type === "guaranteedInvalid" ||+ (isCustomProperty === false && computedValue.type === "invalid")+ ) {+ if (inherited) {+ computedValue = fallback ?? inheritedValue;+ } else {+ computedValue = fallback ?? initialValue;+ }+ }+ }}// https://drafts.csswg.org/css-cascade-5/#used@@ -169,5 +230,5 @@ export const getComputedStyleDecl = ({usedValue = currentColor.usedValue;}- return { usedValue };+ return { computedValue, usedValue };};diff --git a/packages/css-engine/src/core/to-value.test.ts b/packages/css-engine/src/core/to-value.test.tsindex 96bf6b1025..9cb7a3fb4c 100644--- a/packages/css-engine/src/core/to-value.test.ts+++ b/packages/css-engine/src/core/to-value.test.ts@@ -195,4 +195,11 @@ describe("Convert WS CSS Values to native CSS strings", () => {expect(value).toMatchInlineSnapshot(`"url("fo\\"o\\\\o.png")"`);});++ test("guaranteed-invalid", () => {+ const value = toValue({+ type: "guaranteedInvalid",+ });+ expect(value).toBe("");+ });});diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.tsindex 44c53833bb..5da38e1ad2 100644--- a/packages/css-engine/src/core/to-value.ts+++ b/packages/css-engine/src/core/to-value.ts@@ -116,5 +116,10 @@ export const toValue = (return `${value.name}(${toValue(value.args, transformValue)})`;}+ // https://www.w3.org/TR/css-variables-1/#guaranteed-invalid+ if (value.type === "guaranteedInvalid") {+ return "";+ }+return captureError(new Error("Unknown value type"), value);};diff --git a/packages/css-engine/src/schema.ts b/packages/css-engine/src/schema.tsindex d4202fe5cc..57fb769adb 100644--- a/packages/css-engine/src/schema.ts+++ b/packages/css-engine/src/schema.ts@@ -80,6 +80,13 @@ export const ImageValue = z.object({export type ImageValue = z.infer<typeof ImageValue>;+// initial value of custom properties+// https://www.w3.org/TR/css-variables-1/#guaranteed-invalid+export const GuaranteedInvalidValue = z.object({+ type: z.literal("guaranteedInvalid"),+});+export type GuaranteedInvalidValue = z.infer<typeof GuaranteedInvalidValue>;+// We want to be able to render the invalid value// and show it is invalid visually, without saving it to the dbexport const InvalidValue = z.object({@@ -142,6 +149,7 @@ const ValidStaticStyleValue = z.union([UnparsedValue,TupleValue,FunctionValue,+ GuaranteedInvalidValue,]);export type ValidStaticStyleValue = z.infer<typeof ValidStaticStyleValue>;@@ -165,7 +173,8 @@ export const isValidStaticStyleValue = (staticStyleValue.type === "rgb" ||staticStyleValue.type === "unparsed" ||staticStyleValue.type === "tuple" ||- staticStyleValue.type === "function"+ staticStyleValue.type === "function" ||+ staticStyleValue.type === "guaranteedInvalid");};