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.

(feat): Add ability to edit name of a tree node (#1909)

Jaya Krishna Namburu37b7672a438d
diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source.tsx
index f511fac711..7ae8bcb634 100644
--- a/apps/builder/app/builder/features/style-panel/style-source/style-source.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source.tsx
@@ -11,7 +11,7 @@ import {
Flex,
} from "@webstudio-is/design-system";
import { ChevronDownIcon } from "@webstudio-is/icons";
-import { useLayoutEffect, useRef, type ReactNode } from "react";
+import { type ReactNode } from "react";
import { useContentEditable } from "~/shared/dom-hooks";
const menuTriggerVisibilityVar = cssVars.define("menu-trigger-visibility");
@@ -141,31 +141,6 @@ const EditableText = ({
);
};
-// 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 StyleSourceContainer = styled(Box, {
display: "inline-flex",
borderRadius: theme.borderRadius[3],
@@ -270,7 +245,6 @@ export const StyleSource = ({
onChangeEditing,
onSelect,
}: StyleSourceProps) => {
- const ref = useForceRecalcStyle<HTMLDivElement>("max-width", isEditing);
const showMenu = isEditing === false && isDragging === false;
return (
@@ -281,7 +255,6 @@ export const StyleSource = ({
disabled={disabled}
aria-current={selected && state === undefined}
role="button"
- ref={ref}
>
<Flex css={{ flexGrow: 1, padding: theme.spacing[2] }}>
<StyleSourceButton
diff --git a/apps/builder/app/builder/shared/tree/index.tsx b/apps/builder/app/builder/shared/tree/index.tsx
index 304ca8daf1..bf3760c4f6 100644
--- a/apps/builder/app/builder/shared/tree/index.tsx
+++ b/apps/builder/app/builder/shared/tree/index.tsx
@@ -6,23 +6,29 @@ import {
TreeItemBody,
type TreeProps,
type TreeItemRenderProps,
+ styled,
+ theme,
} from "@webstudio-is/design-system";
import type { Instance } from "@webstudio-is/project-build";
+import store from "immerhin";
import { type WsComponentMeta } from "@webstudio-is/react-sdk";
import {
+ editingItemIdStore,
instancesStore,
registeredComponentMetasStore,
} from "~/shared/nano-states";
import { MetaIcon } from "../meta-icon";
+import { useContentEditable } from "~/shared/dom-hooks";
export const InstanceTree = (
props: Omit<
TreeProps<Instance>,
- "renderItem" | "canLeaveParent" | "getItemChildren"
+ "renderItem" | "canLeaveParent" | "getItemChildren" | "editingItemId"
>
) => {
const metas = useStore(registeredComponentMetasStore);
const instances = useStore(instancesStore);
+ const editingItemId = useStore(editingItemIdStore);
const canLeaveParent = useCallback(
(instanceId: Instance["id"]) => {
@@ -59,21 +65,49 @@ export const InstanceTree = (
[instances]
);
+ const updateInstanceLabel = useCallback(
+ (instanceId: string, value: string) => {
+ store.createTransaction([instancesStore], (instances) => {
+ const instance = instances.get(instanceId);
+ if (instance === undefined) {
+ return;
+ }
+ instance.label = value;
+ });
+ },
+ []
+ );
+
const renderItem = useCallback(
(props: TreeItemRenderProps<Instance>) => {
const meta = metas.get(props.itemData.component);
if (meta === undefined) {
return <></>;
}
+ const label = getInstanceLabel(props.itemData, meta);
+ const isEditing = props.itemData.id === editingItemId;
+
return (
- <TreeItemBody {...props} selectionEvent="focus">
- <TreeItemLabel prefix={<MetaIcon icon={meta.icon} />}>
- {getInstanceLabel(props.itemData, meta)}
- </TreeItemLabel>
+ <TreeItemBody {...props} selectionEvent="focus" isEditing={isEditing}>
+ <TreeItem
+ isEditable={true}
+ isEditing={isEditing}
+ onChangeValue={(val) => {
+ updateInstanceLabel(props.itemData.id, val);
+ }}
+ onChangeEditing={(isEditing) => {
+ editingItemIdStore.set(
+ isEditing === true ? props.itemData.id : undefined
+ );
+ }}
+ prefix={<MetaIcon icon={meta.icon} />}
+ >
+ {label}
+ </TreeItem>
</TreeItemBody>
);
},
- [metas]
+ [metas, updateInstanceLabel, editingItemId]
);
return (
@@ -82,6 +116,7 @@ export const InstanceTree = (
canLeaveParent={canLeaveParent}
getItemChildren={getItemChildren}
renderItem={renderItem}
+ editingItemId={editingItemId}
/>
);
};
@@ -92,3 +127,54 @@ export const getInstanceLabel = (
) => {
return instance.label || meta.label;
};
+
+const TreeItem = ({
+ prefix,
+ children,
+ isEditing,
+ isEditable = false,
+ onChangeValue,
+ onChangeEditing,
+}: {
+ isEditable: boolean;
+ isEditing: boolean;
+ prefix?: React.ReactNode;
+ children: React.ReactNode;
+ onChangeValue: (value: string) => void;
+ onChangeEditing: (isEditing: boolean) => void;
+}) => {
+ const { ref, handlers } = useContentEditable({
+ isEditable,
+ isEditing,
+ onChangeValue,
+ onChangeEditing,
+ });
+
+ return (
+ <EditableTreeItemLabel
+ ref={ref}
+ {...handlers}
+ isEditing={isEditing}
+ prefix={prefix}
+ >
+ {children}
+ </EditableTreeItemLabel>
+ );
+};
+
+const EditableTreeItemLabel = styled(TreeItemLabel, {
+ variants: {
+ isEditing: {
+ true: {
+ background: theme.colors.backgroundControls,
+ padding: theme.spacing[3],
+ borderRadius: theme.spacing[3],
+ color: theme.colors.hiContrast,
+ outline: "none",
+ cursor: "auto",
+ textOverflow: "clip",
+ userSelect: "auto",
+ },
+ },
+ },
+});
diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.ts
index 9059afe53d..78091d1980 100644
--- a/apps/builder/app/shared/nano-states/instances.ts
+++ b/apps/builder/app/shared/nano-states/instances.ts
@@ -2,6 +2,7 @@ import { atom, computed } from "nanostores";
import type { Instance, Instances } from "@webstudio-is/project-build";
import type { InstanceSelector } from "../tree-utils";
import { useSyncInitializeOnce } from "../hook-utils";
+import type { ItemId } from "node_modules/@webstudio-is/design-system/src/components/tree/item-utils";
export const isResizingCanvasStore = atom(false);
@@ -9,6 +10,8 @@ export const selectedInstanceSelectorStore = atom<undefined | InstanceSelector>(
undefined
);
+export const editingItemIdStore = atom<undefined | ItemId>(undefined);
+
export const textEditingInstanceSelectorStore = atom<
undefined | InstanceSelector
>();
diff --git a/apps/builder/app/shared/shortcuts/shortcuts.ts b/apps/builder/app/shared/shortcuts/shortcuts.ts
index 6d060b12a1..7611be8f11 100644
--- a/apps/builder/app/shared/shortcuts/shortcuts.ts
+++ b/apps/builder/app/shared/shortcuts/shortcuts.ts
@@ -2,6 +2,10 @@ import { type Options, useHotkeys } from "react-hotkeys-hook";
import store from "immerhin";
import { deleteSelectedInstance } from "../instance-utils";
import { selectBreakpointByOrder } from "../breakpoints";
+import {
+ editingItemIdStore,
+ selectedInstanceSelectorStore,
+} from "../nano-states";
export const shortcuts = {
esc: "esc",
@@ -51,6 +55,20 @@ export const useSharedShortcuts = ({
[]
);
+ useHotkeys(
+ "meta+e, 'ctrl+e",
+ () => {
+ const selectedInstanceSelector = selectedInstanceSelectorStore.get();
+ if (selectedInstanceSelector === undefined) {
+ return;
+ }
+ const targetInstanceId = selectedInstanceSelector[0];
+ editingItemIdStore.set(targetInstanceId);
+ },
+ {},
+ []
+ );
+
const breakpointShortcuts = Array.from(new Array(9))
.map((_, index) => `meta+${index + 1}, ctrl+${index + 1}`)
.join(", ");
diff --git a/packages/design-system/src/components/tree/tree-node.tsx b/packages/design-system/src/components/tree/tree-node.tsx
index 130a9b55f3..f5c9d27ab4 100644
--- a/packages/design-system/src/components/tree/tree-node.tsx
+++ b/packages/design-system/src/components/tree/tree-node.tsx
@@ -1,4 +1,11 @@
-import { useRef, useEffect, useMemo, useState } from "react";
+import {
+ useRef,
+ useEffect,
+ useMemo,
+ useState,
+ forwardRef,
+ type ForwardRefRenderFunction,
+} from "react";
import {
ChevronFilledDownIcon,
ChevronFilledRightIcon,
@@ -6,7 +13,7 @@ import {
import { cssVars } from "@webstudio-is/css-vars";
import { Box } from "../box";
import { Flex } from "../flex";
-import { DeprecatedText2 } from "../__DEPRECATED__/text2";
+import { Text } from "../text";
import { styled } from "../../stitches.config";
import { theme } from "../../stitches.config";
import {
@@ -256,12 +263,14 @@ export const TreeItemBody = <Data extends { id: string }>({
forceFocus = false,
selectionEvent = "click",
onToggle,
+ isEditing = false,
}: TreeItemRenderProps<Data> & {
children: React.ReactNode;
suffix?: React.ReactNode;
suffixWidth?: string;
alwaysShowSuffix?: boolean;
forceFocus?: boolean;
+ isEditing?: boolean;
selectionEvent?: "click" | "focus";
}) => {
const [focusTarget, setFocusTarget] = useState<
@@ -269,6 +278,7 @@ export const TreeItemBody = <Data extends { id: string }>({
>();
const itemButtonRef = useRef<HTMLButtonElement>(null);
const suffixContainerRef = useRef<HTMLDivElement>(null);
+
const updateFocusTarget = () => {
if (document.activeElement === itemButtonRef.current) {
setFocusTarget("item-button");
@@ -333,9 +343,9 @@ export const TreeItemBody = <Data extends { id: string }>({
{children}
</ItemButton>
- {/* We can't nest the collapsible trigger and suffix inside the ItemButton because
- <button> can't be nested inside <button>,
- click events will be mixed up,
+ {/* We can't nest the collapsible trigger and suffix inside the ItemButton because
+ <button> can't be nested inside <button>,
+ click events will be mixed up,
may hurt accessibility, etc. */}
{shouldRenderExpandButton && (
@@ -356,20 +366,31 @@ export const TreeItemBody = <Data extends { id: string }>({
);
};
-export const TreeItemLabel = ({
- children,
- prefix,
-}: {
- children: React.ReactNode;
- prefix?: React.ReactNode;
-}) => (
- <>
- {prefix}
- <DeprecatedText2 truncate css={{ ml: prefix ? theme.spacing[3] : 0 }}>
- {children}
- </DeprecatedText2>
- </>
-);
+export const TreeItemLabelBase: ForwardRefRenderFunction<
+ HTMLDivElement,
+ {
+ children: React.ReactNode;
+ prefix?: React.ReactNode;
+ }
+> = ({ children, prefix, ...restProps }, ref) => {
+ return (
+ <>
+ {prefix}
+ <Text
+ ref={ref}
+ truncate
+ css={{
+ ml: prefix ? theme.spacing[3] : 0,
+ }}
+ {...restProps}
+ >
+ {children}
+ </Text>
+ </>
+ );
+};
+
+export const TreeItemLabel = forwardRef(TreeItemLabelBase);
export type TreeNodeProps<Data extends { id: ItemId }> = {
itemData: Data;
diff --git a/packages/design-system/src/components/tree/tree.stories.tsx b/packages/design-system/src/components/tree/tree.stories.tsx
index 8888fc09d3..5b3697240d 100644
--- a/packages/design-system/src/components/tree/tree.stories.tsx
+++ b/packages/design-system/src/components/tree/tree.stories.tsx
@@ -84,6 +84,7 @@ export const StressTest = () => {
return (
<Flex css={{ width: 300, height: 500, flexDirection: "column" }}>
<Tree
+ editingItemId={undefined}
findClosestDroppableIndex={(itemSelector) => {
return itemSelector.findIndex((itemId) => {
const item = findItemById(root, itemId);
diff --git a/packages/design-system/src/components/tree/tree.tsx b/packages/design-system/src/components/tree/tree.tsx
index b59243be05..ec65ec9da8 100644
--- a/packages/design-system/src/components/tree/tree.tsx
+++ b/packages/design-system/src/components/tree/tree.tsx
@@ -44,6 +44,7 @@ export type TreeProps<Data extends { id: string }> = {
dropTarget: { itemSelector: ItemSelector; position: number | "end" };
}) => void;
onCancel: () => void;
+ editingItemId: ItemId | undefined;
};
const sharedDropOptions = {
@@ -75,6 +76,7 @@ export const Tree = <Data extends { id: string }>({
onDragItemChange,
onDragEnd,
onCancel,
+ editingItemId,
}: TreeProps<Data>) => {
const { getIsExpanded, setIsExpanded } = useExpandState({
selectedItemSelector,
@@ -259,6 +261,7 @@ export const Tree = <Data extends { id: string }>({
getIsExpanded,
setIsExpanded,
onEsc: dragHandlers.cancelCurrentDrag,
+ editingItemId,
});
return (
@@ -280,9 +283,9 @@ export const Tree = <Data extends { id: string }>({
>
<Box
ref={keyboardNavigation.rootRef}
+ onBlur={keyboardNavigation.handleBlur}
onKeyDown={keyboardNavigation.handleKeyDown}
onClick={keyboardNavigation.handleClick}
- onBlur={keyboardNavigation.handleBlur}
>
<TreeNode
renderItem={renderItem}
@@ -300,7 +303,6 @@ export const Tree = <Data extends { id: string }>({
dropTargetItemSelector={shiftedDropTarget?.itemSelector}
/>
</Box>
-
{shiftedDropTarget?.placement &&
createPortal(
<ListPositionIndicator
@@ -323,6 +325,7 @@ const useKeyboardNavigation = <Data extends { id: string }>({
getIsExpanded,
setIsExpanded,
onEsc,
+ editingItemId,
}: {
root: Data;
selectedItemSelector: undefined | ItemSelector;
@@ -331,6 +334,7 @@ const useKeyboardNavigation = <Data extends { id: string }>({
getIsExpanded: (itemSelector: ItemSelector) => boolean;
setIsExpanded: (itemSelector: ItemSelector, isExpanded: boolean) => void;
onEsc: () => void;
+ editingItemId: ItemId | undefined;
}) => {
const flatCurrentlyExpandedTree = useMemo(() => {
const result: ItemSelector[] = [];
@@ -357,6 +361,10 @@ const useKeyboardNavigation = <Data extends { id: string }>({
return;
}
+ if (editingItemId !== undefined) {
+ return;
+ }
+
if (
event.key === "ArrowRight" &&
getIsExpanded(selectedItemSelector) === false
@@ -442,6 +450,10 @@ const useKeyboardNavigation = <Data extends { id: string }>({
rootRef,
handleKeyDown,
handleClick(event: React.MouseEvent<Element>) {
+ if (editingItemId) {
+ return;
+ }
+
// When clicking on an item button make sure it gets focused.
// (see https://zellwk.com/blog/inconsistent-button-behavior/)
const itemButton = (event.target as HTMLElement).closest(