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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
Style source input (#752)
Oleg Isonen9afd2797974d
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-input/style-source-input.stories.tsxindex 8b84e62818..35f149d122 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-input/style-source-input.stories.tsx@@ -7,29 +7,41 @@ export default {component: StyleSourceInput,};-const items = [- { id: "1", label: "Apple", type: "token" },- { id: "2", label: "Banana", type: "token" },- { id: "3", label: "Orange", type: "token" },+type Item = {+ id: string;+ label: string;+ type: "token" | "local";+ hasMenu: boolean;+};++const localItem: Item = {+ id: "0",+ label: "Local",+ type: "local",+ hasMenu: false,+};++const items: Array<Item> = [+ { id: "1", label: "Apple", type: "token", hasMenu: false },+ { id: "2", label: "Banana", type: "token", hasMenu: false },+ { id: "3", label: "Orange", type: "token", hasMenu: false },];export const Initial: ComponentStory<typeof StyleSourceInput> = () => {- const [value, setValue] = useState([- { id: "0", label: "Local", type: "local" },- ]);+ const [value, setValue] = useState<Array<Item>>([localItem]);return (<StyleSourceInputcss={{ width: 300 }}items={items}value={value}- onCreate={({ label }) => {- const item = { id: uuid(), label, type: "token" };+ onCreateItem={({ label }) => {+ const item: Item = { id: uuid(), label, type: "token", hasMenu: false };setValue([...value, item]);}}- onSelect={(item) => {+ onSelectItem={(item) => {setValue([...value, item]);}}- onRemove={(itemToRemove) => {+ onRemoveItem={(itemToRemove) => {if (itemToRemove.type === "local") {return;}@@ -40,23 +52,20 @@ export const Initial: ComponentStory<typeof StyleSourceInput> = () => {};export const WithItems: ComponentStory<typeof StyleSourceInput> = () => {- const [value, setValue] = useState([- { id: "0", label: "Local", type: "local" },- ...items,- ]);+ const [value, setValue] = useState([localItem, ...items]);return (<StyleSourceInputcss={{ width: 300 }}items={items}value={value}- onCreate={({ label }) => {- const item = { id: uuid(), label, type: "token" };+ onCreateItem={({ label }) => {+ const item: Item = { id: uuid(), label, type: "token", hasMenu: false };setValue([...value, item]);}}- onSelect={(item) => {+ onSelectItem={(item) => {setValue([...value, item]);}}- onRemove={(itemToRemove) => {+ onRemoveItem={(itemToRemove) => {if (itemToRemove.type === "local") {return;}@@ -69,12 +78,13 @@ export const WithItems: ComponentStory<typeof StyleSourceInput> = () => {export const WithTruncatedItem: ComponentStory<typeof StyleSourceInput> = () => {- const [value, setValue] = useState([+ const [value, setValue] = useState<Array<Item>>([{id: "0",label:"Local Something Something Something Something Something Something Something Something Something Something Something",type: "local",+ hasMenu: false,},]);return (@@ -82,14 +92,14 @@ export const WithTruncatedItem: ComponentStory<css={{ width: 300 }}items={items}value={value}- onCreate={({ label }) => {- const item = { id: uuid(), label, type: "token" };+ onCreateItem={({ label }) => {+ const item: Item = { id: uuid(), label, type: "token", hasMenu: false };setValue([...value, item]);}}- onSelect={(item) => {+ onSelectItem={(item) => {setValue([...value, item]);}}- onRemove={(itemToRemove) => {+ onRemoveItem={(itemToRemove) => {if (itemToRemove.type === "local") {return;}@@ -98,3 +108,56 @@ export const WithTruncatedItem: ComponentStory</>);};++export const WithMenu: ComponentStory<typeof StyleSourceInput> = () => {+ const [value, setValue] = useState<Array<Item>>([+ { id: "0", label: "Apple", type: "token", hasMenu: true },+ ]);+ const [editingIndex, setEditingIndex] = useState<number>(-1);+ return (+ <StyleSourceInput+ css={{ width: 300 }}+ items={items}+ value={value}+ editingIndex={editingIndex}+ onCreateItem={({ label }) => {+ const item: Item = { id: uuid(), label, type: "token", hasMenu: true };+ setValue([...value, item]);+ }}+ onSelectItem={(item) => {+ setValue([...value, item]);+ }}+ onRemoveItem={(itemToRemove) => {+ if (itemToRemove.type === "local") {+ return;+ }+ setValue(value.filter((item) => item.id !== itemToRemove.id));+ }}+ onChangeItem={(changedItem) => {+ setValue(+ value.map((item) => {+ if (item.id === changedItem.id) {+ return changedItem;+ }+ return item;+ })+ );+ }}+ 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);+ setEditingIndex(nextValue.indexOf(duplicatedItem));+ }}+ />+ );+};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-input/style-source-input.tsxindex 2b41c3c1d6..8b552b620f 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-input/style-source-input.tsx@@ -1,7 +1,5 @@import {Box,- Button,- Text,ComboboxListbox,ComboboxListboxItem,ComboboxPopper,@@ -14,80 +12,103 @@ import {type CSS,} from "@webstudio-is/design-system";import {- ComponentProps,- ElementRef,forwardRef,- RefObject,+ useEffect,useState,+ type ComponentProps,+ type ForwardRefRenderFunction,+ type RefObject,} from "react";import { mergeRefs } from "@react-aria/utils";+import { StyleSource } from "./style-source";type IntermediateItem = {label: string;+ hasMenu: boolean;};-type StyleSourceButtonProps = {- label: string;-};--const StyleSourceButton = ({ label }: StyleSourceButtonProps) => {- return (- <Button variant="gray" css={{ maxWidth: "100%" }}>- <Text truncate>{label}</Text>- </Button>- );-};--type TextFieldWrapperProps = Omit<ComponentProps<"input">, "value"> &+type TextFieldBaseWrapperProps<Item> = Omit<ComponentProps<"input">, "value"> &Pick<ComponentProps<typeof TextFieldContainer>,"variant" | "state" | "css"> & {- value: Array<IntermediateItem>;+ value: Array<Item>;label: string;disabled?: boolean;containerRef?: RefObject<HTMLDivElement>;inputRef?: RefObject<HTMLInputElement>;+ onRemoveItem?: (item: Item) => void;+ onDuplicateItem?: (item: Item) => void;+ onChangeItem?: (item: Item) => void;+ editingIndex: number;};-const TextField = forwardRef<ElementRef<typeof Box>, TextFieldWrapperProps>(- (props, forwardedRef) => {- const {- css,- disabled,- containerRef,- inputRef,- state,- variant,- onFocus,- onBlur,- onClick,- type,- onKeyDown,- label,- value,- ...textFieldProps- } = props;- const [internalInputRef, focusProps] = useTextFieldFocus({- disabled,- onFocus,- onBlur,- });-- return (- <TextFieldContainer- {...focusProps}- aria-disabled={disabled}- ref={mergeRefs(forwardedRef, containerRef ?? null)}- state={state}- variant={variant}- css={{ ...css, px: "$spacing$3", py: "$spacing$2" }}- onKeyDown={onKeyDown}- >- {value.map((item, index) => (- <StyleSourceButton label={item.label} key={index} />- ))}- {/* We want input to be the first element in DOM so it receives the focus first */}+const TextFieldBase: ForwardRefRenderFunction<+ HTMLDivElement,+ TextFieldBaseWrapperProps<IntermediateItem>+> = (props, forwardedRef) => {+ const {+ css,+ disabled,+ containerRef,+ inputRef,+ state,+ variant,+ onFocus,+ onBlur,+ onClick,+ type,+ onKeyDown,+ label,+ value,+ onRemoveItem,+ onDuplicateItem,+ onChangeItem,+ editingIndex: editingIndexProp,+ ...textFieldProps+ } = props;+ const [editingIndex, setEditingIndex] = useState(editingIndexProp);+ const [internalInputRef, focusProps] = useTextFieldFocus({+ disabled,+ onFocus,+ onBlur,+ });+ useEffect(() => {+ setEditingIndex(editingIndexProp);+ }, [editingIndexProp]);+ return (+ <TextFieldContainer+ {...focusProps}+ aria-disabled={disabled}+ ref={mergeRefs(forwardedRef, containerRef ?? null)}+ state={state}+ variant={variant}+ css={{ ...css, px: "$spacing$3", py: "$spacing$2" }}+ onKeyDown={onKeyDown}+ >+ {value.map((item, index) => (+ <StyleSource+ isEditing={index === editingIndex}+ onEditingChange={(isEditing) => {+ setEditingIndex(isEditing === true ? index : -1);+ }}+ onChange={(label) => {+ setEditingIndex(-1);+ onChangeItem?.({ ...item, label });+ }}+ onDuplicateItem={() => {+ onDuplicateItem?.(item);+ }}+ onRemoveItem={() => {+ onRemoveItem?.(item);+ }}+ label={item.label}+ hasMenu={item.hasMenu}+ key={index}+ />+ ))}+ {/* We want input to be the first element in DOM so it receives the focus first */}+ {editingIndex === -1 && (<TextFieldInput{...textFieldProps}value={label}@@ -95,19 +116,25 @@ const TextField = forwardRef<ElementRef<typeof Box>, TextFieldWrapperProps>(disabled={disabled}onClick={onClick}ref={mergeRefs(internalInputRef, inputRef ?? null)}+ autoFocus/>- </TextFieldContainer>- );- }-);+ )}+ </TextFieldContainer>+ );+};++const TextField = forwardRef(TextFieldBase);TextField.displayName = "TextField";type StyleSourceInputProps<Item> = {items?: Array<Item>;value?: Array<Item>;- onSelect: (item: Item) => void;- onRemove: (item: Item) => void;- onCreate: (item: IntermediateItem) => void;+ editingIndex?: number;+ onSelectItem?: (item: Item) => void;+ onRemoveItem?: (item: Item) => void;+ onCreateItem?: (item: Item) => void;+ onChangeItem?: (item: Item) => void;+ onDuplicateItem?: (item: Item) => void;css?: CSS;};@@ -115,6 +142,7 @@ export const StyleSourceInput = <Item extends IntermediateItem>(props: StyleSourceInputProps<Item>) => {const value = props.value ?? [];+ const editingIndex = props.editingIndex ?? -1;const [label, setLabel] = useState("");const {items,@@ -125,12 +153,12 @@ export const StyleSourceInput = <Item extends IntermediateItem>(isOpen,} = useCombobox({items: props.items ?? [],- value: { label },+ value: { label, hasMenu: true },selectedItem: undefined,itemToString: (item) => (item ? item.label : ""),onItemSelect(item) {setLabel("");- props.onSelect(item as Item);+ props.onSelectItem?.(item as Item);},onInputChange(label) {setLabel(label ?? "");@@ -139,14 +167,13 @@ export const StyleSourceInput = <Item extends IntermediateItem>(const inputProps = getInputProps({onKeyDown(event) {if (event.key === "Backspace" && label === "") {- props.onRemove(value[value.length - 1]);- return;+ props.onRemoveItem?.(value[value.length - 1]);}},onKeyPress(event) {if (event.key === "Enter" && label.trim() !== "") {setLabel("");- props.onCreate({ label });+ props.onCreateItem?.({ label, hasMenu: true } as Item);}},});@@ -157,9 +184,13 @@ export const StyleSourceInput = <Item extends IntermediateItem>(<ComboboxPopperAnchor><TextField{...inputProps}+ onRemoveItem={props.onRemoveItem}+ onChangeItem={props.onChangeItem}+ onDuplicateItem={props.onDuplicateItem}label={label}value={value}css={props.css}+ editingIndex={editingIndex}/></ComboboxPopperAnchor><ComboboxPopperContent align="start" sideOffset={5}>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.tsxnew file mode 100644index 0000000000..98ec427db3--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/style-source-input/style-source.tsx@@ -0,0 +1,230 @@+import { cssVars } from "@webstudio-is/css-vars";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuTrigger,+ IconButton,+ Button,+ 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";++// 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 = {+ onEdit: () => void;+ onDuplicateItem: () => void;+ onRemoveItem: () => 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>+ <DropdownMenuItem onSelect={scheduler.set(props.onDuplicateItem)}>+ Duplicate+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={scheduler.set(props.onRemoveItem)}>+ Remove+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenu>+ );+};++type EditableTextProps = {+ label: string;+ onChange: (value: string) => void;+ isEditing: boolean;+ onEditingChange: (isEditing: boolean) => void;+};++const EditableText = ({+ onChange,+ label,+ isEditing,+ onEditingChange,+}: EditableTextProps) => {+ const ref = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (ref.current === null) {+ return;+ }++ if (isEditing === true) {+ ref.current.setAttribute("contenteditable", "plaintext-only");+ ref.current.focus();+ getSelection()?.selectAllChildren(ref.current);+ return;+ }++ ref.current?.removeAttribute("contenteditable");+ }, [isEditing]);++ const handleFinishEditing = (+ event: KeyboardEvent<Element> | FocusEvent<Element>+ ) => {+ event.preventDefault();+ onEditingChange(false);+ onChange(ref.current?.textContent ?? "");+ };++ const handleKeyDown: KeyboardEventHandler = (event) => {+ if (event.key === "Enter") {+ handleFinishEditing(event);+ }+ };++ const handleClick = () => {+ onEditingChange(true);+ };++ return (+ <Text+ truncate+ ref={ref}+ onKeyDown={handleKeyDown}+ onBlur={handleFinishEditing}+ onClick={handleClick}+ css={{ outline: "none", textOverflow: isEditing ? "clip" : "ellipsis" }}+ >+ {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(Button, {+ maxWidth: "100%",+ position: "relative",+ ...menuCssVars({ show: false }),+ "&:hover": menuCssVars({ show: true }),+});++type EditableItemProps = {+ children: Array<JSX.Element | false>;+ isEditing: boolean;+};++const EditableItem = ({ children, isEditing }: EditableItemProps) => {+ const ref = useForceRecalcStyle<HTMLDivElement>(+ "max-width",+ isEditing === false+ );+ return (+ <Item variant="gray" ref={ref} as="div">+ {children}+ </Item>+ );+};++type StyleSourceProps = {+ label: string;+ hasMenu: boolean;+ isEditing: boolean;+ onEditingChange: (isEditing: boolean) => void;+ onDuplicateItem: () => void;+ onRemoveItem: () => void;+ onChange: (value: string) => void;+};++export const StyleSource = ({+ label,+ hasMenu,+ onChange,+ isEditing,+ onEditingChange,+ ...menuProps+}: StyleSourceProps) => {+ return (+ <EditableItem isEditing={isEditing}>+ <EditableText+ isEditing={isEditing}+ onEditingChange={onEditingChange}+ onChange={onChange}+ label={label}+ />+ {hasMenu === true && isEditing === false && (+ <Menu+ {...menuProps}+ onEdit={() => {+ onEditingChange(true);+ }}+ />+ )}+ </EditableItem>+ );+};