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.

Select span node with selector (#1285)

Bogdan Chadkincd0e01ea565f
diff --git a/apps/builder/app/canvas/features/text-editor/interop.ts b/apps/builder/app/canvas/features/text-editor/interop.ts
index 3a75171cf3..fece6216d4 100644
--- a/apps/builder/app/canvas/features/text-editor/interop.ts
+++ b/apps/builder/app/canvas/features/text-editor/interop.ts
@@ -17,7 +17,7 @@ import type {
InstancesItem,
InstancesList,
} from "@webstudio-is/project-build";
-import { utils } from "@webstudio-is/project";
+import { nanoid } from "nanoid";
import { $isSpanNode, $setNodeSpan } from "./toolbar-connector";
// Map<nodeKey, instanceId>
@@ -46,7 +46,7 @@ const $writeUpdates = (
}
if ($isLinkNode(child)) {
const key = child.getKey();
- const id = refs.get(key) ?? utils.tree.createInstanceId();
+ const id = refs.get(key) ?? nanoid();
refs.set(key, id);
instanceChildren.push({
type: "id",
@@ -70,7 +70,7 @@ const $writeUpdates = (
if ($isSpanNode(child)) {
// prematurely generate span id to select it right after applying
const key = `${child.getKey()}:span`;
- const id = refs.get(key) ?? utils.tree.createInstanceId();
+ const id = refs.get(key) ?? nanoid();
refs.set(key, id);
const childInstance: InstancesItem = {
type: "instance",
@@ -86,7 +86,7 @@ const $writeUpdates = (
for (const [format, component] of lexicalFormats) {
if (child.hasFormat(format)) {
const key = `${child.getKey()}:${format}`;
- const id = refs.get(key) ?? utils.tree.createInstanceId();
+ const id = refs.get(key) ?? nanoid();
refs.set(key, id);
const childInstance: InstancesItem = {
type: "instance",
diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx
index 642c06b848..f18e503461 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx
@@ -135,7 +135,7 @@ export const Basic: ComponentStory<typeof TextEditor> = ({ onChange }) => {
}}
>
<TextEditor
- rootInstanceId={"1"}
+ rootInstanceSelector={["1"]}
instances={instances}
contentEditable={<ContentEditable />}
onChange={onChange}
diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
index 4d502b1df8..f31acf8e5e 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
@@ -25,6 +25,7 @@ import type {
InstancesList,
} from "@webstudio-is/project-build";
import { idAttribute } from "@webstudio-is/react-sdk";
+import type { InstanceSelector } from "~/shared/tree-utils";
import { ToolbarConnectorPlugin } from "./toolbar-connector";
import { type Refs, $convertToLexical, $convertToUpdates } from "./interop";
@@ -117,15 +118,15 @@ const onError = (error: Error) => {
};
type TextEditorProps = {
- rootInstanceId: Instance["id"];
+ rootInstanceSelector: InstanceSelector;
instances: Instances;
contentEditable: JSX.Element;
onChange: (instancesList: InstancesList) => void;
- onSelectInstance: (instanceId: string) => void;
+ onSelectInstance: (instanceId: Instance["id"]) => void;
};
export const TextEditor = ({
- rootInstanceId,
+ rootInstanceSelector,
instances,
contentEditable,
onChange,
@@ -168,7 +169,7 @@ export const TextEditor = ({
// text editor is unmounted when change properties in side panel
// so assume new nodes don't need to preserve instance id
// and store only initial references
- $convertToLexical(instances, rootInstanceId, refs);
+ $convertToLexical(instances, rootInstanceSelector[0], refs);
},
nodes: [LinkNode],
onError,
@@ -198,7 +199,7 @@ export const TextEditor = ({
ignoreSelectionChange={true}
onChange={(editorState) => {
editorState.read(() => {
- const treeRootInstance = instances.get(rootInstanceId);
+ const treeRootInstance = instances.get(rootInstanceSelector[0]);
if (treeRootInstance) {
onChange($convertToUpdates(treeRootInstance, refs));
}
diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
index fe67b00fe3..5113accf6a 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -7,6 +7,7 @@ import {
type Instance,
type Prop,
findTreeInstanceIds,
+ Instances,
} from "@webstudio-is/project-build";
import {
renderWebstudioComponentChildren,
@@ -22,8 +23,11 @@ import {
useTextEditingInstanceId,
} from "~/shared/nano-states";
import { useCssRules } from "~/canvas/shared/styles";
+import {
+ areInstanceSelectorsEqual,
+ InstanceSelector,
+} from "~/shared/tree-utils";
import { SelectedInstanceConnector } from "./selected-instance-connector";
-import { getInstanceSelector } from "~/shared/tree-utils";
import { handleLinkClick } from "./link";
const TextEditor = lazy(() => import("../text-editor"));
@@ -51,14 +55,47 @@ const ContentEditable = ({
type UserProps = Record<Prop["name"], Prop["value"]>;
+// this utility is temporary solution to compute instance selectors
+// for rich text subtree which cannot have slots so its safe to traverse ancestors
+// until editor instance is reached
+//
+// once all lexical formats are replaced with elmenents it should be
+// straightforward to compute selectors from lexical tree
+const getInstanceSelector = (
+ instances: Instances,
+ rootInstanceSelector: InstanceSelector,
+ instanceId: Instance["id"]
+) => {
+ const parentInstancesById = new Map<Instance["id"], Instance["id"]>();
+ for (const instance of instances.values()) {
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ parentInstancesById.set(child.value, instance.id);
+ }
+ }
+ }
+ const selector: InstanceSelector = [];
+ let currentInstanceId: undefined | Instance["id"] = instanceId;
+ while (currentInstanceId) {
+ selector.push(currentInstanceId);
+ currentInstanceId = parentInstancesById.get(currentInstanceId);
+ if (currentInstanceId === rootInstanceSelector[0]) {
+ return [...selector, ...rootInstanceSelector];
+ }
+ }
+ return undefined;
+};
+
type WebstudioComponentDevProps = {
instance: Instance;
+ instanceSelector: InstanceSelector;
children: Array<JSX.Element | string>;
getComponent: GetComponent;
};
export const WebstudioComponentDev = ({
instance,
+ instanceSelector,
children,
getComponent,
}: WebstudioComponentDevProps) => {
@@ -86,8 +123,10 @@ export const WebstudioComponentDev = ({
return result;
}, [instanceProps]);
- // @todo compare instance selectors
- const isSelected = selectedInstanceSelector?.[0] === instanceId;
+ const isSelected = areInstanceSelectorsEqual(
+ selectedInstanceSelector,
+ instanceSelector
+ );
// Scroll the selected instance into view when selected from navigator.
useEffect(() => {
@@ -146,6 +185,7 @@ export const WebstudioComponentDev = ({
</>
);
+ // @todo compare instance selectors
if (editingInstanceId !== instance.id) {
return instanceElement;
}
@@ -153,7 +193,7 @@ export const WebstudioComponentDev = ({
return (
<Suspense fallback={instanceElement}>
<TextEditor
- rootInstanceId={instance.id}
+ rootInstanceSelector={instanceSelector}
instances={instances}
contentEditable={
<ContentEditable
@@ -175,12 +215,15 @@ export const WebstudioComponentDev = ({
}
});
}}
- // @todo provide instance selector
onSelectInstance={(instanceId) => {
setTextEditingInstanceId(undefined);
- selectedInstanceSelectorStore.set(
- getInstanceSelector(instancesStore.get(), instanceId)
+ const instances = instancesStore.get();
+ const newSelectedSelector = getInstanceSelector(
+ instances,
+ instanceSelector,
+ instanceId
);
+ selectedInstanceSelectorStore.set(newSelectedSelector);
}}
/>
</Suspense>
diff --git a/apps/builder/app/shared/tree-utils.test.ts b/apps/builder/app/shared/tree-utils.test.ts
index 6b591b5d96..114864a52e 100644
--- a/apps/builder/app/shared/tree-utils.test.ts
+++ b/apps/builder/app/shared/tree-utils.test.ts
@@ -16,7 +16,6 @@ import {
findClosestDroppableTarget,
findSubtreeLocalStyleSources,
getAncestorInstanceSelector,
- getInstanceSelector,
getInstanceAncestorsAndSelf,
insertInstancesCopyMutable,
insertInstancesMutable,
@@ -127,30 +126,6 @@ test("get ancestor instance selector", () => {
expect(getAncestorInstanceSelector(instanceSelector, "1")).toEqual(["1"]);
});
-test("get instance selector", () => {
- const instances: Instances = new Map([
- createInstancePair("root", "Box", [
- { type: "id", value: "box1" },
- { type: "id", value: "box2" },
- { type: "id", value: "box4" },
- ]),
- createInstancePair("box1", "Box", []),
- createInstancePair("box2", "Box", [{ type: "id", value: "box3" }]),
- createInstancePair("box4", "Box", []),
- createInstancePair("box3", "Box", [
- { type: "id", value: "child1" },
- { type: "id", value: "child2" },
- ]),
- createInstancePair("child1", "Box", []),
- createInstancePair("child2", "Box", []),
- ]);
- expect(getInstanceSelector(instances, "box3")).toEqual([
- "box3",
- "box2",
- "root",
- ]);
-});
-
test("find closest droppable target", () => {
const instances = new Map([
createInstancePair("root", "Body", [
diff --git a/apps/builder/app/shared/tree-utils.ts b/apps/builder/app/shared/tree-utils.ts
index 77441e9b7c..16d51f2300 100644
--- a/apps/builder/app/shared/tree-utils.ts
+++ b/apps/builder/app/shared/tree-utils.ts
@@ -44,30 +44,6 @@ export const areInstanceSelectorsEqual = (
return left.join(",") === right.join(",");
};
-// this utility is temporary solution to compute instance selectors
-// before all logic is migrated to get it from rendered context
-// @todo should be deleted before adding slots
-export const getInstanceSelector = (
- instances: Instances,
- instanceId: Instance["id"]
-) => {
- const parentInstancesById = new Map<Instance["id"], Instance["id"]>();
- for (const instance of instances.values()) {
- for (const child of instance.children) {
- if (child.type === "id") {
- parentInstancesById.set(child.value, instance.id);
- }
- }
- }
- const selector: InstanceSelector = [];
- let currentInstanceId: undefined | Instance["id"] = instanceId;
- while (currentInstanceId) {
- selector.push(currentInstanceId);
- currentInstanceId = parentInstancesById.get(currentInstanceId);
- }
- return selector;
-};
-
export const createComponentInstance = (
component: Instance["component"]
): InstancesItem => {
diff --git a/packages/project/src/index.ts b/packages/project/src/index.ts
index 916e7c5f50..e7e07d6038 100644
--- a/packages/project/src/index.ts
+++ b/packages/project/src/index.ts
@@ -1,9 +1,7 @@
import * as breakpointsUtils from "./shared/breakpoints";
-import * as treeUtils from "./shared/tree-utils";
export const utils = {
breakpoints: breakpointsUtils,
- tree: treeUtils,
} as const;
export * from "./shared/styles";
diff --git a/packages/project/src/shared/tree-utils/create-instance.test.ts b/packages/project/src/shared/tree-utils/create-instance.test.ts
deleted file mode 100644
index c359b39898..0000000000
--- a/packages/project/src/shared/tree-utils/create-instance.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { describe, test, expect } from "@jest/globals";
-import { createInstance } from "./create-instance";
-
-describe("create instance", () => {
- test("instance without id should be auto generated", () => {
- const createdInstance = createInstance({
- component: "Box",
- });
-
- expect(typeof createdInstance.id).toBe("string");
- });
-
- test("instance without children should be empty by default", () => {
- const createdInstance = createInstance({
- component: "Box",
- });
- expect(createdInstance.children.length).toBe(0);
- });
-
- test("instance with children ", () => {
- const createdInstance = createInstance({
- component: "Box",
- children: [
- {
- type: "instance",
- id: "1",
- component: "Box",
- children: [],
- },
- ],
- });
- expect(createdInstance.children).toEqual([
- {
- type: "instance",
- id: "1",
- component: "Box",
- children: [],
- },
- ]);
- });
-});
diff --git a/packages/project/src/shared/tree-utils/create-instance.ts b/packages/project/src/shared/tree-utils/create-instance.ts
deleted file mode 100644
index 22680b24df..0000000000
--- a/packages/project/src/shared/tree-utils/create-instance.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { nanoid } from "nanoid";
-import type { Instance } from "@webstudio-is/project-build";
-import { getComponentMeta } from "@webstudio-is/react-sdk";
-
-export const createInstanceId = () => {
- return nanoid();
-};
-
-export const createInstance = ({
- component,
- id,
- children,
-}: {
- component: Instance["component"];
- id?: Instance["id"];
- children?: Instance["children"];
-}): Instance => {
- const componentMeta = getComponentMeta(component);
- return {
- type: "instance",
- component,
- id: id ?? createInstanceId(),
- children:
- children === undefined
- ? componentMeta?.children?.map((value) => ({ type: "text", value })) ??
- []
- : children,
- };
-};
diff --git a/packages/project/src/shared/tree-utils/index.ts b/packages/project/src/shared/tree-utils/index.ts
deleted file mode 100644
index 2835c96c85..0000000000
--- a/packages/project/src/shared/tree-utils/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./create-instance";
diff --git a/packages/react-sdk/src/tree/create-elements-tree.tsx b/packages/react-sdk/src/tree/create-elements-tree.tsx
index 4054500da1..382b0d4ba9 100644
--- a/packages/react-sdk/src/tree/create-elements-tree.tsx
+++ b/packages/react-sdk/src/tree/create-elements-tree.tsx
@@ -8,6 +8,8 @@ import type { Assets, PropsByInstanceId } from "../props";
import type { WebstudioComponent } from "./webstudio-component";
import { SessionStoragePolyfill } from "./session-storage-polyfill";
+type InstanceSelector = Instance["id"][];
+
export const createElementsTree = ({
sandbox,
instance,
@@ -23,14 +25,17 @@ export const createElementsTree = ({
Component: (props: ComponentProps<typeof WebstudioComponent>) => JSX.Element;
getComponent: GetComponent;
}) => {
+ const rootInstanceSelector = [instance.id];
const children = createInstanceChildrenElements({
+ instanceSelector: rootInstanceSelector,
Component,
children: instance.children,
getComponent,
});
- const body = createInstanceElement({
+ const root = createInstanceElement({
Component,
instance,
+ instanceSelector: rootInstanceSelector,
children: [
<Fragment key="children">
{children}
@@ -43,16 +48,18 @@ export const createElementsTree = ({
});
return (
<ReactSdkContext.Provider value={{ propsByInstanceIdStore, assetsStore }}>
- {body}
+ {root}
</ReactSdkContext.Provider>
);
};
const createInstanceChildrenElements = ({
+ instanceSelector,
children,
Component,
getComponent,
}: {
+ instanceSelector: InstanceSelector;
children: Instance["children"];
Component: (props: ComponentProps<typeof WebstudioComponent>) => JSX.Element;
getComponent: GetComponent;
@@ -63,13 +70,16 @@ const createInstanceChildrenElements = ({
elements.push(child.value);
continue;
}
+ const childInstanceSelector = [child.id, ...instanceSelector];
const children = createInstanceChildrenElements({
+ instanceSelector: childInstanceSelector,
children: child.children,
Component,
getComponent,
});
const element = createInstanceElement({
instance: child,
+ instanceSelector: childInstanceSelector,
Component,
children,
getComponent,
@@ -82,20 +92,24 @@ const createInstanceChildrenElements = ({
const createInstanceElement = ({
Component,
instance,
+ instanceSelector,
children = [],
getComponent,
}: {
instance: Instance;
+ instanceSelector: InstanceSelector;
Component: (props: ComponentProps<typeof WebstudioComponent>) => JSX.Element;
children?: Array<JSX.Element | string>;
getComponent: GetComponent;
}) => {
- const props = {
- instance,
- children,
- key: instance.id,
- getComponent,
- };
-
- return <Component {...props} />;
+ return (
+ <Component
+ key={instance.id}
+ instance={instance}
+ instanceSelector={instanceSelector}
+ getComponent={getComponent}
+ >
+ {children}
+ </Component>
+ );
};
diff --git a/packages/react-sdk/src/tree/webstudio-component.tsx b/packages/react-sdk/src/tree/webstudio-component.tsx
index cbbee1cb4c..d16a0c2107 100644
--- a/packages/react-sdk/src/tree/webstudio-component.tsx
+++ b/packages/react-sdk/src/tree/webstudio-component.tsx
@@ -28,6 +28,7 @@ export const renderWebstudioComponentChildren = (
type WebstudioComponentProps = {
instance: Instance;
+ instanceSelector: Instance["id"][];
children: Array<JSX.Element | string>;
getComponent: GetComponent;
};