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
feat: merge longhand css into shorthands (#3615)
Bogdan Chadkin0e468fe7481e
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/navigator/css-preview.tsx b/apps/builder/app/builder/features/sidebar-left/panels/navigator/css-preview.tsxindex be97ac7a24..86f66af8bf 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/navigator/css-preview.tsx+++ b/apps/builder/app/builder/features/sidebar-left/panels/navigator/css-preview.tsx@@ -8,7 +8,11 @@ import {type StyleInfo,useStyleInfo,} from "../../../style-panel/shared/style-info";-import { generateStyleMap } from "@webstudio-is/css-engine";+import {+ generateStyleMap,+ hyphenateProperty,+ mergeStyles,+} from "@webstudio-is/css-engine";import type { StyleMap, StyleProperty } from "@webstudio-is/css-engine";import { CollapsibleSection } from "~/builder/shared/collapsible-section";import { useMemo } from "react";@@ -34,6 +38,7 @@ const getCssText = (currentStyle: StyleInfo) => {let property: StyleProperty;for (property in currentStyle) {const value = currentStyle[property];+ property = hyphenateProperty(property) as StyleProperty;if (value === undefined) {continue;}@@ -67,7 +72,7 @@ const getCssText = (currentStyle: StyleInfo) => {return;}result.push(`/* ${comment} */`);- result.push(generateStyleMap({ style }));+ result.push(generateStyleMap({ style: mergeStyles(style) }));};add("Style Sources", sourceStyles);diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/index.css b/fixtures/webstudio-cloudflare-template/app/__generated__/index.cssindex ddd2cbf784..b4de25d1b5 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/index.css+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/index.css@@ -5,10 +5,6 @@ html {}@media all {body:where([data-ws-component="Body"]) {- margin-top: 0;- margin-right: 0;- margin-bottom: 0;- margin-left: 0;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;@@ -19,6 +15,7 @@ html {border-left-width: 1px;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;+ margin: 0;}h1:where([data-ws-component="Heading"]) {box-sizing: border-box;diff --git a/fixtures/webstudio-custom-template/app/__generated__/[script-test]._index.tsx b/fixtures/webstudio-custom-template/app/__generated__/[script-test]._index.tsxindex 208bd3365f..8badc8e422 100644--- a/fixtures/webstudio-custom-template/app/__generated__/[script-test]._index.tsx+++ b/fixtures/webstudio-custom-template/app/__generated__/[script-test]._index.tsx@@ -39,7 +39,7 @@ const Page = ({}: { system: any }) => {<Bodydata-ws-id="LW98_-srDnnagkR10lsk4"data-ws-component="Body"- className="c306nq8 cp7h9on ciostvv c12dzlms"+ className="cjrgi00"><Heading data-ws-id="SHXddDLFWST_sy44UfGQO" data-ws-component="Heading">{"Script Test"}diff --git a/fixtures/webstudio-custom-template/app/__generated__/_index.tsx b/fixtures/webstudio-custom-template/app/__generated__/_index.tsxindex ad753bce69..67c755a845 100644--- a/fixtures/webstudio-custom-template/app/__generated__/_index.tsx+++ b/fixtures/webstudio-custom-template/app/__generated__/_index.tsx@@ -104,7 +104,7 @@ const Page = ({}: { system: any }) => {<Bodydata-ws-id="ibXgMoi9_ipHx1gVrvii0"data-ws-component="Body"- className="c306nq8 ciostvv cp7h9on c12dzlms"+ className="cjrgi00"><Headingdata-ws-id="7pwqBSgrfuuOfk1JblWcL"diff --git a/fixtures/webstudio-custom-template/app/__generated__/index.css b/fixtures/webstudio-custom-template/app/__generated__/index.cssindex 4bfb6d99c6..4b4e47b82e 100644--- a/fixtures/webstudio-custom-template/app/__generated__/index.css+++ b/fixtures/webstudio-custom-template/app/__generated__/index.css@@ -13,10 +13,6 @@ html {}@media all {body:where([data-ws-component="Body"]) {- margin-top: 0;- margin-right: 0;- margin-bottom: 0;- margin-left: 0;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;@@ -27,6 +23,7 @@ html {border-left-width: 1px;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;+ margin: 0;}h1:where([data-ws-component="Heading"]) {box-sizing: border-box;@@ -109,10 +106,6 @@ html {font-family: inherit;font-size: 100%;line-height: 1.15;- margin-top: 0;- margin-right: 0;- margin-bottom: 0;- margin-left: 0;box-sizing: border-box;border-top-width: 1px;border-right-width: 1px;@@ -123,6 +116,7 @@ html {border-bottom-style: solid;border-left-style: solid;text-transform: none;+ margin: 0;}div:where([data-ws-component="Box"]) {box-sizing: border-box;@@ -261,17 +255,8 @@ html {.c4o64du {background-size: auto, auto, auto;}- .c306nq8 {- margin-top: 15px;- }- .cp7h9on {- margin-bottom: 15px;- }- .ciostvv {- margin-right: 15px;- }- .c12dzlms {- margin-left: 15px;+ .cjrgi00 {+ margin: 15px;}.c17osjft {position: relative;diff --git a/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/index.css b/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/index.cssindex ddd2cbf784..b4de25d1b5 100644--- a/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/index.css+++ b/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/index.css@@ -5,10 +5,6 @@ html {}@media all {body:where([data-ws-component="Body"]) {- margin-top: 0;- margin-right: 0;- margin-bottom: 0;- margin-left: 0;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;@@ -19,6 +15,7 @@ html {border-left-width: 1px;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;+ margin: 0;}h1:where([data-ws-component="Heading"]) {box-sizing: border-box;diff --git a/fixtures/webstudio-remix-netlify-functions/app/__generated__/index.css b/fixtures/webstudio-remix-netlify-functions/app/__generated__/index.cssindex ddd2cbf784..b4de25d1b5 100644--- a/fixtures/webstudio-remix-netlify-functions/app/__generated__/index.css+++ b/fixtures/webstudio-remix-netlify-functions/app/__generated__/index.css@@ -5,10 +5,6 @@ html {}@media all {body:where([data-ws-component="Body"]) {- margin-top: 0;- margin-right: 0;- margin-bottom: 0;- margin-left: 0;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;@@ -19,6 +15,7 @@ html {border-left-width: 1px;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;+ margin: 0;}h1:where([data-ws-component="Heading"]) {box-sizing: border-box;diff --git a/fixtures/webstudio-remix-vercel/app/__generated__/[radix]._index.tsx b/fixtures/webstudio-remix-vercel/app/__generated__/[radix]._index.tsxindex 3eb284be36..81d362dcdf 100644--- a/fixtures/webstudio-remix-vercel/app/__generated__/[radix]._index.tsx+++ b/fixtures/webstudio-remix-vercel/app/__generated__/[radix]._index.tsx@@ -67,7 +67,7 @@ const Page = ({}: { system: any }) => {data-ws-id="zJ927zk9txwUbYycKB7QA"data-ws-component="@webstudio-is/sdk-components-react-radix:AccordionItem"data-ws-index="0"- className="c11jd1pp cpr1920 czj7fc1"+ className="c2onvcp"><AccordionHeaderdata-ws-id="sMxg7xT1hwYt05hbOvoPL"@@ -77,7 +77,7 @@ const Page = ({}: { system: any }) => {<AccordionTriggerdata-ws-id="qQSA4NoyKC88O68mBiQe2"data-ws-component="@webstudio-is/sdk-components-react-radix:AccordionTrigger"- className="c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax c1ad236a cg783j6 c1s4llbc"+ className="c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax cg783j6 c1ad236a c1s4llbc"><Text data-ws-id="q-DVI4YTNrQ1LizmEyJHI" data-ws-component="Text">{"Is it accessible?"}@@ -109,7 +109,7 @@ const Page = ({}: { system: any }) => {data-ws-id="C838wkvIcA1BQu30Xu2G8"data-ws-component="@webstudio-is/sdk-components-react-radix:AccordionItem"data-ws-index="1"- className="c11jd1pp cpr1920 czj7fc1"+ className="c2onvcp"><AccordionHeaderdata-ws-id="fYUOB_brm6s0Ky68lzMfU"@@ -119,7 +119,7 @@ const Page = ({}: { system: any }) => {<AccordionTriggerdata-ws-id="dfd4gonev_AX6BpuCsxjb"data-ws-component="@webstudio-is/sdk-components-react-radix:AccordionTrigger"- className="c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax c1ad236a cg783j6 c1s4llbc"+ className="c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax cg783j6 c1ad236a c1s4llbc"><Text data-ws-id="lZ7sI6Kw_0VZkURriKscB" data-ws-component="Text">{"Is it styled?"}@@ -153,7 +153,7 @@ const Page = ({}: { system: any }) => {data-ws-id="65djoTmSBGemZ2L5izQ5M"data-ws-component="@webstudio-is/sdk-components-react-radix:AccordionItem"data-ws-index="2"- className="c11jd1pp cpr1920 czj7fc1"+ className="c2onvcp"><AccordionHeaderdata-ws-id="UJYfe6kH7HqhH0YYeJwe7"@@ -163,7 +163,7 @@ const Page = ({}: { system: any }) => {<AccordionTriggerdata-ws-id="600nGddaNxGGdsuGgpxJR"data-ws-component="@webstudio-is/sdk-components-react-radix:AccordionTrigger"- className="c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax c1ad236a cg783j6 c1s4llbc"+ className="c13v7j50 c1qxdkbn chhejm9 c13bviim cpjvam0 c1tw5o2 cqw88jp c44srea c14kxsax cg783j6 c1ad236a c1s4llbc"><Text data-ws-id="1iNKIMG91n83PzJnEdxq9" data-ws-component="Text">{"Is it animated?"}diff --git a/fixtures/webstudio-remix-vercel/app/__generated__/_index.tsx b/fixtures/webstudio-remix-vercel/app/__generated__/_index.tsxindex 5886af81b4..e7ac20b7de 100644--- a/fixtures/webstudio-remix-vercel/app/__generated__/_index.tsx+++ b/fixtures/webstudio-remix-vercel/app/__generated__/_index.tsx@@ -76,7 +76,7 @@ const Page = ({}: { system: any }) => {<Bodydata-ws-id="On9cvWCxr5rdZtY9O1Bv0"data-ws-component="Body"- className="c1rv17ff ceuqm0z c1dj16g6 c11ai4np"+ className="cielobv"><Headingdata-ws-id="nVMWvMsaLCcb0o1wuNQgg"diff --git a/fixtures/webstudio-remix-vercel/app/__generated__/index.css b/fixtures/webstudio-remix-vercel/app/__generated__/index.cssindex b1ee4375b6..e166dfb377 100644--- a/fixtures/webstudio-remix-vercel/app/__generated__/index.css+++ b/fixtures/webstudio-remix-vercel/app/__generated__/index.css@@ -5,10 +5,6 @@ html {}@media all {body:where([data-ws-component="Body"]) {- margin-top: 0;- margin-right: 0;- margin-bottom: 0;- margin-left: 0;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;@@ -19,6 +15,7 @@ html {border-left-width: 1px;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;+ margin: 0;}h1:where([data-ws-component="Heading"]) {box-sizing: border-box;@@ -224,30 +221,13 @@ html {font-family: inherit;font-size: 100%;line-height: 1.15;- margin-top: 0;- margin-right: 0;- margin-bottom: 0;- margin-left: 0;box-sizing: border-box;- border-top-width: 0px;- border-right-width: 0px;- border-bottom-width: 0px;- border-left-width: 0px;- border-top-style: solid;- border-right-style: solid;- border-bottom-style: solid;- border-left-style: solid;text-transform: none;background-color: transparent;background-image: none;- border-top-color: rgba(226, 232, 240, 1);- border-right-color: rgba(226, 232, 240, 1);- border-bottom-color: rgba(226, 232, 240, 1);- border-left-color: rgba(226, 232, 240, 1);- padding-left: 0px;- padding-right: 0px;- padding-top: 0px;- padding-bottom: 0px;+ border: 0px solid rgba(226, 232, 240, 1);+ margin: 0;+ padding: 0px;}div:where([data-ws-component="@webstudio-is/sdk-components-react-radix:AccordionContent"]@@ -281,10 +261,6 @@ html {font-family: inherit;font-size: 100%;line-height: 1.15;- margin-top: 0;- margin-right: 0;- margin-bottom: 0;- margin-left: 0;box-sizing: border-box;border-top-width: 1px;border-right-width: 1px;@@ -295,15 +271,12 @@ html {border-bottom-style: solid;border-left-style: solid;display: block;+ margin: 0;}button:where([data-ws-component="Button"]) {font-family: inherit;font-size: 100%;line-height: 1.15;- margin-top: 0;- margin-right: 0;- margin-bottom: 0;- margin-left: 0;box-sizing: border-box;border-top-width: 1px;border-right-width: 1px;@@ -314,6 +287,7 @@ html {border-bottom-style: solid;border-left-style: solid;text-transform: none;+ margin: 0;}}@media all {@@ -344,26 +318,11 @@ html {.c1czoo99 {aspect-ratio: 1;}- .c1rv17ff {- padding-top: 16px;- }- .ceuqm0z {- padding-right: 16px;+ .cielobv {+ padding: 16px;}- .c1dj16g6 {- padding-left: 16px;- }- .c11ai4np {- padding-bottom: 16px;- }- .c11jd1pp {- border-bottom-width: 1px;- }- .cpr1920 {- border-bottom-style: solid;- }- .czj7fc1 {- border-bottom-color: rgba(226, 232, 240, 1);+ .c2onvcp {+ border-bottom: 1px solid rgba(226, 232, 240, 1);}.chhejm9 {flex-shrink: 1;@@ -386,12 +345,12 @@ html {.c14kxsax {font-weight: 500;}- .c1ad236a:hover {- text-decoration-line: underline;- }.cg783j6 {--accordion-trigger-icon-transform: 0deg;}+ .c1ad236a:hover {+ text-decoration-line: underline;+ }.c1s4llbc[data-state="open"] {--accordion-trigger-icon-transform: 180deg;}diff --git a/packages/css-data/src/shorthands.test.ts b/packages/css-data/src/shorthands.test.tsindex 2f59213687..23b433165b 100644--- a/packages/css-data/src/shorthands.test.ts+++ b/packages/css-data/src/shorthands.test.ts@@ -80,12 +80,12 @@ test("expand border edges", () => {// omit valuesexpect(expandShorthands([["border-top", "1px"]])).toEqual([["border-top-width", "1px"],- ["border-top-style", "initial"],- ["border-top-color", "initial"],+ ["border-top-style", "none"],+ ["border-top-color", "currentcolor"],]);expect(expandShorthands([["border-top", "red"]])).toEqual([- ["border-top-width", "initial"],- ["border-top-style", "initial"],+ ["border-top-width", "medium"],+ ["border-top-style", "none"],["border-top-color", "red"],]);});@@ -169,6 +169,11 @@ test("expand outline", () => {["outline-style", "solid"],["outline-color", "red"],]);+ expect(expandShorthands([["outline", "1px solid"]])).toEqual([+ ["outline-width", "1px"],+ ["outline-style", "solid"],+ ["outline-color", "auto"],+ ]);});test("expand margin/padding", () => {diff --git a/packages/css-data/src/shorthands.ts b/packages/css-data/src/shorthands.tsindex 08108d591f..3797005b19 100644--- a/packages/css-data/src/shorthands.ts+++ b/packages/css-data/src/shorthands.ts@@ -139,15 +139,17 @@ const expandBorder = function* (property: string, value: CssNode) {case "border-top":case "border-right":case "border-bottom":- case "border-left":- case "outline": {+ case "border-left": {const [width, style, color] = parseUnordered(["<line-width>", "<line-style>", "<color>"],value);- yield [`${property}-width`, width ?? createInitialNode()] as const;- yield [`${property}-style`, style ?? createInitialNode()] as const;- yield [`${property}-color`, color ?? createInitialNode()] as const;+ yield [`${property}-width`, width ?? createIdentifier("medium")] as const;+ yield [`${property}-style`, style ?? createIdentifier("none")] as const;+ yield [+ `${property}-color`,+ color ?? createIdentifier("currentcolor"),+ ] as const;break;}default:@@ -895,6 +897,17 @@ const expandShorthand = function* (property: string, value: CssNode) {yield* expandBorderImage(value);break;+ case "outline": {+ const [color, style, width] = parseUnordered(+ [`<'outline-color'>`, `<'outline-style'>`, `<'outline-width'>`],+ value+ );+ yield [`${property}-width`, width ?? createIdentifier("medium")] as const;+ yield [`${property}-style`, style ?? createIdentifier("none")] as const;+ yield [`${property}-color`, color ?? createIdentifier("auto")] as const;+ break;+ }+case "mask":yield* expandMask(value);break;diff --git a/packages/css-engine/src/core/atomic.test.ts b/packages/css-engine/src/core/atomic.test.tsindex 681b691999..feddbe2525 100644--- a/packages/css-engine/src/core/atomic.test.ts+++ b/packages/css-engine/src/core/atomic.test.ts@@ -1,6 +1,8 @@import { test, expect } from "@jest/globals";import { createRegularStyleSheet } from "./create-style-sheet";import { generateAtomic } from "./atomic";+import type { NestingRule } from "./rules";+import type { StyleValue } from "../schema";const mediaRuleOptions0 = { minWidth: 0 } as const;const mediaId0 = "0";@@ -206,11 +208,11 @@ test("support descendant suffix", () => {`);});-test("generated prefixed and unprefixed in the same rule", () => {+test("generate prefixed and unprefixed in the same rule", () => {const sheet = createRegularStyleSheet();sheet.addMediaRule("x");- const rule1 = sheet.addNestingRule("instance");- rule1.setDeclaration({+ const rule = sheet.addNestingRule("instance");+ rule.setDeclaration({breakpoint: "x",selector: "",property: "textSizeAdjust",@@ -226,3 +228,54 @@ test("generated prefixed and unprefixed in the same rule", () => {}"`);});++test("generate merged properties as single rule", () => {+ const sheet = createRegularStyleSheet();+ sheet.addMediaRule("x");+ const setMargins = (rule: NestingRule, value: StyleValue) => {+ rule.setDeclaration({+ breakpoint: "x",+ selector: "",+ property: "marginTop",+ value,+ });+ rule.setDeclaration({+ breakpoint: "x",+ selector: "",+ property: "marginRight",+ value,+ });+ rule.setDeclaration({+ breakpoint: "x",+ selector: "",+ property: "marginBottom",+ value,+ });+ rule.setDeclaration({+ breakpoint: "x",+ selector: "",+ property: "marginLeft",+ value,+ });+ };+ setMargins(sheet.addNestingRule("instance"), {+ type: "keyword",+ value: "auto",+ });+ setMargins(sheet.addNestingRule("instance", " img"), {+ type: "unit",+ value: 10,+ unit: "px",+ });+ expect(generateAtomic(sheet, { getKey: () => "" }).cssText)+ .toMatchInlineSnapshot(`+"@media all {+ .cdj9gv4 {+ margin: auto+ }+ .c340vfr img {+ margin: 10px+ }+}"+`);+});diff --git a/packages/css-engine/src/core/atomic.ts b/packages/css-engine/src/core/atomic.tsindex 0eb72910de..8a06ef24aa 100644--- a/packages/css-engine/src/core/atomic.ts+++ b/packages/css-engine/src/core/atomic.ts@@ -23,7 +23,7 @@ export const generateAtomic = (sheet: StyleSheet, options: Options) => {classesMap.set(groupKey, classList);}// convert each declaration into separate rule- for (const declaration of rule.getDeclarations()) {+ for (const declaration of rule.getMergedDeclarations()) {const atomicHash = hash(descendantSuffix +declaration.breakpoint +diff --git a/packages/css-engine/src/core/index.ts b/packages/css-engine/src/core/index.tsindex f337b9684f..222d4023ff 100644--- a/packages/css-engine/src/core/index.ts+++ b/packages/css-engine/src/core/index.ts@@ -5,6 +5,8 @@ export type {PlaintextRule,FontFaceRule,} from "./rules";+export { prefixStyles } from "./prefixer";+export { mergeStyles } from "./merger";export { generateStyleMap } from "./rules";export type { StyleSheetRegular } from "./style-sheet-regular";export * from "./create-style-sheet";diff --git a/packages/css-engine/src/core/merger.test.ts b/packages/css-engine/src/core/merger.test.tsnew file mode 100644index 0000000000..e57959f845--- /dev/null+++ b/packages/css-engine/src/core/merger.test.ts@@ -0,0 +1,162 @@+import { expect, test } from "@jest/globals";+import { mergeStyles } from "./merger";+import type { StyleMap } from "./rules";+import { toValue } from "./to-value";++const toStringMap = (style: StyleMap) =>+ Array.from(+ style.entries(),+ ([property, value]) => [property, toValue(value)] as const+ );++test("merge border when all parts are set", () => {+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["border-top-width", { type: "unit", value: 1, unit: "px" }],+ ["border-top-style", { type: "keyword", value: "solid" }],+ ["border-top-color", { type: "keyword", value: "red" }],+ ])+ )+ )+ ).toEqual([["border-top", "1px solid red"]]);+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["border-width", { type: "unit", value: 1, unit: "px" }],+ ["border-style", { type: "keyword", value: "solid" }],+ ["border-color", { type: "keyword", value: "red" }],+ ])+ )+ )+ ).toEqual([["border", "1px solid red"]]);+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["border-width", { type: "unit", value: 1, unit: "px" }],+ ["border-style", { type: "keyword", value: "solid" }],+ ])+ )+ )+ ).toEqual([+ ["border-width", "1px"],+ ["border-style", "solid"],+ ]);+});++test("should not merge border with initial", () => {+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["border-width", { type: "keyword", value: "initial" }],+ ["border-style", { type: "keyword", value: "solid" }],+ ["border-color", { type: "keyword", value: "red" }],+ ])+ )+ )+ ).toEqual([+ ["border-width", "initial"],+ ["border-style", "solid"],+ ["border-color", "red"],+ ]);+});++test("merge border with vars", () => {+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["border-width", { type: "var", value: "width", fallbacks: [] }],+ ["border-style", { type: "var", value: "style", fallbacks: [] }],+ ["border-color", { type: "var", value: "color", fallbacks: [] }],+ ])+ )+ )+ ).toEqual([["border", "var(--width) var(--style) var(--color)"]]);+});++test("merge margin/padding when the same value is set", () => {+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["margin-top", { type: "unit", value: 10, unit: "px" }],+ ["margin-right", { type: "unit", value: 10, unit: "px" }],+ ["margin-bottom", { type: "unit", value: 10, unit: "px" }],+ ["margin-left", { type: "unit", value: 10, unit: "px" }],+ ])+ )+ )+ ).toEqual([["margin", "10px"]]);+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["padding-top", { type: "unit", value: 10, unit: "px" }],+ ["padding-right", { type: "unit", value: 10, unit: "px" }],+ ["padding-bottom", { type: "unit", value: 10, unit: "px" }],+ ["padding-left", { type: "unit", value: 10, unit: "px" }],+ ])+ )+ )+ ).toEqual([["padding", "10px"]]);+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["padding-top", { type: "unit", value: 10, unit: "px" }],+ ["padding-right", { type: "unit", value: 10, unit: "px" }],+ ["padding-bottom", { type: "unit", value: 10, unit: "px" }],+ ])+ )+ )+ ).toEqual([+ ["padding-top", "10px"],+ ["padding-right", "10px"],+ ["padding-bottom", "10px"],+ ]);+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["padding-top", { type: "unit", value: 1, unit: "px" }],+ ["padding-right", { type: "unit", value: 2, unit: "px" }],+ ["padding-bottom", { type: "unit", value: 10, unit: "px" }],+ ["padding-left", { type: "unit", value: 10, unit: "px" }],+ ])+ )+ )+ ).toEqual([+ ["padding-top", "1px"],+ ["padding-right", "2px"],+ ["padding-bottom", "10px"],+ ["padding-left", "10px"],+ ]);+});++test("merge border longhands", () => {+ expect(+ toStringMap(+ mergeStyles(+ new Map([+ ["border-top-width", { type: "unit", value: 1, unit: "px" }],+ ["border-top-style", { type: "keyword", value: "solid" }],+ ["border-top-color", { type: "keyword", value: "red" }],+ ["border-right-width", { type: "unit", value: 1, unit: "px" }],+ ["border-right-style", { type: "keyword", value: "solid" }],+ ["border-right-color", { type: "keyword", value: "red" }],+ ["border-bottom-width", { type: "unit", value: 1, unit: "px" }],+ ["border-bottom-style", { type: "keyword", value: "solid" }],+ ["border-bottom-color", { type: "keyword", value: "red" }],+ ["border-left-width", { type: "unit", value: 1, unit: "px" }],+ ["border-left-style", { type: "keyword", value: "solid" }],+ ["border-left-color", { type: "keyword", value: "red" }],+ ])+ )+ )+ ).toEqual([["border", "1px solid red"]]);+});diff --git a/packages/css-engine/src/core/merger.ts b/packages/css-engine/src/core/merger.tsnew file mode 100644index 0000000000..8e2751990f--- /dev/null+++ b/packages/css-engine/src/core/merger.ts@@ -0,0 +1,70 @@+import { StyleValue, TupleValueItem } from "../schema";+import type { StyleMap } from "./rules";+import { toValue } from "./to-value";++const cssWideKeywords = new Set(["initial", "inherit", "unset", "revert"]);++/**+ * Css wide keywords cannot be used in shorthand parts+ */+const isLonghandValue = (value?: StyleValue): value is StyleValue => {+ if (value === undefined) {+ return false;+ }+ if (value.type === "keyword" && cssWideKeywords.has(value.value)) {+ return false;+ }+ return true;+};++const mergeBorder = (styleMap: StyleMap, base: string) => {+ // support any type in tuple, adding only+ // var would cause circular dependency issue in zod schema+ const width = styleMap.get(`${base}-width`) as undefined | TupleValueItem;+ const style = styleMap.get(`${base}-style`) as undefined | TupleValueItem;+ const color = styleMap.get(`${base}-color`) as undefined | TupleValueItem;+ if (+ isLonghandValue(width) &&+ isLonghandValue(style) &&+ isLonghandValue(color)+ ) {+ styleMap.delete(`${base}-width`);+ styleMap.delete(`${base}-style`);+ styleMap.delete(`${base}-color`);+ styleMap.set(base, { type: "tuple", value: [width, style, color] });+ }+};++const mergeBox = (styleMap: StyleMap, base: string) => {+ const topValue = styleMap.get(`${base}-top`);+ const top = toValue(topValue);+ const right = toValue(styleMap.get(`${base}-right`));+ const bottom = toValue(styleMap.get(`${base}-bottom`));+ const left = toValue(styleMap.get(`${base}-left`));+ if (+ isLonghandValue(topValue) &&+ top === right &&+ top === bottom &&+ top === left+ ) {+ styleMap.delete(`${base}-top`);+ styleMap.delete(`${base}-right`);+ styleMap.delete(`${base}-bottom`);+ styleMap.delete(`${base}-left`);+ styleMap.set(base, topValue);+ }+};++export const mergeStyles = (styleMap: StyleMap) => {+ const newStyle = new Map(styleMap);+ mergeBorder(newStyle, "border-top");+ mergeBorder(newStyle, "border-right");+ mergeBorder(newStyle, "border-bottom");+ mergeBorder(newStyle, "border-left");+ mergeBorder(newStyle, "border");+ mergeBorder(newStyle, "outline");+ mergeBox(newStyle, "border");+ mergeBox(newStyle, "margin");+ mergeBox(newStyle, "padding");+ return newStyle;+};diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.tsindex 63b0413d9a..93e9383249 100644--- a/packages/css-engine/src/core/rules.ts+++ b/packages/css-engine/src/core/rules.ts@@ -2,6 +2,53 @@ import type { StyleValue } from "../schema";import { toValue, type TransformValue } from "./to-value";import { hyphenateProperty } from "./to-property";import { prefixStyles } from "./prefixer";+import { mergeStyles } from "./merger";++const mapGroupBy = <Item, Key>(+ array: Item[] | Iterable<Item>,+ getKey: (item: Item) => Key+) => {+ const groups = new Map<Key, Item[]>();+ for (const item of array) {+ const key = getKey(item);+ let group = groups.get(key);+ if (group === undefined) {+ group = [];+ groups.set(key, group);+ }+ group.push(item);+ }+ return groups;+};++/**+ * Merge styles on every group by breakpoint and selector+ * and convert back to declarations list+ */+const mergeDeclarations = (declarations: Iterable<Declaration>) => {+ const newDeclarations: Declaration[] = [];+ const groups = mapGroupBy(+ declarations,+ (declaration) => declaration.breakpoint + declaration.selector+ );+ for (const groupDeclarations of groups.values()) {+ const { breakpoint, selector } = groupDeclarations[0];+ const merged = mergeStyles(+ new Map(+ groupDeclarations.map((item) => [item.property, item.value] as const)+ )+ );+ for (const [property, value] of merged) {+ newDeclarations.push({+ breakpoint,+ selector,+ property,+ value,+ });+ }+ }+ return newDeclarations;+};export type StyleMap = Map<string, StyleValue>;@@ -25,7 +72,7 @@ export const generateStyleMap = ({return lines;};-type Declaration = {+export type Declaration = {breakpoint: string;selector: string;property: string;@@ -154,7 +201,7 @@ export class NestingRule {this.#declarations.delete(getDeclarationKey(declaration));this.#cache.delete(declaration.breakpoint);}- getDeclarations() {+ #getDeclarations() {// apply mixins first and then merge added declarationsconst declarations = new Map<string, Declaration>();for (const mixin of this.#mixins) {@@ -171,6 +218,9 @@ export class NestingRule {}return declarations.values();}+ getMergedDeclarations() {+ return mergeDeclarations(this.#getDeclarations());+ }toString({breakpoint,indent = 0,@@ -198,7 +248,7 @@ export class NestingRule {return cached.generated;}const styleBySelector = new Map<string, StyleMap>();- for (const declaration of this.getDeclarations()) {+ for (const declaration of this.getMergedDeclarations()) {// generate declarations only for specified breakpointif (declaration.breakpoint !== breakpoint) {continue;diff --git a/packages/css-engine/src/core/style-sheet-regular.test.ts b/packages/css-engine/src/core/style-sheet-regular.test.tsindex 0a62b538cc..b479ef8bdb 100644--- a/packages/css-engine/src/core/style-sheet-regular.test.ts+++ b/packages/css-engine/src/core/style-sheet-regular.test.ts@@ -1,6 +1,8 @@import { describe, test, expect } from "@jest/globals";import { createRegularStyleSheet } from "./create-style-sheet";import type { TransformValue } from "./to-value";+import type { NestingRule } from "./rules";+import type { StyleValue } from "../schema";const mediaRuleOptions0 = { minWidth: 0 } as const;const mediaId0 = "0";@@ -713,3 +715,53 @@ describe("Style Sheet Regular", () => {`);});});++test("generate merged properties as single rule", () => {+ const sheet = createRegularStyleSheet();+ sheet.addMediaRule("x");+ const setMargins = (rule: NestingRule, value: StyleValue) => {+ rule.setDeclaration({+ breakpoint: "x",+ selector: "",+ property: "marginTop",+ value,+ });+ rule.setDeclaration({+ breakpoint: "x",+ selector: "",+ property: "marginRight",+ value,+ });+ rule.setDeclaration({+ breakpoint: "x",+ selector: "",+ property: "marginBottom",+ value,+ });+ rule.setDeclaration({+ breakpoint: "x",+ selector: "",+ property: "marginLeft",+ value,+ });+ };+ setMargins(sheet.addNestingRule("instance"), {+ type: "keyword",+ value: "auto",+ });+ setMargins(sheet.addNestingRule("instance", " img"), {+ type: "unit",+ value: 10,+ unit: "px",+ });+ expect(sheet.cssText).toMatchInlineSnapshot(`+"@media all {+ instance {+ margin: auto+ }+ instance img {+ margin: 10px+ }+}"+`);+});