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 breakpoints and states in style object model (#3055)
Bogdan Chadkin9296cd6c1a9b
diff --git a/apps/builder/app/shared/style-object-model.test.ts b/apps/builder/app/shared/style-object-model.test.tsindex 19f9472208..c18e4b3c9a 100644--- a/apps/builder/app/shared/style-object-model.test.ts+++ b/apps/builder/app/shared/style-object-model.test.ts@@ -8,14 +8,14 @@ import {const getStyleByStyleSourceId = (styles: StyleDecl[]) => {const styleByStyleSourceId = new Map<- StyleSource["id"],- Map<StyleDecl["property"], StyleDecl>+ `${StyleSource["id"]}:${string}`,+ StyleDecl[]>();for (const styleDecl of styles) {- const styleSourceStyles =- styleByStyleSourceId.get(styleDecl.styleSourceId) ?? new Map();- styleByStyleSourceId.set(styleDecl.styleSourceId, styleSourceStyles);- styleSourceStyles.set(styleDecl.property, styleDecl);+ const key = `${styleDecl.styleSourceId}:${styleDecl.property}` as const;+ const styleSourceStyles = styleByStyleSourceId.get(key) ?? [];+ styleByStyleSourceId.set(key, styleSourceStyles);+ styleSourceStyles.push(styleDecl);}return styleByStyleSourceId;};@@ -35,6 +35,8 @@ test("use cascaded style when specified and fallback to initial value", () => {};const styleSelector: StyleSelector = {instanceSelector: ["body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};// cascaded propertyexpect(@@ -65,6 +67,8 @@ test("support initial keyword", () => {};const styleSelector: StyleSelector = {instanceSelector: ["body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "width" }).usedValue@@ -108,6 +112,8 @@ test("support inherit keyword", () => {};const styleSelector: StyleSelector = {instanceSelector: ["level3", "level2", "level1"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};// should inherit declared valueexpect(@@ -155,6 +161,8 @@ test("support unset keyword", () => {};const styleSelector: StyleSelector = {instanceSelector: ["level2", "level1"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};// when property is not inherited use initial valueexpect(@@ -191,6 +199,8 @@ test("inherit style from ancestors", () => {};const styleSelector: StyleSelector = {instanceSelector: ["level3", "level2", "level1"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};// inherited valueexpect(@@ -234,6 +244,8 @@ test("support currentcolor keyword", () => {};const styleSelector: StyleSelector = {instanceSelector: ["level2", "level1"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "borderTopColor" })@@ -276,6 +288,8 @@ test("in color property currentcolor is inherited", () => {};const styleSelector: StyleSelector = {instanceSelector: ["level3", "level2", "level1"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue@@ -297,6 +311,8 @@ test("in root color property currentcolor is initial", () => {};const styleSelector: StyleSelector = {instanceSelector: ["body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue@@ -324,6 +340,8 @@ test("support custom properties", () => {};const styleSelector: StyleSelector = {instanceSelector: ["body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "--my-property" })@@ -353,6 +371,8 @@ test("use fallback value when custom property does not exist", () => {};const styleSelector: StyleSelector = {instanceSelector: ["body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue@@ -374,6 +394,8 @@ test("use initial value when custom property does not exist", () => {};const styleSelector: StyleSelector = {instanceSelector: ["body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue@@ -416,6 +438,8 @@ test("use inherited value when custom property does not exist", () => {};const styleSelector: StyleSelector = {instanceSelector: ["box", "body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};// inherited property use inherited valueexpect(@@ -452,6 +476,8 @@ test("inherit custom property", () => {};const styleSelector: StyleSelector = {instanceSelector: ["level3", "level2", "level1"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "--my-property" })@@ -500,6 +526,8 @@ test("resolve dependency cycles in custom properties", () => {};const styleSelector: StyleSelector = {instanceSelector: ["box", "body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue@@ -549,6 +577,8 @@ test("resolve non-cyclic references in custom properties", () => {};const styleSelector: StyleSelector = {instanceSelector: ["box", "body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),};expect(getComputedStyleDecl({ model, styleSelector, property: "color" }).usedValue@@ -558,3 +588,252 @@ test("resolve non-cyclic references in custom properties", () => {.usedValue).toEqual({ type: "keyword", value: "red" });});++test("cascade value from matching breakpoints", () => {+ // @media small { body { width: 20px } }+ // @media large { body { width: 30px } }+ // @media base { body { width: 10px } }+ const styles: StyleDecl[] = [+ {+ breakpointId: "small",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 20, unit: "px" },+ },+ {+ breakpointId: "large",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 30, unit: "px" },+ },+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 10, unit: "px" },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ matchingBreakpoints: ["base", "small", "large"],+ matchingStates: new Set(),+ };+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "width" }).usedValue+ ).toEqual({ type: "unit", unit: "px", value: 30 });+});++test("ignore values from not matching breakpoints", () => {+ // @media base { body { width: 10px } }+ // @media small { body { width: 20px } }+ // @media large { body { width: 30px } }+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 10, unit: "px" },+ },+ {+ breakpointId: "small",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 20, unit: "px" },+ },+ {+ breakpointId: "large",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 30, unit: "px" },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ // large is not matching breakpoint+ matchingBreakpoints: ["base", "small"],+ matchingStates: new Set(),+ };+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "width" }).usedValue+ ).toEqual({ type: "unit", unit: "px", value: 20 });+});++test("cascade value from matching style sources", () => {+ // .bodyLocal { width: 20px }+ // .bodyToken { width: 20px }+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 20, unit: "px" },+ },+ {+ breakpointId: "base",+ styleSourceId: "bodyToken",+ property: "width",+ value: { type: "unit", value: 10, unit: "px" },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyToken", "bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set(),+ };+ // the latest token value wins+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "width" }).usedValue+ ).toEqual({ type: "unit", unit: "px", value: 20 });+});++test("cascade values with states as more specific", () => {+ // body:hover { width: 20px }+ // body { width: 10px }+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ state: ":hover",+ property: "width",+ value: { type: "unit", value: 20, unit: "px" },+ },+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 10, unit: "px" },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set([":hover"]),+ };+ // value with state wins+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "width" }).usedValue+ ).toEqual({ type: "unit", unit: "px", value: 20 });+});++test("ignore values from not matching states", () => {+ // body { width: 10px }+ // body:hover { width: 20px }+ // body:focus { width: 30px }+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 10, unit: "px" },+ },+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ state: ":hover",+ property: "width",+ value: { type: "unit", value: 20, unit: "px" },+ },+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ state: ":focus",+ property: "width",+ value: { type: "unit", value: 30, unit: "px" },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ matchingBreakpoints: ["base"],+ matchingStates: new Set([":hover"]),+ };+ // ignore :focus state because it is not matching+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "width" }).usedValue+ ).toEqual({ type: "unit", unit: "px", value: 20 });+});++test("breakpoints are more specific than style sources", () => {+ // @media small { body { width: 20px } }+ // @media base { body { width: 10px } }+ const styles: StyleDecl[] = [+ {+ breakpointId: "small",+ styleSourceId: "bodyToken",+ property: "width",+ value: { type: "unit", value: 20, unit: "px" },+ },+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 10, unit: "px" },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyToken", "bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ matchingBreakpoints: ["base", "small"],+ matchingStates: new Set(),+ };+ // bigger breakpoint on current style source should overide+ // when the next style source has the same property on smaller breakpoint+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "width" }).usedValue+ ).toEqual({ type: "unit", unit: "px", value: 20 });+});++test("states are more specific than breakpoints", () => {+ // @media base { body:hover { width: 10px } }+ // @media small { body { width: 20px } }+ const styles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "bodyLocal",+ state: ":hover",+ property: "width",+ value: { type: "unit", value: 20, unit: "px" },+ },+ {+ breakpointId: "small",+ styleSourceId: "bodyLocal",+ property: "width",+ value: { type: "unit", value: 10, unit: "px" },+ },+ ];+ const model: StyleObjectModel = {+ styleSourcesByInstanceId: new Map([["body", ["bodyLocal"]]]),+ styleByStyleSourceId: getStyleByStyleSourceId(styles),+ };+ const styleSelector: StyleSelector = {+ instanceSelector: ["body"],+ matchingBreakpoints: ["base", "small"],+ matchingStates: new Set([":hover"]),+ };+ // values with states override values without states on bigger breakpoint+ expect(+ getComputedStyleDecl({ model, styleSelector, property: "width" }).usedValue+ ).toEqual({ type: "unit", unit: "px", value: 20 });+});diff --git a/apps/builder/app/shared/style-object-model.ts b/apps/builder/app/shared/style-object-model.tsindex b8844ece19..8c55e76bd3 100644--- a/apps/builder/app/shared/style-object-model.ts+++ b/apps/builder/app/shared/style-object-model.ts@@ -1,6 +1,11 @@import { properties } from "@webstudio-is/css-data";import { StyleValue } from "@webstudio-is/css-engine";-import type { Instance, StyleDecl, StyleSource } from "@webstudio-is/sdk";+import type {+ StyleDecl,+ Breakpoint,+ Instance,+ StyleSource,+} from "@webstudio-is/sdk";/***@@ -33,6 +38,7 @@ import type { Instance, StyleDecl, StyleSource } from "@webstudio-is/sdk";*/type InstanceSelector = string[];+type Property = string;/*** style selector is a full address in a tree@@ -40,43 +46,126 @@ type InstanceSelector = string[];*/export type StyleSelector = {instanceSelector: InstanceSelector;+ /**+ * all currently matching and ordered breakpoints+ */+ matchingBreakpoints: Breakpoint["id"][];+ /**+ * all currently matching and ordered breakpoints+ */+ matchingStates: Set<string>;};-type Style = Map<string, StyleDecl>;-/*** model contains all data and cache of computed styles* and manages reactive subscriptions*/export type StyleObjectModel = {styleSourcesByInstanceId: Map<Instance["id"], StyleSource["id"][]>;- styleByStyleSourceId: Map<StyleSource["id"], Style>;+ styleByStyleSourceId: Map<`${StyleSource["id"]}:${Property}`, StyleDecl[]>;+};++/**+ *+ * Standard specificity is defined as ID-CLASS-TYPE.+ * Though webstudio does not rely on these and also+ * cannot rely on order of declarations.+ *+ * Instead webstudio define own specificity format+ * STATE-BREAKPOINT-STYLESOURCE+ *+ * Declaration with selected STATE gets 2, with any other STATE gets 1+ * Declaration BREAKPOINT is its position in ordered list+ * Declaration STYLESOURCE is its position in predefined list+ * excluding everything after selected STYLESOURCE+ *+ */+type Specificity = [STATE: number, BREAKPOINT: number, STYLESOURCE: number];++const compareSpecificity = (left: Specificity, right: Specificity) => {+ // STATE-BREAKPOINT-STYLESOURCE+ const stateDiff = left[0] - right[0];+ if (stateDiff !== 0) {+ return stateDiff;+ }+ const breakpointDiff = left[1] - right[1];+ if (breakpointDiff !== 0) {+ return breakpointDiff;+ }+ const styleSourceDiff = left[2] - right[2];+ if (styleSourceDiff !== 0) {+ return styleSourceDiff;+ }+ return 0;+};++const getSpecificity = ({+ styleDecl,+ matchingBreakpoints,+ matchingStyleSources,+}: {+ styleDecl: StyleDecl;+ matchingBreakpoints: Breakpoint["id"][];+ matchingStyleSources: StyleSource["id"][];+}): Specificity => {+ const state = styleDecl.state === undefined ? 0 : 1;+ const breakpoint = matchingBreakpoints.indexOf(styleDecl.breakpointId);+ const styleSource = matchingStyleSources.indexOf(styleDecl.styleSourceId);+ return [state, breakpoint, styleSource];};const getCascadedValue = ({model,+ matchingBreakpoints,+ matchingStates,instanceId,property,}: {model: StyleObjectModel;+ matchingBreakpoints: Breakpoint["id"][];+ matchingStates: Set<string>;instanceId: Instance["id"];- property: string;+ property: Property;}) => {+ const { styleSourcesByInstanceId, styleByStyleSourceId } = model;+// https://drafts.csswg.org/css-cascade-5/#declared- const declaredValues = [];- const styleSourceIds = model.styleSourcesByInstanceId.get(instanceId);+ type DeclaredValue = { specificity: Specificity; value: StyleValue };+ const declaredValues: DeclaredValue[] = [];++ // order values by style sources+ const styleSourceIds = styleSourcesByInstanceId.get(instanceId);if (styleSourceIds) {for (const styleSourceId of styleSourceIds) {- const style = model.styleByStyleSourceId.get(styleSourceId);- const styleDecl = style?.get(property);- if (styleDecl) {- declaredValues.push(styleDecl.value);+ const styles = styleByStyleSourceId.get(`${styleSourceId}:${property}`);+ if (styles === undefined) {+ continue;+ }+ for (const styleDecl of styles) {+ // exclude values from not matching breakpoints+ if (matchingBreakpoints.includes(styleDecl.breakpointId) === false) {+ continue;+ }+ if (styleDecl.state && matchingStates.has(styleDecl.state) === false) {+ continue;+ }+ // precompute specificity for all values before sorting+ const specificity = getSpecificity({+ styleDecl,+ matchingBreakpoints,+ matchingStyleSources: styleSourceIds,+ });+ declaredValues.push({ value: styleDecl.value, specificity });}}}+ declaredValues.sort((left, right) =>+ compareSpecificity(left.specificity, right.specificity)+ );+// https://drafts.csswg.org/css-cascade-5/#cascaded- const cascadedValue = declaredValues.at(-1);+ const cascadedValue = declaredValues.at(-1)?.value;return { cascadedValue };};@@ -101,10 +190,8 @@ const customPropertyData = {* @todo* - html* - preset- * - cascaded* - selected style source* - selected state- * - breakpoints**/export const getComputedStyleDecl = ({@@ -115,16 +202,17 @@ export const getComputedStyleDecl = ({}: {model: StyleObjectModel;styleSelector: StyleSelector;- property: string;+ property: Property;/*** for internal use only*/- customPropertiesGraph?: Map<Instance["id"], Set<string>>;+ customPropertiesGraph?: Map<Instance["id"], Set<Property>>;}): {computedValue: StyleValue;usedValue: StyleValue;} => {- const { instanceSelector } = styleSelector;+ const { instanceSelector, matchingBreakpoints, matchingStates } =+ styleSelector;const isCustomProperty = property.startsWith("--");const propertyData = isCustomProperty? customPropertyData@@ -146,7 +234,13 @@ export const getComputedStyleDecl = ({const inheritedValue: StyleValue = computedValue;// https://drafts.csswg.org/css-cascade-5/#cascaded- const { cascadedValue } = getCascadedValue({ model, instanceId, property });+ const { cascadedValue } = getCascadedValue({+ model,+ matchingBreakpoints,+ matchingStates,+ instanceId,+ property,+ });// resolve specified value// https://drafts.csswg.org/css-cascade-5/#specified