Skip to content

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.

experimental: Use css editor in keyframes (#4952)

Oleg Isonen62b0418476f6
diff --git a/apps/builder/app/builder/features/navigator/css-preview.tsx b/apps/builder/app/builder/features/navigator/css-preview.tsx
index e75584d440..a21edb2965 100644
--- a/apps/builder/app/builder/features/navigator/css-preview.tsx
+++ b/apps/builder/app/builder/features/navigator/css-preview.tsx
@@ -11,7 +11,7 @@ import type { StyleMap } from "@webstudio-is/css-engine";
import { CollapsibleSection } from "~/builder/shared/collapsible-section";
import { highlightCss } from "~/builder/shared/code-highlight";
import type { ComputedStyleDecl } from "~/shared/style-object-model";
-import { $definedComputedStyles } from "~/builder/features/style-panel/shared/model";
+import { $computedStyleDeclarations } from "~/builder/features/style-panel/shared/model";
import { $selectedInstance } from "~/shared/awareness";
const preStyle = css(textVariants.mono, {
@@ -71,12 +71,12 @@ const getCssText = (
};
const $highlightedCss = computed(
- [$selectedInstance, $definedComputedStyles],
- (instance, definedComputedStyles) => {
+ [$selectedInstance, $computedStyleDeclarations],
+ (instance, computedStyleDeclarations) => {
if (instance === undefined) {
return;
}
- const cssText = getCssText(definedComputedStyles, instance.id);
+ const cssText = getCssText(computedStyleDeclarations, instance.id);
return highlightCss(cssText);
}
);
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx
index 4a4fa7f3ea..d5f1f87fc7 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx
+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx
@@ -1,7 +1,9 @@
-import { parseCss } from "@webstudio-is/css-data";
-import { StyleValue, toValue } from "@webstudio-is/css-engine";
import {
- Text,
+ StyleValue,
+ toValue,
+ type CssProperty,
+} from "@webstudio-is/css-engine";
+import {
Grid,
IconButton,
Label,
@@ -9,7 +11,11 @@ import {
Tooltip,
ScrollArea,
theme,
+ SectionTitle,
+ SectionTitleButton,
+ SectionTitleLabel,
Box,
+ Button,
} from "@webstudio-is/design-system";
import { MinusIcon, PlusIcon } from "@webstudio-is/icons";
import type { AnimationKeyframe } from "@webstudio-is/sdk";
@@ -18,10 +24,10 @@ import {
CssValueInput,
type IntermediateStyleValue,
} from "~/builder/features/style-panel/shared/css-value-input";
-import { toKebabCase } from "~/builder/features/style-panel/shared/keyword-utils";
-import { CodeEditor } from "~/builder/shared/code-editor";
import { useIds } from "~/shared/form-utils";
import { calcOffsets, findInsertionIndex, moveItem } from "./keyframe-helpers";
+import { CssEditor, type CssEditorApi } from "~/builder/shared/css-editor";
+import type { ComputedStyleDecl } from "~/shared/style-object-model";
const unitOptions = [
{
@@ -125,21 +131,32 @@ const Keyframe = ({
onChange: (value: AnimationKeyframe | undefined) => void;
}) => {
const ids = useIds(["offset"]);
+ const apiRef = useRef<CssEditorApi>();
- const cssProperties = useMemo(() => {
- let result = ``;
- for (const [property, style] of Object.entries(value.styles)) {
- result = `${result}${toKebabCase(property)}: ${toValue(style)};\n`;
- }
- return result;
- }, [value.styles]);
+ const declarations: Array<ComputedStyleDecl> = useMemo(
+ () =>
+ (Object.keys(value.styles) as Array<CssProperty>).map((property) => {
+ const styleValue = value.styles[property];
+ return {
+ property,
+ source: { name: "local" },
+ cascadedValue: styleValue,
+ computedValue: styleValue,
+ usedValue: styleValue,
+ };
+ }),
+ [value.styles]
+ );
return (
<>
<Grid
gap={1}
align={"center"}
- css={{ gridTemplateColumns: "1fr 1fr auto" }}
+ css={{
+ gridTemplateColumns: "1fr 1fr auto",
+ paddingInline: theme.panel.paddingInline,
+ }}
>
<Label htmlFor={ids.offset}>Offset</Label>
<OffsetInput
@@ -157,25 +174,49 @@ const Keyframe = ({
</Tooltip>
</Grid>
<Grid>
- <CodeEditor
- lang="css-properties"
- size="keyframe"
- value={cssProperties}
- onChange={() => {
- /* do nothing */
+ <CssEditor
+ showSearch={false}
+ propertiesPosition="top"
+ virtualize={false}
+ declarations={declarations}
+ apiRef={apiRef}
+ onAddDeclarations={(addedStyleMap) => {
+ const styles = { ...value.styles };
+ for (const [property, value] of addedStyleMap) {
+ styles[property] = value;
+ }
+ onChange({ ...value, styles });
+ }}
+ onDeleteProperty={(property, options = {}) => {
+ if (options.isEphemeral === true) {
+ return;
+ }
+ const styles = { ...value.styles };
+ delete styles[property];
+ onChange({ ...value, styles });
}}
- onChangeComplete={(cssText) => {
- const parsedStyles = parseCss(`selector{${cssText}}`);
- onChange({
- ...value,
- styles: parsedStyles.reduce(
- (r, { property, value }) => ({ ...r, [property]: value }),
- {}
- ),
- });
+ onSetProperty={(property) => {
+ return (newValue) => {
+ const styles = { ...value.styles, [property]: newValue };
+ onChange({ ...value, styles });
+ };
+ }}
+ onDeleteAllDeclarations={() => {
+ onChange({ ...value, styles: {} });
}}
/>
</Grid>
+ <Box css={{ paddingInline: theme.panel.paddingInline }}>
+ <Button
+ onClick={() => {
+ apiRef.current?.showAddStyleInput();
+ }}
+ prefix={<PlusIcon />}
+ color="ghost"
+ >
+ Add
+ </Button>
+ </Box>
</>
);
};
@@ -187,8 +228,6 @@ export const Keyframes = ({
value: AnimationKeyframe[];
onChange: (value: AnimationKeyframe[]) => void;
}) => {
- const ids = useIds(["addKeyframe"]);
-
// To preserve focus on children swap
const keyRefs = useRef(
Array.from({ length: keyframes.length }, (_, index) => index)
@@ -204,43 +243,24 @@ export const Keyframes = ({
const offsets = calcOffsets(keyframes);
return (
- <Grid
- css={{
- minHeight: 0,
- }}
- gap={1}
- >
- <Grid
- gap={1}
- align={"center"}
- css={{
- paddingInline: theme.panel.paddingInline,
- gridTemplateColumns: "1fr auto",
- }}
- >
- <Label htmlFor={ids.addKeyframe}>
- <Text variant={"titles"}>Keyframes</Text>
- </Label>
- <IconButton
- id={ids.addKeyframe}
- onClick={() => {
- onChange([...keyframes, { offset: undefined, styles: {} }]);
- keyRefs.current = [...keyRefs.current, keyframes.length];
- }}
- >
- <PlusIcon />
- </IconButton>
- </Grid>
- <Box
- css={{
- paddingInline: theme.panel.paddingInline,
- }}
+ <Grid gap={1}>
+ <SectionTitle
+ collapsible={false}
+ suffix={
+ <SectionTitleButton
+ tabIndex={0}
+ prefix={<PlusIcon />}
+ onClick={() => {
+ onChange([...keyframes, { offset: undefined, styles: {} }]);
+ keyRefs.current = [...keyRefs.current, keyframes.length];
+ }}
+ />
+ }
>
- <Separator />
- </Box>
-
+ <SectionTitleLabel>Keyframes</SectionTitleLabel>
+ </SectionTitle>
<ScrollArea>
- <Grid gap={2} css={{ padding: theme.panel.padding }}>
+ <Grid gap={2}>
{keyframes.map((value, index) => (
<Fragment key={keyRefs.current[index]}>
{index > 0 && <Separator />}
diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.tsx b/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.tsx
index 3242ccee2d..8269c28767 100644
--- a/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.tsx
@@ -20,7 +20,7 @@ import {
import { useComputedStyles } from "../../shared/model";
import { getDots } from "../../shared/style-section";
import { CssEditor, type CssEditorApi } from "../../../../shared/css-editor";
-import { $advancedStylesLonghands } from "./stores";
+import { $advancedStyleDeclarations } from "./stores";
import { $selectedInstanceKey } from "~/shared/awareness";
import { getSetting } from "~/builder/shared/client-settings";
@@ -38,7 +38,6 @@ const AdvancedStyleSection = (props: {
const styles = useComputedStyles(properties);
return (
<CollapsibleSectionRoot
- label={label}
isOpen={isOpen}
onOpenChange={setIsOpen}
fullWidth
@@ -65,9 +64,11 @@ const AdvancedStyleSection = (props: {
};
export const Section = () => {
- const styleMap = useStore($advancedStylesLonghands);
+ const advancedStyleDeclarations = useStore($advancedStyleDeclarations);
const apiRef = useRef<CssEditorApi>();
- const properties = Array.from(styleMap.keys());
+ const properties = advancedStyleDeclarations.map(
+ (styleDecl) => styleDecl.property
+ );
const selectedInstanceKey = useStore($selectedInstanceKey);
// Memorizing recent properties by instance id, so that when user switches between instances and comes back
// they are still in-place
@@ -135,7 +136,7 @@ export const Section = () => {
}}
>
<CssEditor
- styleMap={styleMap}
+ declarations={advancedStyleDeclarations}
onDeleteProperty={handleDeleteProperty}
onSetProperty={setProperty}
onAddDeclarations={handleAddDeclarations}
diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/stores.ts b/apps/builder/app/builder/features/style-panel/sections/advanced/stores.ts
index 06a9410130..2573fd6681 100644
--- a/apps/builder/app/builder/features/style-panel/sections/advanced/stores.ts
+++ b/apps/builder/app/builder/features/style-panel/sections/advanced/stores.ts
@@ -1,14 +1,10 @@
import { computed } from "nanostores";
-import type { CssProperty, CssStyleMap } from "@webstudio-is/css-engine";
-import { $matchingBreakpoints, getDefinedStyles } from "../../shared/model";
+import type { CssProperty } from "@webstudio-is/css-engine";
+import { $computedStyleDeclarations } from "../../shared/model";
import { sections } from "../sections";
-import {
- $registeredComponentMetas,
- $styles,
- $styleSourceSelections,
-} from "~/shared/nano-states";
-import { $selectedInstancePath } from "~/shared/awareness";
import { $settings } from "~/builder/shared/client-settings";
+import type { ComputedStyleDecl } from "~/shared/style-object-model";
+import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
// @todo will be fully deleted https://github.com/webstudio-is/webstudio/issues/4871
const initialProperties = new Set<CssProperty>([
@@ -19,39 +15,10 @@ const initialProperties = new Set<CssProperty>([
"user-select",
]);
-export const $advancedStylesLonghands = computed(
- [
- // prevent showing properties inherited from root
- // to not bloat advanced panel
- $selectedInstancePath,
- $registeredComponentMetas,
- $styleSourceSelections,
- $matchingBreakpoints,
- $styles,
- $settings,
- ],
- (
- instancePath,
- metas,
- styleSourceSelections,
- matchingBreakpoints,
- styles,
- settings
- ) => {
- const advancedStyles: CssStyleMap = new Map();
-
- if (instancePath === undefined) {
- return advancedStyles;
- }
-
- const definedStyles = getDefinedStyles({
- instancePath,
- metas,
- matchingBreakpoints,
- styleSourceSelections,
- styles,
- });
-
+export const $advancedStyleDeclarations = computed(
+ [$computedStyleDeclarations, $settings],
+ (computedStyleDeclarations, settings) => {
+ const advancedStyles: Array<ComputedStyleDecl> = [];
// All properties used by the panels except the advanced panel
const visualProperties = new Set<CssProperty>([]);
for (const { properties } of sections.values()) {
@@ -59,24 +26,36 @@ export const $advancedStylesLonghands = computed(
visualProperties.add(property);
}
}
- for (const style of definedStyles) {
- const { property, value, listed } = style;
- const hyphenatedProperty = property;
+ for (const styleDecl of computedStyleDeclarations) {
+ // We don't want to show the massive amount of root variables on child instances.
+ // @todo add filters to the UI to allow user decide.
+ if (
+ styleDecl.source.name === "remote" &&
+ styleDecl.source.instanceId === ROOT_INSTANCE_ID
+ ) {
+ continue;
+ }
+ const { property, listed } = styleDecl;
// When property is listed, it was added from advanced panel.
// If we are in advanced mode, we show them all.
if (
- visualProperties.has(hyphenatedProperty) === false ||
+ visualProperties.has(property) === false ||
listed ||
settings.stylePanelMode === "advanced"
) {
- advancedStyles.set(hyphenatedProperty, value);
+ advancedStyles.push(styleDecl);
}
}
// In advanced mode we assume user knows the properties they need, so we don't need to show these.
// @todo https://github.com/webstudio-is/webstudio/issues/4871
if (settings.stylePanelMode !== "advanced") {
- for (const initialProperty of initialProperties) {
- advancedStyles.set(initialProperty, { type: "guaranteedInvalid" });
+ for (const property of initialProperties) {
+ const styleDecl = computedStyleDeclarations.find(
+ (styleDecl) => styleDecl.property === property
+ );
+ if (styleDecl) {
+ advancedStyles.push(styleDecl);
+ }
}
}
diff --git a/apps/builder/app/builder/features/style-panel/sections/transitions/transition-property.tsx b/apps/builder/app/builder/features/style-panel/sections/transitions/transition-property.tsx
index cda5a09597..8c4d3032c5 100644
--- a/apps/builder/app/builder/features/style-panel/sections/transitions/transition-property.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/transitions/transition-property.tsx
@@ -23,7 +23,7 @@ import {
type UnparsedValue,
} from "@webstudio-is/css-engine";
import { setUnion } from "~/shared/shim";
-import { $definedStyles } from "../../shared/model";
+import { $computedStyleDeclarations } from "../../shared/model";
type AnimatableProperty = (typeof animatableProperties)[number];
@@ -65,10 +65,10 @@ const commonPropertiesSet = new Set(commonTransitionProperties);
* on current breakpoints across all states
*/
const $animatableDefinedProperties = computed(
- [$definedStyles],
- (definedStyles) => {
+ [$computedStyleDeclarations],
+ (computedStyleDeclarations) => {
const animatableProperties = new Set<string>();
- for (const { property } of definedStyles) {
+ for (const { property } of computedStyleDeclarations) {
if (isAnimatableProperty(property)) {
animatableProperties.add(property);
}
diff --git a/apps/builder/app/builder/features/style-panel/shared/model.tsx b/apps/builder/app/builder/features/style-panel/shared/model.tsx
index 5b0bd17df6..1b88a0f1e2 100644
--- a/apps/builder/app/builder/features/style-panel/shared/model.tsx
+++ b/apps/builder/app/builder/features/style-panel/shared/model.tsx
@@ -18,7 +18,6 @@ import {
type StyleSourceSelections,
type Breakpoint,
type Instance,
- type StyleDecl,
type WsComponentMeta,
} from "@webstudio-is/sdk";
import { rootComponent } from "@webstudio-is/sdk";
@@ -129,12 +128,7 @@ export const $matchingBreakpoints = computed(
}
);
-export type DefinedStyleDecl = Pick<StyleDecl, "listed" | "value"> & {
- property: CssProperty;
- styleSourceId: undefined | StyleDecl["styleSourceId"];
-};
-
-export const getDefinedStyles = ({
+const getDefinedStyles = ({
instancePath,
metas,
matchingBreakpoints: matchingBreakpointsArray,
@@ -147,24 +141,25 @@ export const getDefinedStyles = ({
styleSourceSelections: StyleSourceSelections;
styles: Styles;
}) => {
+ type Defined = {
+ property: CssProperty;
+ listed?: boolean;
+ };
+
const inheritedStyleSources = new Set();
const instanceStyleSources = new Set();
const matchingBreakpoints = new Set(matchingBreakpointsArray);
const startingInstanceSelector = instancePath[0].instanceSelector;
- const instanceStyles = new Set<DefinedStyleDecl>();
- const inheritedStyles = new Set<DefinedStyleDecl>();
- const presetStyles = new Set<DefinedStyleDecl>();
+ const instanceStyles = new Set<Defined>();
+ const inheritedStyles = new Set<Defined>();
+ const presetStyles = new Set<Defined>();
for (const { instance } of instancePath) {
const meta = metas.get(instance.component);
for (const preset of Object.values(meta?.presetStyle ?? {})) {
for (const styleDecl of preset) {
- presetStyles.add({
- styleSourceId: undefined,
- property: styleDecl.property,
- value: styleDecl.value,
- });
+ presetStyles.add({ property: styleDecl.property });
}
}
const styleSources = styleSourceSelections.get(instance.id)?.values;
@@ -185,9 +180,7 @@ export const getDefinedStyles = ({
instanceStyleSources.has(styleDecl.styleSourceId)
) {
instanceStyles.add({
- styleSourceId: styleDecl.styleSourceId,
property,
- value: styleDecl.value,
listed: styleDecl.listed,
});
}
@@ -199,9 +192,7 @@ export const getDefinedStyles = ({
inherited
) {
inheritedStyles.add({
- styleSourceId: styleDecl.styleSourceId,
property,
- value: styleDecl.value,
listed: styleDecl.listed,
});
}
@@ -212,35 +203,13 @@ export const getDefinedStyles = ({
return Intl.Collator().compare(a.property, b.property);
};
- return new Set([
+ return [
...Array.from(instanceStyles).sort(sortByProperty),
...Array.from(inheritedStyles).sort(sortByProperty),
...Array.from(presetStyles).sort(sortByProperty),
- ]);
+ ];
};
-export const $definedStyles = computed(
- [
- $selectedInstancePathWithRoot,
- $registeredComponentMetas,
- $styleSourceSelections,
- $matchingBreakpoints,
- $styles,
- ],
- (instancePath, metas, styleSourceSelections, matchingBreakpoints, styles) => {
- if (instancePath === undefined) {
- return new Set<DefinedStyleDecl>();
- }
- return getDefinedStyles({
- instancePath,
- metas,
- matchingBreakpoints,
- styleSourceSelections,
- styles,
- });
- }
-);
-
const $model = computed(
[
$styles,
@@ -272,20 +241,37 @@ const $model = computed(
}
);
-/**
- * Will be deleted along with CSS Preview.
- * @deprecated
- */
-export const $definedComputedStyles = computed(
+export const $computedStyleDeclarations = computed(
[
- $definedStyles,
$model,
$selectedInstancePathWithRoot,
$selectedOrLastStyleSourceSelector,
+ $registeredComponentMetas,
+ $matchingBreakpoints,
+ $styleSourceSelections,
+ $styles,
],
- (definedStyles, model, instancePath, styleSourceSelector) => {
+ (
+ model,
+ instancePath,
+ styleSourceSelector,
+ metas,
+ matchingBreakpoints,
+ styleSourceSelections,
+ styles
+ ) => {
+ if (instancePath === undefined) {
+ return [];
+ }
+ const definedStyles = getDefinedStyles({
+ instancePath,
+ metas,
+ matchingBreakpoints,
+ styleSourceSelections,
+ styles,
+ });
const computedStyles = new Map<string, ComputedStyleDecl>();
- for (const { property } of definedStyles) {
+ for (const { property, listed } of definedStyles) {
// deduplicate by property name
if (computedStyles.has(property)) {
continue;
@@ -297,6 +283,10 @@ export const $definedComputedStyles = computed(
state: styleSourceSelector?.state,
property,
});
+ // @todo We will delete it once we have added additional filters to advanced panel and
+ // don't need to differentiate this any more.
+ computedStyleDecl.listed = listed;
+
computedStyles.set(property, computedStyleDecl);
}
return Array.from(computedStyles.values());
@@ -304,7 +294,7 @@ export const $definedComputedStyles = computed(
);
export const $availableVariables = computed(
- $definedComputedStyles,
+ $computedStyleDeclarations,
(computedStyles) => {
const availableVariables: VarValue[] = [];
for (const styleDecl of computedStyles) {
diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx
index a27d53bae5..5d8b35cacd 100644
--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx
@@ -61,7 +61,8 @@ import { useSortable } from "./use-sortable";
import { matchSorter } from "match-sorter";
import { StyleSourceBadge } from "./style-source-badge";
import { humanizeString } from "~/shared/string-utils";
-import { $definedStyles, type DefinedStyleDecl } from "../shared/model";
+import { $computedStyleDeclarations } from "../shared/model";
+import type { ComputedStyleDecl } from "~/shared/style-object-model";
type IntermediateItem = {
id: StyleSource["id"];
@@ -119,7 +120,7 @@ type TextFieldBaseWrapperProps<Item extends IntermediateItem> = Omit<
// Returns true if style source has defined styles including on the states.
const getHasStylesMap = <Item extends IntermediateItem>(
styleSourceItems: Array<Item>,
- definedStyles: Set<Partial<DefinedStyleDecl>>
+ computedStyleDeclarations: Array<ComputedStyleDecl>
) => {
const map = new Map<Item["id"], boolean>();
for (const item of styleSourceItems) {
@@ -127,8 +128,8 @@ const getHasStylesMap = <Item extends IntermediateItem>(
if (item.states.length > 0) {
map.set(item.id, true);
}
- for (const style of definedStyles) {
- if (item.id === style.styleSourceId) {
+ for (const style of computedStyleDeclarations) {
+ if (item.id === style.source.styleSourceId) {
map.set(item.id, true);
break;
}
@@ -177,14 +178,14 @@ const TextFieldBase: ForwardRefRenderFunction<
internalInputRef.current?.focus();
}, [internalInputRef]);
- const definedStyles = useStore($definedStyles);
+ const computedStyleDeclarations = useStore($computedStyleDeclarations);
const hasStyles = useCallback(
(styleSourceId: string) => {
- const hasStylesMap = getHasStylesMap(value, definedStyles);
+ const hasStylesMap = getHasStylesMap(value, computedStyleDeclarations);
return hasStylesMap.get(styleSourceId) ?? false;
},
- [value, definedStyles]
+ [value, computedStyleDeclarations]
);
return (
diff --git a/apps/builder/app/builder/shared/collapsible-section.tsx b/apps/builder/app/builder/shared/collapsible-section.tsx
index 1d7f499829..1d614e1b98 100644
--- a/apps/builder/app/builder/shared/collapsible-section.tsx
+++ b/apps/builder/app/builder/shared/collapsible-section.tsx
@@ -117,7 +117,7 @@ type CollapsibleSectionBaseProps = {
trigger?: ReactNode;
children: ReactNode;
fullWidth?: boolean;
- label: string;
+ label?: string;
isOpen?: boolean;
onOpenChange?: (value: boolean) => void;
};
diff --git a/apps/builder/app/builder/shared/css-editor/css-editor-context-menu.tsx b/apps/builder/app/builder/shared/css-editor/css-editor-context-menu.tsx
index 540200c466..7456675c81 100644
--- a/apps/builder/app/builder/shared/css-editor/css-editor-context-menu.tsx
+++ b/apps/builder/app/builder/shared/css-editor/css-editor-context-menu.tsx
@@ -13,20 +13,21 @@ import {
type CssProperty,
type CssStyleMap,
} from "@webstudio-is/css-engine";
+import type { ComputedStyleDecl } from "~/shared/style-object-model";
export const copyAttribute = "data-declaration";
export const CssEditorContextMenu = ({
children,
- properties,
- styleMap,
+ foundProperties,
+ declarations,
onPaste,
onDeleteProperty,
onDeleteAllDeclarations,
}: {
children: ReactNode;
- properties: Array<CssProperty>;
- styleMap: CssStyleMap;
+ foundProperties: Array<CssProperty>;
+ declarations: Array<ComputedStyleDecl>;
onPaste: (cssText: string) => void;
onDeleteProperty: (property: CssProperty) => void;
onDeleteAllDeclarations: (styleMap: CssStyleMap) => void;
@@ -42,10 +43,11 @@ export const CssEditorContextMenu = ({
// We want to only copy properties that are currently in front of the user.
// That includes search or any future filters.
const currentStyleMap: CssStyleMap = new Map();
- for (const [property, value] of styleMap) {
- const isEmpty = toValue(value) === "";
- if (properties.includes(property) && isEmpty === false) {
- currentStyleMap.set(property, value);
+
+ for (const styleDecl of declarations) {
+ const isEmpty = toValue(styleDecl.cascadedValue) === "";
+ if (foundProperties.includes(styleDecl.property) && isEmpty === false) {
+ currentStyleMap.set(styleDecl.property, styleDecl.cascadedValue);
}
}
return currentStyleMap;
@@ -63,20 +65,26 @@ export const CssEditorContextMenu = ({
if (property === undefined) {
return;
}
- const value = styleMap.get(property);
+ const styleDecl = declarations.find(
+ (styleDecl) => styleDecl.property === property
+ );
- if (value === undefined) {
+ if (styleDecl === undefined) {
return;
}
- const css = generateStyleMap(new Map([[property, value]]));
+ const css = generateStyleMap(
+ new Map([[styleDecl.property, styleDecl.cascadedValue]])
+ );
navigator.clipboard.writeText(css);
};
const handleDelete = () => {
const property = lastClickedProperty.current as CssProperty;
- const value = styleMap.get(property);
- if (value === undefined) {
+ const styleDecl = declarations.find(
+ (styleDecl) => styleDecl.property === property
+ );
+ if (styleDecl === undefined) {
return;
}
onDeleteProperty(property);
diff --git a/apps/builder/app/builder/shared/css-editor/css-editor.stories.tsx b/apps/builder/app/builder/shared/css-editor/css-editor.stories.tsx
index c09665ce2d..de55ece7f9 100644
--- a/apps/builder/app/builder/shared/css-editor/css-editor.stories.tsx
+++ b/apps/builder/app/builder/shared/css-editor/css-editor.stories.tsx
@@ -1,58 +1,31 @@
-import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
-import { registerContainers } from "~/shared/sync";
import { CssEditor as CssEditorComponent } from "./css-editor";
-import {
- $breakpoints,
- $instances,
- $selectedBreakpointId,
- $styles,
- $styleSourceSelections,
-} from "~/shared/nano-states";
-import { setProperty } from "../../features/style-panel/shared/use-style-data";
-import { $awareness } from "~/shared/awareness";
-import type { CssStyleMap } from "@webstudio-is/css-engine";
-
-const backgroundImage: StyleDecl = {
- breakpointId: "base",
- styleSourceId: "local",
- property: "backgroundImage",
- value: {
- type: "layers",
- value: [{ type: "keyword", value: "none" }],
- },
-};
-
-registerContainers();
-$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
-$selectedBreakpointId.set("base");
-$styles.set(new Map([[getStyleDeclKey(backgroundImage), backgroundImage]]));
-$styleSourceSelections.set(
- new Map([["box", { instanceId: "box", values: ["local"] }]])
-);
-$instances.set(
- new Map([
- ["box", { type: "instance", id: "box", component: "Box", children: [] }],
- ])
-);
-$awareness.set({
- pageId: "",
- instanceSelector: ["box"],
-});
-
-setProperty("accentColor")({ type: "keyword", value: "red" });
-setProperty("alignContent")({ type: "keyword", value: "normal" });
-setProperty("opacity")({ type: "unit", unit: "number", value: 11.2 });
+import type { ComputedStyleDecl } from "~/shared/style-object-model";
export const CssEditor = () => {
- const styleMap: CssStyleMap = new Map([
- ["background-image", backgroundImage.value],
+ const declarations = [
+ [
+ "background-image",
+ {
+ type: "layers",
+ value: [{ type: "keyword", value: "none" }],
+ },
+ ],
["accent-color", { type: "keyword", value: "red" }],
["align-content", { type: "keyword", value: "normal" }],
["opacity", { type: "unit", unit: "number", value: 11.2 }],
- ]);
+ ].map(([property, value]) => {
+ return {
+ property,
+ source: { name: "local" },
+ cascadedValue: value,
+ computedValue: value,
+ usedValue: value,
+ } as ComputedStyleDecl;
+ });
+
return (
<CssEditorComponent
- styleMap={styleMap}
+ declarations={declarations}
onDeleteProperty={() => undefined}
onSetProperty={() => () => undefined}
onAddDeclarations={() => undefined}
diff --git a/apps/builder/app/builder/shared/css-editor/css-editor.tsx b/apps/builder/app/builder/shared/css-editor/css-editor.tsx
index 0f2a056409..baf166a49a 100644
--- a/apps/builder/app/builder/shared/css-editor/css-editor.tsx
+++ b/apps/builder/app/builder/shared/css-editor/css-editor.tsx
@@ -35,10 +35,7 @@ import {
// @todo all style panel stuff needs to be moved to shared and/or decoupled from style panel
import { CssValueInputContainer } from "../../features/style-panel/shared/css-value-input";
import { styleConfigByName } from "../../features/style-panel/shared/configs";
-import {
- $availableVariables,
- useComputedStyleDecl,
-} from "../../features/style-panel/shared/model";
+import { $availableVariables } from "../../features/style-panel/shared/model";
import { PropertyInfo } from "../../features/style-panel/property-label";
import { ColorPopover } from "../../features/style-panel/shared/color-picker";
import { useClientSupports } from "~/shared/client-supports";
@@ -49,24 +46,25 @@ import type {
DeleteProperty,
SetProperty,
} from "../../features/style-panel/shared/use-style-data";
+import type { ComputedStyleDecl } from "~/shared/style-object-model";
// Used to indent the values when they are on the next line. This way its easier to see
// where the property ends and value begins, especially in case of presets.
const initialIndentation = `20px`;
const AdvancedPropertyLabel = ({
- property,
+ styleDecl,
onReset,
onDeleteProperty,
}: {
- property: CssProperty;
+ styleDecl: ComputedStyleDecl;
onReset?: () => void;
onDeleteProperty: DeleteProperty;
}) => {
- const styleDecl = useComputedStyleDecl(property);
const [isOpen, setIsOpen] = useState(false);
- const description = propertyDescriptions[camelCaseProperty(property)];
+ const description =
+ propertyDescriptions[camelCaseProperty(styleDecl.property)];
return (
<Tooltip
@@ -78,7 +76,7 @@ const AdvancedPropertyLabel = ({
onClick: (event) => {
if (event.altKey) {
event.preventDefault();
- onDeleteProperty(property);
+ onDeleteProperty(styleDecl.property);
onReset?.();
return;
}
@@ -87,16 +85,20 @@ const AdvancedPropertyLabel = ({
}}
content={
<PropertyInfo
- title={property.startsWith("--") ? "CSS Variable" : property}
+ title={
+ styleDecl.property.startsWith("--")
+ ? "CSS Variable"
+ : styleDecl.property
+ }
description={description}
styles={[styleDecl]}
onReset={() => {
- onDeleteProperty(property);
+ onDeleteProperty(styleDecl.property);
setIsOpen(false);
onReset?.();
}}
resetType="delete"
- link={propertiesData[property]?.mdnUrl}
+ link={propertiesData[styleDecl.property]?.mdnUrl}
/>
}
>
@@ -108,21 +110,21 @@ const AdvancedPropertyLabel = ({
marginLeft: `-${initialIndentation}`,
}}
>
- {property}
+ {styleDecl.property}
</Label>
</Tooltip>
);
};
const AdvancedPropertyValue = ({
- property,
+ styleDecl,
onDeleteProperty,
onSetProperty,
onChangeComplete,
onReset,
inputRef: inputRefProp,
}: {
- property: CssProperty;
+ styleDecl: ComputedStyleDecl;
onDeleteProperty: DeleteProperty;
onSetProperty: SetProperty;
onChangeComplete: ComponentProps<
@@ -131,9 +133,6 @@ const AdvancedPropertyValue = ({
onReset: ComponentProps<typeof CssValueInputContainer>["onReset"];
inputRef?: RefObject<HTMLInputElement>;
}) => {
- // @todo conversion should be removed once data is in dash case
- const camelCasedProperty = camelCaseProperty(property);
- const styleDecl = useComputedStyleDecl(camelCasedProperty);
const inputRef = useRef<HTMLInputElement>(null);
const isColor = colord(toValue(styleDecl.usedValue)).isValid();
@@ -150,21 +149,21 @@ const AdvancedPropertyValue = ({
onChange={(styleValue) => {
const options = { isEphemeral: true, listed: true };
if (styleValue) {
- onSetProperty(camelCasedProperty)(styleValue, options);
+ onSetProperty(styleDecl.property)(styleValue, options);
} else {
- onDeleteProperty(camelCasedProperty, options);
+ onDeleteProperty(styleDecl.property, options);
}
}}
onChangeComplete={(styleValue) => {
- onSetProperty(camelCasedProperty)(styleValue);
+ onSetProperty(styleDecl.property)(styleValue);
}}
/>
)
}
- property={camelCasedProperty}
+ property={styleDecl.property}
styleSource={styleDecl.source.name}
getOptions={() => [
- ...styleConfigByName(camelCasedProperty).items.map((item) => ({
+ ...styleConfigByName(styleDecl.property).items.map((item) => ({
type: "keyword" as const,
value: item.name,
})),
@@ -176,12 +175,12 @@ const AdvancedPropertyValue = ({
styleValue.type === "keyword" &&
styleValue.value.startsWith("--")
) {
- onSetProperty(camelCasedProperty)(
+ onSetProperty(styleDecl.property)(
{ type: "var", value: styleValue.value.slice(2) },
{ ...options, listed: true }
);
} else {
- onSetProperty(camelCasedProperty)(styleValue, {
+ onSetProperty(styleDecl.property)(styleValue, {
...options,
listed: true,
});
@@ -254,7 +253,7 @@ const LazyRender = ({ children }: ComponentProps<"div">) => {
const AdvancedDeclarationLonghand = memo(
({
- property,
+ styleDecl,
onChangeComplete,
onDeleteProperty,
onSetProperty,
@@ -262,7 +261,7 @@ const AdvancedDeclarationLonghand = memo(
valueInputRef,
indentation = initialIndentation,
}: {
- property: CssProperty;
+ styleDecl: ComputedStyleDecl;
indentation?: string;
onReset?: () => void;
onSetProperty: SetProperty;
@@ -278,10 +277,10 @@ const AdvancedDeclarationLonghand = memo(
wrap="wrap"
align="center"
justify="start"
- {...{ [copyAttribute]: property }}
+ {...{ [copyAttribute]: styleDecl.property }}
>
<AdvancedPropertyLabel
- property={property}
+ styleDecl={styleDecl}
onReset={onReset}
onDeleteProperty={onDeleteProperty}
/>
@@ -296,7 +295,7 @@ const AdvancedDeclarationLonghand = memo(
:
</Text>
<AdvancedPropertyValue
- property={property}
+ styleDecl={styleDecl}
onChangeComplete={onChangeComplete}
onReset={onReset}
onDeleteProperty={onDeleteProperty}
@@ -315,27 +314,32 @@ export const CssEditor = ({
onSetProperty,
onAddDeclarations,
onDeleteAllDeclarations,
- styleMap,
+ declarations,
apiRef,
showSearch = true,
+ virtualize = true,
+ propertiesPosition = "bottom",
recentProperties = [],
memorizeMinHeight = true,
}: {
+ declarations: Array<ComputedStyleDecl>;
onDeleteProperty: DeleteProperty;
onSetProperty: SetProperty;
onAddDeclarations: (styleMap: CssStyleMap) => void;
onDeleteAllDeclarations: (styleMap: CssStyleMap) => void;
- styleMap: CssStyleMap;
apiRef?: RefObject<CssEditorApi>;
showSearch?: boolean;
// When used as part of some larger scroll area to avoid scroll jumps during search.
// For example advanced section in the style panel.
memorizeMinHeight?: boolean;
+ propertiesPosition?: "top" | "bottom";
+ virtualize?: boolean;
recentProperties?: Array<CssProperty>;
}) => {
const [isAdding, setIsAdding] = useState(false);
const addPropertyInputRef = useRef<HTMLInputElement>(null);
- const recentValueInputRef = useRef<HTMLInputElement>(null);
+ const lastRecentValueInputRef = useRef<HTMLInputElement>(null);
+ const lastRegularValueInputRef = useRef<HTMLInputElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);
const [searchProperties, setSearchProperties] =
useState<Array<CssProperty>>();
@@ -347,7 +351,11 @@ export const CssEditor = ({
},
}));
- const advancedProperties = Array.from(styleMap.keys());
+ const declarationsMap = new Map(
+ declarations.map((decl) => [decl.property, decl])
+ );
+
+ const advancedProperties = declarations.map(({ property }) => property);
const currentProperties =
searchProperties ??
@@ -390,15 +398,12 @@ export const CssEditor = ({
setMinHeight(containerRef.current?.getBoundingClientRect().height ?? 0);
}
- const styles = [];
- for (const [property, value] of styleMap) {
- styles.push({
- // Allows searching for property or value and using something like this:
- // "gr te co" -> "grid-template-columns"
- key: `${property.replaceAll("-", " ")} ${toValue(value)}`,
+ const styles = declarations.map(({ property, cascadedValue }) => {
+ return {
+ key: `${property.replaceAll("-", " ")} ${toValue(cascadedValue)}`,
property,
- });
- }
+ };
+ });
const matched = matchSorter(styles, search, {
keys: ["key"],
@@ -411,7 +416,11 @@ export const CssEditor = ({
setIsAdding(false);
requestAnimationFrame(() => {
// We are either focusing the last value input from the recent list if available or the search input.
- const element = recentValueInputRef.current ?? searchInputRef.current;
+ const element =
+ lastRecentValueInputRef.current ??
+ lastRegularValueInputRef.current ??
+ searchInputRef.current;
+
element?.focus();
element?.select();
});
@@ -436,6 +445,63 @@ export const CssEditor = ({
onDeleteAllDeclarations(styleMap);
};
+ const recentPropertiesAndAddStyleInput = (
+ <Flex
+ direction="column"
+ css={{ paddingInline: theme.panel.paddingInline, gap: 2 }}
+ >
+ {showRecentProperties &&
+ recentProperties.map((property) => {
+ const styleDecl = declarationsMap.get(property);
+ if (styleDecl === undefined) {
+ return;
+ }
+ return (
+ <AdvancedDeclarationLonghand
+ styleDecl={styleDecl}
+ key={property}
+ valueInputRef={lastRecentValueInputRef}
+ onChangeComplete={(event) => {
+ if (event.type === "enter") {
+ handleShowAddStyleInput();
+ }
+ }}
+ onReset={afterChangingStyles}
+ onDeleteProperty={handleDeleteProperty}
+ onSetProperty={onSetProperty}
+ />
+ );
+ })}
+ <Box
+ css={
+ isAdding
+ ? { paddingTop: theme.spacing[3] }
+ : // We hide it visually so you can tab into it to get shown.
+ { overflow: "hidden", height: 0 }
+ }
+ >
+ <AddStyleInput
+ onSubmit={(cssText: string) => {
+ const styles = handleInsertStyles(cssText);
+ if (styles.size > 0) {
+ afterChangingStyles();
+ }
+ }}
+ onClose={afterChangingStyles}
+ onFocus={() => {
+ if (isAdding === false) {
+ handleShowAddStyleInput();
+ }
+ }}
+ onBlur={() => {
+ setIsAdding(false);
+ }}
+ ref={addPropertyInputRef}
+ />
+ </Box>
+ </Flex>
+ );
+
return (
<>
{showSearch && (
@@ -451,66 +517,18 @@ export const CssEditor = ({
onPaste={handleInsertStyles}
onDeleteProperty={handleDeleteProperty}
onDeleteAllDeclarations={handleDeleteAllDeclarations}
- styleMap={styleMap}
- properties={
+ declarations={declarations}
+ foundProperties={
searchProperties ?? [...recentProperties, ...currentProperties]
}
>
<Flex gap="2" direction="column">
- <Flex
- direction="column"
- css={{ paddingInline: theme.panel.paddingInline, gap: 2 }}
- >
- {showRecentProperties &&
- recentProperties.map((property, index, properties) => {
- const isLast = index === properties.length - 1;
- return (
- <AdvancedDeclarationLonghand
- key={property}
- valueInputRef={isLast ? recentValueInputRef : undefined}
- property={property}
- onChangeComplete={(event) => {
- if (event.type === "enter") {
- handleShowAddStyleInput();
- }
- }}
- onReset={afterChangingStyles}
- onDeleteProperty={handleDeleteProperty}
- onSetProperty={onSetProperty}
- />
- );
- })}
- {(showRecentProperties || isAdding) && (
- <Box
- css={
- isAdding
- ? { paddingTop: theme.spacing[3] }
- : // We hide it visually so you can tab into it to get shown.
- { overflow: "hidden", height: 0 }
- }
- >
- <AddStyleInput
- onSubmit={(cssText: string) => {
- const styles = handleInsertStyles(cssText);
- if (styles.size > 0) {
- afterChangingStyles();
- }
- }}
- onClose={afterChangingStyles}
- onFocus={() => {
- if (isAdding === false) {
- handleShowAddStyleInput();
- }
- }}
- onBlur={() => {
- setIsAdding(false);
- }}
- ref={addPropertyInputRef}
- />
- </Box>
- )}
- </Flex>
- {showRecentProperties && <Separator />}
+ {propertiesPosition === "bottom" && (
+ <>
+ {recentPropertiesAndAddStyleInput}
+ {showRecentProperties && <Separator />}
+ </>
+ )}
<Flex
direction="column"
css={{ paddingInline: theme.panel.paddingInline, gap: 2 }}
@@ -518,17 +536,37 @@ export const CssEditor = ({
ref={containerRef}
>
{currentProperties.map((property) => {
- return (
- <LazyRender key={property}>
- <AdvancedDeclarationLonghand
- property={property}
- onDeleteProperty={handleDeleteProperty}
- onSetProperty={onSetProperty}
- />
- </LazyRender>
+ const styleDecl = declarationsMap.get(property);
+ if (styleDecl === undefined) {
+ return;
+ }
+
+ const declarationElement = (
+ <AdvancedDeclarationLonghand
+ styleDecl={styleDecl}
+ onDeleteProperty={handleDeleteProperty}
+ onSetProperty={onSetProperty}
+ valueInputRef={lastRegularValueInputRef}
+ key={property}
+ />
);
+ // When using it in keyframes with layout where delcarations are on top of add input button,
+ // we need to focus last added value, but the logic for waiting for the last rendered event would add up complexity.
+ // For now we just manually avoid virtualization in this layout.
+ if (virtualize) {
+ return (
+ <LazyRender key={property}>{declarationElement}</LazyRender>
+ );
+ }
+ return declarationElement;
})}
</Flex>
+ {propertiesPosition === "top" && (
+ <>
+ {showRecentProperties && <Separator />}
+ {recentPropertiesAndAddStyleInput}
+ </>
+ )}
</Flex>
</CssEditorContextMenu>
</>
diff --git a/apps/builder/app/shared/style-object-model.ts b/apps/builder/app/shared/style-object-model.ts
index a3d9f7cf79..0b82600251 100644
--- a/apps/builder/app/shared/style-object-model.ts
+++ b/apps/builder/app/shared/style-object-model.ts
@@ -286,6 +286,9 @@ export type ComputedStyleDecl = {
cascadedValue: StyleValue;
computedValue: StyleValue;
usedValue: StyleValue;
+ // @todo We will delete it once we have added additional filters to advanced panel and
+ // don't need to differentiate this any more.
+ listed?: boolean;
};
/**
diff --git a/packages/design-system/src/components/grid.tsx b/packages/design-system/src/components/grid.tsx
index 1e50b40350..8b0fe1c313 100644
--- a/packages/design-system/src/components/grid.tsx
+++ b/packages/design-system/src/components/grid.tsx
@@ -4,6 +4,7 @@ import { theme } from "../stitches.config";
export const Grid = styled("div", {
boxSizing: "border-box",
display: "grid",
+ minHeight: 0,
variants: {
align: {
diff --git a/packages/sdk/src/schema/animation-schema.ts b/packages/sdk/src/schema/animation-schema.ts
index 69628cfdd4..57ee7ca246 100644
--- a/packages/sdk/src/schema/animation-schema.ts
+++ b/packages/sdk/src/schema/animation-schema.ts
@@ -81,6 +81,7 @@ export const insetUnitValueSchema = z.union([
]);
// @todo: Fix Keyframe Styles
+// Can we use CssStyleMap for this? This type ends up not enforcing kebab case like.
export const keyframeStylesSchema = z.record(StyleValue);
// Animation Keyframe