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.

Style source input states (#785)

Oleg Isonene790af958a61
diff --git a/apps/designer/app/designer/features/style-panel/style-source-input/style-source.tsx b/apps/designer/app/designer/features/style-panel/style-source-input/style-source.tsx
deleted file mode 100644
index 562af1792c..0000000000
--- a/apps/designer/app/designer/features/style-panel/style-source-input/style-source.tsx
+++ /dev/null
@@ -1,338 +0,0 @@
-import { cssVars } from "@webstudio-is/css-vars";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuPortal,
- DropdownMenuTrigger,
- IconButton,
- Text,
- styled,
-} from "@webstudio-is/design-system";
-import { ChevronDownIcon } from "@webstudio-is/icons";
-import {
- useEffect,
- useLayoutEffect,
- useRef,
- type KeyboardEvent,
- type KeyboardEventHandler,
- type FocusEvent,
-} from "react";
-import { theme } from "@webstudio-is/design-system";
-
-// Used to schedule function calls to be executed after at a later point in time.
-// Since menu is managing focus, we need to execute that callback when the management is done.
-const useCallScheduler = () => {
- const ref = useRef<(() => void) | undefined>();
- const call = () => {
- ref.current?.();
- ref.current = undefined;
- };
- const set = (fn: () => void) => () => {
- ref.current = fn;
- };
- return { call, set };
-};
-
-const menuTriggerVisibilityVar = cssVars.define("menu-trigger-visibility");
-
-const menuCssVars = ({ show }: { show: boolean }) => ({
- [menuTriggerVisibilityVar]: show ? "visible" : "hidden",
-});
-
-type MenuProps = {
- state: ItemState;
- onEdit: () => void;
- onDisable: () => void;
- onEnable: () => void;
- onDuplicate: () => void;
- onRemove: () => void;
-};
-
-const Menu = (props: MenuProps) => {
- const scheduler = useCallScheduler();
- return (
- <DropdownMenu modal>
- <DropdownMenuTrigger asChild>
- {/* Migrate to a Button component once implemented https://github.com/webstudio-is/webstudio-designer/issues/450 */}
- <IconButton
- aria-label="Menu Button"
- css={{
- position: "absolute",
- right: 0,
- visibility: cssVars.use(menuTriggerVisibilityVar),
- }}
- >
- <ChevronDownIcon />
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuPortal>
- <DropdownMenuContent onCloseAutoFocus={scheduler.call}>
- <DropdownMenuItem onSelect={scheduler.set(props.onEdit)}>
- Edit Name
- </DropdownMenuItem>
- {props.state === "disabled" && (
- <DropdownMenuItem onSelect={scheduler.set(props.onEnable)}>
- Enable
- </DropdownMenuItem>
- )}
- {props.state !== "disabled" && (
- <DropdownMenuItem onSelect={scheduler.set(props.onDisable)}>
- Disable
- </DropdownMenuItem>
- )}
- <DropdownMenuItem onSelect={scheduler.set(props.onDuplicate)}>
- Duplicate
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={scheduler.set(props.onRemove)}>
- Remove
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenuPortal>
- </DropdownMenu>
- );
-};
-
-export type ItemState =
- | "unselected"
- | "selected"
- | "editing"
- | "disabled"
- | "dragging";
-
-export type ItemSource = "token" | "tag" | "state" | "local";
-
-const useEditableText = ({
- state,
- onStateChange,
- onChange,
- onClick,
-}: {
- state: ItemState;
- onStateChange: (state: ItemState) => void;
- onChange: (value: string) => void;
- onClick: () => void;
-}) => {
- const elementRef = useRef<HTMLDivElement>(null);
- const lastValueRef = useRef<string>("");
- const lastStateRef = useRef<ItemState>(state);
- const getValue = () => elementRef.current?.textContent ?? "";
-
- useEffect(() => {
- if (elementRef.current === null) {
- return;
- }
-
- if (state === "editing") {
- elementRef.current.setAttribute("contenteditable", "plaintext-only");
- elementRef.current.focus();
- getSelection()?.selectAllChildren(elementRef.current);
- lastValueRef.current = getValue();
- return;
- }
-
- elementRef.current?.removeAttribute("contenteditable");
- lastStateRef.current = state;
- }, [state]);
-
- const handleFinishEditing = (
- event: KeyboardEvent<Element> | FocusEvent<Element>
- ) => {
- if (state !== "editing" || elementRef.current === null) {
- return;
- }
- event.preventDefault();
- onStateChange(lastStateRef.current);
- // Reverting to the previous value when user hits Escape
- if ("key" in event && event.key === "Escape") {
- elementRef.current.textContent = lastValueRef.current;
- return;
- }
- onChange(getValue());
- lastValueRef.current = "";
- };
-
- const handleKeyDown: KeyboardEventHandler = (event) => {
- if (event.key === "Enter" || event.key === "Escape") {
- handleFinishEditing(event);
- }
- };
-
- const handleDoubleClick = () => {
- onStateChange("editing");
- };
-
- const handlers = {
- onKeyDown: handleKeyDown,
- onBlur: handleFinishEditing,
- onClick,
- onDoubleClick: handleDoubleClick,
- };
-
- return { ref: elementRef, handlers };
-};
-
-type EditableTextProps = {
- label: string;
- onChange: (value: string) => void;
- state: ItemState;
- onStateChange: (state: ItemState) => void;
- onClick: () => void;
-};
-
-const EditableText = ({
- onChange,
- label,
- state,
- onStateChange,
- onClick,
-}: EditableTextProps) => {
- const { ref, handlers } = useEditableText({
- state,
- onStateChange,
- onChange,
- onClick,
- });
-
- return (
- <Text
- truncate
- ref={ref}
- css={{
- outline: "none",
- textOverflow: state === "editing" ? "clip" : "ellipsis",
- }}
- {...handlers}
- >
- {label}
- </Text>
- );
-};
-
-// Forces layout to recalc max-width when editing is done, because otherwise,
-// layout will keep the value from before engaging contenteditable.
-const useForceRecalcStyle = <Element extends HTMLElement>(
- property: string,
- calculate: boolean
-) => {
- const ref = useRef<Element>(null);
- useLayoutEffect(() => {
- const element = ref.current;
- if (calculate === false || element === null) {
- return;
- }
- element.style.setProperty(property, "initial");
- const restore = () => {
- element.style.removeProperty(property);
- };
- const requestId = requestAnimationFrame(restore);
- return () => {
- cancelAnimationFrame(requestId);
- restore();
- };
- }, [calculate, property]);
- return ref;
-};
-
-const Item = styled("div", {
- display: "inline-flex",
- borderRadius: theme.borderRadius[3],
- padding: theme.spacing[4],
- maxWidth: "100%",
- minWidth: 0,
- position: "relative",
- color: theme.colors.foregroundContrastMain,
- ...menuCssVars({ show: false }),
- "&:hover": menuCssVars({ show: true }),
- variants: {
- source: {
- local: {
- backgroundColor: theme.colors.backgroundStyleSourceToken,
- },
- token: {
- backgroundColor: theme.colors.backgroundStyleSourceToken,
- },
- tag: {
- backgroundColor: theme.colors.backgroundStyleSourceTag,
- },
- state: {
- backgroundColor: theme.colors.backgroundStyleSourceState,
- },
- },
- state: {
- selected: {},
- unselected: {
- backgroundColor: theme.colors.backgroundStyleSourceNeutral,
- },
- disabled: {
- // @todo styling
- opacity: 0.5,
- },
- editing: {},
- dragging: {
- backgroundColor: theme.colors.backgroundStyleSourceDisabled,
- },
- },
- },
- defaultVariants: {
- state: "unselected",
- },
-});
-
-type StyleSourceProps = {
- id: string;
- label: string;
- hasMenu: boolean;
- state: ItemState;
- source: ItemSource;
- onStateChange: (state: ItemState) => void;
- onSelect: () => void;
- onDuplicate: () => void;
- onRemove: () => void;
- onChange: (value: string) => void;
-};
-
-export const StyleSource = ({
- id,
- label,
- hasMenu,
- state,
- source,
- onChange,
- onStateChange,
- onSelect,
- onDuplicate,
- onRemove,
-}: StyleSourceProps) => {
- const ref = useForceRecalcStyle<HTMLDivElement>(
- "max-width",
- state === "editing"
- );
- return (
- <Item state={state} source={source} data-id={id} ref={ref}>
- <EditableText
- state={state}
- onStateChange={onStateChange}
- onClick={onSelect}
- onChange={onChange}
- label={label}
- />
- {hasMenu === true && state !== "editing" && (
- <Menu
- state={state}
- onDuplicate={onDuplicate}
- onRemove={onRemove}
- onEnable={() => {
- onStateChange("unselected");
- }}
- onDisable={() => {
- onStateChange("disabled");
- }}
- onEdit={() => {
- onStateChange("editing");
- }}
- />
- )}
- </Item>
- );
-};
diff --git a/apps/designer/app/designer/features/style-panel/style-source-input/index.ts b/apps/designer/app/designer/features/style-panel/style-source/index.ts
similarity index 73%
rename from apps/designer/app/designer/features/style-panel/style-source-input/index.ts
rename to apps/designer/app/designer/features/style-panel/style-source/index.ts
index 59f1d6aeb5..a5ed9a9aa7 100644
--- a/apps/designer/app/designer/features/style-panel/style-source-input/index.ts
+++ b/apps/designer/app/designer/features/style-panel/style-source/index.ts
@@ -1,2 +1,3 @@
export * from "./style-source-input";
+export * from "./style-source-badge";
export { type ItemState, type ItemSource } from "./style-source";
diff --git a/apps/designer/app/designer/features/style-panel/style-source/style-source-badge.stories.tsx b/apps/designer/app/designer/features/style-panel/style-source/style-source-badge.stories.tsx
new file mode 100644
index 0000000000..cb4ffadaa1
--- /dev/null
+++ b/apps/designer/app/designer/features/style-panel/style-source/style-source-badge.stories.tsx
@@ -0,0 +1,23 @@
+import type { ComponentStory } from "@storybook/react";
+import { Flex } from "@webstudio-is/design-system";
+import { StyleSourceBadge } from "./style-source-badge";
+
+export default {
+ component: StyleSourceBadge,
+};
+
+export const All: ComponentStory<typeof StyleSourceBadge> = () => {
+ return (
+ <Flex gap="1">
+ <StyleSourceBadge source="tag" variant="small">
+ Tag
+ </StyleSourceBadge>
+ <StyleSourceBadge source="token" variant="small">
+ Token
+ </StyleSourceBadge>
+ <StyleSourceBadge source="state" variant="small">
+ State
+ </StyleSourceBadge>
+ </Flex>
+ );
+};
diff --git a/apps/designer/app/designer/features/style-panel/style-source/style-source-badge.tsx b/apps/designer/app/designer/features/style-panel/style-source/style-source-badge.tsx
new file mode 100644
index 0000000000..64d5896d71
--- /dev/null
+++ b/apps/designer/app/designer/features/style-panel/style-source/style-source-badge.tsx
@@ -0,0 +1,24 @@
+import { styled, Text } from "@webstudio-is/design-system";
+import { theme } from "@webstudio-is/design-system";
+
+export const StyleSourceBadge = styled(Text, {
+ display: "inline-flex",
+ borderRadius: theme.borderRadius[2],
+ px: theme.spacing[3],
+ height: theme.spacing[9],
+ color: theme.colors.foregroundContrastMain,
+ alignItems: "center",
+ variants: {
+ source: {
+ token: {
+ backgroundColor: theme.colors.backgroundStyleSourceToken,
+ },
+ tag: {
+ backgroundColor: theme.colors.backgroundStyleSourceTag,
+ },
+ state: {
+ backgroundColor: theme.colors.backgroundStyleSourceState,
+ },
+ },
+ },
+});
diff --git a/apps/designer/app/designer/features/style-panel/style-source-input/style-source-input.stories.tsx b/apps/designer/app/designer/features/style-panel/style-source/style-source-input.stories.tsx
similarity index 72%
rename from apps/designer/app/designer/features/style-panel/style-source-input/style-source-input.stories.tsx
rename to apps/designer/app/designer/features/style-panel/style-source/style-source-input.stories.tsx
index 158f4bdd3f..536fee63cc 100644
--- a/apps/designer/app/designer/features/style-panel/style-source-input/style-source-input.stories.tsx
+++ b/apps/designer/app/designer/features/style-panel/style-source/style-source-input.stories.tsx
@@ -11,37 +11,38 @@ type Item = {
id: string;
label: string;
source: ItemSource;
- hasMenu: boolean;
+ isEditable: boolean;
state: ItemState;
};
-const items: Array<Item> = [
- {
- id: uuid(),
- label: "Local",
- source: "local",
- hasMenu: false,
- state: "unselected",
- },
+const localItem: Item = {
+ id: uuid(),
+ label: "Local",
+ source: "local",
+ isEditable: false,
+ state: "selected",
+};
+
+const getItems = (): Array<Item> => [
{
id: uuid(),
- label: "Apple",
+ label: "Token",
source: "token",
- hasMenu: false,
+ isEditable: true,
state: "unselected",
},
{
id: uuid(),
- label: "Banana",
+ label: "Tag",
source: "tag",
- hasMenu: false,
+ isEditable: true,
state: "unselected",
},
{
id: uuid(),
- label: "Orange",
+ label: "State",
source: "state",
- hasMenu: false,
+ isEditable: true,
state: "unselected",
},
];
@@ -55,10 +56,19 @@ const createItem = (
id: uuid(),
label,
source: "token",
- hasMenu: true,
- state: "unselected",
+ isEditable: true,
+ state: "selected",
};
- setValue([...value, item]);
+ const nextValue = value.map((item) => {
+ if (item.state === "selected") {
+ return {
+ ...item,
+ state: "unselected" as const,
+ };
+ }
+ return item;
+ });
+ setValue([...nextValue, item]);
};
const removeItem = (
@@ -73,11 +83,11 @@ const removeItem = (
};
export const Basic: ComponentStory<typeof StyleSourceInput> = () => {
- const [value, setValue] = useState(items);
+ const [value, setValue] = useState([localItem, ...getItems()]);
return (
<StyleSourceInput
css={{ width: 300 }}
- items={items}
+ items={getItems()}
value={value}
onCreateItem={({ label }) => {
createItem(label, value, setValue);
@@ -102,14 +112,14 @@ export const WithTruncatedItem: ComponentStory<
label:
"Local Something Something Something Something Something Something Something Something Something Something Something",
source: "local",
- hasMenu: false,
- state: "unselected",
+ isEditable: true,
+ state: "selected",
},
]);
return (
<StyleSourceInput
css={{ width: 300 }}
- items={items}
+ items={getItems()}
value={value}
onCreateItem={({ label }) => {
createItem(label, value, setValue);
@@ -127,28 +137,39 @@ export const WithTruncatedItem: ComponentStory<
export const Complete: ComponentStory<typeof StyleSourceInput> = () => {
const [value, setValue] = useState<Array<Item>>([
- ...items,
+ localItem,
+ ...getItems(),
{
id: uuid(),
- label: "Grape",
+ label: "Disabled",
source: "token",
- hasMenu: true,
- state: "selected",
+
+ isEditable: true,
+ state: "disabled",
},
]);
- const [editingItemId, setEditingItemId] = useState<string>();
- const [currentItemId, setCurrentItemId] = useState<string | undefined>(
- value.at(-1)?.id
- );
+ const [editingItem, setEditingItem] = useState<Item>();
+
return (
<StyleSourceInput
css={{ width: 300 }}
- items={items}
+ items={getItems()}
value={value}
- editingItemId={editingItemId}
- currentItemId={currentItemId}
- onSelectItem={setCurrentItemId}
- onChangeEditing={setEditingItemId}
+ editingItem={editingItem}
+ onSelectItem={(itemToSelect) => {
+ setValue(
+ value.map((item) => {
+ if (item.id === itemToSelect?.id) {
+ return { ...item, state: "selected" };
+ }
+ if (item.state === "selected") {
+ return { ...item, state: "unselected" };
+ }
+ return item;
+ })
+ );
+ }}
+ onEditItem={setEditingItem}
onCreateItem={({ label }) => {
createItem(label, value, setValue);
}}
@@ -188,21 +209,6 @@ export const Complete: ComponentStory<typeof StyleSourceInput> = () => {
})
);
}}
- onDuplicateItem={(itemToDuplicate) => {
- const duplicatedItem = {
- ...itemToDuplicate,
- id: uuid(),
- label: itemToDuplicate.label + " Copy",
- };
- const nextValue = value.map((item) => {
- if (item.id === itemToDuplicate.id) {
- return duplicatedItem;
- }
- return item;
- });
- setValue(nextValue);
- setEditingItemId(duplicatedItem.id);
- }}
onSort={setValue}
/>
);
diff --git a/apps/designer/app/designer/features/style-panel/style-source-input/style-source-input.tsx b/apps/designer/app/designer/features/style-panel/style-source/style-source-input.tsx
similarity index 77%
rename from apps/designer/app/designer/features/style-panel/style-source-input/style-source-input.tsx
rename to apps/designer/app/designer/features/style-panel/style-source/style-source-input.tsx
index ba5452cf83..14c1454f3c 100644
--- a/apps/designer/app/designer/features/style-panel/style-source-input/style-source-input.tsx
+++ b/apps/designer/app/designer/features/style-panel/style-source/style-source-input.tsx
@@ -1,3 +1,17 @@
+/*
+ * Style Source Input functionality
+ * - Type a new input with autocomplete
+ * - Select an existing source from a list
+ * - Enter a new source
+ * - Hover the source to see the menu
+ * - Menu provides: Remove, Duplicate, Disable, Edit name
+ * - Drag and drop to reorder
+ * - Click to toggle select/unselect
+ * - Double click to edit name
+ * - Local source can only be disabled, nothing else should be possible
+ * - Hit Backspace to delete the last Source item when you are in the input
+ */
+
import {
Box,
ComboboxListbox,
@@ -19,14 +33,19 @@ import {
type RefObject,
} from "react";
import { mergeRefs } from "@react-aria/utils";
-import { ItemSource, StyleSource, type ItemState } from "./style-source";
+import {
+ ItemSource,
+ menuCssVars,
+ StyleSource,
+ type ItemState,
+} from "./style-source";
import { useSortable } from "./use-sortable";
import { theme } from "@webstudio-is/design-system";
type IntermediateItem = {
id: string;
label: string;
- hasMenu: boolean;
+ isEditable: boolean;
state: ItemState;
source: ItemSource;
};
@@ -42,15 +61,13 @@ type TextFieldBaseWrapperProps<Item> = Omit<ComponentProps<"input">, "value"> &
containerRef?: RefObject<HTMLDivElement>;
inputRef?: RefObject<HTMLInputElement>;
onRemoveItem?: (item: Item) => void;
- onDuplicateItem?: (item: Item) => void;
onChangeItem?: (item: Item) => void;
onDisableItem?: (item: Item) => void;
onEnableItem?: (item: Item) => void;
onSort?: (items: Array<Item>) => void;
- onSelectItem?: (id: string) => void;
- onChangeEditing?: (id?: string) => void;
- editingItemId?: string;
- currentItemId?: string;
+ onSelectItem?: (item?: Item) => void;
+ onEditItem?: (item?: Item) => void;
+ editingItem?: Item;
};
const TextFieldBase: ForwardRefRenderFunction<
@@ -72,15 +89,13 @@ const TextFieldBase: ForwardRefRenderFunction<
label,
value,
onRemoveItem,
- onDuplicateItem,
onChangeItem,
onDisableItem,
onEnableItem,
onSort,
onSelectItem,
- onChangeEditing,
- currentItemId,
- editingItemId,
+ onEditItem,
+ editingItem,
...textFieldProps
} = props;
const [internalInputRef, focusProps] = useTextFieldFocus({
@@ -101,21 +116,23 @@ const TextFieldBase: ForwardRefRenderFunction<
state={state}
variant={textFieldVariant}
css={{ ...css, px: theme.spacing[3], py: theme.spacing[2] }}
+ style={
+ dragItemId ? menuCssVars({ show: false, override: true }) : undefined
+ }
onKeyDown={onKeyDown}
>
{value.map((item, index) => (
<StyleSource
id={item.id}
- state={
- item.id === dragItemId
- ? "dragging"
- : item.id === editingItemId
- ? "editing"
- : item.state
- }
+ isDragging={item.id === dragItemId}
+ isEditing={item.id === editingItem?.id}
+ state={item.state}
source={item.source}
- onStateChange={(state) => {
- onChangeEditing?.(state === "editing" ? item.id : undefined);
+ isEditable={item.isEditable}
+ onChangeEditing={(isEditing) => {
+ onEditItem?.(isEditing ? item : undefined);
+ }}
+ onChangeState={(state) => {
if (state === "disabled") {
onDisableItem?.(item);
}
@@ -124,26 +141,22 @@ const TextFieldBase: ForwardRefRenderFunction<
}
}}
onSelect={() => {
- onSelectItem?.(item.id);
+ onSelectItem?.(item.state === "selected" ? undefined : item);
}}
- onChange={(label) => {
- onChangeEditing?.();
+ onChangeValue={(label) => {
+ onEditItem?.();
onChangeItem?.({ ...item, label });
}}
- onDuplicate={() => {
- onDuplicateItem?.(item);
- }}
onRemove={() => {
onRemoveItem?.(item);
}}
label={item.label}
- hasMenu={item.hasMenu}
key={index}
/>
))}
{placementIndicator}
{/* We want input to be the first element in DOM so it receives the focus first */}
- {editingItemId === undefined && (
+ {editingItem?.id === undefined && (
<TextFieldInput
{...textFieldProps}
value={label}
@@ -152,6 +165,7 @@ const TextFieldBase: ForwardRefRenderFunction<
onClick={onClick}
ref={mergeRefs(internalInputRef, inputRef ?? null)}
autoFocus
+ aria-label="New Style Source Input"
/>
)}
</TextFieldContainer>
@@ -164,15 +178,13 @@ TextField.displayName = "TextField";
type StyleSourceInputProps<Item> = {
items?: Array<Item>;
value?: Array<Item>;
- editingItemId?: string;
- currentItemId?: string;
+ editingItem?: Item;
onSelectAutocompleteItem?: (item: Item) => void;
onRemoveItem?: (item: Item) => void;
onCreateItem?: (item: Item) => void;
onChangeItem?: (item: Item) => void;
- onSelectItem?: (id: string) => void;
- onChangeEditing?: (id?: string) => void;
- onDuplicateItem?: (item: Item) => void;
+ onSelectItem?: (item?: Item) => void;
+ onEditItem?: (item?: Item) => void;
onDisableItem?: (item: Item) => void;
onEnableItem?: (item: Item) => void;
onSort?: (items: Array<Item>) => void;
@@ -195,10 +207,10 @@ export const StyleSourceInput = <Item extends IntermediateItem>(
items: props.items ?? [],
value: {
label,
- hasMenu: true,
state: "unselected",
id: "",
source: "local",
+ isEditable: true,
},
selectedItem: undefined,
itemToString: (item) => (item ? item.label : ""),
@@ -219,7 +231,7 @@ export const StyleSourceInput = <Item extends IntermediateItem>(
onKeyPress(event) {
if (event.key === "Enter" && label.trim() !== "") {
setLabel("");
- props.onCreateItem?.({ label, hasMenu: true } as Item);
+ props.onCreateItem?.({ label } as Item);
}
},
});
@@ -233,16 +245,14 @@ export const StyleSourceInput = <Item extends IntermediateItem>(
onRemoveItem={props.onRemoveItem}
onChangeItem={props.onChangeItem}
onSelectItem={props.onSelectItem}
- onChangeEditing={props.onChangeEditing}
- onDuplicateItem={props.onDuplicateItem}
+ onEditItem={props.onEditItem}
onDisableItem={props.onDisableItem}
onEnableItem={props.onEnableItem}
onSort={props.onSort}
label={label}
value={value}
css={props.css}
- editingItemId={props.editingItemId}
- currentItemId={props.currentItemId}
+ editingItem={props.editingItem}
/>
</ComboboxPopperAnchor>
<ComboboxPopperContent align="start" sideOffset={5}>
diff --git a/apps/designer/app/designer/features/style-panel/style-source/style-source.tsx b/apps/designer/app/designer/features/style-panel/style-source/style-source.tsx
new file mode 100644
index 0000000000..edb989f966
--- /dev/null
+++ b/apps/designer/app/designer/features/style-panel/style-source/style-source.tsx
@@ -0,0 +1,458 @@
+import { cssVars } from "@webstudio-is/css-vars";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuTrigger,
+ Text,
+ styled,
+ Box,
+ theme,
+} from "@webstudio-is/design-system";
+import { ChevronDownIcon } from "@webstudio-is/icons";
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ forwardRef,
+ type KeyboardEvent,
+ type KeyboardEventHandler,
+ type FocusEvent,
+} from "react";
+
+// Used to schedule function calls to be executed after at a later point in time.
+// Since menu is managing focus, we need to execute that callback when the management is done.
+const useCallScheduler = () => {
+ const ref = useRef<(() => void) | undefined>();
+ const call = () => {
+ ref.current?.();
+ ref.current = undefined;
+ };
+ const set = (fn: () => void) => () => {
+ ref.current = fn;
+ };
+ return { call, set };
+};
+
+const menuTriggerVisibilityVar = cssVars.define("menu-trigger-visibility");
+const menuTriggerVisibilityOverrideVar = cssVars.define(
+ "menu-trigger-visibility-override"
+);
+
+export const menuCssVars = ({
+ show,
+ override = false,
+}: {
+ show: boolean;
+ override?: boolean;
+}) => {
+ const property = override
+ ? menuTriggerVisibilityOverrideVar
+ : menuTriggerVisibilityVar;
+
+ return {
+ [property]: show ? "visible" : "hidden",
+ };
+};
+
+const MenuTrigger = styled("button", {
+ display: "inline-flex",
+ border: "none",
+ boxSizing: "border-box",
+ minWidth: 0,
+ alignItems: "center",
+ position: "absolute",
+ right: 0,
+ top: 0,
+ height: "100%",
+ padding: 0,
+ borderTopRightRadius: theme.borderRadius[4],
+ borderBottomRightRadius: theme.borderRadius[4],
+ color: theme.colors.foregroundContrastMain,
+ visibility: cssVars.use(
+ menuTriggerVisibilityOverrideVar,
+ cssVars.use(menuTriggerVisibilityVar)
+ ),
+ background: "transparent",
+ variants: {
+ source: {
+ local: {
+ "&:hover": {
+ background: theme.colors.backgroundButtonHover,
+ },
+ },
+ token: {
+ "&:hover": {
+ background: theme.colors.backgroundButtonHover,
+ },
+ },
+ tag: {
+ "&:hover": {
+ background: theme.colors.backgroundButtonHover,
+ },
+ },
+ state: {
+ "&:hover": {
+ background: theme.colors.backgroundButtonHover,
+ },
+ },
+ },
+ },
+});
+
+const MenuTriggerGradient = styled(Box, {
+ position: "absolute",
+ top: 0,
+ right: 0,
+ width: theme.spacing[11],
+ height: "100%",
+ visibility: cssVars.use(
+ menuTriggerVisibilityOverrideVar,
+ cssVars.use(menuTriggerVisibilityVar)
+ ),
+ borderTopRightRadius: theme.borderRadius[4],
+ borderBottomRightRadius: theme.borderRadius[4],
+ pointerEvents: "none",
+ variants: {
+ source: {
+ local: {
+ background: theme.colors.backgroundStyleSourceGradientToken,
+ },
+ token: {
+ background: theme.colors.backgroundStyleSourceGradientToken,
+ },
+ tag: {
+ background: theme.colors.backgroundStyleSourceGradientTag,
+ },
+ state: {
+ background: theme.colors.backgroundStyleSourceGradientState,
+ },
+ },
+ },
+});
+
+type MenuProps = {
+ source: ItemSource;
+ state: ItemState;
+ onEdit: () => void;
+ onDisable: () => void;
+ onEnable: () => void;
+ onRemove: () => void;
+};
+
+const Menu = (props: MenuProps) => {
+ const scheduler = useCallScheduler();
+ const canEdit = props.source !== "local";
+ const canDisable = props.state !== "disabled";
+ const canEnable = props.state === "disabled";
+ const canRemove = props.source !== "local";
+ return (
+ <DropdownMenu modal>
+ <MenuTriggerGradient source={props.source} />
+ <DropdownMenuTrigger asChild>
+ <MenuTrigger aria-label="Menu Button" source={props.source}>
+ <ChevronDownIcon />
+ </MenuTrigger>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent onCloseAutoFocus={scheduler.call}>
+ {canEdit && (
+ <DropdownMenuItem onSelect={scheduler.set(props.onEdit)}>
+ Edit Name
+ </DropdownMenuItem>
+ )}
+ {canEnable && (
+ <DropdownMenuItem onSelect={scheduler.set(props.onEnable)}>
+ Enable
+ </DropdownMenuItem>
+ )}
+ {canDisable && (
+ <DropdownMenuItem onSelect={scheduler.set(props.onDisable)}>
+ Disable
+ </DropdownMenuItem>
+ )}
+ {canRemove && (
+ <DropdownMenuItem onSelect={scheduler.set(props.onRemove)}>
+ Remove
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenu>
+ );
+};
+
+export type ItemState = "unselected" | "selected" | "disabled";
+
+export type ItemSource = "token" | "tag" | "state" | "local";
+
+const useEditableText = ({
+ isEditable,
+ isEditing,
+ onChangeEditing,
+ onChangeValue,
+ onClick,
+}: {
+ isEditable: boolean;
+ isEditing: boolean;
+ onChangeEditing: (isEditing: boolean) => void;
+ onChangeValue: (value: string) => void;
+ onClick: () => void;
+}) => {
+ const elementRef = useRef<HTMLDivElement>(null);
+ const lastValueRef = useRef<string>("");
+ const getValue = () => elementRef.current?.textContent ?? "";
+
+ useEffect(() => {
+ if (elementRef.current === null) {
+ return;
+ }
+
+ if (isEditing) {
+ elementRef.current.setAttribute("contenteditable", "plaintext-only");
+ elementRef.current.focus();
+ getSelection()?.selectAllChildren(elementRef.current);
+ lastValueRef.current = getValue();
+ return;
+ }
+
+ elementRef.current?.removeAttribute("contenteditable");
+ }, [isEditing]);
+
+ const handleFinishEditing = (
+ event: KeyboardEvent<Element> | FocusEvent<Element>
+ ) => {
+ event.preventDefault();
+ if (isEditing) {
+ onChangeEditing(false);
+ }
+ onChangeValue(getValue());
+ lastValueRef.current = "";
+ };
+
+ const handleKeyDown: KeyboardEventHandler = (event) => {
+ if (event.key === "Enter") {
+ handleFinishEditing(event);
+ return;
+ }
+ if (event.key === "Escape" && elementRef.current !== null) {
+ elementRef.current.textContent = lastValueRef.current;
+ handleFinishEditing(event);
+ }
+ };
+
+ const handleDoubleClick = () => {
+ if (isEditable) {
+ onChangeEditing(true);
+ }
+ };
+
+ const handlers = {
+ onKeyDown: handleKeyDown,
+ onBlur: handleFinishEditing,
+ onClick,
+ onDoubleClick: handleDoubleClick,
+ };
+
+ return { ref: elementRef, handlers };
+};
+
+type EditableTextProps = {
+ label: string;
+ isEditable: boolean;
+ isEditing: boolean;
+ onChangeEditing: (isEditing: boolean) => void;
+ onChangeValue: (value: string) => void;
+ onClick: () => void;
+};
+
+const EditableText = ({
+ label,
+ isEditable,
+ isEditing,
+ onChangeEditing,
+ onChangeValue,
+ onClick,
+}: EditableTextProps) => {
+ const { ref, handlers } = useEditableText({
+ isEditable,
+ isEditing,
+ onChangeEditing,
+ onChangeValue,
+ onClick,
+ });
+
+ return (
+ <Text
+ truncate
+ ref={ref}
+ css={{
+ outline: "none",
+ textOverflow: isEditing ? "clip" : "ellipsis",
+ }}
+ {...handlers}
+ >
+ {label}
+ </Text>
+ );
+};
+
+// Forces layout to recalc max-width when editing is done, because otherwise,
+// layout will keep the value from before engaging contenteditable.
+const useForceRecalcStyle = <Element extends HTMLElement>(
+ property: string,
+ calculate: boolean
+) => {
+ const ref = useRef<Element>(null);
+ useLayoutEffect(() => {
+ const element = ref.current;
+ if (calculate === false || element === null) {
+ return;
+ }
+ element.style.setProperty(property, "initial");
+ const restore = () => {
+ element.style.removeProperty(property);
+ };
+ const requestId = requestAnimationFrame(restore);
+ return () => {
+ cancelAnimationFrame(requestId);
+ restore();
+ };
+ }, [calculate, property]);
+ return ref;
+};
+
+const StyledSourceButton = styled(Box, {
+ display: "inline-flex",
+ borderRadius: theme.borderRadius[3],
+ padding: theme.spacing[4],
+ maxWidth: "100%",
+ position: "relative",
+ color: theme.colors.foregroundContrastMain,
+ ...menuCssVars({ show: false }),
+ "&:hover": menuCssVars({ show: true }),
+ variants: {
+ source: {
+ local: {
+ backgroundColor: theme.colors.backgroundStyleSourceToken,
+ },
+ token: {
+ backgroundColor: theme.colors.backgroundStyleSourceToken,
+ },
+ tag: {
+ backgroundColor: theme.colors.backgroundStyleSourceTag,
+ },
+ state: {
+ backgroundColor: theme.colors.backgroundStyleSourceState,
+ },
+ },
+ state: {
+ selected: {},
+ unselected: {
+ "&:not(:hover)": {
+ backgroundColor: theme.colors.backgroundStyleSourceNeutral,
+ },
+ },
+ disabled: {
+ "&:not(:hover)": {
+ backgroundColor: theme.colors.backgroundStyleSourceDisabled,
+ },
+ },
+ },
+ },
+ defaultVariants: {
+ state: "unselected",
+ },
+});
+
+type SourceButtonProps = {
+ id: string;
+ state: ItemState;
+ source: ItemSource;
+ children: Array<JSX.Element | boolean>;
+};
+
+const SourceButton = forwardRef<HTMLDivElement, SourceButtonProps>(
+ ({ id, state, source, children }, ref) => {
+ return (
+ <StyledSourceButton
+ state={state}
+ source={source}
+ data-id={id}
+ aria-current={state === "selected"}
+ role="button"
+ ref={ref}
+ >
+ {children}
+ </StyledSourceButton>
+ );
+ }
+);
+SourceButton.displayName = "SourceButton";
+
+type StyleSourceProps = {
+ id: string;
+ label: string;
+ isEditable: boolean;
+ isEditing: boolean;
+ isDragging: boolean;
+ state: ItemState;
+ source: ItemSource;
+ onChangeState: (state: ItemState) => void;
+ onSelect: () => void;
+ onRemove: () => void;
+ onChangeValue: (value: string) => void;
+ onChangeEditing: (isEditing: boolean) => void;
+};
+
+export const StyleSource = ({
+ id,
+ label,
+ state,
+ isEditable,
+ isEditing,
+ isDragging,
+ source,
+ onChangeValue,
+ onChangeEditing,
+ onChangeState,
+ onSelect,
+ onRemove,
+}: StyleSourceProps) => {
+ const ref = useForceRecalcStyle<HTMLDivElement>("max-width", isEditing);
+ const showMenu = isEditing === false && isDragging === false;
+
+ return (
+ <SourceButton state={state} source={source} id={id} ref={ref}>
+ <EditableText
+ isEditable={isEditable}
+ isEditing={isEditing}
+ onChangeEditing={onChangeEditing}
+ onClick={() => {
+ if (state !== "disabled" && isEditing === false) {
+ onSelect();
+ }
+ }}
+ onChangeValue={onChangeValue}
+ label={label}
+ />
+ {showMenu && (
+ <Menu
+ source={source}
+ state={state}
+ onRemove={onRemove}
+ onEnable={() => {
+ onChangeState("unselected");
+ }}
+ onDisable={() => {
+ onChangeState("disabled");
+ }}
+ onEdit={() => {
+ onChangeEditing(true);
+ }}
+ />
+ )}
+ </SourceButton>
+ );
+};
diff --git a/apps/designer/app/designer/features/style-panel/style-source-input/use-sortable.tsx b/apps/designer/app/designer/features/style-panel/style-source/use-sortable.tsx
similarity index 100%
rename from apps/designer/app/designer/features/style-panel/style-source-input/use-sortable.tsx
rename to apps/designer/app/designer/features/style-panel/style-source/use-sortable.tsx
diff --git a/packages/design-system/src/components/button.tsx b/packages/design-system/src/components/button.tsx
index eccc278509..127534e2ad 100644
--- a/packages/design-system/src/components/button.tsx
+++ b/packages/design-system/src/components/button.tsx
@@ -5,8 +5,7 @@
import React, { forwardRef, type Ref, type ComponentProps } from "react";
import { Text } from "./text";
-import { styled } from "../stitches.config";
-import { theme } from "../stitches.config";
+import { styled, theme } from "../stitches.config";
// CSS supports multiple gradients as backgrounds but not multiple colors
const backgroundColors = ({
diff --git a/packages/design-system/src/components/text.tsx b/packages/design-system/src/components/text.tsx
index 8dad3a612b..31f91b0425 100644
--- a/packages/design-system/src/components/text.tsx
+++ b/packages/design-system/src/components/text.tsx
@@ -1,5 +1,4 @@
-import { css, styled } from "../stitches.config";
-import { theme } from "../stitches.config";
+import { css, styled, theme } from "../stitches.config";
export const textStyles = css({
// Reset
@@ -20,6 +19,11 @@ export const textStyles = css({
fontSize: theme.fontSize[3],
letterSpacing: "0.005em",
},
+ small: {
+ fontWeight: 400,
+ fontSize: theme.fontSize[2],
+ letterSpacing: "0.01em",
+ },
tiny: {
fontWeight: 400,
fontSize: theme.fontSize[1],