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: Reusable css editor (#4945)

Oleg Isonen5ba9dc38a8f8
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 48a5e57e67..f9e813e103 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
@@ -1,66 +1,26 @@
-import { mergeRefs } from "@react-aria/utils";
-import { flushSync } from "react-dom";
-import { colord } from "colord";
-import {
- memo,
- useEffect,
- useRef,
- useState,
- type ChangeEvent,
- type ComponentProps,
- type ReactNode,
- type RefObject,
-} from "react";
+import { useRef, useState, type ReactNode } from "react";
import { useStore } from "@nanostores/react";
-import { matchSorter } from "match-sorter";
import { PlusIcon } from "@webstudio-is/icons";
import {
- Box,
- Flex,
- Label,
- SearchField,
SectionTitle,
SectionTitleButton,
SectionTitleLabel,
- Separator,
- Text,
- theme,
- Tooltip,
} from "@webstudio-is/design-system";
-import {
- camelCaseProperty,
- propertyDescriptions,
-} from "@webstudio-is/css-data";
-import {
- hyphenateProperty,
- toValue,
- type CssProperty,
-} from "@webstudio-is/css-engine";
+import { type CssProperty, type CssStyleMap } from "@webstudio-is/css-engine";
import {
CollapsibleSectionRoot,
useOpenState,
} from "~/builder/shared/collapsible-section";
-import { CssValueInputContainer } from "../../shared/css-value-input";
-import { styleConfigByName } from "../../shared/configs";
import {
createBatchUpdate,
deleteProperty,
setProperty,
+ type DeleteProperty,
} from "../../shared/use-style-data";
-import {
- $availableVariables,
- useComputedStyleDecl,
- useComputedStyles,
-} from "../../shared/model";
+import { useComputedStyles } from "../../shared/model";
import { getDots } from "../../shared/style-section";
-import { PropertyInfo } from "../../property-label";
-import { ColorPopover } from "../../shared/color-picker";
-import { useClientSupports } from "~/shared/client-supports";
-import { CopyPasteMenu, copyAttribute } from "./copy-paste-menu";
+import { CssEditor, type CssEditorApi } from "../../../../shared/css-editor";
import { $advancedStylesLonghands } from "./stores";
-import { $settings } from "~/builder/shared/client-settings";
-import { AddStyleInput } from "./add-style-input";
-import { parseStyleInput } from "./parse-style-input";
import { $selectedInstanceKey } from "~/shared/awareness";
// Only here to keep the same section module interface
@@ -103,296 +63,21 @@ const AdvancedStyleSection = (props: {
);
};
-const insertStyles = (css: string) => {
- const styleMap = parseStyleInput(css);
- if (styleMap.size === 0) {
- return new Map();
- }
- const batch = createBatchUpdate();
- for (const [property, value] of styleMap) {
- batch.setProperty(property as CssProperty)(value);
- }
- batch.publish({ listed: true });
- return styleMap;
-};
-
-// 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,
- onReset,
-}: {
- property: CssProperty;
- onReset?: () => void;
-}) => {
- const styleDecl = useComputedStyleDecl(property);
- const label = hyphenateProperty(property);
- const description = propertyDescriptions[camelCaseProperty(property)];
- const [isOpen, setIsOpen] = useState(false);
- return (
- <Tooltip
- open={isOpen}
- onOpenChange={setIsOpen}
- // prevent closing tooltip on content click
- onPointerDown={(event) => event.preventDefault()}
- triggerProps={{
- onClick: (event) => {
- if (event.altKey) {
- event.preventDefault();
- deleteProperty(property);
- onReset?.();
- return;
- }
- setIsOpen(true);
- },
- }}
- content={
- <PropertyInfo
- title={property.startsWith("--") ? "CSS Variable" : label}
- description={description}
- styles={[styleDecl]}
- onReset={() => {
- deleteProperty(property);
- setIsOpen(false);
- onReset?.();
- }}
- resetType="delete"
- />
- }
- >
- <Label
- color={styleDecl.source.name}
- text="mono"
- css={{
- backgroundColor: "transparent",
- marginLeft: `-${initialIndentation}`,
- }}
- >
- {label}
- </Label>
- </Tooltip>
- );
-};
-
-const AdvancedPropertyValue = ({
- property,
- onChangeComplete,
- onReset,
- inputRef: inputRefProp,
-}: {
- property: CssProperty;
- onChangeComplete: ComponentProps<
- typeof CssValueInputContainer
- >["onChangeComplete"];
- onReset: ComponentProps<typeof CssValueInputContainer>["onReset"];
- inputRef?: RefObject<HTMLInputElement>;
-}) => {
- // @todo conversion should be removed once data is in dash case
- const styleDecl = useComputedStyleDecl(property);
- const inputRef = useRef<HTMLInputElement>(null);
- const isColor = colord(toValue(styleDecl.usedValue)).isValid();
-
- return (
- <CssValueInputContainer
- inputRef={mergeRefs(inputRef, inputRefProp)}
- variant="chromeless"
- text="mono"
- fieldSizing="content"
- prefix={
- isColor && (
- <ColorPopover
- value={styleDecl.usedValue}
- onChange={(styleValue) => {
- const options = { isEphemeral: true, listed: true };
- if (styleValue) {
- setProperty(property)(styleValue, options);
- } else {
- deleteProperty(property, options);
- }
- }}
- onChangeComplete={(styleValue) => {
- setProperty(property)(styleValue);
- }}
- />
- )
- }
- property={property}
- styleSource={styleDecl.source.name}
- getOptions={() => [
- ...styleConfigByName(property).items.map((item) => ({
- type: "keyword" as const,
- value: item.name,
- })),
- ...$availableVariables.get(),
- ]}
- value={styleDecl.cascadedValue}
- setValue={(styleValue, options) => {
- if (
- styleValue.type === "keyword" &&
- styleValue.value.startsWith("--")
- ) {
- setProperty(property)(
- { type: "var", value: styleValue.value.slice(2) },
- { ...options, listed: true }
- );
- } else {
- setProperty(property)(styleValue, {
- ...options,
- listed: true,
- });
- }
- }}
- deleteProperty={deleteProperty}
- onChangeComplete={onChangeComplete}
- onReset={onReset}
- />
- );
-};
-
-/**
- * The Advanced section in the Style Panel on </> Global Root has performance issues.
- * To fix this, we skip rendering properties not visible in the viewport using the contentvisibilityautostatechange event,
- * and the contentVisibility and containIntrinsicSize CSS properties.
- */
-const LazyRender = ({ children }: ComponentProps<"div">) => {
- const visibilityChangeEventSupported = useClientSupports(
- () => "oncontentvisibilityautostatechange" in document.body
- );
- const ref = useRef<HTMLDivElement>(null);
- const [isVisible, setIsVisible] = useState(!visibilityChangeEventSupported);
-
- useEffect(() => {
- if (!visibilityChangeEventSupported) {
- return;
- }
-
- if (ref.current == null) {
- return;
- }
-
- const controller = new AbortController();
-
- ref.current.addEventListener(
- "contentvisibilityautostatechange",
- (event) => {
- setIsVisible(!event.skipped);
- },
- {
- signal: controller.signal,
- }
- );
-
- return () => {
- controller.abort();
- };
- }, [visibilityChangeEventSupported]);
-
- return (
- <div
- ref={ref}
- style={{
- display: "inline-block",
- contentVisibility: "auto",
- // https://developer.mozilla.org/en-US/docs/Web/CSS/contain-intrinsic-size
- // containIntrinsicSize is used to set the default size of an element before any content is loaded.
- // This helps in preventing layout shifts and provides a better user experience by maintaining a consistent layout.
- // It also affects the contentvisibilityautostatechange event to be called properly,
- // with "auto" it will call it with skipped false for all initial elements.
- // 44px is the height of the property row with 2 lines of text. This value can be adjusted slightly.
- containIntrinsicSize: "auto 44px",
- }}
- >
- {isVisible ? children : undefined}
- </div>
- );
-};
-
-const AdvancedDeclarationLonghand = memo(
- ({
- property,
- onChangeComplete,
- onReset,
- valueInputRef,
- indentation = initialIndentation,
- }: {
- property: CssProperty;
- indentation?: string;
- onReset?: () => void;
- onChangeComplete?: ComponentProps<
- typeof CssValueInputContainer
- >["onChangeComplete"];
- valueInputRef?: RefObject<HTMLInputElement>;
- }) => {
- return (
- <Flex
- css={{ paddingLeft: indentation }}
- wrap="wrap"
- align="center"
- justify="start"
- {...{ [copyAttribute]: property }}
- >
- <AdvancedPropertyLabel property={property} onReset={onReset} />
- <Text
- variant="mono"
- // Improves the visual separation of value from the property.
- css={{
- textIndent: "-0.5ch",
- fontWeight: "bold",
- }}
- >
- :
- </Text>
- <AdvancedPropertyValue
- property={property}
- onChangeComplete={onChangeComplete}
- onReset={onReset}
- inputRef={valueInputRef}
- />
- </Flex>
- );
- }
-);
-
export const Section = () => {
- const [isAdding, setIsAdding] = useState(false);
- const advancedStyles = useStore($advancedStylesLonghands);
+ const styleMap = useStore($advancedStylesLonghands);
+ const apiRef = useRef<CssEditorApi>();
+ const properties = Array.from(styleMap.keys()) as Array<CssProperty>;
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
const [recentPropertiesMap, setRecentPropertiesMap] = useState<
Map<string, Array<CssProperty>>
>(new Map());
- const addPropertyInputRef = useRef<HTMLInputElement>(null);
- const recentValueInputRef = useRef<HTMLInputElement>(null);
- const searchInputRef = useRef<HTMLInputElement>(null);
- const [searchProperties, setSearchProperties] =
- useState<Array<CssProperty>>();
- const containerRef = useRef<HTMLDivElement>(null);
- const [minHeight, setMinHeight] = useState<number>(0);
-
- const advancedProperties = Array.from(
- advancedStyles.keys()
- ) as Array<CssProperty>;
const recentProperties = selectedInstanceKey
? (recentPropertiesMap.get(selectedInstanceKey) ?? [])
: [];
- const currentProperties =
- searchProperties ??
- advancedProperties.filter(
- (property) => recentProperties.includes(property) === false
- );
-
- const showRecentProperties =
- recentProperties.length > 0 && searchProperties === undefined;
-
- const memorizeMinHeight = () => {
- setMinHeight(containerRef.current?.getBoundingClientRect().height ?? 0);
- };
-
const updateRecentProperties = (properties: Array<CssProperty>) => {
if (selectedInstanceKey === undefined) {
return;
@@ -405,153 +90,46 @@ export const Section = () => {
setRecentPropertiesMap(newRecentPropertiesMap);
};
- const handleInsertStyles = (cssText: string) => {
- const styleMap = insertStyles(cssText);
+ const handleAddProperties = (styleMap: CssStyleMap) => {
+ const batch = createBatchUpdate();
+ for (const [property, value] of styleMap) {
+ batch.setProperty(property as CssProperty)(value);
+ }
+ batch.publish({ listed: true });
+
const insertedProperties = Array.from(
styleMap.keys()
) as Array<CssProperty>;
updateRecentProperties([...recentProperties, ...insertedProperties]);
- return styleMap;
};
- const handleShowAddStyleInput = () => {
- flushSync(() => {
- setIsAdding(true);
- });
- // User can click twice on the add button, so we need to focus the input on the second click after autoFocus isn't working.
- addPropertyInputRef.current?.focus();
- };
+ const handleDeleteProperty: DeleteProperty = (property, options = {}) => {
+ deleteProperty(property, options);
- const handleAbortSearch = () => {
- setMinHeight(0);
- setSearchProperties(undefined);
- };
-
- const handleSearch = (event: ChangeEvent<HTMLInputElement>) => {
- const search = event.target.value.trim();
- if (search === "") {
- return handleAbortSearch();
- }
- // This is not needed in advanced mode because the input won't jump there as it is on top
- if ($settings.get().stylePanelMode !== "advanced") {
- memorizeMinHeight();
- }
-
- const styles = [];
- for (const [property, value] of advancedStyles) {
- styles.push({ property, value: toValue(value) });
+ if (options.isEphemeral === true) {
+ return;
}
-
- const matched = matchSorter(styles, search, {
- keys: ["property", "value"],
- }).map(({ property }) => property);
-
- setSearchProperties(matched as CssProperty[]);
- };
-
- const afterChangingStyles = () => {
- 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;
- element?.focus();
- element?.select();
- });
+ updateRecentProperties(
+ recentProperties.filter((recentProperty) => recentProperty !== property)
+ );
};
return (
<AdvancedStyleSection
label="Advanced"
- properties={advancedProperties}
- onAdd={handleShowAddStyleInput}
+ properties={properties}
+ onAdd={() => {
+ apiRef.current?.showAddStyleInput();
+ }}
>
- <Box css={{ paddingInline: theme.panel.paddingInline }}>
- <SearchField
- inputRef={searchInputRef}
- onChange={handleSearch}
- onAbort={handleAbortSearch}
- />
- </Box>
- <CopyPasteMenu
- onPaste={handleInsertStyles}
- properties={[...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={() => {
- updateRecentProperties(
- recentProperties.filter(
- (recentProperty) => recentProperty !== property
- )
- );
- afterChangingStyles();
- }}
- />
- );
- })}
- {(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 />}
- <Flex
- direction="column"
- css={{ paddingInline: theme.panel.paddingInline, gap: 2 }}
- style={{ minHeight }}
- ref={containerRef}
- >
- {currentProperties.map((property) => {
- return (
- <LazyRender key={property}>
- <AdvancedDeclarationLonghand property={property} />
- </LazyRender>
- );
- })}
- </Flex>
- </Flex>
- </CopyPasteMenu>
+ <CssEditor
+ styleMap={styleMap}
+ onDeleteProperty={handleDeleteProperty}
+ onSetProperty={setProperty}
+ onAddProperties={handleAddProperties}
+ apiRef={apiRef}
+ recentProperties={recentProperties}
+ />
</AdvancedStyleSection>
);
};
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 27489d8728..372b467a25 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
@@ -2,7 +2,7 @@ import { computed } from "nanostores";
import {
hyphenateProperty,
type CssProperty,
- type StyleMap,
+ type CssStyleMap,
} from "@webstudio-is/css-engine";
import { $matchingBreakpoints, getDefinedStyles } from "../../shared/model";
import { sections } from "../sections";
@@ -42,7 +42,7 @@ export const $advancedStylesLonghands = computed(
styles,
settings
) => {
- const advancedStyles: StyleMap = new Map();
+ const advancedStyles: CssStyleMap = new Map();
if (instancePath === undefined) {
return advancedStyles;
diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/add-style-input.tsx b/apps/builder/app/builder/shared/css-editor/add-style-input.tsx
similarity index 98%
rename from apps/builder/app/builder/features/style-panel/sections/advanced/add-style-input.tsx
rename to apps/builder/app/builder/shared/css-editor/add-style-input.tsx
index 276eb2e881..0a118a2809 100644
--- a/apps/builder/app/builder/features/style-panel/sections/advanced/add-style-input.tsx
+++ b/apps/builder/app/builder/shared/css-editor/add-style-input.tsx
@@ -30,7 +30,10 @@ import {
toValue,
type StyleProperty,
} from "@webstudio-is/css-engine";
-import { deleteProperty, setProperty } from "../../shared/use-style-data";
+import {
+ deleteProperty,
+ setProperty,
+} from "../../features/style-panel/shared/use-style-data";
import { composeEventHandlers } from "~/shared/event-utils";
import { parseStyleInput } from "./parse-style-input";
diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/copy-paste-menu.tsx b/apps/builder/app/builder/shared/css-editor/copy-paste-menu.tsx
similarity index 86%
rename from apps/builder/app/builder/features/style-panel/sections/advanced/copy-paste-menu.tsx
rename to apps/builder/app/builder/shared/css-editor/copy-paste-menu.tsx
index b449200940..63d98d0b0d 100644
--- a/apps/builder/app/builder/features/style-panel/sections/advanced/copy-paste-menu.tsx
+++ b/apps/builder/app/builder/shared/css-editor/copy-paste-menu.tsx
@@ -11,23 +11,23 @@ import {
hyphenateProperty,
mergeStyles,
toValue,
- type StyleMap,
+ type CssProperty,
+ type CssStyleMap,
} from "@webstudio-is/css-engine";
-import { useStore } from "@nanostores/react";
-import { $advancedStylesLonghands } from "./stores";
export const copyAttribute = "data-declaration";
export const CopyPasteMenu = ({
children,
properties,
+ styleMap,
onPaste,
}: {
children: ReactNode;
properties: Array<string>;
+ styleMap: CssStyleMap;
onPaste: (cssText: string) => void;
}) => {
- const advancedStylesLonghands = useStore($advancedStylesLonghands);
const lastClickedProperty = useRef<string>();
const handlePaste = () => {
@@ -37,8 +37,8 @@ export const CopyPasteMenu = ({
const handleCopyAll = () => {
// We want to only copy properties that are currently in front of the user.
// That includes search or any future filters.
- const currentStyleMap: StyleMap = new Map();
- for (const [property, value] of advancedStylesLonghands) {
+ const currentStyleMap: CssStyleMap = new Map();
+ for (const [property, value] of styleMap) {
const isEmpty = toValue(value) === "";
if (properties.includes(property) && isEmpty === false) {
currentStyleMap.set(hyphenateProperty(property), value);
@@ -55,7 +55,7 @@ export const CopyPasteMenu = ({
if (property === undefined) {
return;
}
- const value = advancedStylesLonghands.get(property);
+ const value = styleMap.get(property as CssProperty);
if (value === undefined) {
return;
diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.stories.tsx b/apps/builder/app/builder/shared/css-editor/css-editor.stories.tsx
similarity index 61%
rename from apps/builder/app/builder/features/style-panel/sections/advanced/advanced.stories.tsx
rename to apps/builder/app/builder/shared/css-editor/css-editor.stories.tsx
index 5d9fceabdf..2c6f41930f 100644
--- a/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.stories.tsx
+++ b/apps/builder/app/builder/shared/css-editor/css-editor.stories.tsx
@@ -1,6 +1,6 @@
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
import { registerContainers } from "~/shared/sync";
-import { Section } from "./advanced";
+import { CssEditor as CssEditorComponent } from "./css-editor";
import {
$breakpoints,
$instances,
@@ -8,8 +8,9 @@ import {
$styles,
$styleSourceSelections,
} from "~/shared/nano-states";
-import { setProperty } from "../../shared/use-style-data";
+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",
@@ -42,11 +43,24 @@ setProperty("accentColor")({ type: "keyword", value: "red" });
setProperty("alignContent")({ type: "keyword", value: "normal" });
setProperty("opacity")({ type: "unit", unit: "number", value: 11.2 });
-export const Advanced = () => {
- return <Section />;
+export const CssEditor = () => {
+ const styleMap: CssStyleMap = new Map([
+ ["background-image", backgroundImage.value],
+ ["accent-color", { type: "keyword", value: "red" }],
+ ["align-content", { type: "keyword", value: "normal" }],
+ ["opacity", { type: "unit", unit: "number", value: 11.2 }],
+ ]);
+ return (
+ <CssEditorComponent
+ styleMap={styleMap}
+ onDeleteProperty={() => undefined}
+ onSetProperty={() => () => undefined}
+ onAddProperties={() => undefined}
+ />
+ );
};
export default {
- title: "Style Panel/Advanced",
- component: Advanced,
+ title: "Style Panel",
+ component: CssEditor,
};
diff --git a/apps/builder/app/builder/shared/css-editor/css-editor.tsx b/apps/builder/app/builder/shared/css-editor/css-editor.tsx
new file mode 100644
index 0000000000..84d931e82a
--- /dev/null
+++ b/apps/builder/app/builder/shared/css-editor/css-editor.tsx
@@ -0,0 +1,502 @@
+import { mergeRefs } from "@react-aria/utils";
+import { flushSync } from "react-dom";
+import { colord } from "colord";
+import {
+ memo,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+ type ChangeEvent,
+ type ComponentProps,
+ type RefObject,
+} from "react";
+import { matchSorter } from "match-sorter";
+import {
+ Box,
+ Flex,
+ Label,
+ SearchField,
+ Separator,
+ Text,
+ theme,
+ Tooltip,
+} from "@webstudio-is/design-system";
+import {
+ camelCaseProperty,
+ propertyDescriptions,
+} from "@webstudio-is/css-data";
+import {
+ toValue,
+ type CssProperty,
+ type CssStyleMap,
+} from "@webstudio-is/css-engine";
+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 { PropertyInfo } from "../../features/style-panel/property-label";
+import { ColorPopover } from "../../features/style-panel/shared/color-picker";
+import { useClientSupports } from "~/shared/client-supports";
+import { CopyPasteMenu, copyAttribute } from "./copy-paste-menu";
+import { AddStyleInput } from "./add-style-input";
+import { parseStyleInput } from "./parse-style-input";
+import type {
+ DeleteProperty,
+ SetProperty,
+} from "../../features/style-panel/shared/use-style-data";
+
+// 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,
+ onReset,
+ onDeleteProperty,
+}: {
+ property: CssProperty;
+ onReset?: () => void;
+ onDeleteProperty: DeleteProperty;
+}) => {
+ const styleDecl = useComputedStyleDecl(property);
+ const description = propertyDescriptions[camelCaseProperty(property)];
+
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <Tooltip
+ open={isOpen}
+ onOpenChange={setIsOpen}
+ // prevent closing tooltip on content click
+ onPointerDown={(event) => event.preventDefault()}
+ triggerProps={{
+ onClick: (event) => {
+ if (event.altKey) {
+ event.preventDefault();
+ onDeleteProperty(property);
+ onReset?.();
+ return;
+ }
+ setIsOpen(true);
+ },
+ }}
+ content={
+ <PropertyInfo
+ title={property.startsWith("--") ? "CSS Variable" : property}
+ description={description}
+ styles={[styleDecl]}
+ onReset={() => {
+ onDeleteProperty(property);
+ setIsOpen(false);
+ onReset?.();
+ }}
+ resetType="delete"
+ />
+ }
+ >
+ <Label
+ color={styleDecl.source.name}
+ text="mono"
+ css={{
+ backgroundColor: "transparent",
+ marginLeft: `-${initialIndentation}`,
+ }}
+ >
+ {property}
+ </Label>
+ </Tooltip>
+ );
+};
+
+const AdvancedPropertyValue = ({
+ property,
+ onDeleteProperty,
+ onSetProperty,
+ onChangeComplete,
+ onReset,
+ inputRef: inputRefProp,
+}: {
+ property: CssProperty;
+ onDeleteProperty: DeleteProperty;
+ onSetProperty: SetProperty;
+ onChangeComplete: ComponentProps<
+ typeof CssValueInputContainer
+ >["onChangeComplete"];
+ 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();
+
+ return (
+ <CssValueInputContainer
+ inputRef={mergeRefs(inputRef, inputRefProp)}
+ variant="chromeless"
+ text="mono"
+ fieldSizing="content"
+ prefix={
+ isColor && (
+ <ColorPopover
+ value={styleDecl.usedValue}
+ onChange={(styleValue) => {
+ const options = { isEphemeral: true, listed: true };
+ if (styleValue) {
+ onSetProperty(camelCasedProperty)(styleValue, options);
+ } else {
+ onDeleteProperty(camelCasedProperty, options);
+ }
+ }}
+ onChangeComplete={(styleValue) => {
+ onSetProperty(camelCasedProperty)(styleValue);
+ }}
+ />
+ )
+ }
+ property={camelCasedProperty}
+ styleSource={styleDecl.source.name}
+ getOptions={() => [
+ ...styleConfigByName(camelCasedProperty).items.map((item) => ({
+ type: "keyword" as const,
+ value: item.name,
+ })),
+ ...$availableVariables.get(),
+ ]}
+ value={styleDecl.cascadedValue}
+ setValue={(styleValue, options) => {
+ if (
+ styleValue.type === "keyword" &&
+ styleValue.value.startsWith("--")
+ ) {
+ onSetProperty(camelCasedProperty)(
+ { type: "var", value: styleValue.value.slice(2) },
+ { ...options, listed: true }
+ );
+ } else {
+ onSetProperty(camelCasedProperty)(styleValue, {
+ ...options,
+ listed: true,
+ });
+ }
+ }}
+ deleteProperty={onDeleteProperty}
+ onChangeComplete={onChangeComplete}
+ onReset={onReset}
+ />
+ );
+};
+
+/**
+ * The Advanced section in the Style Panel on </> Global Root has performance issues.
+ * To fix this, we skip rendering properties not visible in the viewport using the contentvisibilityautostatechange event,
+ * and the contentVisibility and containIntrinsicSize CSS properties.
+ */
+const LazyRender = ({ children }: ComponentProps<"div">) => {
+ const visibilityChangeEventSupported = useClientSupports(
+ () => "oncontentvisibilityautostatechange" in document.body
+ );
+ const ref = useRef<HTMLDivElement>(null);
+ const [isVisible, setIsVisible] = useState(!visibilityChangeEventSupported);
+
+ useEffect(() => {
+ if (!visibilityChangeEventSupported) {
+ return;
+ }
+
+ if (ref.current == null) {
+ return;
+ }
+
+ const controller = new AbortController();
+
+ ref.current.addEventListener(
+ "contentvisibilityautostatechange",
+ (event) => {
+ setIsVisible(!event.skipped);
+ },
+ {
+ signal: controller.signal,
+ }
+ );
+
+ return () => {
+ controller.abort();
+ };
+ }, [visibilityChangeEventSupported]);
+
+ return (
+ <div
+ ref={ref}
+ style={{
+ display: "inline-block",
+ contentVisibility: "auto",
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/contain-intrinsic-size
+ // containIntrinsicSize is used to set the default size of an element before any content is loaded.
+ // This helps in preventing layout shifts and provides a better user experience by maintaining a consistent layout.
+ // It also affects the contentvisibilityautostatechange event to be called properly,
+ // with "auto" it will call it with skipped false for all initial elements.
+ // 44px is the height of the property row with 2 lines of text. This value can be adjusted slightly.
+ containIntrinsicSize: "auto 44px",
+ }}
+ >
+ {isVisible ? children : undefined}
+ </div>
+ );
+};
+
+const AdvancedDeclarationLonghand = memo(
+ ({
+ property,
+ onChangeComplete,
+ onDeleteProperty,
+ onSetProperty,
+ onReset,
+ valueInputRef,
+ indentation = initialIndentation,
+ }: {
+ property: CssProperty;
+ indentation?: string;
+ onReset?: () => void;
+ onSetProperty: SetProperty;
+ onDeleteProperty: DeleteProperty;
+ onChangeComplete?: ComponentProps<
+ typeof CssValueInputContainer
+ >["onChangeComplete"];
+ valueInputRef?: RefObject<HTMLInputElement>;
+ }) => {
+ return (
+ <Flex
+ css={{ paddingLeft: indentation }}
+ wrap="wrap"
+ align="center"
+ justify="start"
+ {...{ [copyAttribute]: property }}
+ >
+ <AdvancedPropertyLabel
+ property={property}
+ onReset={onReset}
+ onDeleteProperty={onDeleteProperty}
+ />
+ <Text
+ variant="mono"
+ // Improves the visual separation of value from the property.
+ css={{
+ textIndent: "-0.5ch",
+ fontWeight: "bold",
+ }}
+ >
+ :
+ </Text>
+ <AdvancedPropertyValue
+ property={property}
+ onChangeComplete={onChangeComplete}
+ onReset={onReset}
+ onDeleteProperty={onDeleteProperty}
+ onSetProperty={onSetProperty}
+ inputRef={valueInputRef}
+ />
+ </Flex>
+ );
+ }
+);
+
+export type CssEditorApi = { showAddStyleInput: () => void } | undefined;
+
+export const CssEditor = ({
+ onDeleteProperty,
+ onSetProperty,
+ onAddProperties,
+ styleMap,
+ apiRef,
+ showSearch = true,
+ recentProperties = [],
+}: {
+ onDeleteProperty: DeleteProperty;
+ onSetProperty: SetProperty;
+ onAddProperties: (styleMap: CssStyleMap) => void;
+ styleMap: CssStyleMap;
+ apiRef?: RefObject<CssEditorApi>;
+ showSearch?: boolean;
+ recentProperties?: Array<CssProperty>;
+}) => {
+ const [isAdding, setIsAdding] = useState(false);
+ const addPropertyInputRef = useRef<HTMLInputElement>(null);
+ const recentValueInputRef = useRef<HTMLInputElement>(null);
+ const searchInputRef = useRef<HTMLInputElement>(null);
+ const [searchProperties, setSearchProperties] =
+ useState<Array<CssProperty>>();
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [minHeight, setMinHeight] = useState<number>(0);
+ useImperativeHandle(apiRef, () => ({
+ showAddStyleInput() {
+ handleShowAddStyleInput();
+ },
+ }));
+
+ const advancedProperties = Array.from(styleMap.keys()) as Array<CssProperty>;
+
+ const currentProperties =
+ searchProperties ??
+ advancedProperties.filter(
+ (property) => recentProperties.includes(property) === false
+ );
+
+ const showRecentProperties =
+ recentProperties.length > 0 && searchProperties === undefined;
+
+ const memorizeMinHeight = () => {
+ setMinHeight(containerRef.current?.getBoundingClientRect().height ?? 0);
+ };
+
+ const handleInsertStyles = (cssText: string) => {
+ const styleMap = parseStyleInput(cssText);
+ if (styleMap.size === 0) {
+ return new Map();
+ }
+ onAddProperties(styleMap);
+ return styleMap;
+ };
+
+ const handleShowAddStyleInput = () => {
+ flushSync(() => {
+ setIsAdding(true);
+ });
+ // User can click twice on the add button, so we need to focus the input on the second click after autoFocus isn't working.
+ addPropertyInputRef.current?.focus();
+ };
+
+ const handleAbortSearch = () => {
+ setMinHeight(0);
+ setSearchProperties(undefined);
+ };
+
+ const handleSearch = (event: ChangeEvent<HTMLInputElement>) => {
+ const search = event.target.value.trim();
+ if (search === "") {
+ return handleAbortSearch();
+ }
+
+ memorizeMinHeight();
+
+ const styles = [];
+ for (const [property, value] of styleMap) {
+ styles.push({ property, value: toValue(value) });
+ }
+
+ const matched = matchSorter(styles, search, {
+ keys: ["property", "value"],
+ }).map(({ property }) => property);
+
+ setSearchProperties(matched as CssProperty[]);
+ };
+
+ const afterChangingStyles = () => {
+ 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;
+ element?.focus();
+ element?.select();
+ });
+ };
+
+ return (
+ <>
+ {showSearch && (
+ <Box css={{ paddingInline: theme.panel.paddingInline }}>
+ <SearchField
+ inputRef={searchInputRef}
+ onChange={handleSearch}
+ onAbort={handleAbortSearch}
+ />
+ </Box>
+ )}
+ <CopyPasteMenu
+ onPaste={handleInsertStyles}
+ styleMap={styleMap}
+ properties={
+ 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={onDeleteProperty}
+ 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 />}
+ <Flex
+ direction="column"
+ css={{ paddingInline: theme.panel.paddingInline, gap: 2 }}
+ style={{ minHeight }}
+ ref={containerRef}
+ >
+ {currentProperties.map((property) => {
+ return (
+ <LazyRender key={property}>
+ <AdvancedDeclarationLonghand
+ property={property}
+ onDeleteProperty={onDeleteProperty}
+ onSetProperty={onSetProperty}
+ />
+ </LazyRender>
+ );
+ })}
+ </Flex>
+ </Flex>
+ </CopyPasteMenu>
+ </>
+ );
+};
diff --git a/apps/builder/app/builder/shared/css-editor/index.ts b/apps/builder/app/builder/shared/css-editor/index.ts
new file mode 100644
index 0000000000..e3abb50d2c
--- /dev/null
+++ b/apps/builder/app/builder/shared/css-editor/index.ts
@@ -0,0 +1 @@
+export { CssEditor, type CssEditorApi } from "./css-editor";
diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/parse-style-input.test.ts b/apps/builder/app/builder/shared/css-editor/parse-style-input.test.ts
similarity index 100%
rename from apps/builder/app/builder/features/style-panel/sections/advanced/parse-style-input.test.ts
rename to apps/builder/app/builder/shared/css-editor/parse-style-input.test.ts
diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/parse-style-input.ts b/apps/builder/app/builder/shared/css-editor/parse-style-input.ts
similarity index 90%
rename from apps/builder/app/builder/features/style-panel/sections/advanced/parse-style-input.ts
rename to apps/builder/app/builder/shared/css-editor/parse-style-input.ts
index fb769ae785..196372beb3 100644
--- a/apps/builder/app/builder/features/style-panel/sections/advanced/parse-style-input.ts
+++ b/apps/builder/app/builder/shared/css-editor/parse-style-input.ts
@@ -4,7 +4,7 @@ import {
camelCaseProperty,
shorthandProperties,
} from "@webstudio-is/css-data";
-import { type CssProperty, type StyleMap } from "@webstudio-is/css-engine";
+import { type CssProperty, type CssStyleMap } from "@webstudio-is/css-engine";
import { lexer } from "css-tree";
// When user provides only a property name, we need to make it `property:;` to be able to parse it.
@@ -42,12 +42,12 @@ const ensureValue = (css: string) => {
* - Property and value: color: red
* - Multiple properties: color: red; background: blue
*/
-export const parseStyleInput = (css: string): StyleMap => {
+export const parseStyleInput = (css: string): CssStyleMap => {
css = ensureValue(css);
const styles = parseCss(`selector{${css}}`);
- const styleMap: StyleMap = new Map();
+ const styleMap: CssStyleMap = new Map();
for (const { property, value } of styles) {
// somethingunknown: red; -> --somethingunknown: red;
diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.ts
index 0614331547..2a6ae79fbb 100644
--- a/packages/css-engine/src/core/rules.ts
+++ b/packages/css-engine/src/core/rules.ts
@@ -50,6 +50,10 @@ const mergeDeclarations = (declarations: Iterable<Declaration>) => {
return newDeclarations;
};
+/**
+ * Use CssStyleMap instead to enforce hyphenated properties.
+ * @deprecated
+ */
export type StyleMap = Map<string, StyleValue>;
export const generateStyleMap = (
diff --git a/packages/css-engine/src/schema.ts b/packages/css-engine/src/schema.ts
index e7cf1af485..aa6663e553 100644
--- a/packages/css-engine/src/schema.ts
+++ b/packages/css-engine/src/schema.ts
@@ -12,6 +12,8 @@ export type StyleProperty = CamelCasedProperty | CustomProperty;
export type CssProperty = HyphenatedProperty | CustomProperty;
+export type CssStyleMap = Map<CssProperty, StyleValue>;
+
const Unit = z.string() as z.ZodType<GeneratedUnit | "number">;
export type Unit = z.infer<typeof Unit>;