Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import {
type ParsedStyleDecl,
properties,
parseCss,
type ParsedStyleDecl,
camelCaseProperty,
} from "@webstudio-is/css-data";
import { type StyleProperty } from "@webstudio-is/css-engine";
import { camelCase } from "change-case";
import type { CssProperty, StyleProperty } from "@webstudio-is/css-engine";
import { lexer } from "css-tree";

type StyleDecl = Omit<ParsedStyleDecl, "property"> & {
property: StyleProperty;
};

/**
* Does several attempts to parse:
* - Custom property "--foo"
Expand All @@ -16,7 +20,7 @@ import { lexer } from "css-tree";
* - Property and value: color: red
* - Multiple properties: color: red; background: blue
*/
export const parseStyleInput = (css: string): Array<ParsedStyleDecl> => {
export const parseStyleInput = (css: string): Array<StyleDecl> => {
css = css.trim();
// Is it a custom property "--foo"?
if (css.startsWith("--") && lexer.match("<custom-ident>", css).matched) {
Expand All @@ -30,12 +34,11 @@ export const parseStyleInput = (css: string): Array<ParsedStyleDecl> => {
}

// Is it a known regular property?
const camelCasedProperty = camelCase(css);
if (camelCasedProperty in properties) {
if (camelCaseProperty(css as CssProperty) in properties) {
return [
{
selector: "selector",
property: css as StyleProperty,
property: camelCaseProperty(css as CssProperty),
value: { type: "unset", value: "" },
},
];
Expand All @@ -52,20 +55,29 @@ export const parseStyleInput = (css: string): Array<ParsedStyleDecl> => {
];
}

const styles = parseCss(`selector{${css}}`);
const hyphenatedStyles = parseCss(`selector{${css}}`);
const newStyles: StyleDecl[] = [];

for (const style of styles) {
for (const { property, ...styleDecl } of hyphenatedStyles) {
// somethingunknown: red; -> --somethingunknown: red;
if (
// Note: currently in tests it returns unparsed, but in the client it returns invalid,
// because we use native APIs when available in parseCss.
style.value.type === "invalid" ||
(style.value.type === "unparsed" &&
style.property.startsWith("--") === false)
styleDecl.value.type === "invalid" ||
(styleDecl.value.type === "unparsed" &&
property.startsWith("--") === false)
) {
style.property = `--${style.property}`;
newStyles.push({
...styleDecl,
property: `--${property}`,
});
} else {
newStyles.push({
...styleDecl,
property: camelCaseProperty(property),
});
}
}

return styles;
return newStyles;
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import {
completionKeymap,
type CompletionSource,
} from "@codemirror/autocomplete";
import { parseCss } from "@webstudio-is/css-data";
import { camelCaseProperty, parseCss } from "@webstudio-is/css-data";
import { css as style } from "@webstudio-is/design-system";
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
import {
EditorContent,
EditorDialog,
Expand All @@ -18,7 +19,10 @@ import {
} from "~/builder/shared/code-editor-base";
import { $availableVariables } from "./model";

export const parseCssFragment = (css: string, fallbacks: string[]) => {
export const parseCssFragment = (
css: string,
fallbacks: string[]
): Map<StyleProperty, StyleValue> => {
let parsed = parseCss(`.styles{${css}}`);
if (parsed.length === 0) {
for (const fallbackProperty of fallbacks) {
Expand All @@ -30,7 +34,10 @@ export const parseCssFragment = (css: string, fallbacks: string[]) => {
}
}
return new Map(
parsed.map((styleDecl) => [styleDecl.property, styleDecl.value])
parsed.map((styleDecl) => [
camelCaseProperty(styleDecl.property),
styleDecl.value,
])
);
};

Expand Down
10 changes: 5 additions & 5 deletions apps/builder/app/shared/copy-paste/plugin-webflow/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import type { WfAsset, WfElementNode, WfNode, WfStyle } from "./schema";
import { nanoid } from "nanoid";
import { $styleSources } from "~/shared/nano-states";
import {
camelCaseProperty,
parseCss,
pseudoElements,
type ParsedStyleDecl,
} from "@webstudio-is/css-data";
import { kebabCase } from "change-case";
import { equalMedia, hyphenateProperty } from "@webstudio-is/css-engine";
import type { WfStylePresets } from "./style-presets-overrides";
import { builderApi } from "~/shared/builder-api";
Expand Down Expand Up @@ -103,7 +103,7 @@ const replaceAtImages = (
};

const processStyles = (parsedStyles: ParsedStyleDecl[]) => {
const styles = new Map();
const styles = new Map<string, ParsedStyleDecl>();
for (const parsedStyleDecl of parsedStyles) {
const { breakpoint, selector, state, property } = parsedStyleDecl;
const key = `${breakpoint}:${selector}:${state}:${property}`;
Expand All @@ -113,7 +113,7 @@ const processStyles = (parsedStyles: ParsedStyleDecl[]) => {
const { breakpoint, selector, state, property } = parsedStyleDecl;
const key = `${breakpoint}:${selector}:${state}:${property}`;
styles.set(key, parsedStyleDecl);
if (property === "backgroundClip") {
if (property === "background-clip") {
const colorKey = `${breakpoint}:${selector}:${state}:color`;
styles.delete(colorKey);
styles.set(colorKey, {
Expand Down Expand Up @@ -197,12 +197,12 @@ const addNodeStyles = ({
fragment.styles.push({
styleSourceId,
breakpointId: breakpoint.id,
property: style.property,
property: camelCaseProperty(style.property),
value: style.value,
state: style.state,
});
if (style.value.type === "invalid") {
const error = `Invalid style value: Local "${kebabCase(style.property)}: ${style.value.value}"`;
const error = `Invalid style value: Local "${hyphenateProperty(style.property)}: ${style.value.value}"`;
toast.error(error);
console.error(error);
}
Expand Down
4 changes: 2 additions & 2 deletions apps/builder/app/shared/style-object-model.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
getStyleDeclKey,
} from "@webstudio-is/sdk";
import { $, renderData } from "@webstudio-is/template";
import { parseCss } from "@webstudio-is/css-data";
import { camelCaseProperty, parseCss } from "@webstudio-is/css-data";
import type { StyleValue } from "@webstudio-is/css-engine";
import {
type StyleObjectModel,
Expand Down Expand Up @@ -54,7 +54,7 @@ const createModel = ({
styleSourceId: selector,
breakpointId: breakpoint ?? "base",
state,
property,
property: camelCaseProperty(property),
value,
};
styles.set(getStyleDeclKey(styleDecl), styleDecl);
Expand Down
13 changes: 10 additions & 3 deletions packages/ai/src/chains/operations/edit-styles.server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { parseTailwindToWebstudio } from "@webstudio-is/css-data";
import {
camelCaseProperty,
parseTailwindToWebstudio,
} from "@webstudio-is/css-data";
import type { aiOperation, wsOperation } from "./edit-styles";

export { name } from "./edit-styles";
Expand All @@ -11,10 +14,14 @@ export const aiOperationToWs = async (
if (operation.className === "") {
throw new Error(`Operation ${operation.operation} className is empty`);
}
const styles = await parseTailwindToWebstudio(operation.className);
const hyphenatedStyles = await parseTailwindToWebstudio(operation.className);
const newStyles = hyphenatedStyles.map(({ property, ...styleDecl }) => ({
...styleDecl,
property: camelCaseProperty(property),
}));
return {
operation: "applyStyles",
instanceIds: operation.wsIds,
styles: styles,
styles: newStyles,
};
};
10 changes: 8 additions & 2 deletions packages/css-data/bin/css-to-ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { parseArgs, type ParseArgsConfig } from "node:util";
import * as path from "node:path";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { parseCss } from "../src/parse-css";
import { camelCaseProperty, parseCss } from "../src/parse-css";

const cliOptions = {
allowPositionals: true,
Expand Down Expand Up @@ -34,7 +34,13 @@ const objectGroupBy = <Item>(list: Item[], by: (item: Item) => string) => {
};

const css = readFileSync(sourcePath, "utf8");
const parsed = parseCss(css);
const parsed = parseCss(css).map(({ property, ...styleDecl }) => ({
selector: styleDecl.selector,
breakpoint: styleDecl.breakpoint,
state: styleDecl.state,
property: camelCaseProperty(property),
value: styleDecl.value,
}));
const records = objectGroupBy(parsed, (item) => item.selector);
mkdirSync(path.dirname(destinationPath), { recursive: true });
const code = `/* eslint-disable */
Expand Down
7 changes: 5 additions & 2 deletions packages/css-data/bin/html.css.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import type { StyleValue } from "@webstudio-is/css-engine";
import { parseCss } from "../src/parse-css";
import { camelCaseProperty, parseCss } from "../src/parse-css";

const css = readFileSync("./src/html.css", "utf8");
const parsed = parseCss(css);
const result: [string, StyleValue][] = [];
for (const styleDecl of parsed) {
result.push([`${styleDecl.selector}:${styleDecl.property}`, styleDecl.value]);
result.push([
`${styleDecl.selector}:${camelCaseProperty(styleDecl.property)}`,
styleDecl.value,
]);
}
let code = "";
code += `import type { HtmlTags } from "html-tags";\n`;
Expand Down
46 changes: 20 additions & 26 deletions packages/css-data/bin/mdn-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,18 @@ import properties from "mdn-data/css/properties.json";
import syntaxes from "mdn-data/css/syntaxes.json";
import selectors from "mdn-data/css/selectors.json";
import data from "css-tree/dist/data";
import { camelCase } from "change-case";
import type {
KeywordValue,
StyleValue,
Unit,
UnitValue,
UnparsedValue,
FontFamilyValue,
import {
type KeywordValue,
type StyleValue,
type Unit,
type UnitValue,
type UnparsedValue,
type FontFamilyValue,
hyphenateProperty,
type CssProperty,
} from "@webstudio-is/css-engine";
import * as customData from "../src/custom-data";

/**
* Store prefixed properties without change
* and convert to camel case only unprefixed properties
* @todo stop converting to camel case and use hyphenated format
*/
const normalizePropertyName = (property: string) => {
if (property.startsWith("-")) {
return property;
}
return camelCase(property);
};
import { camelCaseProperty } from "../src/parse-css";

const units: Record<string, Array<string>> = {
number: [],
Expand Down Expand Up @@ -233,7 +223,7 @@ const walkSyntax = (
walk(parsed);
};

type FilteredProperties = { [property in Property]: Value };
type FilteredProperties = { [property: string]: Value };

const experimentalProperties = [
"appearance",
Expand Down Expand Up @@ -299,7 +289,7 @@ const propertiesData = {
...customData.propertiesData,
};

let property: Property;
let property: string;
for (property in filteredProperties) {
const config = filteredProperties[property];
const unitGroups = new Set<string>();
Expand All @@ -326,7 +316,7 @@ for (property in filteredProperties) {
);
}

propertiesData[normalizePropertyName(property)] = {
propertiesData[camelCaseProperty(property as CssProperty)] = {
unitGroups: Array.from(unitGroups),
inherited: config.inherited,
initial: parseInitialValue(property, config.initial, unitGroups),
Expand Down Expand Up @@ -367,7 +357,7 @@ const keywordValues = (() => {
const result = { ...customData.keywordValues };

for (const property in filteredProperties) {
const key = normalizePropertyName(property);
const key = camelCaseProperty(property as CssProperty);
// prevent merging with custom keywords
if (result[key]) {
continue;
Expand Down Expand Up @@ -416,10 +406,14 @@ writeToFile("pseudo-elements.ts", "pseudoElements", pseudoElements);

let types = "";

const propertyLiterals = Object.keys(propertiesData).map((property) =>
const camelCasedProperties = Object.keys(propertiesData).map((property) =>
JSON.stringify(property)
);
types += `export type Property = ${propertyLiterals.join(" | ")};\n\n`;
types += `export type CamelCasedProperty = ${camelCasedProperties.join(" | ")};\n\n`;
const hyphenatedProperties = Object.keys(propertiesData).map((property) =>
JSON.stringify(hyphenateProperty(property))
);
types += `export type HyphenatedProperty = ${hyphenatedProperties.join(" | ")};\n\n`;

const unitLiterals = Object.values(units)
.flat()
Expand Down
2 changes: 1 addition & 1 deletion packages/css-data/src/__generated__/properties.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading