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
Sortable style source items (#770)
Oleg Isonen6a5fa7822a9b
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 8c8391d3a8..75fc4eda8c 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@@ -67,6 +67,7 @@ export const Initial: ComponentStory<typeof StyleSourceInput> = () => {}setValue(value.filter((item) => item.id !== itemToRemove.id));}}+ onSort={setValue}/>);};@@ -97,6 +98,7 @@ export const WithItems: ComponentStory<typeof StyleSourceInput> = () => {}setValue(value.filter((item) => item.id !== itemToRemove.id));}}+ onSort={setValue}/>);};@@ -138,6 +140,7 @@ export const WithTruncatedItem: ComponentStory<}setValue(value.filter((item) => item.id !== itemToRemove.id));}}+ onSort={setValue}/>);};@@ -223,6 +226,7 @@ export const WithMenu: ComponentStory<typeof StyleSourceInput> = () => {setValue(nextValue);setEditingIndex(nextValue.indexOf(duplicatedItem));}}+ 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-input/style-source-input.tsxindex 7ce868bf81..6a4db9a4ff 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@@ -21,8 +21,10 @@ import {} from "react";import { mergeRefs } from "@react-aria/utils";import { StyleSource, type ItemState } from "./style-source";+import { useSortable } from "./use-sortable";type IntermediateItem = {+ id: string;label: string;hasMenu: boolean;state: ItemState;@@ -43,6 +45,7 @@ type TextFieldBaseWrapperProps<Item> = Omit<ComponentProps<"input">, "value"> &onChangeItem?: (item: Item) => void;onDisableItem?: (item: Item) => void;onEnableItem?: (item: Item) => void;+ onSort?: (items: Array<Item>) => void;editingIndex: number;};@@ -69,6 +72,7 @@ const TextFieldBase: ForwardRefRenderFunction<onChangeItem,onDisableItem,onEnableItem,+ onSort,editingIndex: editingIndexProp,...textFieldProps} = props;@@ -81,11 +85,16 @@ const TextFieldBase: ForwardRefRenderFunction<useEffect(() => {setEditingIndex(editingIndexProp);}, [editingIndexProp]);+ const { sortableRefCallback, dragItemId, placementIndicator } = useSortable({+ items: value,+ onSort,+ });+return (<TextFieldContainer{...focusProps}aria-disabled={disabled}- ref={mergeRefs(forwardedRef, containerRef ?? null)}+ ref={mergeRefs(forwardedRef, containerRef ?? null, sortableRefCallback)}state={state}variant={variant}css={{ ...css, px: "$spacing$3", py: "$spacing$2" }}@@ -93,7 +102,14 @@ const TextFieldBase: ForwardRefRenderFunction<>{value.map((item, index) => (<StyleSource- state={index === editingIndex ? "editing" : item.state}+ id={item.id}+ state={+ item.id === dragItemId+ ? "dragging"+ : index === editingIndex+ ? "editing"+ : item.state+ }onStateChange={(state) => {setEditingIndex(state === "editing" ? index : -1);if (state === "disabled") {@@ -118,6 +134,7 @@ const TextFieldBase: ForwardRefRenderFunction<key={index}/>))}+ {placementIndicator}{/* We want input to be the first element in DOM so it receives the focus first */}{editingIndex === -1 && (<TextFieldInput@@ -148,6 +165,7 @@ type StyleSourceInputProps<Item> = {onDuplicateItem?: (item: Item) => void;onDisableItem?: (item: Item) => void;onEnableItem?: (item: Item) => void;+ onSort?: (items: Array<Item>) => void;css?: CSS;};@@ -166,7 +184,7 @@ export const StyleSourceInput = <Item extends IntermediateItem>(isOpen,} = useCombobox({items: props.items ?? [],- value: { label, hasMenu: true, state: "initial" },+ value: { label, hasMenu: true, state: "initial", id: "" },selectedItem: undefined,itemToString: (item) => (item ? item.label : ""),onItemSelect(item) {@@ -202,6 +220,7 @@ export const StyleSourceInput = <Item extends IntermediateItem>(onDuplicateItem={props.onDuplicateItem}onDisableItem={props.onDisableItem}onEnableItem={props.onEnableItem}+ onSort={props.onSort}label={label}value={value}css={props.css}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.tsxindex eb6cd40275..7341a31822 100644--- 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@@ -93,7 +93,7 @@ const Menu = (props: MenuProps) => {);};-export type ItemState = "initial" | "editing" | "disabled";+export type ItemState = "initial" | "editing" | "disabled" | "dragging";type EditableTextProps = {label: string;@@ -198,28 +198,34 @@ const Item = styled(Button, {},editing: {},initial: {},+ dragging: {+ // @todo styling+ opacity: 0.5,+ },},},});type EditableItemProps = {+ id: string;children: Array<JSX.Element | false>;state: ItemState;};-const EditableItem = ({ children, state }: EditableItemProps) => {+const EditableItem = ({ children, state, id }: EditableItemProps) => {const ref = useForceRecalcStyle<HTMLDivElement>("max-width",state === "editing");return (- <Item variant="gray" state={state} ref={ref} as="div">+ <Item variant="gray" state={state} ref={ref} as="div" data-id={id}>{children}</Item>);};type StyleSourceProps = {+ id: string;label: string;hasMenu: boolean;state: ItemState;@@ -230,15 +236,17 @@ type StyleSourceProps = {};export const StyleSource = ({+ id,label,hasMenu,state,onChange,onStateChange,- ...menuProps+ onDuplicate,+ onRemove,}: StyleSourceProps) => {return (- <EditableItem state={state}>+ <EditableItem state={state} id={id}><EditableTextstate={state}onStateChange={onStateChange}@@ -247,8 +255,9 @@ export const StyleSource = ({/>{hasMenu === true && state !== "editing" && (<Menu- {...menuProps}state={state}+ onDuplicate={onDuplicate}+ onRemove={onRemove}onEnable={() => {onStateChange("initial");}}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-input/use-sortable.tsxnew file mode 100644index 0000000000..3b48912160--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/style-source-input/use-sortable.tsx@@ -0,0 +1,116 @@+import { useState, useRef } from "react";+import {+ PlacementIndicator,+ useDrag,+ useDragCursor,+ useDrop,+ type DropTarget,+} from "@webstudio-is/design-system";++type UseSortable<Item> = {+ items: Array<Item>;+ onSort?: (items: Array<Item>) => void;+};++const getItemId = (element: Element) =>+ element instanceof HTMLElement ? element.dataset?.id : undefined;++export const useSortable = <Item extends { id: string }>({+ items,+ onSort,+}: UseSortable<Item>) => {+ const [dropTarget, setDropTarget] = useState<DropTarget<true>>();+ const [dragItemId, setDragItemId] = useState<string>();+ const rootRef = useRef<HTMLDivElement | null>(null);++ useDragCursor(dragItemId !== undefined);++ // drop target is always root+ // we need useDrop only for dropTarget.placement & dropTarget.indexWithinChildren+ const useDropHandlers = useDrop<true>({+ elementToData() {+ return true;+ },+ swapDropTarget() {+ if (rootRef.current === null) {+ throw new Error("Unexpected empty rootRef during drag");+ }+ return { data: true, element: rootRef.current };+ },+ onDropTargetChange(dropTarget) {+ setDropTarget(dropTarget);+ },+ getValidChildren(parent) {+ return [...parent.children].filter(+ (child) => getItemId(child) !== undefined+ );+ },+ childrenOrientation: { type: "horizontal", reverse: false },+ });++ const useDragHandlers = useDrag<string>({+ elementToData(element) {+ // disable drag unless there are at least 2 items+ if (items.length < 2) {+ return false;+ }++ const closest = element.closest("[data-id]");+ if (closest === null) {+ return false;+ }++ return getItemId(closest) || false;+ },+ onStart({ data }) {+ setDragItemId(data);+ useDropHandlers.handleStart();+ },+ onMove: (point) => {+ useDropHandlers.handleMove(point);+ },+ onEnd({ isCanceled }) {+ useDropHandlers.handleEnd({ isCanceled });+ setDragItemId(undefined);+ setDropTarget(undefined);++ if (isCanceled || dropTarget === undefined || dragItemId === undefined) {+ return;+ }++ const oldIndex = items.findIndex((item) => item.id === dragItemId);+ if (oldIndex !== -1) {+ let newIndex = dropTarget.indexWithinChildren;++ // placement.index does not take into account the fact that the drag item will be removed.+ // we need to do this to account for it.+ if (oldIndex < newIndex) {+ newIndex = Math.max(0, newIndex - 1);+ }++ if (oldIndex !== newIndex) {+ const newItems = [...items];+ newItems.splice(oldIndex, 1);+ newItems.splice(newIndex, 0, items[oldIndex]);+ onSort?.(newItems);+ }+ }+ },+ });++ const placementIndicator = dropTarget ? (+ <PlacementIndicator placement={dropTarget.placement} />+ ) : undefined;++ const sortableRefCallback = (element: HTMLDivElement | null) => {+ useDropHandlers.rootRef(element);+ useDragHandlers.rootRef(element);+ rootRef.current = element;+ };++ return {+ sortableRefCallback,+ dragItemId,+ placementIndicator,+ };+};diff --git a/packages/design-system/src/components/primitives/dnd/use-drop.ts b/packages/design-system/src/components/primitives/dnd/use-drop.tsindex 4e14e5d8ee..3151e36977 100644--- a/packages/design-system/src/components/primitives/dnd/use-drop.ts+++ b/packages/design-system/src/components/primitives/dnd/use-drop.ts@@ -11,6 +11,7 @@ import {type Point,type Placement,type Area,+ type ChildrenOrientation,} from "./geometry-utils";import { getLocalChildrenOrientation, getChildrenRects } from "./dom-utils";@@ -69,6 +70,10 @@ type UseDropProps<Data> = {// Distance from an edge when placement is put next to an element edgeplacementPadding?: number;++ // If not provided, will be guessed automatically based+ // on the actual orientation of the children+ childrenOrientation?: ChildrenOrientation;};// When emulatePointerAlwaysInRootBounds=true,@@ -143,12 +148,14 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {| Rect| undefined;- const childrenOrientation = getLocalChildrenOrientation(- partialDropTarget.element,- latestProps.current.getValidChildren ?? ((parent) => parent.children),- childrenRects,- closestChildIndex- );+ const childrenOrientation =+ latestProps.current.childrenOrientation ??+ getLocalChildrenOrientation(+ partialDropTarget.element,+ latestProps.current.getValidChildren ?? ((parent) => parent.children),+ childrenRects,+ closestChildIndex+ );const indexAdjustment = getIndexAdjustment(pointerRelativeToParent,@@ -176,11 +183,24 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {indexAdjustment === 0 ? closestChildIndex - 1 : closestChildIndex + 1] as Rect | undefined;- const placement =- toGlobalCoordinates(- getPlacementBetween(closestChildRect, neighbourRect)- ) ||- toGlobalCoordinates(+ let placement = toGlobalCoordinates(+ getPlacementBetween(closestChildRect, neighbourRect)+ );++ // If childrenOrientation is set explicitly, we want to honor it:+ // discard placement generated by getPlacementBetween if it has wrong direction+ const propsChildrenOrientation =+ latestProps.current.childrenOrientation;+ if (+ propsChildrenOrientation !== undefined &&+ placement !== undefined &&+ placement.direction === propsChildrenOrientation.type+ ) {+ placement = undefined;+ }++ if (placement === undefined) {+ placement = toGlobalCoordinates(getPlacementNextTo(parentRect,closestChildRect,@@ -188,12 +208,16 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {indexAdjustment > 0 ? "forward" : "backward",latestProps.current.placementPadding)- ) ||- getPlacementInside(+ );+ }++ if (placement === undefined) {+ placement = getPlacementInside(parentRect,childrenOrientation,latestProps.current.placementPadding);+ }const dropTarget: DropTarget<Data> = {...partialDropTarget,