Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Make Form progress text editable (#6617)
Oleg Isonen283929bb49aa
diff --git a/apps/builder/app/shared/instance-utils/insert.test.tsx b/apps/builder/app/shared/instance-utils/insert.test.tsxindex 09377e14fb..1d1f6757e3 100644--- a/apps/builder/app/shared/instance-utils/insert.test.tsx+++ b/apps/builder/app/shared/instance-utils/insert.test.tsx@@ -52,9 +52,10 @@ import {$styles,$resources,} from "~/shared/sync/data-stores";-import { registerContainers } from "../sync/sync-stores";+import { registerContainers, serverSyncStore } from "../sync/sync-stores";import {findAvailableVariables,+ getEditableTextTarget,getInstancePath,} from "@webstudio-is/project-build/runtime";import { getInstanceKey, selectPage } from "../nano-states";@@ -145,6 +146,47 @@ describe("insert webstudio element at", () => {);});+ test("keeps existing text editable when adding an element beside it", async () => {+ serverSyncStore.transactionManager.currentStack = [];+ serverSyncStore.transactionManager.undoneStack = [];+ serverSyncStore.popAll();+ $instances.set(+ renderData(+ <Body ws:id="bodyId">+ <ws.element ws:id="divId" ws:tag="div">+ test+ </ws.element>+ </Body>+ ).instances+ );+ await insertWebstudioElementAt({+ parentSelector: ["divId", "bodyId"],+ position: "end",+ });+ const instances = $instances.get();+ const [messageChild, insertedChild] =+ instances.get("divId")?.children ?? [];+ const wrapperId = messageChild?.value ?? "";+ expect(instances.get(messageChild?.value ?? "")).toMatchObject({+ tag: "span",+ children: [{ type: "text", value: "test" }],+ });+ expect(instances.get(insertedChild?.value ?? "")?.tag).toBe("div");++ serverSyncStore.undo();+ expect($instances.get().get("divId")?.children).toEqual([+ { type: "text", value: "test" },+ ]);+ expect($instances.get().has(wrapperId)).toBe(false);++ serverSyncStore.redo();+ expect($instances.get().get("divId")?.children).toEqual([+ messageChild,+ insertedChild,+ ]);+ expect($instances.get().has(wrapperId)).toBe(true);+ });+test("insert element with li tag into ul", async () => {$instances.set(renderData(@@ -939,15 +981,21 @@ describe("insert webstudio component at", () => {(instance) => instance.label === "Progress");expect(status).toBeDefined();+ expect(status?.children).toHaveLength(2);+ const messageId = status?.children[0]?.value;+ const message = $instances.get().get(messageId ?? "");+ expect(message?.tag).toBe("span");+ expect(message && getEditableTextTarget(message)?.child).toMatchObject({+ type: "text",+ value: "Submitting…",+ });expect(Array.from($props.get().values()).find((prop) =>prop.instanceId === status?.id && prop.name === "data-ws-show")).toMatchObject({ type: "expression" });- const summaryId = status?.children.find(- (child) => child.type === "id"- )?.value;+ const summaryId = status?.children[1]?.value;const summary = $instances.get().get(summaryId ?? "");const summaryText = summary?.children.find((child) => child.type === "expression"diff --git a/docs/university/core-components/form.md b/docs/university/core-components/form.mdindex c942b4a58a..fc3f6267d1 100644--- a/docs/university/core-components/form.md+++ b/docs/university/core-components/form.md@@ -239,7 +239,7 @@ The default Form contains four containers:Their **Show** bindings use `formProgress.status` for Progress and `formState` for the other containers. By default, the fields remain visible while submitting and after a failure. Success hides the fields and shows the success message.-Select the message containers in Navigator to edit their text and design. Progress shows “Submitting…” and, when the browser measures the request, a short byte summary such as “1.2 MB / 3 MB”. The message stays visible while actions finish.+Select the message containers in Navigator to design them. To edit the Progress text, select its first Span child. Progress shows “Submitting…” and, when the browser measures the request, a short byte summary such as “1.2 MB / 3 MB”. The message stays visible while actions finish.### Keep the fields visiblediff --git a/packages/project-build/src/mcp-form.integration.test.ts b/packages/project-build/src/mcp-form.integration.test.tsindex dc0aee3c33..839085a420 100644--- a/packages/project-build/src/mcp-form.integration.test.ts+++ b/packages/project-build/src/mcp-form.integration.test.ts@@ -25,6 +25,7 @@ import {const operationCommands = new Set(["insert-component",+ "insert-fragment","list-instances","inspect-instance","list-resources",@@ -744,6 +745,14 @@ test("discovers, commits, and reads back the new Form through MCP", async () =>}>).find(({ label }) => label === "Progress");expect(status?.component).toBe("ws:element");+ const progressInspection = await call("inspect-instance", {+ instanceId: status?.id,+ include: ["children"],+ });+ expect(progressInspection.data.children).toEqual([+ expect.objectContaining({ tag: "span", indexWithinParent: 0 }),+ expect.objectContaining({ tag: "span", indexWithinParent: 1 }),+ ]);const progressReference = encodeDataSourceVariable(progress?.id ?? "");await call("bind-props", {bindings: [@@ -789,6 +798,26 @@ test("discovers, commits, and reads back the new Form through MCP", async () =>}),]));++ const textContainer = await call("insert-fragment", {+ parentInstanceId: "instance-root",+ fragment: "<div>test</div>",+ });+ const textContainerId = (textContainer.data.rootInstanceIds as string[])[0];+ await call("insert-fragment", {+ parentInstanceId: textContainerId,+ fragment: "<span>bytes</span>",+ });+ const [wrappedText, insertedSpan] =+ remote.state.instances?.get(textContainerId)?.children ?? [];+ expect(wrappedText?.type).toBe("id");+ expect(insertedSpan?.type).toBe("id");+ expect(remote.state.instances?.get(wrappedText?.value ?? "")).toMatchObject(+ {+ tag: "span",+ children: [{ type: "text", value: "test" }],+ }+ );} finally {await client.close();await server.close();diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.tsindex 61e6fd987a..09b6c32a43 100644--- a/packages/project-build/src/runtime/components.test.ts+++ b/packages/project-build/src/runtime/components.test.ts@@ -30,6 +30,7 @@ import { createEmptyWebstudioFragment } from "./component-template";import { insertCollectionInput } from "./collection";import { isLikelyWebstudioJsxFragment, parseWebstudioJsxFragment } from "./jsx";import { inspectWebstudioJsxFragmentSyntax } from "./jsx/syntax";+import { applyBuilderPatchTransactions } from "../state/patch";const createPages = (rootInstanceId: Instance["id"],@@ -306,6 +307,196 @@ test("replaces only the child at an explicit insert index", async () => {).toBe(false);});+test("keeps existing text editable when inserting an element beside it", async () => {+ const parent: Instance = {+ type: "instance",+ id: "parent",+ component: elementComponent,+ tag: "div",+ children: [{ type: "text", value: "test" }],+ };+ const state = createState(parent);+ const fragment = await parseWebstudioJsxFragment("<span>bytes</span>");+ const mutation = insertFragment(+ state,+ { parentInstanceId: parent.id, fragment },+ { createId: createIdFactory() }+ );+ const next = applyBuilderPatchTransactions(state, [+ { id: "insert", payload: mutation.payload },+ ]).state;+ const [textChild, insertedChild] =+ next.instances?.get(parent.id)?.children ?? [];+ expect(textChild?.type).toBe("id");+ expect(insertedChild).toEqual({+ type: "id",+ value: mutation.result.rootInstanceIds[0],+ });+ expect(next.instances?.get(textChild?.value ?? "")).toMatchObject({+ tag: "span",+ children: [{ type: "text", value: "test" }],+ });+ expect(mutation.result.instanceIds).toContain(textChild?.value);+ expect(mutation.result.rootInstanceIds).toEqual([insertedChild?.value]);+});++test("wraps existing text when prepending an element", async () => {+ const parent: Instance = {+ type: "instance",+ id: "parent",+ component: elementComponent,+ tag: "div",+ children: [{ type: "text", value: "test" }],+ };+ const state = createState(parent);+ const mutation = insertFragment(+ state,+ {+ parentInstanceId: parent.id,+ fragment: await parseWebstudioJsxFragment("<span>first</span>"),+ mode: "prepend",+ },+ { createId: createIdFactory() }+ );+ const next = applyBuilderPatchTransactions(state, [+ { id: "prepend", payload: mutation.payload },+ ]).state;+ const [insertedChild, wrappedText] =+ next.instances?.get(parent.id)?.children ?? [];+ expect(insertedChild?.value).toBe(mutation.result.rootInstanceIds[0]);+ expect(next.instances?.get(wrappedText?.value ?? "")?.children).toEqual([+ { type: "text", value: "test" },+ ]);+});++test("rejects wrapper ID collisions without changing the original tree", async () => {+ const parent: Instance = {+ type: "instance",+ id: "parent",+ component: elementComponent,+ tag: "div",+ children: [{ type: "text", value: "test" }],+ };+ const state = createState(parent);+ state.instances.set("generated-1", {+ type: "instance",+ id: "generated-1",+ component: elementComponent,+ tag: "span",+ children: [],+ });+ const fragment = await parseWebstudioJsxFragment("<span>new</span>");+ expect(() =>+ insertFragment(+ state,+ { parentInstanceId: parent.id, fragment },+ { createId: createIdFactory() }+ )+ ).toThrow("Generated record ID already exists in instances.");+ expect(state.instances.get(parent.id)?.children).toEqual([+ { type: "text", value: "test" },+ ]);+ expect(state.instances.size).toBe(2);+});++test("keeps the raw child position when replacing inside rich text", async () => {+ const parent: Instance = {+ type: "instance",+ id: "parent",+ component: elementComponent,+ tag: "div",+ children: [+ { type: "text", value: "before" },+ { type: "id", value: "old" },+ { type: "text", value: "after" },+ ],+ };+ const state = createState(parent);+ state.instances.set("old", {+ type: "instance",+ id: "old",+ component: elementComponent,+ tag: "span",+ children: [{ type: "text", value: "old" }],+ });+ const mutation = insertFragment(+ state,+ {+ parentInstanceId: parent.id,+ fragment: await parseWebstudioJsxFragment("<span>new</span>"),+ mode: "replace",+ insertIndex: 1,+ },+ { createId: createIdFactory() }+ );+ const next = applyBuilderPatchTransactions(state, [+ { id: "replace", payload: mutation.payload },+ ]).state;+ const children = next.instances?.get(parent.id)?.children ?? [];+ expect(children).toHaveLength(3);+ expect(children[1]).toEqual({+ type: "id",+ value: mutation.result.rootInstanceIds[0],+ });+ expect(next.instances?.get(children[0]?.value ?? "")?.children).toEqual([+ { type: "text", value: "before" },+ ]);+ expect(next.instances?.get(children[2]?.value ?? "")?.children).toEqual([+ { type: "text", value: "after" },+ ]);+ expect(next.instances?.has("old")).toBe(false);+});++test("does not keep wrapper spans when replacing all rich text", async () => {+ const parent: Instance = {+ type: "instance",+ id: "parent",+ component: elementComponent,+ tag: "div",+ children: [{ type: "text", value: "old" }],+ };+ const state = createState(parent);+ const mutation = insertFragment(+ state,+ {+ parentInstanceId: parent.id,+ fragment: await parseWebstudioJsxFragment("<span>new</span>"),+ mode: "replace",+ },+ { createId: createIdFactory() }+ );+ const next = applyBuilderPatchTransactions(state, [+ { id: "replace", payload: mutation.payload },+ ]).state;+ expect(next.instances?.get(parent.id)?.children).toEqual([+ { type: "id", value: mutation.result.rootInstanceIds[0] },+ ]);+ expect(mutation.result.instanceIds).toEqual(mutation.result.rootInstanceIds);+});++test("preserves intentionally mixed text inside an inserted fragment", async () => {+ const state = createState(createParent());+ const mutation = insertFragment(+ state,+ {+ parentInstanceId: "parent",+ fragment: await parseWebstudioJsxFragment(+ "<div>intro <span>emphasis</span></div>"+ ),+ },+ { createId: createIdFactory() }+ );+ const next = applyBuilderPatchTransactions(state, [+ { id: "insert", payload: mutation.payload },+ ]).state;+ expect(+ next.instances?.get(mutation.result.rootInstanceIds[0] ?? "")?.children+ ).toEqual([+ { type: "text", value: "intro " },+ { type: "id", value: expect.any(String) },+ ]);+});+test("uses the public collision-safe component identifier as the template name", async () => {const parent: Instance = {type: "instance",diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.tsindex c58a66b646..cff3474ebb 100644--- a/packages/project-build/src/runtime/components.ts+++ b/packages/project-build/src/runtime/components.ts@@ -79,6 +79,7 @@ import {import { z } from "zod";import { getBlockTemplateNameConfirmation } from "./block";import { hasMdxComponentAdapter } from "./mdx-component-adapters";+import { wrapEditableChildrenAroundInsertIndexMutable } from "./tree";export const insertComponentInput = z.object({parentInstanceId: z.string(),@@ -527,6 +528,15 @@ const createFragmentInsertPayload = ({after: after.instances,skip: new Set([parent.id]),}),+ ...(equal(after.instances.get(parent.id)?.children, parent.children)+ ? []+ : [+ {+ op: "replace" as const,+ path: [parent.id, "children"],+ value: after.instances.get(parent.id)?.children,+ },+ ]),...(shouldSetChildrenArray? [{@@ -894,6 +904,33 @@ const createInsertFragmentMutation = <return child;});+ const insertionParent = nextData.instances.get(parent.id);+ if (insertionParent === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ const originalChildren = insertionParent.children;+ if (mode === "replace" && explicitInsertIndex !== undefined) {+ insertionParent.children = [+ ...originalChildren.slice(0, insertIndex),+ ...originalChildren.slice(insertIndex + 1),+ ];+ }+ const wrapped =+ insertedChildren.some((child) => child.type === "id") &&+ !(mode === "replace" && explicitInsertIndex === undefined)+ ? wrapEditableChildrenAroundInsertIndexMutable({+ instances: nextData.instances,+ props: nextData.props,+ metas: componentMetas,+ parentId: parent.id,+ position: insertIndex,+ createId: context.createId,+ })+ : undefined;+ if (wrapped === undefined) {+ insertionParent.children = originalChildren;+ }+ const effectiveInsertIndex = wrapped ?? insertIndex;assignUniqueBlockTemplateNamesMutable({instanceIds: insertedChildren.flatMap((child) =>child.type === "id" ? [child.value] : []@@ -939,19 +976,25 @@ const createInsertFragmentMutation = <const validationParent: Instance = {...parent,children:- mode === "replace"- ? explicitInsertIndex === undefined- ? insertedChildren+ wrapped !== undefined+ ? [+ ...insertionParent.children.slice(0, effectiveInsertIndex),+ ...insertedChildren,+ ...insertionParent.children.slice(effectiveInsertIndex),+ ]+ : mode === "replace"+ ? explicitInsertIndex === undefined+ ? insertedChildren+ : [+ ...parentChildren.slice(0, insertIndex),+ ...insertedChildren,+ ...parentChildren.slice(insertIndex + 1),+ ]: [...parentChildren.slice(0, insertIndex),...insertedChildren,- ...parentChildren.slice(insertIndex + 1),- ]- : [- ...parentChildren.slice(0, insertIndex),- ...insertedChildren,- ...parentChildren.slice(insertIndex),- ],+ ...parentChildren.slice(insertIndex),+ ],};validationInstances.set(parent.id, validationParent);const { instanceSelector: parentSelector } =@@ -994,9 +1037,10 @@ const createInsertFragmentMutation = <removedInstanceIds: string[]): ComponentInsertResult & Details =>({- instanceIds: Array.from(newInstanceIds.values()).filter(+ instanceIds: Array.from(nextData.instances.keys()).filter((instanceId) =>instanceId !== ROOT_INSTANCE_ID &&+ instanceId !== normalizedSlotDropTarget?.parentSelector[0] &&mutationState.instances.has(instanceId) === false),rootInstanceIds: insertedChildren.flatMap((child) =>@@ -1021,7 +1065,7 @@ const createInsertFragmentMutation = <if (mode === "prepend") {parent.children.splice(0, 0, ...insertedChildren);} else {- parent.children.splice(insertIndex, 0, ...insertedChildren);+ parent.children.splice(effectiveInsertIndex, 0, ...insertedChildren);}const insertPayload = createFragmentPayload({before: mutationState,@@ -1059,7 +1103,7 @@ const createInsertFragmentMutation = <before: mutationState,after: nextData,parent,- insertIndex,+ insertIndex: effectiveInsertIndex,insertedChildren,});return createRuntimeMutation({diff --git a/packages/project-build/src/runtime/tree.ts b/packages/project-build/src/runtime/tree.tsindex a59364dd2d..a6f0a1b2a9 100644--- a/packages/project-build/src/runtime/tree.ts+++ b/packages/project-build/src/runtime/tree.ts@@ -16,6 +16,7 @@ import { findClosestInstanceMatchingFragment } from "./matcher";import { getSlotFragmentDropTargetMutable } from "./slot";import type { InstancePath, InstanceSelector } from "./instance-path";import { canMoveInstanceInContentMode } from "./block";+import { throwBuilderRuntimeError } from "./errors";export type { InstanceSelector } from "./instance-path";@@ -114,18 +115,26 @@ const adjustChildrenPosition = (return newPosition + 1;};-export const wrapEditableChildrenAroundDropTargetMutable = (- instances: Instances,- props: Props,- metas: Map<string, WsComponentMeta>,- dropTarget: DroppableTarget,- createId: () => string-) => {- const [parentId] = dropTarget.parentSelector;+export const wrapEditableChildrenAroundInsertIndexMutable = ({+ instances,+ props,+ metas,+ parentId,+ position,+ createId,+}: {+ instances: Instances;+ props: Props;+ metas: Map<string, WsComponentMeta>;+ parentId: Instance["id"];+ position: number;+ createId: () => string;+}) => {const parentInstance = instances.get(parentId);- if (parentInstance === undefined || parentInstance.children.length === 0) {+ if (parentInstance === undefined || !parentInstance.children?.length) {return;}+ const children = parentInstance.children;const isParentRichText = isRichTextTree({instances,props,@@ -135,40 +144,75 @@ export const wrapEditableChildrenAroundDropTargetMutable = (if (!isParentRichText) {return;}- const position =- dropTarget.position === "end"- ? parentInstance.children.length- : adjustChildrenPosition(parentInstance.children, dropTarget.position);-const newChildren: Instance["children"] = [];+ const createWrapperId = () => {+ const id = createId();+ if (instances.has(id)) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Generated record ID already exists in instances."+ );+ }+ return id;+ };let newPosition = 0;if (position !== 0) {const leftSpan: Instance = {- id: createId(),+ id: createWrapperId(),type: "instance",component: elementComponent,tag: "span",- children: parentInstance.children.slice(0, position),+ children: children.slice(0, position),};newChildren.push({ type: "id", value: leftSpan.id });instances.set(leftSpan.id, leftSpan);newPosition = 1;}- if (position < parentInstance.children.length) {+ if (position < children.length) {const rightSpan: Instance = {- id: createId(),+ id: createWrapperId(),type: "instance",component: elementComponent,tag: "span",- children: parentInstance.children.slice(position),+ children: children.slice(position),};newChildren.push({ type: "id", value: rightSpan.id });instances.set(rightSpan.id, rightSpan);}parentInstance.children = newChildren;+ return newPosition;+};++export const wrapEditableChildrenAroundDropTargetMutable = (+ instances: Instances,+ props: Props,+ metas: Map<string, WsComponentMeta>,+ dropTarget: DroppableTarget,+ createId: () => string+) => {+ const [parentId] = dropTarget.parentSelector;+ const parent = instances.get(parentId);+ if (parent === undefined) {+ return;+ }+ const position =+ dropTarget.position === "end"+ ? (parent.children?.length ?? 0)+ : adjustChildrenPosition(parent.children ?? [], dropTarget.position);+ const wrappedPosition = wrapEditableChildrenAroundInsertIndexMutable({+ instances,+ props,+ metas,+ parentId,+ position,+ createId,+ });+ if (wrappedPosition === undefined) {+ return;+ }return {parentSelector: dropTarget.parentSelector,- position: newPosition,+ position: wrappedPosition,};};diff --git a/packages/sdk-components-registry/src/core-templates.test.tsx b/packages/sdk-components-registry/src/core-templates.test.tsxindex 4dee006cd2..95ef27fe76 100644--- a/packages/sdk-components-registry/src/core-templates.test.tsx+++ b/packages/sdk-components-registry/src/core-templates.test.tsx@@ -267,7 +267,14 @@ test("Form Progress shows measured request bytes while the Form is pending", ()))).toBe(false);- const spanId = status.children.find(({ type }) => type === "id")?.value;+ expect(status.children).toHaveLength(2);+ const messageId = status.children[0]?.value;+ const message = fragment.instances.find(({ id }) => id === messageId);+ expect(message?.tag).toBe("span");+ expect(message?.children).toEqual([+ { type: "text", value: "Submitting…", placeholder: true },+ ]);+ const spanId = status.children[1]?.value;const span = fragment.instances.find(({ id }) => id === spanId)!;const showBytes = fragment.props.find(({ instanceId, name }) => instanceId === span.id && name === "data-ws-show"diff --git a/packages/sdk-components-registry/src/core-templates.tsx b/packages/sdk-components-registry/src/core-templates.tsxindex a84b0fcad4..a1d951944d 100644--- a/packages/sdk-components-registry/src/core-templates.tsx+++ b/packages/sdk-components-registry/src/core-templates.tsx@@ -324,7 +324,7 @@ export const coreTemplates = {role="status"aria-live="polite">- {new PlaceholderValue("Submitting…")}+ <span>{new PlaceholderValue("Submitting…")}</span><spanws:show={expression`${formProgress}.loaded >= 0 && ${formProgress}.total > 0`}>