Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: migrate css preview to new style engine #4353

Merged
merged 1 commit into from
Nov 4, 2024
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
81 changes: 37 additions & 44 deletions apps/builder/app/builder/features/navigator/css-preview.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
import {
ScrollArea,
css,
textVariants,
theme,
} from "@webstudio-is/design-system";
// @todo feature should not import another feature
import {
type StyleInfo,
useStyleInfo,
} from "~/builder/features/style-panel/shared/style-info";
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";
import { captureError } from "@webstudio-is/error-utils";
import { highlightCss } from "~/builder/shared/code-highlight";
import type { ComputedStyleDecl } from "~/shared/style-object-model";
import { $selectedInstanceSelector } from "~/shared/nano-states";
import { $definedComputedStyles } from "~/builder/features/style-panel/shared/model";

const preStyle = css(textVariants.mono, {
margin: 0,
Expand All @@ -27,43 +25,40 @@ const preStyle = css(textVariants.mono, {
cursor: "text",
});

// - Compiles a CSS string from the style info
// - Compiles a CSS string from the style engine
// - Groups by category and separates categories with comments
const getCssText = (currentStyle: StyleInfo) => {
const getCssText = (
computedStyles: ComputedStyleDecl[],
instanceId: string
) => {
const sourceStyles: StyleMap = new Map();
const inheritedStyles: StyleMap = new Map();
const cascadedStyles: StyleMap = new Map();
const presetStyles: StyleMap = new Map();

// Aggregate styles by category so we can group them when rendering.
let property: StyleProperty;
for (property in currentStyle) {
const value = currentStyle[property];
property = hyphenateProperty(property) as StyleProperty;
if (value === undefined) {
continue;
}
if (value.local ?? value.nextSource?.value ?? value.previousSource?.value) {
sourceStyles.set(property, value.value);
continue;
for (const styleDecl of computedStyles) {
const property = hyphenateProperty(styleDecl.property) as StyleProperty;
let group;
if (
styleDecl.source.name === "local" ||
styleDecl.source.name === "overwritten"
) {
group = sourceStyles;
}
if (value.preset) {
presetStyles.set(property, value.value);
continue;
if (styleDecl.source.name === "remote") {
group = cascadedStyles;
}
if (value.cascaded?.value) {
cascadedStyles.set(property, value.value);
continue;
if (styleDecl.source.name === "preset") {
group = presetStyles;
}
if (value.inherited?.value) {
inheritedStyles.set(property, value.value);
continue;
if (group) {
if (styleDecl.source.instanceId === instanceId) {
group.set(property, styleDecl.cascadedValue);
} else {
inheritedStyles.set(property, styleDecl.cascadedValue);
}
}
if (value.value) {
// Doesn't need handling
continue;
}
captureError(new Error("Unknown style source"), value);
}

const result: Array<string> = [];
Expand All @@ -84,25 +79,23 @@ const getCssText = (currentStyle: StyleInfo) => {
return result.join("\n");
};

const useHighlightedCss = () => {
const currentStyle = useStyleInfo();

return useMemo(() => {
if (Object.keys(currentStyle).length === 0) {
const $highlightedCss = computed(
[$selectedInstanceSelector, $definedComputedStyles],
(instanceSelector, computedStyles) => {
if (instanceSelector === undefined) {
return;
}
const cssText = getCssText(currentStyle);
const [instanceId] = instanceSelector;
const cssText = getCssText(computedStyles, instanceId);
return highlightCss(cssText);
}, [currentStyle]);
};
}
);

export const CssPreview = () => {
const code = useHighlightedCss();

const code = useStore($highlightedCss);
if (code === undefined) {
return null;
}

return (
<CollapsibleSection label="CSS Preview" fullWidth>
<ScrollArea css={{ padding: theme.panel.padding }}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ export const PropsSection = (props: PropsSectionProps) => {

return (
<>
<Row css={{ py: theme.spacing[3] }}>
<Row css={{ py: theme.panel.paddingBlock }}>
{logic.systemProps.map((item) => renderProperty(props, item))}
</Row>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ import { PropertyInfo } from "../../property-label";
import { sections } from "../sections";
import { ColorPopover } from "../../shared/color-picker";
import {
$instances,
$registeredComponentMetas,
$selectedInstanceSelector,
$styles,
$styleSourceSelections,
Expand Down Expand Up @@ -377,11 +379,20 @@ const initialProperties = new Set<StyleProperty>([
const $advancedProperties = computed(
[
$selectedInstanceSelector,
$instances,
$registeredComponentMetas,
$styleSourceSelections,
$matchingBreakpoints,
$styles,
],
(instanceSelector, styleSourceSelections, matchingBreakpoints, styles) => {
(
instanceSelector,
instances,
metas,
styleSourceSelections,
matchingBreakpoints,
styles
) => {
if (instanceSelector === undefined) {
return [];
}
Expand All @@ -393,6 +404,8 @@ const $advancedProperties = computed(
instanceSelector;
const definedStyles = getDefinedStyles({
instanceSelector: instanceAndRootSelector,
instances,
metas,
matchingBreakpoints,
styleSourceSelections,
styles,
Expand Down
112 changes: 75 additions & 37 deletions apps/builder/app/builder/features/style-panel/shared/model.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import {
type VarValue,
} from "@webstudio-is/css-engine";
import {
Instances,
ROOT_INSTANCE_ID,
Styles,
StyleSourceSelections,
type Breakpoint,
type Instance,
type StyleDecl,
} from "@webstudio-is/sdk";
import { rootComponent } from "@webstudio-is/react-sdk";
import { rootComponent, WsComponentMeta } from "@webstudio-is/react-sdk";
import {
$breakpoints,
$instances,
Expand Down Expand Up @@ -96,20 +97,36 @@ export const $matchingBreakpoints = computed(

export const getDefinedStyles = ({
instanceSelector,
instances,
metas,
matchingBreakpoints: matchingBreakpointsArray,
styleSourceSelections,
styles,
}: {
instanceSelector: InstanceSelector;
instances: Instances;
metas: Map<string, WsComponentMeta>;
matchingBreakpoints: Breakpoint["id"][];
styleSourceSelections: StyleSourceSelections;
styles: Styles;
}) => {
const definedStyles = new Set<StyleDecl>();
const definedStyles = new Set<{
property: StyleProperty;
listed?: boolean;
}>();
const inheritedStyleSources = new Set();
const instanceStyleSources = new Set();
const matchingBreakpoints = new Set(matchingBreakpointsArray);
for (const instanceId of instanceSelector) {
const instance = instances.get(instanceId);
const meta = instance?.component
? metas.get(instance.component)
: undefined;
for (const presetStyles of Object.values(meta?.presetStyle ?? {})) {
for (const styleDecl of presetStyles) {
definedStyles.add(styleDecl);
}
}
const styleSources = styleSourceSelections.get(instanceId)?.values;
if (styleSources) {
for (const styleSourceId of styleSources) {
Expand Down Expand Up @@ -143,23 +160,43 @@ export const getDefinedStyles = ({
return definedStyles;
};

const $instanceAndRootSelector = computed(
$selectedInstanceSelector,
(instanceSelector) => {
if (instanceSelector === undefined) {
return;
}
if (instanceSelector[0] === ROOT_INSTANCE_ID) {
return instanceSelector;
}
return [...instanceSelector, ROOT_INSTANCE_ID];
}
);

export const $definedStyles = computed(
[
$selectedInstanceSelector,
$instanceAndRootSelector,
$instances,
$registeredComponentMetas,
$styleSourceSelections,
$matchingBreakpoints,
$styles,
],
(instanceSelector, styleSourceSelections, matchingBreakpoints, styles) => {
(
instanceSelector,
instances,
metas,
styleSourceSelections,
matchingBreakpoints,
styles
) => {
if (instanceSelector === undefined) {
return new Set<StyleDecl>();
}
const instanceAndRootSelector =
instanceSelector[0] === ROOT_INSTANCE_ID
? instanceSelector
: [...instanceSelector, ROOT_INSTANCE_ID];
return getDefinedStyles({
instanceSelector: instanceAndRootSelector,
instanceSelector,
instances,
metas,
matchingBreakpoints,
styleSourceSelections,
styles,
Expand Down Expand Up @@ -198,46 +235,47 @@ const $model = computed(
}
);

const $instanceAndRootSelector = computed(
$selectedInstanceSelector,
(instanceSelector) => {
if (instanceSelector === undefined) {
return;
}
if (instanceSelector[0] === ROOT_INSTANCE_ID) {
return instanceSelector;
}
return [...instanceSelector, ROOT_INSTANCE_ID];
}
);

export const $availableVariables = computed(
export const $definedComputedStyles = computed(
[
$definedStyles,
$model,
$instanceAndRootSelector,
$selectedOrLastStyleSourceSelector,
],
(definedStyles, model, instanceSelector, styleSourceSelector) => {
const availableVariables = new Map<string, VarValue>();
const computedStyles = new Map<string, ComputedStyleDecl>();
for (const { property } of definedStyles) {
if (property.startsWith("--")) {
const { computedValue } = getComputedStyleDecl({
model,
instanceSelector,
styleSourceId: styleSourceSelector?.styleSourceId,
state: styleSourceSelector?.state,
property,
});
// deduplicate by property name
availableVariables.set(property, {
// deduplicate by property name
if (computedStyles.has(property)) {
continue;
}
const computedStyleDecl = getComputedStyleDecl({
model,
instanceSelector,
styleSourceId: styleSourceSelector?.styleSourceId,
state: styleSourceSelector?.state,
property,
});
computedStyles.set(property, computedStyleDecl);
}
return Array.from(computedStyles.values());
}
);

export const $availableVariables = computed(
$definedComputedStyles,
(computedStyles) => {
const availableVariables: VarValue[] = [];
for (const styleDecl of computedStyles) {
if (styleDecl.property.startsWith("--")) {
availableVariables.push({
type: "var",
value: property.slice(2),
fallback: toVarFallback(computedValue),
value: styleDecl.property.slice(2),
fallback: toVarFallback(styleDecl.computedValue),
});
}
}
return Array.from(availableVariables.values());
return availableVariables;
}
);

Expand Down
5 changes: 2 additions & 3 deletions apps/builder/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"dependencies": {
"@atlaskit/pragmatic-drag-and-drop": "^1.3.1",
"@codemirror/autocomplete": "^6.18.1",
"@codemirror/commands": "^6.7.0",
"@codemirror/commands": "^6.7.1",
"@codemirror/lang-css": "^6.3.0",
"@codemirror/lang-html": "^6.4.9",
"@codemirror/lang-javascript": "^6.2.2",
Expand All @@ -36,7 +36,7 @@
"@lexical/react": "^0.16.0",
"@lexical/selection": "^0.16.0",
"@lexical/utils": "^0.16.0",
"@lezer/common": "^1.2.2",
"@lezer/common": "^1.2.3",
"@lezer/css": "^1.1.9",
"@lezer/highlight": "^1.2.1",
"@nanostores/react": "^0.7.1",
Expand All @@ -60,7 +60,6 @@
"@webstudio-is/dashboard": "workspace:*",
"@webstudio-is/design-system": "workspace:*",
"@webstudio-is/domain": "workspace:*",
"@webstudio-is/error-utils": "workspace:*",
"@webstudio-is/feature-flags": "workspace:*",
"@webstudio-is/fonts": "workspace:*",
"@webstudio-is/http-client": "workspace:*",
Expand Down
Loading