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.

fix: expose existing text bindings in mixed content (#6008)

Oleg Isonen08e1e19b3fda
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.test.ts b/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.test.ts
new file mode 100644
index 0000000000..28d9bd3aaa
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.test.ts
@@ -0,0 +1,67 @@
+import { expect, test } from "vitest";
+import type { Instance } from "@webstudio-is/sdk";
+import { getTextContentUpdateOperation } from "./text-content-utils";
+
+const createInstance = (children: Instance["children"]): Instance => ({
+ type: "instance",
+ id: "reading-time",
+ component: "ws:element",
+ tag: "span",
+ children,
+});
+
+test("updates the targeted expression without replacing its siblings", () => {
+ expect(
+ getTextContentUpdateOperation({
+ instance: createInstance([
+ { type: "text", value: " · " },
+ { type: "expression", value: "1 + 1" },
+ ]),
+ type: "expression",
+ value: "2 + 2",
+ })
+ ).toEqual({
+ id: "instances.updateText",
+ input: {
+ instanceId: "reading-time",
+ childIndex: 1,
+ mode: "expression",
+ text: "2 + 2",
+ },
+ });
+});
+
+test("does not replace unsupported nonempty content", () => {
+ expect(
+ getTextContentUpdateOperation({
+ instance: undefined,
+ type: "text",
+ value: "replacement",
+ })
+ ).toBeUndefined();
+ expect(
+ getTextContentUpdateOperation({
+ instance: createInstance([{ type: "id", value: "nested" }]),
+ type: "text",
+ value: "replacement",
+ })
+ ).toBeUndefined();
+});
+
+test("sets text content on an empty instance", () => {
+ expect(
+ getTextContentUpdateOperation({
+ instance: createInstance([]),
+ type: "text",
+ value: "content",
+ })
+ ).toEqual({
+ id: "instances.setTextContent",
+ input: {
+ operation: "set",
+ instanceId: "reading-time",
+ mode: "text",
+ text: "content",
+ },
+ });
+});
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.ts b/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.ts
new file mode 100644
index 0000000000..026ad24f97
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content-utils.ts
@@ -0,0 +1,40 @@
+import type { Instance } from "@webstudio-is/sdk";
+import { getEditableTextTarget } from "@webstudio-is/project-build/runtime";
+
+export const getTextContentUpdateOperation = ({
+ instance,
+ type,
+ value,
+}: {
+ instance: Instance | undefined;
+ type: "text" | "expression";
+ value: string;
+}) => {
+ if (instance === undefined) {
+ return;
+ }
+ const childIndex = getEditableTextTarget(instance)?.childIndex;
+ if (childIndex !== undefined) {
+ return {
+ id: "instances.updateText" as const,
+ input: {
+ instanceId: instance.id,
+ childIndex,
+ mode: type,
+ text: value,
+ },
+ };
+ }
+ if (instance.children.length > 0) {
+ return;
+ }
+ return {
+ id: "instances.setTextContent" as const,
+ input: {
+ operation: "set" as const,
+ instanceId: instance.id,
+ mode: type,
+ text: value,
+ },
+ };
+};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsx
new file mode 100644
index 0000000000..b191c65899
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsx
@@ -0,0 +1,223 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { act } from "react-dom/test-utils";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { EditorView } from "@codemirror/view";
+import { TooltipProvider } from "@webstudio-is/design-system";
+import { textContentAttribute } from "@webstudio-is/react-sdk";
+import type { Instance } from "@webstudio-is/sdk";
+import { createDefaultPages } from "@webstudio-is/project-build";
+import { $builderMode } from "~/shared/nano-states";
+import { $instances, $pages } from "~/shared/sync/data-stores";
+import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";
+import { TextContent } from "./text-content";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+registerContainers();
+
+let container: HTMLDivElement;
+let root: Root;
+const rangeGetClientRects = Object.getOwnPropertyDescriptor(
+ Range.prototype,
+ "getClientRects"
+);
+
+const setReadingTimeChildren = (children: Instance["children"]) => {
+ $instances.set(
+ new Map([
+ [
+ "reading-time",
+ {
+ type: "instance" as const,
+ id: "reading-time",
+ component: "ws:element",
+ tag: "span",
+ children,
+ },
+ ],
+ ])
+ );
+};
+
+beforeEach(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ Object.defineProperty(Range.prototype, "getClientRects", {
+ configurable: true,
+ value: () => [],
+ });
+ serverSyncStore.transactionManager.currentStack = [];
+ serverSyncStore.transactionManager.undoneStack = [];
+ serverSyncStore.popAll();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ $builderMode.set("design");
+ $pages.set(createDefaultPages({ rootInstanceId: "reading-time" }));
+ setReadingTimeChildren([
+ { type: "text", value: " · " },
+ { type: "expression", value: "1 + 1" },
+ ]);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ $instances.set(new Map());
+ vi.unstubAllGlobals();
+ if (rangeGetClientRects === undefined) {
+ delete (Range.prototype as { getClientRects?: unknown }).getClientRects;
+ } else {
+ Object.defineProperty(
+ Range.prototype,
+ "getClientRects",
+ rangeGetClientRects
+ );
+ }
+});
+
+const renderTextContent = (computedValue = " · 2") => {
+ act(() => {
+ root.render(
+ <TooltipProvider>
+ <TextContent
+ instanceId="reading-time"
+ meta={{ control: "textContent", type: "string", required: false }}
+ prop={undefined}
+ propName={textContentAttribute}
+ computedValue={computedValue}
+ onChange={() => {}}
+ />
+ </TooltipProvider>
+ );
+ });
+};
+
+const openBindingPopover = async () => {
+ const trigger = container.querySelector<HTMLButtonElement>(
+ 'button[data-variant="bound"]'
+ );
+ if (trigger === null) {
+ throw new Error("Expected the bound expression trigger");
+ }
+ await act(async () => {
+ trigger.click();
+ await new Promise<void>((resolve) =>
+ requestAnimationFrame(() => resolve())
+ );
+ });
+};
+
+const getResetBindingButton = () => {
+ const button = document.querySelector<HTMLButtonElement>(
+ '[aria-label="Reset binding"]'
+ );
+ if (button === null) {
+ throw new Error("Expected the reset binding button");
+ }
+ return button;
+};
+
+test("renders the existing bound Text content control for the expression child", () => {
+ renderTextContent();
+
+ expect(container.textContent).toContain("Text Content");
+ expect(container.querySelector('[role="textbox"]')?.textContent).toBe("2");
+ expect(container.querySelector('[data-variant="bound"]')).not.toBeNull();
+});
+
+test("updates only the targeted expression child through the binding editor", async () => {
+ renderTextContent();
+ await openBindingPopover();
+
+ const editorElement = document.querySelector<HTMLElement>(
+ '[role="dialog"] [role="textbox"]'
+ );
+ if (editorElement === null) {
+ throw new Error("Expected the expression editor");
+ }
+ const view = EditorView.findFromDOM(editorElement);
+ if (view === null) {
+ throw new Error("Expected the CodeMirror view");
+ }
+
+ act(() => {
+ view.dispatch({
+ changes: {
+ from: 0,
+ to: view.state.doc.length,
+ insert: "2 + 2",
+ },
+ });
+ });
+ act(() => {
+ view.focus();
+ view.contentDOM.blur();
+ });
+
+ expect($instances.get().get("reading-time")?.children).toEqual([
+ { type: "text", value: " · " },
+ { type: "expression", value: "2 + 2" },
+ ]);
+});
+
+test("resets a mixed expression without replacing its text sibling", async () => {
+ setReadingTimeChildren([
+ { type: "text", value: " · " },
+ { type: "expression", value: '"test"' },
+ ]);
+ renderTextContent(" · test");
+ await openBindingPopover();
+
+ const resetButton = getResetBindingButton();
+ expect(resetButton.disabled).toBe(false);
+ act(() => resetButton.click());
+
+ expect($instances.get().get("reading-time")?.children).toEqual([
+ { type: "text", value: " · test" },
+ ]);
+});
+
+test("resets and consolidates every expression on the instance", async () => {
+ setReadingTimeChildren([
+ { type: "text", value: "A" },
+ { type: "expression", value: '"B"' },
+ { type: "expression", value: '"C"' },
+ { type: "text", value: "D" },
+ ]);
+ renderTextContent("ABCD");
+ await openBindingPopover();
+
+ const resetButton = getResetBindingButton();
+ expect(resetButton.disabled).toBe(false);
+ act(() => resetButton.click());
+
+ expect($instances.get().get("reading-time")?.children).toEqual([
+ { type: "text", value: "ABCD" },
+ ]);
+});
+
+test("resets a sole expression to its evaluated text value", async () => {
+ setReadingTimeChildren([{ type: "expression", value: "1 + 1" }]);
+ renderTextContent("2");
+ await openBindingPopover();
+
+ const resetButton = getResetBindingButton();
+ expect(resetButton.disabled).toBe(false);
+ act(() => resetButton.click());
+
+ expect($instances.get().get("reading-time")?.children).toEqual([
+ { type: "text", value: "2" },
+ ]);
+});
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
index 0a04094b10..e07f29750b 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
@@ -24,6 +24,9 @@ import { CodeEditor } from "~/shared/code-editor";
import { type ControlProps, VerticalLayout } from "../shared";
import { FieldLabel, useIsBindingResetForbidden } from "../property-label";
import { useBindableControl } from "./use-bindable-control";
+import { evaluateExpressionWithinScope } from "~/builder/shared/binding-popover";
+import { getEditableTextTarget } from "@webstudio-is/project-build/runtime";
+import { getTextContentUpdateOperation } from "./text-content-utils";
const useInstance = (instanceId: Instance["id"]) => {
const $store = useMemo(() => {
@@ -32,50 +35,78 @@ const useInstance = (instanceId: Instance["id"]) => {
return useStore($store);
};
-const updateChildren = (
- instanceId: Instance["id"],
- type: "text" | "expression",
- value: string
-) => {
- executeRuntimeMutation({
- id: "instances.setTextContent",
- input: {
- operation: "set",
- instanceId,
- mode: type,
- text: value,
- },
- });
-};
-
export const TextContent = ({
instanceId,
computedValue,
}: ControlProps<"textContent">) => {
const instance = useInstance(instanceId);
- const hasChildren = (instance?.children.length ?? 0) > 0;
- // text content control is rendered only when empty or single child are present
- const child = instance?.children?.[0] ?? { type: "text", value: "" };
- const localValue = useDraftValue(String(computedValue ?? ""), (value) => {
- updateBindableValue({
- expression: child.type === "expression" ? child.value : undefined,
- value,
- onChangeValue: (value) => updateChildren(instanceId, "text", value),
+ const childrenCount = instance?.children.length ?? 0;
+ const hasChildren = childrenCount > 0;
+ const hasMixedContent = childrenCount > 1;
+ const target = instance && getEditableTextTarget(instance);
+ const child = target?.child ?? { type: "text" as const, value: "" };
+ const updateChild = (type: "text" | "expression", value: string) => {
+ const operation = getTextContentUpdateOperation({ instance, type, value });
+ if (operation !== undefined) {
+ executeRuntimeMutation(operation);
+ }
+ };
+ const resetBindings = (evaluatedValue: unknown) => {
+ if (instance === undefined || target === undefined) {
+ return;
+ }
+ const replacements = instance.children.flatMap((child, childIndex) => {
+ if (child.type !== "expression") {
+ return [];
+ }
+ const value =
+ childIndex === target.childIndex
+ ? evaluatedValue
+ : evaluateExpressionWithinScope(child.value, binding.scope);
+ return [
+ {
+ childIndex,
+ expression: child.value,
+ text: String(value),
+ },
+ ];
});
- });
+ executeRuntimeMutation({
+ id: "instances.setTextContent",
+ input: {
+ operation: "inlineExpressions",
+ instanceId: instance.id,
+ replacements,
+ },
+ });
+ };
- let expression: undefined | string;
- if (child.type === "text") {
- expression = JSON.stringify(child.value);
- }
- if (child.type === "expression") {
- expression = child.value;
- }
+ const expression =
+ child.type === "text" ? JSON.stringify(child.value) : child.value;
const binding = useBindableControl({
boundExpression: child.type === "expression" ? expression : undefined,
- fallbackExpression: expression ?? "",
+ fallbackExpression: expression,
});
+ let displayedValue = computedValue;
+ if (hasMixedContent && child.type === "expression") {
+ try {
+ displayedValue = evaluateExpressionWithinScope(
+ child.value,
+ binding.scope
+ );
+ } catch {
+ displayedValue = undefined;
+ }
+ }
+ const localValue = useDraftValue(String(displayedValue ?? ""), (value) => {
+ updateBindableValue({
+ expression: child.type === "expression" ? child.value : undefined,
+ value,
+ onChangeValue: (value) => updateChild("text", value),
+ });
+ });
+
const isBindingResetForbidden = useIsBindingResetForbidden();
const isResetDisabled =
child.type === "expression" && isBindingResetForbidden;
@@ -103,7 +134,7 @@ export const TextContent = ({
</>
}
resettable={hasChildren}
- resetDisabled={isResetDisabled}
+ resetDisabled={isResetDisabled || hasMixedContent}
onReset={() => {
executeRuntimeMutation({
id: "instances.setTextContent",
@@ -121,13 +152,10 @@ export const TextContent = ({
<BindableExpressionControl
{...binding}
value={localValue.value}
- showBinding={expression !== undefined}
validate={(value) => validatePrimitiveValue(value, "Text Content")}
- onChangeValue={(value) => updateChildren(instanceId, "text", value)}
- onChangeExpression={(value) =>
- updateChildren(instanceId, "expression", value)
- }
- onRemove={(value) => updateChildren(instanceId, "text", String(value))}
+ onChangeValue={(value) => updateChild("text", value)}
+ onChangeExpression={(value) => updateChild("expression", value)}
+ onRemove={resetBindings}
renderControl={({ readOnly }) => (
<CodeEditor
title={
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.ts
index 4e8b03565b..ce487a644c 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.ts
+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.ts
@@ -1,10 +1,16 @@
import { describe, expect, test } from "vitest";
-import type { Prop, PropMeta } from "@webstudio-is/sdk";
+import type {
+ Instance,
+ Prop,
+ PropMeta,
+ WsComponentMeta,
+} from "@webstudio-is/sdk";
import { textContentAttribute } from "@webstudio-is/react-sdk";
import { __testing__ } from "./use-props-logic";
import type { ContentModeCapabilities } from "@webstudio-is/project-build/runtime";
-const { isPropVisibleInContentMode, getAndDelete } = __testing__;
+const { isPropVisibleInContentMode, getAndDelete, canShowTextContent } =
+ __testing__;
const getInput = (
input: Partial<Parameters<typeof isPropVisibleInContentMode>[0]> = {}
@@ -147,3 +153,89 @@ describe("getAndDelete", () => {
expect(map).toEqual(new Map([["key", 1]]));
});
});
+
+describe("canShowTextContent", () => {
+ const metas = new Map<string, WsComponentMeta>();
+ const props = new Map<string, Prop>();
+
+ test("shows directly selected scalar content inside a rich-text tree", () => {
+ const paragraph: Instance = {
+ type: "instance",
+ id: "paragraph",
+ component: "ws:element",
+ tag: "p",
+ children: [
+ { type: "text", value: "Prefix" },
+ { type: "id", value: "nested" },
+ ],
+ };
+ const instance: Instance = {
+ type: "instance",
+ id: "nested",
+ component: "ws:element",
+ tag: "span",
+ children: [{ type: "text", value: "static" }],
+ };
+ const instances = new Map([
+ [paragraph.id, paragraph],
+ [instance.id, instance],
+ ]);
+ expect(
+ canShowTextContent({
+ instance,
+ instanceSelector: [instance.id, paragraph.id],
+ instances,
+ props,
+ metas,
+ isContentMode: false,
+ })
+ ).toBe(true);
+ const boundInstance: Instance = {
+ ...instance,
+ children: [{ type: "expression", value: "value" }],
+ };
+ expect(
+ canShowTextContent({
+ instance: boundInstance,
+ instanceSelector: [boundInstance.id, paragraph.id],
+ instances: new Map([
+ [paragraph.id, paragraph],
+ [boundInstance.id, boundInstance],
+ ]),
+ props,
+ metas,
+ isContentMode: false,
+ })
+ ).toBe(true);
+ });
+
+ test("preserves existing text eligibility on non-text-capable components", () => {
+ const instance: Instance = {
+ type: "instance",
+ id: "head-slot",
+ component: "HeadSlot",
+ children: [{ type: "text", value: "Legacy text" }],
+ };
+ const metas = new Map<string, WsComponentMeta>([
+ [
+ "HeadSlot",
+ {
+ label: "Head slot",
+ Icon: () => null,
+ contentModel: { category: "instance", children: ["instance"] },
+ } as WsComponentMeta,
+ ],
+ ]);
+
+ expect(
+ canShowTextContent({
+ instance,
+ instanceSelector: [instance.id],
+ instances: new Map([[instance.id, instance]]),
+ props: new Map(),
+ metas,
+ isContentMode: false,
+ })
+ ).toBe(true);
+ });
+});
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts
index f49301fa34..43f4c561bf 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts
+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts
@@ -1,9 +1,20 @@
-import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
-import type { PropMeta, Instance, Prop } from "@webstudio-is/sdk";
+import type {
+ PropMeta,
+ Instance,
+ Prop,
+ Props,
+ WsComponentMeta,
+} from "@webstudio-is/sdk";
import { descendantComponent } from "@webstudio-is/sdk";
import {
+ canHaveTextContent,
+ createStartingPropValueFromMeta,
+ getDefaultPropMetaForType,
getContentModeCapabilities,
+ isRichText,
+ isRichTextTree,
+ showAttributeMeta,
type ContentModeCapabilities,
} from "@webstudio-is/project-build/runtime";
import {
@@ -19,21 +30,13 @@ import {
import { $instances } from "~/shared/sync/data-stores";
import { $props } from "~/shared/sync/data-stores";
import { $styleSources } from "~/shared/sync/data-stores";
-import {
- isRichText,
- isRichTextTree,
-} from "@webstudio-is/project-build/runtime";
-import {
- createStartingPropValueFromMeta,
- getDefaultPropMetaForType,
- showAttributeMeta,
-} from "@webstudio-is/project-build/runtime";
import { $selectedInstancePath } from "~/shared/nano-states";
import {
$selectedInstanceInitialPropNames,
$selectedInstancePropsMetas,
type PropValue,
} from "../shared";
+import { getEditableTextTarget } from "@webstudio-is/project-build/runtime";
type PropOrName = { prop?: Prop; propName: string };
@@ -100,41 +103,50 @@ const getAndDelete = <Value>(map: Map<string, Value>, key: string) => {
return value;
};
+const canShowTextContent = ({
+ instance,
+ instanceSelector,
+ instances,
+ props,
+ metas,
+ isContentMode,
+}: {
+ instance: Instance;
+ instanceSelector: Instance["id"][] | undefined;
+ instances: Map<Instance["id"], Instance>;
+ props: Props;
+ metas: Map<string, WsComponentMeta>;
+ isContentMode: boolean;
+}) => {
+ const target = getEditableTextTarget(instance);
+ if (
+ instanceSelector === undefined ||
+ (instance.children.length > 0 && target === undefined)
+ ) {
+ return false;
+ }
+ const input = {
+ instanceId: instanceSelector[0],
+ instances,
+ props,
+ metas,
+ };
+ if (
+ (isContentMode
+ ? isRichTextTree(input)
+ : isRichText({ ...input, instanceSelector })) === true
+ ) {
+ return true;
+ }
+ return canHaveTextContent(input);
+};
+
export const __testing__ = {
isPropVisibleInContentMode,
getAndDelete,
+ canShowTextContent,
};
-const $canHaveTextContent = computed(
- [
- $instances,
- $props,
- $registeredComponentMetas,
- $selectedInstancePath,
- $isContentMode,
- ],
- (instances, props, metas, instancePath, isContentMode) => {
- if (instancePath === undefined) {
- return false;
- }
- const [{ instanceSelector }] = instancePath;
- if (isContentMode) {
- return isRichTextTree({
- instanceId: instanceSelector[0],
- instances,
- props,
- metas,
- });
- }
- return isRichText({
- instances,
- props,
- metas,
- instanceSelector,
- });
- }
-);
-
/** usePropsLogic expects that key={instanceId} is used on the ancestor component */
export const usePropsLogic = ({
instance,
@@ -196,19 +208,17 @@ export const usePropsLogic = ({
});
}
- const canHaveTextContent = useStore($canHaveTextContent);
const getTextContentTarget = () => {
- const canEditChildren = (target: Instance) => {
- const hasNoChildren = target.children.length === 0;
- const hasOnlyTextChild =
- target.children.length === 1 && target.children[0].type === "text";
- const hasOnlyExpressionChild =
- target.children.length === 1 &&
- target.children[0].type === "expression";
- return hasNoChildren || hasOnlyTextChild || hasOnlyExpressionChild;
- };
-
- if (canHaveTextContent && canEditChildren(instance)) {
+ if (
+ canShowTextContent({
+ instance,
+ instanceSelector: selectedInstancePath?.[0].instanceSelector,
+ instances,
+ props: allProps,
+ metas,
+ isContentMode,
+ })
+ ) {
return {
instanceId: instance.id,
instanceSelector: selectedInstancePath?.[0].instanceSelector,
@@ -221,7 +231,8 @@ export const usePropsLogic = ({
const childInstance = instances.get(child.value);
if (
childInstance?.component === "Text" &&
- canEditChildren(childInstance)
+ (childInstance.children.length === 0 ||
+ getEditableTextTarget(childInstance) !== undefined)
) {
return {
instanceId: childInstance.id,
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts
index 6ab4cfa799..f2a254699e 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts
@@ -1,5 +1,5 @@
import type { WebstudioFragment } from "@webstudio-is/sdk";
-import { findAllEditableInstanceSelector } from "@webstudio-is/project-build/runtime";
+import { findTextEditorTarget } from "@webstudio-is/project-build/runtime";
import {
executeRuntimeMutationAsync,
getWebstudioData,
@@ -177,15 +177,12 @@ export const insertTemplateAt = async (
return;
}
const data = getWebstudioData();
- const selectors: InstanceSelector[] = [];
- findAllEditableInstanceSelector({
+ const editableInstanceSelector = findTextEditorTarget({
instanceSelector: selectedInstanceSelector,
instances: data.instances,
props: data.props,
metas: $registeredComponentMetas.get(),
- results: selectors,
});
- const editableInstanceSelector = selectors[0];
$textEditingInstanceSelector.set(
editableInstanceSelector
? { selector: editableInstanceSelector, reason: "new" }
diff --git a/apps/builder/app/builder/shared/bindable-expression.tsx b/apps/builder/app/builder/shared/bindable-expression.tsx
index ee8e8851e9..c4dba47e10 100644
--- a/apps/builder/app/builder/shared/bindable-expression.tsx
+++ b/apps/builder/app/builder/shared/bindable-expression.tsx
@@ -107,7 +107,7 @@ export const BindableExpressionControl = <Value,>({
parseValue?: (value: Value) => unknown;
onChangeValue: (value: Value) => void;
onChangeExpression: (expression: string) => void;
- onRemove: (evaluatedValue: unknown) => void;
+ onRemove?: (evaluatedValue: unknown) => void;
bindingState?: BindingState;
}) => {
if (bindingState === undefined) {
diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsx
index 6f4e49e967..8328183bce 100644
--- a/apps/builder/app/builder/shared/binding-popover.tsx
+++ b/apps/builder/app/builder/shared/binding-popover.tsx
@@ -338,7 +338,7 @@ export const BindingPopover = ({
validate?: (value: unknown) => undefined | string;
value?: string;
onChange: (newValue: string) => void;
- onRemove: (evaluatedValue: unknown) => void;
+ onRemove?: (evaluatedValue: unknown) => void;
}) => {
const [isOpen, onOpenChange] = useState(false);
const hasUnsavedChange = useRef<boolean>(false);
@@ -382,9 +382,12 @@ export const BindingPopover = ({
aria-label="Reset binding"
prefix={<TrashIcon />}
color="ghost"
- disabled={variant === "default"}
+ disabled={variant === "default" || onRemove === undefined}
onClick={(event) => {
event.preventDefault();
+ if (onRemove === undefined) {
+ return;
+ }
// inline variables and close dialog
const evaluatedValue = evaluateExpressionWithinScope(
normalizedValue,
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 3876a7216b..9e251c5879 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
@@ -1,4 +1,4 @@
-import { findAllEditableInstanceSelector } from "@webstudio-is/project-build/runtime";
+import { findAllNavigableTextInstanceSelectors } from "@webstudio-is/project-build/runtime";
import { color } from "@webstudio-is/css-engine";
import {
useState,
@@ -1616,13 +1616,11 @@ export const TextEditor = ({
return;
}
- const editableInstanceSelectors: InstanceSelector[] = [];
- findAllEditableInstanceSelector({
+ const editableInstanceSelectors = findAllNavigableTextInstanceSelectors({
instanceSelector: [rootInstanceId],
instances,
props,
metas,
- results: editableInstanceSelectors,
});
const currentIndex = editableInstanceSelectors.findIndex(
@@ -1646,20 +1644,6 @@ export const TextEditor = ({
const nextSelector = editableInstanceSelectors[nextIndex];
- const nextInstance = instances.get(nextSelector[0]);
- if (nextInstance === undefined) {
- continue;
- }
-
- const hasExpressionChildren = nextInstance.children.some(
- (child) => child.type === "expression"
- );
-
- // opinionated: Skip if binded (double click is working)
- if (hasExpressionChildren) {
- continue;
- }
-
// Skip invisible elements
if (getVisibleElementsByInstanceSelector(nextSelector).length === 0) {
continue;
diff --git a/apps/builder/app/canvas/instance-selection-events.test.ts b/apps/builder/app/canvas/instance-selection-events.test.ts
index 217fde97cd..e2398d9e93 100644
--- a/apps/builder/app/canvas/instance-selection-events.test.ts
+++ b/apps/builder/app/canvas/instance-selection-events.test.ts
@@ -1,26 +1,25 @@
import { afterEach, beforeEach, describe, expect, test } from "vitest";
-import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";
import {
$allSelectedInstanceSelectors,
+ $textEditingInstanceSelector,
selectInstances,
} from "~/shared/nano-states";
+import { $instances } from "~/shared/sync/data-stores";
import { subscribeInstanceSelection } from "./instance-selection-events";
import { $ephemeralStyles } from "./stores";
-
-const createElement = (selector: string) => {
- const element = document.createElement("div");
- const [id] = selector.split(",");
- element.setAttribute(idAttribute, id);
- element.setAttribute(selectorIdAttribute, selector);
- document.body.appendChild(element);
- return element;
-};
+import {
+ createBoundTextInstances,
+ createCanvasElement,
+ createMixedBoundTextInstances,
+} from "./test-utils";
let abortController: AbortController;
beforeEach(() => {
document.body.innerHTML = "";
selectInstances([]);
+ $instances.set(new Map());
+ $textEditingInstanceSelector.set(undefined);
$ephemeralStyles.set([]);
abortController = new AbortController();
subscribeInstanceSelection({ signal: abortController.signal });
@@ -33,8 +32,8 @@ afterEach(() => {
describe("canvas instance selection", () => {
test("plain click selects one instance and replaces multi-selection", () => {
- const box = createElement("box,body");
- const heading = createElement("heading,body");
+ const box = createCanvasElement({ selector: "box,body" });
+ const heading = createCanvasElement({ selector: "heading,body" });
box.dispatchEvent(new MouseEvent("click", { bubbles: true }));
heading.dispatchEvent(
@@ -51,8 +50,8 @@ describe("canvas instance selection", () => {
});
test("cmd-click toggles rendered instances without clearing existing selection", () => {
- const box = createElement("box,body");
- const heading = createElement("heading,body");
+ const box = createCanvasElement({ selector: "box,body" });
+ const heading = createCanvasElement({ selector: "heading,body" });
box.dispatchEvent(new MouseEvent("click", { bubbles: true }));
heading.dispatchEvent(
@@ -71,9 +70,9 @@ describe("canvas instance selection", () => {
});
test("shift-click selects a rendered DOM-order range from the canvas anchor", () => {
- const box = createElement("box,body");
- createElement("heading,body");
- const footer = createElement("footer,body");
+ const box = createCanvasElement({ selector: "box,body" });
+ createCanvasElement({ selector: "heading,body" });
+ const footer = createCanvasElement({ selector: "footer,body" });
box.dispatchEvent(new MouseEvent("click", { bubbles: true }));
footer.dispatchEvent(
@@ -88,9 +87,9 @@ describe("canvas instance selection", () => {
});
test("does not reuse range anchor after subscription is recreated", () => {
- const box = createElement("box,body");
- createElement("heading,body");
- const footer = createElement("footer,body");
+ const box = createCanvasElement({ selector: "box,body" });
+ createCanvasElement({ selector: "heading,body" });
+ const footer = createCanvasElement({ selector: "footer,body" });
box.dispatchEvent(new MouseEvent("click", { bubbles: true }));
abortController.abort();
@@ -106,8 +105,8 @@ describe("canvas instance selection", () => {
});
test("clears stale ephemeral styles when canvas click creates multi-selection", () => {
- const box = createElement("box,body");
- const heading = createElement("heading,body");
+ const box = createCanvasElement({ selector: "box,body" });
+ const heading = createCanvasElement({ selector: "heading,body" });
$ephemeralStyles.set([
{
breakpointId: "base",
@@ -124,4 +123,45 @@ describe("canvas instance selection", () => {
expect($ephemeralStyles.get()).toEqual([]);
});
+
+ test("edits a literal child without promoting its mixed rich-text parent", () => {
+ $instances.set(createMixedBoundTextInstances());
+ const separator = createCanvasElement({
+ selector: "separator,paragraph,body",
+ });
+
+ separator.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
+
+ expect($allSelectedInstanceSelectors.get()).toEqual([
+ ["separator", "paragraph", "body"],
+ ]);
+ expect($textEditingInstanceSelector.get()?.selector).toEqual([
+ "separator",
+ "paragraph",
+ "body",
+ ]);
+ });
+
+ test("does not edit a directly bound text instance on canvas", () => {
+ $instances.set(createBoundTextInstances());
+ const element = createCanvasElement({ selector: "bound-text" });
+
+ element.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
+
+ expect($textEditingInstanceSelector.get()).toBeUndefined();
+ });
+
+ test("does not edit mixed bound text on canvas", () => {
+ $instances.set(createMixedBoundTextInstances());
+ const element = createCanvasElement({
+ selector: "reading-time,paragraph,body",
+ });
+
+ element.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
+
+ expect($allSelectedInstanceSelectors.get()).toEqual([
+ ["reading-time", "paragraph", "body"],
+ ]);
+ expect($textEditingInstanceSelector.get()).toBeUndefined();
+ });
});
diff --git a/apps/builder/app/canvas/instance-selection-events.ts b/apps/builder/app/canvas/instance-selection-events.ts
index 484075d72f..8f549c1094 100644
--- a/apps/builder/app/canvas/instance-selection-events.ts
+++ b/apps/builder/app/canvas/instance-selection-events.ts
@@ -18,7 +18,7 @@ import { $instances } from "~/shared/sync/data-stores";
import { $ephemeralStyles } from "~/canvas/stores";
import { emitCommand } from "./shared/commands";
import { shallowEqual } from "shallow-equal";
-import { findClosestRichText } from "@webstudio-is/project-build/runtime";
+import { findClosestTextEditorTarget } from "@webstudio-is/project-build/runtime";
import {
areInstanceSelectorsEqual,
type InstanceSelector,
@@ -128,7 +128,7 @@ const handleEdit = (
const instances = $instances.get();
- let editableInstanceSelector = findClosestRichText({
+ let editableInstanceSelector = findClosestTextEditorTarget({
instanceSelector,
instances,
props: $props.get(),
@@ -136,23 +136,8 @@ const handleEdit = (
htmlTagsByInstanceId: $propsIndex.get().htmlTagsByInstanceId,
});
- // Do not allow edit bindable text instances with expression children in Content Mode
if (editableInstanceSelector !== undefined && $isContentMode.get()) {
- const instance = instances.get(editableInstanceSelector[0]);
- if (instance === undefined) {
- return false;
- }
-
- const hasExpressionChildren = instance.children.some(
- (child) => child.type === "expression"
- );
-
- if (hasExpressionChildren) {
- editableInstanceSelector = undefined;
- }
-
if (
- editableInstanceSelector !== undefined &&
isTextEditableInContentMode({
isContentMode: true,
instanceSelector: editableInstanceSelector,
diff --git a/apps/builder/app/canvas/selected-instance-effects.test.ts b/apps/builder/app/canvas/selected-instance-effects.test.ts
index 3100c77257..c4d746c101 100644
--- a/apps/builder/app/canvas/selected-instance-effects.test.ts
+++ b/apps/builder/app/canvas/selected-instance-effects.test.ts
@@ -1,5 +1,4 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";
import {
$allSelectedInstanceSelectors,
$selectedInstanceOutline,
@@ -9,6 +8,7 @@ import {
import { $instances, $styleSourceSelections } from "~/shared/sync/data-stores";
import { subscribeSelected } from "./selected-instance-effects";
import { subscribeInstanceSelection } from "./instance-selection-events";
+import { createCanvasElement } from "./test-utils";
const createInstance = (id: string) => ({
type: "instance" as const,
@@ -17,25 +17,6 @@ const createInstance = (id: string) => ({
children: [],
});
-const createElement = ({
- selector,
- rect,
- parent = document.body,
-}: {
- selector: string;
- rect: { left: number; top: number; width: number; height: number };
- parent?: HTMLElement;
-}) => {
- const element = document.createElement("div");
- const [id] = selector.split(",");
- element.setAttribute(idAttribute, id);
- element.setAttribute(selectorIdAttribute, selector);
- element.getBoundingClientRect = () =>
- new TestDOMRect(rect.left, rect.top, rect.width, rect.height) as DOMRect;
- parent.appendChild(element);
- return element;
-};
-
class ResizeObserver {
observe() {}
disconnect() {}
@@ -128,7 +109,7 @@ afterEach(() => {
describe("subscribeSelected", () => {
test("creates both outline stores for one selected instance", () => {
- createElement({
+ createCanvasElement({
selector: "box,body",
rect: { left: 10, top: 20, width: 100, height: 50 },
});
@@ -156,11 +137,11 @@ describe("subscribeSelected", () => {
});
test("creates an outline for every selected instance without single outline", () => {
- createElement({
+ createCanvasElement({
selector: "box,body",
rect: { left: 10, top: 20, width: 100, height: 50 },
});
- createElement({
+ createCanvasElement({
selector: "heading,body",
rect: { left: 20, top: 40, width: 140, height: 70 },
});
@@ -181,16 +162,16 @@ describe("subscribeSelected", () => {
});
test("does not fall back to parent rect for zero-size multi-selected instances", () => {
- const parent = createElement({
+ const parent = createCanvasElement({
selector: "parent,body",
rect: { left: 5, top: 10, width: 500, height: 300 },
});
- createElement({
+ createCanvasElement({
selector: "box,parent,body",
rect: { left: 0, top: 0, width: 0, height: 0 },
parent,
});
- createElement({
+ createCanvasElement({
selector: "heading,parent,body",
rect: { left: 20, top: 40, width: 140, height: 70 },
parent,
@@ -223,11 +204,11 @@ describe("subscribeSelected", () => {
});
test("creates outlines when instances are selected by canvas clicks", () => {
- const box = createElement({
+ const box = createCanvasElement({
selector: "box,body",
rect: { left: 10, top: 20, width: 100, height: 50 },
});
- const heading = createElement({
+ const heading = createCanvasElement({
selector: "heading,body",
rect: { left: 20, top: 40, width: 140, height: 70 },
});
diff --git a/apps/builder/app/canvas/shared/commands.test.ts b/apps/builder/app/canvas/shared/commands.test.ts
index 8fafe2cf34..139fd1a2a1 100644
--- a/apps/builder/app/canvas/shared/commands.test.ts
+++ b/apps/builder/app/canvas/shared/commands.test.ts
@@ -7,14 +7,45 @@ import {
selectInstance,
selectInstances,
} from "~/shared/nano-states";
+import { $instances } from "~/shared/sync/data-stores";
+import {
+ createBoundTextInstances,
+ createCanvasElement,
+ createMixedBoundTextInstances,
+} from "../test-utils";
import { emitCommand } from "./commands";
afterEach(() => {
+ document.body.innerHTML = "";
+ $instances.set(new Map());
selectInstance(undefined);
$textEditingInstanceSelector.set(undefined);
$textToolbar.set(undefined);
});
+test("enters the first literal descendant of a mixed rich-text tree", () => {
+ $instances.set(createMixedBoundTextInstances());
+ createCanvasElement({ selector: "separator,paragraph" });
+ selectInstance(["paragraph"]);
+
+ emitCommand("editInstanceText");
+
+ expect($textEditingInstanceSelector.get()?.selector).toEqual([
+ "separator",
+ "paragraph",
+ ]);
+});
+
+test("does not enter text editing for a directly bound instance", () => {
+ $instances.set(createBoundTextInstances());
+ createCanvasElement({ selector: "bound-text" });
+ selectInstance(["bound-text"]);
+
+ emitCommand("editInstanceText");
+
+ expect($textEditingInstanceSelector.get()).toBeUndefined();
+});
+
describe("escapeSelection", () => {
test("closes text toolbar before exiting text editing or clearing selection", () => {
selectInstance(["text", "body"]);
diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.ts
index e6ae124e7e..345051d3bc 100644
--- a/apps/builder/app/canvas/shared/commands.ts
+++ b/apps/builder/app/canvas/shared/commands.ts
@@ -2,7 +2,7 @@ import { FORMAT_TEXT_COMMAND } from "lexical";
import { TOGGLE_LINK_COMMAND } from "@lexical/link";
import { createCommandsEmitter } from "~/shared/commands-emitter";
import { getElementByInstanceSelector } from "~/shared/dom-utils";
-import { findAllEditableInstanceSelector } from "@webstudio-is/project-build/runtime";
+import { findTextEditorTarget } from "@webstudio-is/project-build/runtime";
import {
$allSelectedInstanceSelectors,
$isContentMode,
@@ -21,12 +21,8 @@ import {
getActiveEditor,
hasSelectionFormat,
} from "../features/text-editor/toolbar-connector";
-import {
- isDescendantOrSelf,
- type InstanceSelector,
-} from "@webstudio-is/project-build/runtime";
+import { isDescendantOrSelf } from "@webstudio-is/project-build/runtime";
import { deleteSelectedInstance } from "~/shared/instance-utils/mutation";
-import { findClosestRichText } from "@webstudio-is/project-build/runtime";
import { getDeletablePageActionTarget } from "~/shared/page-action-target";
import { isTextEditableInContentMode } from "./content-mode";
@@ -87,7 +83,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
return;
}
- let editableInstanceSelector = findClosestRichText({
+ const editableInstanceSelector = findTextEditorTarget({
instanceSelector: selectedInstanceSelector,
instances: $instances.get(),
props: $props.get(),
@@ -96,23 +92,8 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
});
if (editableInstanceSelector === undefined) {
- const selectors: InstanceSelector[] = [];
-
- findAllEditableInstanceSelector({
- instanceSelector: selectedInstanceSelector,
- instances: $instances.get(),
- props: $props.get(),
- metas: $registeredComponentMetas.get(),
- htmlTagsByInstanceId: $propsIndex.get().htmlTagsByInstanceId,
- results: selectors,
- });
-
- if (selectors.length === 0) {
- $textEditingInstanceSelector.set(undefined);
- return;
- }
-
- editableInstanceSelector = selectors[0];
+ $textEditingInstanceSelector.set(undefined);
+ return;
}
if (
diff --git a/apps/builder/app/canvas/shared/styles.test.ts b/apps/builder/app/canvas/shared/styles.test.ts
index 775f171fea..19ad26e27b 100644
--- a/apps/builder/app/canvas/shared/styles.test.ts
+++ b/apps/builder/app/canvas/shared/styles.test.ts
@@ -25,7 +25,6 @@ const {
computeStylesDiff,
toDeclarationParams,
toVarValue,
- hasExpressionChildren,
renderStateStyles,
simulateConditionBreakpoints,
shouldRenderInBackgroundTask,
@@ -501,88 +500,29 @@ describe("computeInstanceStyles", () => {
});
describe("computeEditableCursorRules", () => {
- const createInstance = (
- id: string,
- children: Instance["children"] = []
- ): Instance => ({
- id,
- type: "instance",
- component: "Box",
- children,
- });
-
test("returns empty array when no selectors", () => {
- const result = computeEditableCursorRules([], new Map());
+ const result = computeEditableCursorRules([]);
expect(result).toEqual([]);
});
test("generates cursor rule for editable instances", () => {
- const instances = new Map<string, Instance>([
- ["inst-1", createInstance("inst-1")],
- ["inst-2", createInstance("inst-2")],
- ]);
const selectors = [["inst-1"], ["inst-2"]] as [string][];
- const result = computeEditableCursorRules(selectors, instances);
+ const result = computeEditableCursorRules(selectors);
expect(result).toHaveLength(1);
expect(result[0]).toContain('[data-ws-id="inst-1"]');
expect(result[0]).toContain('[data-ws-id="inst-2"]');
expect(result[0]).toContain("cursor: text");
});
- test("excludes instances with expression children", () => {
- const instances = new Map<string, Instance>([
- ["inst-1", createInstance("inst-1")],
- [
- "inst-2",
- createInstance("inst-2", [{ type: "expression", value: "someExpr" }]),
- ],
- ]);
- const selectors = [["inst-1"], ["inst-2"]] as [string][];
- const result = computeEditableCursorRules(selectors, instances);
- expect(result).toHaveLength(1);
- expect(result[0]).toContain('[data-ws-id="inst-1"]');
- expect(result[0]).not.toContain('[data-ws-id="inst-2"]');
- });
-
- test("excludes instances not found in map", () => {
- const instances = new Map<string, Instance>([
- ["inst-1", createInstance("inst-1")],
- ]);
- const selectors = [["inst-1"], ["inst-missing"]] as [string][];
- const result = computeEditableCursorRules(selectors, instances);
- expect(result).toHaveLength(1);
- expect(result[0]).toContain('[data-ws-id="inst-1"]');
- expect(result[0]).not.toContain("inst-missing");
- });
-
test("chunks selectors into groups of 20", () => {
- const instances = new Map<string, Instance>();
const selectors: [string][] = [];
for (let i = 0; i < 25; i++) {
const id = `inst-${i}`;
- instances.set(id, createInstance(id));
selectors.push([id]);
}
- const result = computeEditableCursorRules(selectors, instances);
+ const result = computeEditableCursorRules(selectors);
expect(result).toHaveLength(2);
});
-
- test("skips empty chunks", () => {
- const instances = new Map<string, Instance>();
- // All instances have expression children, so all chunks are empty
- for (let i = 0; i < 5; i++) {
- const id = `inst-${i}`;
- instances.set(
- id,
- createInstance(id, [{ type: "expression", value: "expr" }])
- );
- }
- const selectors = Array.from(instances.keys()).map((id) => [id]) as [
- string,
- ][];
- const result = computeEditableCursorRules(selectors, instances);
- expect(result).toEqual([]);
- });
});
describe("computeStylesDiff", () => {
@@ -771,61 +711,6 @@ describe("getPresetStyleSelector", () => {
});
});
-describe("hasExpressionChildren", () => {
- const createInstance = (
- id: string,
- children: Instance["children"] = []
- ): Instance => ({
- id,
- type: "instance",
- component: "Box",
- children,
- });
-
- test("returns false for instance with no children", () => {
- expect(hasExpressionChildren(createInstance("box"))).toBe(false);
- });
-
- test("returns false for instance with only id children", () => {
- expect(
- hasExpressionChildren(
- createInstance("box", [
- { type: "id", value: "child-1" },
- { type: "id", value: "child-2" },
- ])
- )
- ).toBe(false);
- });
-
- test("returns false for instance with text children", () => {
- expect(
- hasExpressionChildren(
- createInstance("box", [{ type: "text", value: "hello" }])
- )
- ).toBe(false);
- });
-
- test("returns true for instance with expression child", () => {
- expect(
- hasExpressionChildren(
- createInstance("box", [{ type: "expression", value: "someExpr" }])
- )
- ).toBe(true);
- });
-
- test("returns true when expression is mixed with other children", () => {
- expect(
- hasExpressionChildren(
- createInstance("box", [
- { type: "text", value: "hello" },
- { type: "expression", value: "expr" },
- { type: "id", value: "child" },
- ])
- )
- ).toBe(true);
- });
-});
-
describe("toVarValue", () => {
test("returns var type with escaped property name", () => {
const result = toVarValue(
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index 291ce8dbad..3786e663cf 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -49,8 +49,10 @@ import {
$selectedInstanceSelector,
$selectedPage,
} from "~/shared/nano-states";
-import { findAllEditableInstanceSelector } from "@webstudio-is/project-build/runtime";
-import type { InstanceSelector } from "@webstudio-is/project-build/runtime";
+import {
+ findAllNavigableTextInstanceSelectors,
+ type InstanceSelector,
+} from "@webstudio-is/project-build/runtime";
import { getAllElementsByInstanceSelector } from "~/shared/dom-utils";
import { createComputedStyleDeclStore } from "~/builder/features/style-panel/shared/model";
@@ -80,9 +82,6 @@ export const editablePlaceholderAttribute = "data-ws-editable-placeholder";
// https://developer.mozilla.org/en-US/docs/Web/CSS/attr#backwards_compatibility
export const editingPlaceholderVariable = "--ws-editing-placeholder";
-const hasExpressionChildren = (instance: Instance) =>
- instance.children.some((child) => child.type === "expression");
-
const helperStylesShared = [
// Display a placeholder text for elements that are editable but currently empty
`:is([${editablePlaceholderAttribute}]):empty::before {
@@ -199,31 +198,20 @@ const subscribeDesignModeHelperStyles = () => {
* Groups selectors into chunks to avoid overly long :is() selectors.
*/
const computeEditableCursorRules = (
- editableInstanceSelectors: InstanceSelector[],
- instances: Map<Instance["id"], Instance>
+ editableInstanceSelectors: InstanceSelector[]
) => {
const rules: string[] = [];
// 20 is arbitrary but keeps selector length reasonable
const chunkSize = 20;
for (let i = 0; i < editableInstanceSelectors.length; i += chunkSize) {
- const chunk = editableInstanceSelectors
- .slice(i, i + chunkSize)
- .filter((selector) => {
- const instance = instances.get(selector[0]);
- if (instance === undefined) {
- return false;
- }
- // Instances with expression children are not directly editable
- return hasExpressionChildren(instance) === false;
- });
- if (chunk.length === 0) {
- continue;
- }
+ const chunk = editableInstanceSelectors.slice(i, i + chunkSize);
const selectors = chunk.map(
(selector) => `[${idAttribute}="${selector[0]}"]`
);
rules.push(
- `:is(${selectors.join(", ")}), :is(${selectors.join(", ")}) a { cursor: text; }`
+ `:is(${selectors.join(", ")}), :is(${selectors.join(
+ ", "
+ )}) a { cursor: text; }`
);
}
return rules;
@@ -245,20 +233,17 @@ const subscribeContentEditModeHelperStyles = () => {
// to better distinguish clickable vs editable elements, needs more investigation
const rootInstanceId = $selectedPage.get()?.rootInstanceId;
if (rootInstanceId !== undefined) {
- const editableInstanceSelectors: InstanceSelector[] = [];
const instances = $instances.get();
- findAllEditableInstanceSelector({
+ const editableInstanceSelectors = findAllNavigableTextInstanceSelectors({
instanceSelector: [rootInstanceId],
instances,
props: $props.get(),
metas: $registeredComponentMetas.get(),
- results: editableInstanceSelectors,
});
for (const rule of computeEditableCursorRules(
- editableInstanceSelectors,
- instances
+ editableInstanceSelectors
)) {
helpersSheet.addPlaintextRule(rule);
}
@@ -918,7 +903,6 @@ export const __testing__ = {
computeStylesDiff,
toDeclarationParams,
toVarValue,
- hasExpressionChildren,
renderStateStyles,
simulateConditionBreakpoints,
shouldRenderInBackgroundTask,
diff --git a/apps/builder/app/canvas/test-utils.ts b/apps/builder/app/canvas/test-utils.ts
new file mode 100644
index 0000000000..a7b3c233e3
--- /dev/null
+++ b/apps/builder/app/canvas/test-utils.ts
@@ -0,0 +1,92 @@
+import type { Instances } from "@webstudio-is/sdk";
+import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";
+
+export const createCanvasElement = ({
+ selector,
+ rect,
+ parent = document.body,
+}: {
+ selector: string;
+ rect?: { left: number; top: number; width: number; height: number };
+ parent?: HTMLElement;
+}) => {
+ const element = document.createElement("div");
+ const [id] = selector.split(",");
+ element.setAttribute(idAttribute, id);
+ element.setAttribute(selectorIdAttribute, selector);
+ if (rect !== undefined) {
+ element.getBoundingClientRect = () =>
+ DOMRect.fromRect({
+ x: rect.left,
+ y: rect.top,
+ width: rect.width,
+ height: rect.height,
+ });
+ }
+ parent.appendChild(element);
+ return element;
+};
+
+export const createBoundTextInstances = (): Instances =>
+ new Map([
+ [
+ "bound-text",
+ {
+ type: "instance",
+ id: "bound-text",
+ component: "ws:element",
+ tag: "span",
+ children: [{ type: "expression", value: "value" }],
+ },
+ ],
+ ]);
+
+export const createMixedBoundTextInstances = (): Instances =>
+ new Map([
+ [
+ "separator",
+ {
+ type: "instance",
+ id: "separator",
+ component: "ws:element",
+ tag: "span",
+ children: [{ type: "text", value: " · " }],
+ },
+ ],
+ [
+ "reading-time",
+ {
+ type: "instance",
+ id: "reading-time",
+ component: "ws:element",
+ tag: "span",
+ children: [
+ { type: "text", value: " · " },
+ { type: "expression", value: 'readTime ?? ""' },
+ ],
+ },
+ ],
+ [
+ "paragraph",
+ {
+ type: "instance",
+ id: "paragraph",
+ component: "ws:element",
+ tag: "p",
+ children: [
+ { type: "text", value: "" },
+ { type: "id", value: "separator" },
+ { type: "id", value: "reading-time" },
+ ],
+ },
+ ],
+ [
+ "body",
+ {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [{ type: "id", value: "paragraph" }],
+ },
+ ],
+ ]);
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index 2a2e51b7ca..1d8beed342 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -61413,6 +61413,44 @@ export const runtimeOperationContractData = [
},
required: ["operation", "instanceId"],
},
+ {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ const: "inlineExpressions",
+ },
+ instanceId: {
+ type: "string",
+ description:
+ "Instance id whose expression children will become text.",
+ },
+ replacements: {
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ childIndex: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ expression: {
+ type: "string",
+ },
+ text: {
+ type: "string",
+ },
+ },
+ required: ["childIndex", "expression", "text"],
+ },
+ description:
+ "Evaluated text for every expression child. The index and original expression must match the current instance.",
+ },
+ },
+ required: ["operation", "instanceId", "replacements"],
+ },
],
},
outputSchema: {
@@ -61423,7 +61461,7 @@ export const runtimeOperationContractData = [
},
operation: {
type: "string",
- enum: ["set", "reset"],
+ enum: ["set", "reset", "inlineExpressions"],
},
mode: {
type: "string",
diff --git a/packages/project-build/src/runtime/content-model.test.tsx b/packages/project-build/src/runtime/content-model.test.tsx
index 296dfa92f9..7d9ac78c16 100644
--- a/packages/project-build/src/runtime/content-model.test.tsx
+++ b/packages/project-build/src/runtime/content-model.test.tsx
@@ -3,6 +3,7 @@ import { type Prop, type Props } from "@webstudio-is/sdk";
import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
import { $, expression, renderData, ws } from "@webstudio-is/template";
import {
+ canHaveTextContent,
findClosestContainer,
findClosestNonTextualContainer,
findClosestRichText,
@@ -12,6 +13,45 @@ import {
const defaultMetas = componentMetas;
+test("checks direct text capability without promoting the outer rich-text root", () => {
+ const { instances, props } = renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="p" ws:id="paragraphId">
+ prefix
+ <ws.element ws:tag="span" ws:id="readingTimeId">
+ · reading time
+ </ws.element>
+ </ws.element>
+ <ws.element ws:tag="input" ws:id="inputId"></ws.element>
+ </ws.element>
+ );
+
+ expect(
+ canHaveTextContent({
+ instanceId: "readingTimeId",
+ instances,
+ props,
+ metas: defaultMetas,
+ })
+ ).toBe(true);
+ expect(
+ canHaveTextContent({
+ instanceId: "paragraphId",
+ instances,
+ props,
+ metas: defaultMetas,
+ })
+ ).toBe(true);
+ expect(
+ canHaveTextContent({
+ instanceId: "inputId",
+ instances,
+ props,
+ metas: defaultMetas,
+ })
+ ).toBe(false);
+});
+
test("support element with ws:tag", () => {
expect(
isTreeSatisfyingContentModel({
diff --git a/packages/project-build/src/runtime/content-model.ts b/packages/project-build/src/runtime/content-model.ts
index 8f55e4e256..e76cefe52f 100644
--- a/packages/project-build/src/runtime/content-model.ts
+++ b/packages/project-build/src/runtime/content-model.ts
@@ -205,6 +205,53 @@ const defaultComponentContentModel: ContentModel = {
const getComponentContentModel = (meta: undefined | WsComponentMeta) =>
meta?.contentModel ?? defaultComponentContentModel;
+const isTextContentCapableInstance = ({
+ instance,
+ props,
+ metas,
+ htmlTagsByInstanceId,
+}: {
+ instance: Instance;
+ props: Props;
+ metas: Metas;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
+}) => {
+ const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });
+ const elementContentModel = getElementContentModel(tag);
+ return (
+ (elementContentModel === undefined ||
+ elementContentModel.children.length > 0) &&
+ getComponentContentModel(metas.get(instance.component)).children.includes(
+ "rich-text"
+ )
+ );
+};
+
+export const canHaveTextContent = ({
+ instanceId,
+ instances,
+ props,
+ metas,
+ htmlTagsByInstanceId,
+}: {
+ instanceId: Instance["id"];
+ instances: Instances;
+ props: Props;
+ metas: Metas;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
+}) => {
+ const instance = instances.get(instanceId);
+ if (instance === undefined) {
+ return false;
+ }
+ return isTextContentCapableInstance({
+ instance,
+ props,
+ metas,
+ htmlTagsByInstanceId,
+ });
+};
+
const isComponentSatisfyingContentModel = ({
metas,
component,
@@ -568,15 +615,12 @@ export const isRichTextTree = ({
if (instance === undefined) {
return false;
}
- const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });
- const elementContentModel = getElementContentModel(tag);
- const componentContentModel = getComponentContentModel(
- metas.get(instance.component)
- );
- const isRichText =
- (elementContentModel === undefined ||
- elementContentModel.children.length > 0) &&
- componentContentModel.children.includes("rich-text");
+ const isRichText = isTextContentCapableInstance({
+ instance,
+ props,
+ metas,
+ htmlTagsByInstanceId,
+ });
// only empty instance with rich text content can be edited
if (instance.children.length === 0) {
return isRichText;
diff --git a/packages/project-build/src/runtime/instances.test.ts b/packages/project-build/src/runtime/instances.test.ts
index a864d76055..97ac87a28c 100644
--- a/packages/project-build/src/runtime/instances.test.ts
+++ b/packages/project-build/src/runtime/instances.test.ts
@@ -41,6 +41,7 @@ import {
getSameParentAdjustedInsertIndex,
getTextContentChild,
getTextContentErrors,
+ getEditableTextTarget,
isTextContentChild,
listInstances,
deleteInstances,
@@ -754,6 +755,75 @@ describe("text content utils", () => {
}
);
+ test.each([
+ {
+ name: "left",
+ children: [
+ { type: "text" as const, value: "Prefix " },
+ { type: "expression" as const, value: '"value"' },
+ { type: "id" as const, value: "boundary" },
+ ],
+ childIndex: 1,
+ expectedChildren: [
+ { type: "text", value: "Prefix value" },
+ { type: "id", value: "boundary" },
+ ],
+ },
+ {
+ name: "right",
+ children: [
+ { type: "id" as const, value: "boundary" },
+ { type: "expression" as const, value: '"value"' },
+ { type: "text" as const, value: " suffix" },
+ ],
+ childIndex: 1,
+ expectedChildren: [
+ { type: "id", value: "boundary" },
+ { type: "text", value: "value suffix" },
+ ],
+ },
+ {
+ name: "both sides",
+ children: [
+ { type: "text" as const, value: "Prefix " },
+ { type: "expression" as const, value: '"value"' },
+ { type: "text" as const, value: " suffix" },
+ ],
+ childIndex: 1,
+ expectedChildren: [{ type: "text", value: "Prefix value suffix" }],
+ },
+ ])(
+ "merges adjacent text on the $name",
+ ({ children, childIndex, expectedChildren }) => {
+ const result = updateTextInstance(
+ {
+ instances: new Map([
+ ["instance", createInstance("instance", children)],
+ ]),
+ },
+ {
+ instanceId: "instance",
+ childIndex,
+ text: "value",
+ mode: "text",
+ }
+ );
+
+ expect(result.payload).toEqual([
+ {
+ namespace: "instances",
+ patches: [
+ {
+ op: "replace",
+ path: ["instance", "children"],
+ value: expectedChildren,
+ },
+ ],
+ },
+ ]);
+ }
+ );
+
test("validates expression text only when expression mode is requested", () => {
expect(() =>
updateTextInstance(
@@ -837,6 +907,82 @@ describe("text content utils", () => {
);
});
+ test("inlines every expression and normalizes adjacent text", () => {
+ const result = setTextContent(
+ {
+ instances: new Map([
+ [
+ "instance",
+ createInstance("instance", [
+ { type: "text", value: "A" },
+ { type: "expression", value: '"B"' },
+ { type: "expression", value: '"C"' },
+ { type: "text", value: "D" },
+ { type: "id", value: "boundary" },
+ { type: "expression", value: '"E"' },
+ ]),
+ ],
+ ]),
+ },
+ {
+ operation: "inlineExpressions",
+ instanceId: "instance",
+ replacements: [
+ { childIndex: 1, expression: '"B"', text: "B" },
+ { childIndex: 2, expression: '"C"', text: "C" },
+ { childIndex: 5, expression: '"E"', text: "E" },
+ ],
+ }
+ );
+
+ expect(result).toMatchObject({
+ kind: "mutation",
+ result: {
+ instanceId: "instance",
+ operation: "inlineExpressions",
+ },
+ });
+ expect(result.payload).toEqual([
+ {
+ namespace: "instances",
+ patches: [
+ {
+ op: "replace",
+ path: ["instance", "children"],
+ value: [
+ { type: "text", value: "ABCD" },
+ { type: "id", value: "boundary" },
+ { type: "text", value: "E" },
+ ],
+ },
+ ],
+ },
+ ]);
+ });
+
+ test("rejects an incomplete expression reset", () => {
+ expect(() =>
+ setTextContent(
+ {
+ instances: new Map([
+ [
+ "instance",
+ createInstance("instance", [
+ { type: "expression", value: "first" },
+ { type: "expression", value: "second" },
+ ]),
+ ],
+ ]),
+ },
+ {
+ operation: "inlineExpressions",
+ instanceId: "instance",
+ replacements: [{ childIndex: 0, expression: "first", text: "First" }],
+ }
+ )
+ ).toThrow("Every expression child must have a matching replacement");
+ });
+
test("validates expression when setting text content", () => {
expect(() =>
setTextContent(
@@ -876,6 +1022,33 @@ describe("text content utils", () => {
});
});
+describe("getEditableTextTarget", () => {
+ test("finds a binding among surrounding static text", () => {
+ expect(
+ getEditableTextTarget(
+ createInstance("instance", [
+ { type: "text", value: " · " },
+ { type: "expression", value: 'readTime ?? ""' },
+ ])
+ )
+ ).toEqual({
+ childIndex: 1,
+ child: { type: "expression", value: 'readTime ?? ""' },
+ });
+ });
+
+ test("rejects mixed content with nested instances and no binding", () => {
+ expect(
+ getEditableTextTarget(
+ createInstance("instance", [
+ { type: "text", value: "prefix" },
+ { type: "id", value: "nested" },
+ ])
+ )
+ ).toBeUndefined();
+ });
+});
+
describe("wrapInstance", () => {
test("wraps selected instance with a runtime-generated parent", () => {
const result = wrapInstance(
diff --git a/packages/project-build/src/runtime/instances.ts b/packages/project-build/src/runtime/instances.ts
index 2c753feaeb..a013bf9211 100644
--- a/packages/project-build/src/runtime/instances.ts
+++ b/packages/project-build/src/runtime/instances.ts
@@ -224,6 +224,24 @@ export const setTextContentInput = z.discriminatedUnion("operation", [
operation: z.literal("reset"),
instanceId: z.string().describe("Instance id to reset to no text content."),
}),
+ z.object({
+ operation: z.literal("inlineExpressions"),
+ instanceId: z
+ .string()
+ .describe("Instance id whose expression children will become text."),
+ replacements: z
+ .array(
+ z.object({
+ childIndex: z.number().int().nonnegative(),
+ expression: z.string(),
+ text: z.string(),
+ })
+ )
+ .min(1)
+ .describe(
+ "Evaluated text for every expression child. The index and original expression must match the current instance."
+ ),
+ }),
]);
export const updateTextTreeInput = z.object({
@@ -3272,6 +3290,19 @@ export const getTextContentChild = (instance: Instance, childIndex: number) => {
return isTextContentChild(child) ? child : undefined;
};
+export const getEditableTextTarget = (instance: Instance) => {
+ const [onlyChild] = instance.children;
+ if (instance.children.length === 1 && isTextContentChild(onlyChild)) {
+ return { childIndex: 0, child: onlyChild };
+ }
+
+ for (const [childIndex, child] of instance.children.entries()) {
+ if (child.type === "expression") {
+ return { childIndex, child };
+ }
+ }
+};
+
export const findTextContentChild = (
instances: Iterable<Instance>,
input: {
@@ -3689,10 +3720,8 @@ export const updateTextInstance = (
state: Pick<BuilderState, "instances">,
input: z.infer<typeof updateTextInstanceInput>
) => {
- const result = findTextContentChild(
- getRequiredInstances(state).values(),
- input
- );
+ const instances = getRequiredInstances(state);
+ const result = findTextContentChild(instances.values(), input);
if (result.status === "instance-not-found") {
return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
}
@@ -3715,13 +3744,56 @@ export const updateTextInstance = (
childIndex: input.childIndex,
mode,
};
- if (result.child.value === input.text) {
+ const instance = instances.get(input.instanceId);
+ if (instance === undefined) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
+ }
+ const previousChild = instance.children[input.childIndex - 1];
+ const nextChild = instance.children[input.childIndex + 1];
+ const shouldMergePrevious = mode === "text" && previousChild?.type === "text";
+ const shouldMergeNext = mode === "text" && nextChild?.type === "text";
+ if (
+ result.child.type === mode &&
+ result.child.value === input.text &&
+ shouldMergePrevious === false &&
+ shouldMergeNext === false
+ ) {
return createRuntimeMutation({
payload: [],
result: mutationResult,
invalidatesNamespaces: ["instances"],
});
}
+ if (shouldMergePrevious || shouldMergeNext) {
+ const firstIndex = shouldMergePrevious
+ ? input.childIndex - 1
+ : input.childIndex;
+ const lastIndex = shouldMergeNext ? input.childIndex + 1 : input.childIndex;
+ const value = `${
+ shouldMergePrevious ? previousChild.value : ""
+ }${input.text}${shouldMergeNext ? nextChild.value : ""}`;
+ const children = [
+ ...instance.children.slice(0, firstIndex),
+ createTextContentChild({ type: "text", value }),
+ ...instance.children.slice(lastIndex + 1),
+ ];
+ return createRuntimeMutation({
+ payload: [
+ {
+ namespace: "instances",
+ patches: [
+ {
+ op: "replace",
+ path: [input.instanceId, "children"],
+ value: children,
+ },
+ ],
+ },
+ ],
+ result: mutationResult,
+ invalidatesNamespaces: ["instances"],
+ });
+ }
return createRuntimeMutation({
payload: createTextContentUpdatePayload({
instanceId: input.instanceId,
@@ -3733,6 +3805,19 @@ export const updateTextInstance = (
});
};
+const normalizeAdjacentTextChildren = (children: Instance["children"]) => {
+ const normalized: Instance["children"] = [];
+ for (const child of children) {
+ const previousChild = normalized.at(-1);
+ if (child.type === "text" && previousChild?.type === "text") {
+ previousChild.value += child.value;
+ continue;
+ }
+ normalized.push({ ...child });
+ }
+ return normalized;
+};
+
export const replaceText = (
state: Pick<BuilderState, "pages" | "instances">,
input: z.infer<typeof replaceTextInput>
@@ -3825,6 +3910,60 @@ export const setTextContent = (
});
}
+ if (input.operation === "inlineExpressions") {
+ const expressionCount = instance.children.filter(
+ (child) => child.type === "expression"
+ ).length;
+ const replacements = new Map(
+ input.replacements.map((replacement) => [
+ replacement.childIndex,
+ replacement,
+ ])
+ );
+ if (
+ replacements.size !== input.replacements.length ||
+ replacements.size !== expressionCount ||
+ input.replacements.some((replacement) => {
+ const child = instance.children[replacement.childIndex];
+ return (
+ child?.type !== "expression" || child.value !== replacement.expression
+ );
+ })
+ ) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Every expression child must have a matching replacement"
+ );
+ }
+ const children = normalizeAdjacentTextChildren(
+ instance.children.map((child, childIndex) => {
+ const replacement = replacements.get(childIndex);
+ return replacement === undefined
+ ? child
+ : createTextContentChild({ type: "text", value: replacement.text });
+ })
+ );
+ return createRuntimeMutation({
+ payload: [
+ {
+ namespace: "instances",
+ patches: [
+ {
+ op: "replace",
+ path: [input.instanceId, "children"],
+ value: children,
+ },
+ ],
+ },
+ ],
+ result: {
+ instanceId: input.instanceId,
+ operation: input.operation,
+ },
+ invalidatesNamespaces: ["instances"],
+ });
+ }
+
const errors = getTextContentErrors({
type: input.mode,
value: input.text,
diff --git a/packages/project-build/src/runtime/lookup.test.ts b/packages/project-build/src/runtime/lookup.test.ts
index f85bd10200..6beb537fd4 100644
--- a/packages/project-build/src/runtime/lookup.test.ts
+++ b/packages/project-build/src/runtime/lookup.test.ts
@@ -2,8 +2,10 @@ import { describe, expect, test } from "vitest";
import type { Instance, Prop, WsComponentMeta } from "@webstudio-is/sdk";
import { createDefaultPages } from "../shared/pages-utils";
import {
- findAllEditableInstanceSelector,
+ findAllNavigableTextInstanceSelectors,
+ findClosestTextEditorTarget,
findPageAndSelectorByInstanceId,
+ findTextEditorTarget,
getInstancePath,
} from "./lookup";
@@ -180,26 +182,132 @@ describe("findPageAndSelectorByInstanceId", () => {
});
});
-describe("findAllEditableInstanceSelector", () => {
- test("collects editable rich-text descendants", () => {
- const results: string[][] = [];
- findAllEditableInstanceSelector({
- instanceSelector: ["body"],
+describe("findClosestTextEditorTarget", () => {
+ test("excludes a directly targeted expression from the canvas editor", () => {
+ const instances = new Map([
+ [
+ "bound-text",
+ instance("bound-text", "Span", [
+ { type: "expression", value: "value" },
+ ]),
+ ],
+ ]);
+ const input = {
+ instanceSelector: ["bound-text"],
+ instances,
+ props: new Map<string, Prop>(),
+ metas: new Map([["Span", meta(["rich-text"])]]),
+ };
+
+ expect(findClosestTextEditorTarget(input)).toBeUndefined();
+ expect(findTextEditorTarget(input)).toBeUndefined();
+ });
+});
+
+describe("findAllNavigableTextInstanceSelectors", () => {
+ test("excludes single expressions from navigable targets", () => {
+ const results = findAllNavigableTextInstanceSelectors({
+ instanceSelector: ["bound-text"],
instances: new Map([
[
- "body",
- instance("body", "Body", [{ type: "id", value: "paragraph" }]),
+ "bound-text",
+ instance("bound-text", "Span", [
+ { type: "expression", value: "value" },
+ ]),
],
- ["paragraph", instance("paragraph", "Paragraph")],
- ]),
- props: new Map<string, Prop>(),
- metas: new Map([
- ["Body", meta(["instance"])],
- ["Paragraph", meta(["rich-text"])],
]),
- results,
+ props: new Map(),
+ metas: new Map([["Span", meta(["rich-text"])]]),
+ });
+
+ expect(results).toEqual([]);
+ });
+
+ test("collects editable rich-text descendants", () => {
+ const instances = new Map([
+ ["body", instance("body", "Body", [{ type: "id", value: "paragraph" }])],
+ ["paragraph", instance("paragraph", "Paragraph")],
+ ]);
+ const props = new Map<string, Prop>();
+ const metas = new Map([
+ ["Body", meta(["instance"])],
+ ["Paragraph", meta(["rich-text"])],
+ ]);
+ const results = findAllNavigableTextInstanceSelectors({
+ instanceSelector: ["body"],
+ instances,
+ props,
+ metas,
});
expect(results).toEqual([["paragraph", "body"]]);
+ expect(
+ findTextEditorTarget({
+ instanceSelector: ["body"],
+ instances,
+ props,
+ metas,
+ })
+ ).toEqual(["paragraph", "body"]);
+ });
+
+ test("finds literal descendants within a rich-text tree containing expressions", () => {
+ const instances = new Map([
+ [
+ "paragraph",
+ instance("paragraph", "Paragraph", [
+ { type: "text", value: "Published " },
+ { type: "id", value: "separator" },
+ { type: "id", value: "reading-time" },
+ ]),
+ ],
+ [
+ "separator",
+ instance("separator", "Span", [{ type: "text", value: " · " }]),
+ ],
+ [
+ "reading-time",
+ instance("reading-time", "Span", [
+ { type: "expression", value: 'readTime ?? ""' },
+ ]),
+ ],
+ ]);
+ const props = new Map<string, Prop>();
+ const metas = new Map([
+ ["Paragraph", meta(["rich-text"])],
+ ["Span", meta(["rich-text"])],
+ ]);
+ const results = findAllNavigableTextInstanceSelectors({
+ instanceSelector: ["paragraph"],
+ instances,
+ props,
+ metas,
+ });
+
+ expect(results).toEqual([["separator", "paragraph"]]);
+ expect(
+ findClosestTextEditorTarget({
+ instanceSelector: ["separator", "paragraph"],
+ instances,
+ props,
+ metas,
+ })
+ ).toEqual(["separator", "paragraph"]);
+ expect(
+ findTextEditorTarget({
+ instanceSelector: ["paragraph"],
+ instances,
+ props,
+ metas,
+ })
+ ).toEqual(["separator", "paragraph"]);
+ expect(
+ findClosestTextEditorTarget({
+ instanceSelector: ["reading-time", "paragraph"],
+ instances,
+ props,
+ metas,
+ })
+ ).toBeUndefined();
});
});
diff --git a/packages/project-build/src/runtime/lookup.ts b/packages/project-build/src/runtime/lookup.ts
index ce6a4189f7..6e99371b26 100644
--- a/packages/project-build/src/runtime/lookup.ts
+++ b/packages/project-build/src/runtime/lookup.ts
@@ -80,53 +80,91 @@ export const findPageAndSelectorByInstanceId = (
return { pageId: pages.homePageId, instanceSelector };
};
-export const findAllEditableInstanceSelector = ({
- instanceSelector,
- instances,
- props,
- metas,
- htmlTagsByInstanceId,
- results,
-}: {
+type TextEditorLookupInput = {
instanceSelector: InstanceSelector;
instances: Instances;
props: Props;
metas: Map<string, WsComponentMeta>;
htmlTagsByInstanceId?: Map<Instance["id"], string>;
- results: InstanceSelector[];
-}) => {
- const [instanceId] = instanceSelector;
+};
- if (instanceId === undefined) {
- return;
+const hasExpressionInTree = (
+ instanceId: Instance["id"],
+ instances: Instances,
+ visited = new Set<Instance["id"]>()
+): boolean => {
+ if (visited.has(instanceId)) {
+ return false;
+ }
+ visited.add(instanceId);
+ const instance = instances.get(instanceId);
+ if (instance === undefined) {
+ return false;
}
+ return instance.children.some(
+ (child) =>
+ child.type === "expression" ||
+ (child.type === "id" &&
+ hasExpressionInTree(child.value, instances, visited))
+ );
+};
- if (
- isRichTextTree({
- instanceId,
- instances,
- props,
- metas,
- htmlTagsByInstanceId,
- })
- ) {
- results.push(instanceSelector);
- return;
+const isTextEditorTarget = (
+ instanceId: Instance["id"],
+ args: TextEditorLookupInput
+) =>
+ isRichTextTree({
+ instanceId,
+ instances: args.instances,
+ props: args.props,
+ metas: args.metas,
+ htmlTagsByInstanceId: args.htmlTagsByInstanceId,
+ }) && hasExpressionInTree(instanceId, args.instances) === false;
+
+export const findClosestTextEditorTarget = (
+ args: TextEditorLookupInput
+): undefined | InstanceSelector => {
+ let target: InstanceSelector | undefined;
+ for (let index = 0; index < args.instanceSelector.length; index += 1) {
+ const instanceId = args.instanceSelector[index];
+ if (isTextEditorTarget(instanceId, args) === false) {
+ break;
+ }
+ target = args.instanceSelector.slice(index);
}
+ return target;
+};
- const instance = instances.get(instanceId);
- if (instance) {
+export const findAllNavigableTextInstanceSelectors = (
+ args: TextEditorLookupInput
+) => {
+ const results: InstanceSelector[] = [];
+ const visit = (instanceSelector: InstanceSelector) => {
+ const [instanceId] = instanceSelector;
+ if (instanceId === undefined) {
+ return;
+ }
+ if (isTextEditorTarget(instanceId, args)) {
+ results.push(instanceSelector);
+ return;
+ }
+ const instance = args.instances.get(instanceId);
+ if (instance === undefined) {
+ return;
+ }
for (const child of instance.children) {
if (child.type === "id") {
- findAllEditableInstanceSelector({
- instanceSelector: [child.value, ...instanceSelector],
- instances,
- props,
- metas,
- htmlTagsByInstanceId,
- results,
- });
+ visit([child.value, ...instanceSelector]);
}
}
- }
+ };
+ visit(args.instanceSelector);
+ return results;
+};
+
+export const findTextEditorTarget = (args: TextEditorLookupInput) => {
+ return (
+ findClosestTextEditorTarget(args) ??
+ findAllNavigableTextInstanceSelectors(args)[0]
+ );
};
diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.ts
index 6015294890..58fd5e788c 100644
--- a/packages/project-build/src/runtime/output-schemas.ts
+++ b/packages/project-build/src/runtime/output-schemas.ts
@@ -509,7 +509,7 @@ export const runtimeOutputSchemas = {
}),
"instances.setTextContent": looseObject({
instanceId: id,
- operation: z.enum(["set", "reset"]),
+ operation: z.enum(["set", "reset", "inlineExpressions"]),
mode: z.enum(["text", "expression"]).optional(),
warnings: expressionWarnings.optional(),
}),