mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
perf: Cut repeated Builder E2E setup
This commit is contained in:
1 parent
56a8cdb64c
commit
588bd990f7
20 files changed
+1430
-1982
No files matched your search
@@ -0,0 +1,143 @@
|
||||
import { page, userEvent } from "@vitest/browser/context";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { coreMetas, elementComponent, type Instance } from "@webstudio-is/sdk";
|
||||
import { subscribeCommands } from "~/builder/shared/commands";
|
||||
import {
|
||||
$registeredComponentMetas,
|
||||
$selectedPageId,
|
||||
clearInstanceSelection,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import { expectSlotsShareFragment } from "~/shared/slot-test-utils";
|
||||
import { $instances, $pages, $project } from "~/shared/sync/data-stores";
|
||||
import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";
|
||||
import { NavigatorTree } from "./navigator-tree";
|
||||
|
||||
const instance = (
|
||||
id: string,
|
||||
component: string,
|
||||
label: string,
|
||||
...children: string[]
|
||||
): [string, Instance] => [
|
||||
id,
|
||||
{
|
||||
type: "instance",
|
||||
id,
|
||||
component,
|
||||
label,
|
||||
children: children.map((value) => ({ type: "id", value })),
|
||||
},
|
||||
];
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
let unsubscribeCommands: () => void;
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
registerContainers();
|
||||
|
||||
beforeEach(() => {
|
||||
$registeredComponentMetas.set(new Map(Object.entries(coreMetas)));
|
||||
$pages.set(
|
||||
createDefaultPages({ rootInstanceId: "body", homePageId: "home" })
|
||||
);
|
||||
$selectedPageId.set("home");
|
||||
$project.set({ id: "slot-keyboard" } as Project);
|
||||
$instances.set(
|
||||
new Map([
|
||||
instance("body", elementComponent, "Body", "slot-a", "slot-b"),
|
||||
instance("slot-a", "Slot", "Slot A", "fragment"),
|
||||
instance("slot-b", "Slot", "Slot B", "fragment"),
|
||||
instance("fragment", "Fragment", "Shared fragment", "box", "heading"),
|
||||
instance("box", elementComponent, "Drop Div"),
|
||||
instance("heading", elementComponent, "Slot Heading"),
|
||||
])
|
||||
);
|
||||
selectInstance(["box", "fragment", "slot-a", "body"]);
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<NavigatorTree />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
unsubscribeCommands = subscribeCommands();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
unsubscribeCommands();
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
clearInstanceSelection();
|
||||
$selectedPageId.set(undefined);
|
||||
$pages.set(undefined);
|
||||
$instances.set(new Map());
|
||||
$project.set(undefined);
|
||||
$registeredComponentMetas.set(new Map());
|
||||
serverSyncStore.transactionManager.currentStack = [];
|
||||
serverSyncStore.transactionManager.undoneStack = [];
|
||||
serverSyncStore.popAll();
|
||||
});
|
||||
|
||||
const selectedRows = () =>
|
||||
Array.from(
|
||||
container.querySelectorAll("[data-tree-button][aria-selected='true']"),
|
||||
(button) => button.textContent?.trim()
|
||||
);
|
||||
|
||||
test("Shift+ArrowDown selects exactly one additional row in the shared Slot", async () => {
|
||||
await act(async () =>
|
||||
page.getByRole("button", { name: "Drop Div", exact: true }).click()
|
||||
);
|
||||
expect(selectedRows()).toEqual(["Drop Div"]);
|
||||
|
||||
await act(async () => userEvent.keyboard("{Shift>}{ArrowDown}{/Shift}"));
|
||||
|
||||
expect(selectedRows()).toEqual(["Drop Div", "Slot Heading"]);
|
||||
await expect
|
||||
.element(page.getByRole("button", { name: "Slot Heading", exact: true }))
|
||||
.toHaveFocus();
|
||||
});
|
||||
|
||||
test.each([
|
||||
{
|
||||
label: "Drop Div",
|
||||
key: "ArrowUp",
|
||||
remaining: "heading",
|
||||
order: ["box", "slot-a", "slot-b"],
|
||||
},
|
||||
{
|
||||
label: "Slot Heading",
|
||||
key: "ArrowDown",
|
||||
remaining: "box",
|
||||
order: ["slot-a", "heading", "slot-b"],
|
||||
},
|
||||
])(
|
||||
"Ctrl+$key moves $label out of both Slot occurrences from Navigator focus",
|
||||
async ({ label, key, remaining, order }) => {
|
||||
await act(async () => {
|
||||
await page.getByRole("button", { name: label, exact: true }).click();
|
||||
await userEvent.keyboard(`{Control>}{${key}}{/Control}`);
|
||||
});
|
||||
|
||||
const instances = $instances.get();
|
||||
expectSlotsShareFragment(instances, ["slot-a", "slot-b"]);
|
||||
expect(instances.get("body")?.children).toEqual(
|
||||
order.map((value) => ({ type: "id", value }))
|
||||
);
|
||||
expect(instances.get("fragment")?.children).toEqual([
|
||||
{ type: "id", value: remaining },
|
||||
]);
|
||||
}
|
||||
);
|
||||
@@ -107,6 +107,14 @@ export const insertAsset = async (row: Tables["Asset"]["Insert"]) => {
|
||||
);
|
||||
};
|
||||
|
||||
export const insertAssetFolders = async (
|
||||
rows: Tables["AssetFolder"]["Insert"][]
|
||||
) => {
|
||||
return throwIfError(
|
||||
await postgrest.from("AssetFolder").insert(rows).select()
|
||||
);
|
||||
};
|
||||
|
||||
export const loadDevBuild = async ({
|
||||
projectId,
|
||||
}: {
|
||||
|
||||
@@ -27,20 +27,14 @@ import {
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import { loadDevBuild, updateBuild } from "../db";
|
||||
|
||||
const projectId = process.argv[2];
|
||||
const mode = process.argv[3];
|
||||
const formId = process.argv[4];
|
||||
const [, , projectId, phase, boundFormId, partialFormId] = process.argv;
|
||||
if (
|
||||
projectId === undefined ||
|
||||
(mode !== "bind" &&
|
||||
mode !== "reset" &&
|
||||
mode !== "partial" &&
|
||||
mode !== "empty") ||
|
||||
formId === undefined
|
||||
(phase !== "initial" && phase !== "updated") ||
|
||||
boundFormId === undefined ||
|
||||
partialFormId === undefined
|
||||
) {
|
||||
throw new Error(
|
||||
"Expected a project ID, bind, reset, partial, or empty mode, and Form ID"
|
||||
);
|
||||
throw new Error("Expected a project ID, binding phase, and two Form IDs");
|
||||
}
|
||||
|
||||
const commands = new Set([
|
||||
@@ -71,211 +65,275 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
|
||||
requiresConfirm: contract.requiresConfirm,
|
||||
}));
|
||||
|
||||
let build = await loadDevBuild({ projectId });
|
||||
const parse = <Value>(field: keyof typeof build) =>
|
||||
JSON.parse(String(build[field])) as Value;
|
||||
let remote: ProjectSessionRemoteSnapshot = {
|
||||
projectId,
|
||||
buildId: build.id,
|
||||
version: build.version,
|
||||
state: createBuilderStateFromBuildData({
|
||||
pages: migratePages(parse("pages")),
|
||||
instances: parse("instances"),
|
||||
props: parse("props"),
|
||||
styles: parse("styles"),
|
||||
styleSources: parse("styleSources"),
|
||||
styleSourceSelections: parse("styleSourceSelections"),
|
||||
dataSources: parse("dataSources"),
|
||||
projectSettings: parse("projectSettings"),
|
||||
resources: parse("resources"),
|
||||
breakpoints: parse("breakpoints"),
|
||||
assets: [],
|
||||
assetFolders: [],
|
||||
}),
|
||||
};
|
||||
let stored: ProjectSessionPersistedSnapshot | undefined;
|
||||
let revision = 0;
|
||||
let nextId = 0;
|
||||
const persist = async () => {
|
||||
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
|
||||
build = await updateBuild(build.id, {
|
||||
version: remote.version,
|
||||
pages: JSON.stringify(serializePages(snapshot.pages!)),
|
||||
instances: JSON.stringify(snapshot.instances),
|
||||
props: JSON.stringify(snapshot.props),
|
||||
styles: JSON.stringify(snapshot.styles),
|
||||
styleSources: JSON.stringify(snapshot.styleSources),
|
||||
styleSourceSelections: JSON.stringify(snapshot.styleSourceSelections),
|
||||
dataSources: JSON.stringify(snapshot.dataSources),
|
||||
projectSettings: JSON.stringify(snapshot.projectSettings),
|
||||
resources: JSON.stringify(snapshot.resources),
|
||||
breakpoints: JSON.stringify(snapshot.breakpoints),
|
||||
});
|
||||
};
|
||||
const session = createProjectSession({
|
||||
projectId,
|
||||
compatibilityVersion: "mcp-email-binding-e2e-v1",
|
||||
runtimeContext: { createId: () => `mcp-email-binding-${nextId++}` },
|
||||
storage: {
|
||||
load: async () => stored,
|
||||
save: async (snapshot, options) => {
|
||||
expect(options.expectedRevision).toBe(stored?.revision);
|
||||
stored = { ...snapshot, revision: `revision-${++revision}` };
|
||||
return { revision: stored.revision };
|
||||
},
|
||||
clear: async () => {
|
||||
stored = undefined;
|
||||
},
|
||||
},
|
||||
transport: {
|
||||
fetchNamespaces: async () => remote,
|
||||
commitPatch: async ({ baseVersion, transactions }) => {
|
||||
expect(baseVersion).toBe(remote.version);
|
||||
remote = {
|
||||
...remote,
|
||||
version: remote.version + 1,
|
||||
state: applyBuilderPatchTransactions(remote.state, transactions).state,
|
||||
};
|
||||
await persist();
|
||||
return { version: remote.version };
|
||||
},
|
||||
commitRestorePoint: async () => {
|
||||
throw new Error("Restore points are outside this E2E fixture");
|
||||
},
|
||||
getPermissions: async () => ({
|
||||
canView: true,
|
||||
canEdit: true,
|
||||
canBuild: true,
|
||||
canAdmin: false,
|
||||
canUseApi: true,
|
||||
}),
|
||||
getCompatibility: async () => ({
|
||||
sessionVersion: "mcp-email-binding-e2e-v1",
|
||||
runtimeContractVersion: "test-runtime-contracts",
|
||||
projectSchemaVersion: "test-project-schema",
|
||||
apiCompatibilityVersion: "test-api",
|
||||
}),
|
||||
executeServerOperation: async <Result>({
|
||||
operationId,
|
||||
input,
|
||||
}: {
|
||||
operationId: string;
|
||||
input: unknown;
|
||||
}): Promise<Result> => {
|
||||
const mutation =
|
||||
await executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
|
||||
id: operationId,
|
||||
state: remote.state,
|
||||
input,
|
||||
context: {
|
||||
createId: () => `mcp-email-binding-server-${nextId++}`,
|
||||
projectId: remote.projectId,
|
||||
projectVersion: remote.version,
|
||||
},
|
||||
});
|
||||
expect(mutation.kind).toBe("mutation");
|
||||
remote = {
|
||||
...remote,
|
||||
version: remote.version + 1,
|
||||
state: applyBuilderPatchTransactions(remote.state, [
|
||||
{
|
||||
id: `mcp-email-binding-transaction-${nextId++}`,
|
||||
payload: mutation.payload,
|
||||
},
|
||||
]).state,
|
||||
};
|
||||
await persist();
|
||||
return mutation.result as Result;
|
||||
},
|
||||
},
|
||||
});
|
||||
const server = await createProjectSessionMcpServer({
|
||||
operations,
|
||||
createProjectSession: () => session,
|
||||
executeOperation: async ({ command, input, dryRun }) => {
|
||||
const operation = operations.find(
|
||||
(candidate) => candidate.command === command
|
||||
);
|
||||
const contract = runtimeOperationContracts.find(
|
||||
({ id }) => id === operation?.id
|
||||
);
|
||||
if (operation === undefined || contract === undefined) {
|
||||
throw new Error(`Unexpected MCP operation: ${command}`);
|
||||
}
|
||||
const scopedInput = { ...(input as object), projectId };
|
||||
const result =
|
||||
operation.method === "mutation"
|
||||
? await session.mutate(contract.id, scopedInput, {
|
||||
permit: operation.permit,
|
||||
dryRun,
|
||||
})
|
||||
: await session.read(contract.id, scopedInput, {
|
||||
permit: operation.permit,
|
||||
});
|
||||
const failure = result.diagnostics.find(({ level }) => level === "error");
|
||||
if (failure) {
|
||||
throw new Error(failure.message);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const client = new Client({ name: "mcp-email-binding-e2e", version: "1.0.0" });
|
||||
await Promise.all([
|
||||
server.connect(serverTransport),
|
||||
client.connect(clientTransport),
|
||||
]);
|
||||
const call = async (name: string, args: Record<string, unknown> = {}) => {
|
||||
const response = await client.callTool({ name, arguments: args });
|
||||
if (response.isError) {
|
||||
throw new Error(`${name}: ${JSON.stringify(response.structuredContent)}`);
|
||||
}
|
||||
const payload = response.structuredContent as {
|
||||
ok: boolean;
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
expect(payload.ok, name).toBe(true);
|
||||
return payload.data;
|
||||
};
|
||||
const actions =
|
||||
phase === "initial"
|
||||
? ([
|
||||
["bind", boundFormId],
|
||||
["partial", partialFormId],
|
||||
] as const)
|
||||
: ([
|
||||
["reset", boundFormId],
|
||||
["empty", partialFormId],
|
||||
] as const);
|
||||
|
||||
try {
|
||||
const form = { id: formId };
|
||||
const resources = await call("list-resources", {
|
||||
scopeInstanceId: form.id,
|
||||
for (const [mode, formId] of actions) {
|
||||
let build = await loadDevBuild({ projectId });
|
||||
const parse = <Value>(field: keyof typeof build) =>
|
||||
JSON.parse(String(build[field])) as Value;
|
||||
let remote: ProjectSessionRemoteSnapshot = {
|
||||
projectId,
|
||||
buildId: build.id,
|
||||
version: build.version,
|
||||
state: createBuilderStateFromBuildData({
|
||||
pages: migratePages(parse("pages")),
|
||||
instances: parse("instances"),
|
||||
props: parse("props"),
|
||||
styles: parse("styles"),
|
||||
styleSources: parse("styleSources"),
|
||||
styleSourceSelections: parse("styleSourceSelections"),
|
||||
dataSources: parse("dataSources"),
|
||||
projectSettings: parse("projectSettings"),
|
||||
resources: parse("resources"),
|
||||
breakpoints: parse("breakpoints"),
|
||||
assets: [],
|
||||
assetFolders: [],
|
||||
}),
|
||||
};
|
||||
let stored: ProjectSessionPersistedSnapshot | undefined;
|
||||
let revision = 0;
|
||||
let nextId = 0;
|
||||
const persist = async () => {
|
||||
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
|
||||
build = await updateBuild(build.id, {
|
||||
version: remote.version,
|
||||
pages: JSON.stringify(serializePages(snapshot.pages!)),
|
||||
instances: JSON.stringify(snapshot.instances),
|
||||
props: JSON.stringify(snapshot.props),
|
||||
styles: JSON.stringify(snapshot.styles),
|
||||
styleSources: JSON.stringify(snapshot.styleSources),
|
||||
styleSourceSelections: JSON.stringify(snapshot.styleSourceSelections),
|
||||
dataSources: JSON.stringify(snapshot.dataSources),
|
||||
projectSettings: JSON.stringify(snapshot.projectSettings),
|
||||
resources: JSON.stringify(snapshot.resources),
|
||||
breakpoints: JSON.stringify(snapshot.breakpoints),
|
||||
});
|
||||
};
|
||||
const session = createProjectSession({
|
||||
projectId,
|
||||
compatibilityVersion: "mcp-email-binding-e2e-v1",
|
||||
runtimeContext: { createId: () => `mcp-email-binding-${nextId++}` },
|
||||
storage: {
|
||||
load: async () => stored,
|
||||
save: async (snapshot, options) => {
|
||||
expect(options.expectedRevision).toBe(stored?.revision);
|
||||
stored = { ...snapshot, revision: `revision-${++revision}` };
|
||||
return { revision: stored.revision };
|
||||
},
|
||||
clear: async () => {
|
||||
stored = undefined;
|
||||
},
|
||||
},
|
||||
transport: {
|
||||
fetchNamespaces: async () => remote,
|
||||
commitPatch: async ({ baseVersion, transactions }) => {
|
||||
expect(baseVersion).toBe(remote.version);
|
||||
remote = {
|
||||
...remote,
|
||||
version: remote.version + 1,
|
||||
state: applyBuilderPatchTransactions(remote.state, transactions)
|
||||
.state,
|
||||
};
|
||||
await persist();
|
||||
return { version: remote.version };
|
||||
},
|
||||
commitRestorePoint: async () => {
|
||||
throw new Error("Restore points are outside this E2E fixture");
|
||||
},
|
||||
getPermissions: async () => ({
|
||||
canView: true,
|
||||
canEdit: true,
|
||||
canBuild: true,
|
||||
canAdmin: false,
|
||||
canUseApi: true,
|
||||
}),
|
||||
getCompatibility: async () => ({
|
||||
sessionVersion: "mcp-email-binding-e2e-v1",
|
||||
runtimeContractVersion: "test-runtime-contracts",
|
||||
projectSchemaVersion: "test-project-schema",
|
||||
apiCompatibilityVersion: "test-api",
|
||||
}),
|
||||
executeServerOperation: async <Result>({
|
||||
operationId,
|
||||
input,
|
||||
}: {
|
||||
operationId: string;
|
||||
input: unknown;
|
||||
}): Promise<Result> => {
|
||||
const mutation =
|
||||
await executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
|
||||
id: operationId,
|
||||
state: remote.state,
|
||||
input,
|
||||
context: {
|
||||
createId: () => `mcp-email-binding-server-${nextId++}`,
|
||||
projectId: remote.projectId,
|
||||
projectVersion: remote.version,
|
||||
},
|
||||
});
|
||||
expect(mutation.kind).toBe("mutation");
|
||||
remote = {
|
||||
...remote,
|
||||
version: remote.version + 1,
|
||||
state: applyBuilderPatchTransactions(remote.state, [
|
||||
{
|
||||
id: `mcp-email-binding-transaction-${nextId++}`,
|
||||
payload: mutation.payload,
|
||||
},
|
||||
]).state,
|
||||
};
|
||||
await persist();
|
||||
return mutation.result as Result;
|
||||
},
|
||||
},
|
||||
});
|
||||
const projectEmail = (
|
||||
resources.resources as Array<{
|
||||
id: string;
|
||||
dataSourceId: string;
|
||||
name: string;
|
||||
}>
|
||||
).find(({ name }) => name === "Email to owner");
|
||||
if (projectEmail === undefined) {
|
||||
throw new Error("Expected the contact Form Project Email Resource");
|
||||
}
|
||||
if (mode === "partial" || mode === "empty") {
|
||||
const visitorEmail = (
|
||||
const server = await createProjectSessionMcpServer({
|
||||
operations,
|
||||
createProjectSession: () => session,
|
||||
executeOperation: async ({ command, input, dryRun }) => {
|
||||
const operation = operations.find(
|
||||
(candidate) => candidate.command === command
|
||||
);
|
||||
const contract = runtimeOperationContracts.find(
|
||||
({ id }) => id === operation?.id
|
||||
);
|
||||
if (operation === undefined || contract === undefined) {
|
||||
throw new Error(`Unexpected MCP operation: ${command}`);
|
||||
}
|
||||
const scopedInput = { ...(input as object), projectId };
|
||||
const result =
|
||||
operation.method === "mutation"
|
||||
? await session.mutate(contract.id, scopedInput, {
|
||||
permit: operation.permit,
|
||||
dryRun,
|
||||
})
|
||||
: await session.read(contract.id, scopedInput, {
|
||||
permit: operation.permit,
|
||||
});
|
||||
const failure = result.diagnostics.find(({ level }) => level === "error");
|
||||
if (failure) {
|
||||
throw new Error(failure.message);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const client = new Client({
|
||||
name: "mcp-email-binding-e2e",
|
||||
version: "1.0.0",
|
||||
});
|
||||
await Promise.all([
|
||||
server.connect(serverTransport),
|
||||
client.connect(clientTransport),
|
||||
]);
|
||||
const call = async (name: string, args: Record<string, unknown> = {}) => {
|
||||
const response = await client.callTool({ name, arguments: args });
|
||||
if (response.isError) {
|
||||
throw new Error(`${name}: ${JSON.stringify(response.structuredContent)}`);
|
||||
}
|
||||
const payload = response.structuredContent as {
|
||||
ok: boolean;
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
expect(payload.ok, name).toBe(true);
|
||||
return payload.data;
|
||||
};
|
||||
|
||||
try {
|
||||
const form = { id: formId };
|
||||
const resources = await call("list-resources", {
|
||||
scopeInstanceId: form.id,
|
||||
});
|
||||
const projectEmail = (
|
||||
resources.resources as Array<{
|
||||
id: string;
|
||||
dataSourceId: string;
|
||||
name: string;
|
||||
}>
|
||||
).find(({ name }) => name === "Email to visitor");
|
||||
if (visitorEmail === undefined) {
|
||||
throw new Error("Expected the contact Form visitor Email Resource");
|
||||
).find(({ name }) => name === "Email to owner");
|
||||
if (projectEmail === undefined) {
|
||||
throw new Error("Expected the contact Form Project Email Resource");
|
||||
}
|
||||
const settings = {
|
||||
recipientMode: "visitor",
|
||||
visitorEmailField: "email",
|
||||
senderExpression: '"Contact Team <team@example.test>"',
|
||||
includeAttachments: false,
|
||||
subject: '"Thanks for writing"',
|
||||
body: '"Initial confirmation"',
|
||||
};
|
||||
if (mode === "partial") {
|
||||
if (mode === "partial" || mode === "empty") {
|
||||
const visitorEmail = (
|
||||
resources.resources as Array<{
|
||||
id: string;
|
||||
dataSourceId: string;
|
||||
name: string;
|
||||
}>
|
||||
).find(({ name }) => name === "Email to visitor");
|
||||
if (visitorEmail === undefined) {
|
||||
throw new Error("Expected the contact Form visitor Email Resource");
|
||||
}
|
||||
const settings = {
|
||||
recipientMode: "visitor",
|
||||
visitorEmailField: "email",
|
||||
senderExpression: '"Contact Team <team@example.test>"',
|
||||
includeAttachments: false,
|
||||
subject: '"Thanks for writing"',
|
||||
body: '"Initial confirmation"',
|
||||
};
|
||||
if (mode === "partial") {
|
||||
await call("update-resource", {
|
||||
resourceId: visitorEmail.id,
|
||||
values: { email: settings },
|
||||
});
|
||||
await call("update-props", {
|
||||
updates: [
|
||||
{
|
||||
instanceId: form.id,
|
||||
name: "action",
|
||||
type: "json",
|
||||
value: [{ dataSourceId: visitorEmail.dataSourceId }],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
const body = mode === "partial" ? '"Custom confirmation"' : '""';
|
||||
await call("update-resource", {
|
||||
resourceId: visitorEmail.id,
|
||||
values: { email: settings },
|
||||
values: { email: { body } },
|
||||
});
|
||||
await call("refresh");
|
||||
const persistedResources = JSON.parse(
|
||||
(await loadDevBuild({ projectId })).resources
|
||||
) as Array<{ id: string; email?: Record<string, unknown> }>;
|
||||
expect(
|
||||
persistedResources.find(({ id }) => id === visitorEmail.id)?.email
|
||||
).toMatchObject({ ...settings, body });
|
||||
} else if (mode === "bind") {
|
||||
const inspection = await call("inspect-instance", {
|
||||
instanceId: form.id,
|
||||
include: ["props"],
|
||||
});
|
||||
const formDataId = (
|
||||
inspection.props as Array<{ name: string; value: unknown }>
|
||||
).find(({ name }) => name === "formData")?.value;
|
||||
if (typeof formDataId !== "string") {
|
||||
throw new Error("Expected the Form data parameter");
|
||||
}
|
||||
const formData = encodeDataSourceVariable(formDataId);
|
||||
await call("update-resource", {
|
||||
resourceId: projectEmail.id,
|
||||
values: {
|
||||
email: {
|
||||
recipientMode: "custom",
|
||||
recipientsExpression: `${formData}.email`,
|
||||
senderExpression: `${formData}.email`,
|
||||
subject: `\`Bound: \${${formData}.subject}\``,
|
||||
body: `\`Message from \${${formData}.name}: \${${formData}.message}\``,
|
||||
},
|
||||
},
|
||||
});
|
||||
await call("update-props", {
|
||||
updates: [
|
||||
@@ -283,119 +341,72 @@ try {
|
||||
instanceId: form.id,
|
||||
name: "action",
|
||||
type: "json",
|
||||
value: [{ dataSourceId: visitorEmail.dataSourceId }],
|
||||
value: [{ dataSourceId: projectEmail.dataSourceId }],
|
||||
},
|
||||
],
|
||||
});
|
||||
} else {
|
||||
const savedResource = (
|
||||
JSON.parse((await loadDevBuild({ projectId })).resources) as Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
control?: string;
|
||||
method: string;
|
||||
url: string;
|
||||
headers: Array<{ name: string; value: string }>;
|
||||
}>
|
||||
).find(({ id }) => id === projectEmail.id);
|
||||
if (savedResource === undefined) {
|
||||
throw new Error("Expected the saved Project Email Resource");
|
||||
}
|
||||
const { id: _id, ...resource } = savedResource;
|
||||
await call("upsert-resource", {
|
||||
resourceId: projectEmail.id,
|
||||
dataSourceId: projectEmail.dataSourceId,
|
||||
scopeInstanceId: form.id,
|
||||
resource: { ...resource, email: { recipientMode: "project" } },
|
||||
});
|
||||
await call("update-project-settings", {
|
||||
meta: {
|
||||
contactEmail: "owner@mcp.test",
|
||||
emailSender: "Contact Form <forms@mcp.test>",
|
||||
},
|
||||
});
|
||||
}
|
||||
const body = mode === "partial" ? '"Custom confirmation"' : '""';
|
||||
await call("update-resource", {
|
||||
resourceId: visitorEmail.id,
|
||||
values: { email: { body } },
|
||||
});
|
||||
await call("refresh");
|
||||
const persistedResources = JSON.parse(
|
||||
(await loadDevBuild({ projectId })).resources
|
||||
) as Array<{ id: string; email?: Record<string, unknown> }>;
|
||||
expect(
|
||||
persistedResources.find(({ id }) => id === visitorEmail.id)?.email
|
||||
).toMatchObject({ ...settings, body });
|
||||
} else if (mode === "bind") {
|
||||
const inspection = await call("inspect-instance", {
|
||||
instanceId: form.id,
|
||||
include: ["props"],
|
||||
});
|
||||
const formDataId = (
|
||||
inspection.props as Array<{ name: string; value: unknown }>
|
||||
).find(({ name }) => name === "formData")?.value;
|
||||
if (typeof formDataId !== "string") {
|
||||
throw new Error("Expected the Form data parameter");
|
||||
const persistedSettings = persistedResources.find(
|
||||
({ id }) => id === projectEmail.id
|
||||
)?.email;
|
||||
if (mode === "partial" || mode === "empty") {
|
||||
const visitorEmail = (
|
||||
resources.resources as Array<{ id: string; name: string }>
|
||||
).find(({ name }) => name === "Email to visitor");
|
||||
expect(
|
||||
persistedResources.find(({ id }) => id === visitorEmail?.id)?.email
|
||||
).toMatchObject({
|
||||
recipientMode: "visitor",
|
||||
visitorEmailField: "email",
|
||||
senderExpression: '"Contact Team <team@example.test>"',
|
||||
includeAttachments: false,
|
||||
subject: '"Thanks for writing"',
|
||||
body: mode === "partial" ? '"Custom confirmation"' : '""',
|
||||
});
|
||||
} else if (mode === "reset") {
|
||||
expect(persistedSettings).toEqual({ recipientMode: "project" });
|
||||
} else {
|
||||
expect(persistedSettings).toMatchObject({
|
||||
recipientMode: "custom",
|
||||
recipientsExpression: expect.any(String),
|
||||
senderExpression: expect.any(String),
|
||||
subject: expect.any(String),
|
||||
body: expect.any(String),
|
||||
});
|
||||
}
|
||||
const formData = encodeDataSourceVariable(formDataId);
|
||||
await call("update-resource", {
|
||||
resourceId: projectEmail.id,
|
||||
values: {
|
||||
email: {
|
||||
recipientMode: "custom",
|
||||
recipientsExpression: `${formData}.email`,
|
||||
senderExpression: `${formData}.email`,
|
||||
subject: `\`Bound: \${${formData}.subject}\``,
|
||||
body: `\`Message from \${${formData}.name}: \${${formData}.message}\``,
|
||||
},
|
||||
},
|
||||
});
|
||||
await call("update-props", {
|
||||
updates: [
|
||||
{
|
||||
instanceId: form.id,
|
||||
name: "action",
|
||||
type: "json",
|
||||
value: [{ dataSourceId: projectEmail.dataSourceId }],
|
||||
},
|
||||
],
|
||||
});
|
||||
} else {
|
||||
const savedResource = (
|
||||
JSON.parse((await loadDevBuild({ projectId })).resources) as Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
control?: string;
|
||||
method: string;
|
||||
url: string;
|
||||
headers: Array<{ name: string; value: string }>;
|
||||
}>
|
||||
).find(({ id }) => id === projectEmail.id);
|
||||
if (savedResource === undefined) {
|
||||
throw new Error("Expected the saved Project Email Resource");
|
||||
}
|
||||
const { id: _id, ...resource } = savedResource;
|
||||
await call("upsert-resource", {
|
||||
resourceId: projectEmail.id,
|
||||
dataSourceId: projectEmail.dataSourceId,
|
||||
scopeInstanceId: form.id,
|
||||
resource: { ...resource, email: { recipientMode: "project" } },
|
||||
});
|
||||
await call("update-project-settings", {
|
||||
meta: {
|
||||
contactEmail: "owner@mcp.test",
|
||||
emailSender: "Contact Form <forms@mcp.test>",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
await call("refresh");
|
||||
const persistedResources = JSON.parse(
|
||||
(await loadDevBuild({ projectId })).resources
|
||||
) as Array<{ id: string; email?: Record<string, unknown> }>;
|
||||
const persistedSettings = persistedResources.find(
|
||||
({ id }) => id === projectEmail.id
|
||||
)?.email;
|
||||
if (mode === "partial" || mode === "empty") {
|
||||
const visitorEmail = (
|
||||
resources.resources as Array<{ id: string; name: string }>
|
||||
).find(({ name }) => name === "Email to visitor");
|
||||
expect(
|
||||
persistedResources.find(({ id }) => id === visitorEmail?.id)?.email
|
||||
).toMatchObject({
|
||||
recipientMode: "visitor",
|
||||
visitorEmailField: "email",
|
||||
senderExpression: '"Contact Team <team@example.test>"',
|
||||
includeAttachments: false,
|
||||
subject: '"Thanks for writing"',
|
||||
body: mode === "partial" ? '"Custom confirmation"' : '""',
|
||||
});
|
||||
} else if (mode === "reset") {
|
||||
expect(persistedSettings).toEqual({ recipientMode: "project" });
|
||||
} else {
|
||||
expect(persistedSettings).toMatchObject({
|
||||
recipientMode: "custom",
|
||||
recipientsExpression: expect.any(String),
|
||||
senderExpression: expect.any(String),
|
||||
subject: expect.any(String),
|
||||
body: expect.any(String),
|
||||
});
|
||||
}
|
||||
process.stdout.write(`${JSON.stringify({ formId: form.id })}\n`);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
@@ -14,6 +14,11 @@ const screenshotModuleUrl = new URL(
|
||||
const { createMcpPreviewHandlers } = await import(previewModuleUrl);
|
||||
const { createScreenshotCaptureSession } = await import(screenshotModuleUrl);
|
||||
|
||||
const browserPath = process.env.WEBSTUDIO_BROWSER_PATH;
|
||||
if (browserPath === undefined) {
|
||||
throw new Error("Expected the Playwright Chromium executable path");
|
||||
}
|
||||
|
||||
let url = "";
|
||||
|
||||
const previewHandlers = createMcpPreviewHandlers({
|
||||
@@ -26,7 +31,15 @@ const previewHandlers = createMcpPreviewHandlers({
|
||||
stop: async () => ({ running: false, url, mode: "iterative" as const }),
|
||||
},
|
||||
isStale: () => false,
|
||||
createCaptureSession: createScreenshotCaptureSession,
|
||||
createCaptureSession: () => {
|
||||
const session = createScreenshotCaptureSession();
|
||||
return {
|
||||
...session,
|
||||
// The test runner already picked the Playwright Chromium executable.
|
||||
submitForm: (options: object) =>
|
||||
session.submitForm({ ...options, browserPath }),
|
||||
};
|
||||
},
|
||||
});
|
||||
const server = await createProjectSessionMcpServer({
|
||||
operations: [],
|
||||
|
||||
@@ -25,21 +25,16 @@ const getBaseBreakpointId = (breakpoints: string) => {
|
||||
const createSlotKeyboardBuildData = ({
|
||||
pages,
|
||||
breakpoints,
|
||||
additionalPairSuffixes,
|
||||
}: {
|
||||
pages: string;
|
||||
breakpoints: string;
|
||||
additionalPairSuffixes: string[];
|
||||
}) => {
|
||||
const rootInstanceId = "slot-keyboard-body";
|
||||
const wrapperId = "slot-keyboard-wrapper";
|
||||
const slotAId = "slot-keyboard-slot-a";
|
||||
const slotBId = "slot-keyboard-slot-b";
|
||||
const fragmentId = "slot-keyboard-fragment";
|
||||
const divId = "slot-keyboard-div";
|
||||
const headingId = "slot-keyboard-heading";
|
||||
const baseBreakpointId = getBaseBreakpointId(breakpoints);
|
||||
const wrapperStyleSourceId = "slot-keyboard-wrapper-style";
|
||||
const divStyleSourceId = "slot-keyboard-div-style";
|
||||
const headingStyleSourceId = "slot-keyboard-heading-style";
|
||||
|
||||
const nextPages = JSON.parse(pages) as {
|
||||
homePageId: string;
|
||||
@@ -53,6 +48,91 @@ const createSlotKeyboardBuildData = ({
|
||||
}
|
||||
homePage.rootInstanceId = rootInstanceId;
|
||||
|
||||
const slotPairs = ["", ...additionalPairSuffixes].map((suffix) => {
|
||||
const slotAId = `slot-keyboard-slot-a${suffix}`;
|
||||
const slotBId = `slot-keyboard-slot-b${suffix}`;
|
||||
const fragmentId = `slot-keyboard-fragment${suffix}`;
|
||||
const divId = `slot-keyboard-div${suffix}`;
|
||||
const headingId = `slot-keyboard-heading${suffix}`;
|
||||
const divStyleSourceId = `slot-keyboard-div-style${suffix}`;
|
||||
const headingStyleSourceId = `slot-keyboard-heading-style${suffix}`;
|
||||
return {
|
||||
children: [
|
||||
{ type: "id", value: slotAId },
|
||||
{ type: "id", value: slotBId },
|
||||
],
|
||||
instances: [
|
||||
{
|
||||
type: "instance",
|
||||
id: slotAId,
|
||||
component: "Slot",
|
||||
label: "Slot A",
|
||||
children: [{ type: "id", value: fragmentId }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: slotBId,
|
||||
component: "Slot",
|
||||
label: "Slot B",
|
||||
children: [{ type: "id", value: fragmentId }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: fragmentId,
|
||||
component: "Fragment",
|
||||
children: [
|
||||
{ type: "id", value: divId },
|
||||
{ type: "id", value: headingId },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: divId,
|
||||
component: "ws:element",
|
||||
tag: "div",
|
||||
label: "Drop Div",
|
||||
children: [{ type: "text", value: "Drop zone" }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: headingId,
|
||||
component: "ws:element",
|
||||
tag: "h1",
|
||||
label: "Slot Heading",
|
||||
children: [{ type: "text", value: "Slot heading" }],
|
||||
},
|
||||
],
|
||||
styleSources: [
|
||||
{ type: "local", id: divStyleSourceId },
|
||||
{ type: "local", id: headingStyleSourceId },
|
||||
],
|
||||
styleSourceSelections: [
|
||||
{ instanceId: divId, values: [divStyleSourceId] },
|
||||
{ instanceId: headingId, values: [headingStyleSourceId] },
|
||||
],
|
||||
styles: [
|
||||
{
|
||||
styleSourceId: divStyleSourceId,
|
||||
breakpointId: baseBreakpointId,
|
||||
property: "minHeight",
|
||||
value: { type: "unit", unit: "px", value: 120 },
|
||||
},
|
||||
{
|
||||
styleSourceId: divStyleSourceId,
|
||||
breakpointId: baseBreakpointId,
|
||||
property: "padding",
|
||||
value: { type: "unit", unit: "px", value: 24 },
|
||||
},
|
||||
{
|
||||
styleSourceId: headingStyleSourceId,
|
||||
breakpointId: baseBreakpointId,
|
||||
property: "marginTop",
|
||||
value: { type: "unit", unit: "px", value: 24 },
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
pages: JSON.stringify(nextPages),
|
||||
instances: JSON.stringify([
|
||||
@@ -69,61 +149,18 @@ const createSlotKeyboardBuildData = ({
|
||||
component: "ws:element",
|
||||
tag: "main",
|
||||
label: "Slot Keyboard Wrapper",
|
||||
children: [
|
||||
{ type: "id", value: slotAId },
|
||||
{ type: "id", value: slotBId },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: slotAId,
|
||||
component: "Slot",
|
||||
label: "Slot A",
|
||||
children: [{ type: "id", value: fragmentId }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: slotBId,
|
||||
component: "Slot",
|
||||
label: "Slot B",
|
||||
children: [{ type: "id", value: fragmentId }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: fragmentId,
|
||||
component: "Fragment",
|
||||
children: [
|
||||
{ type: "id", value: divId },
|
||||
{ type: "id", value: headingId },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: divId,
|
||||
component: "ws:element",
|
||||
tag: "div",
|
||||
label: "Drop Div",
|
||||
children: [{ type: "text", value: "Drop zone" }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: headingId,
|
||||
component: "ws:element",
|
||||
tag: "h1",
|
||||
label: "Slot Heading",
|
||||
children: [{ type: "text", value: "Slot heading" }],
|
||||
children: slotPairs.flatMap((pair) => pair.children),
|
||||
},
|
||||
...slotPairs.flatMap((pair) => pair.instances),
|
||||
]),
|
||||
props: JSON.stringify([]),
|
||||
styleSources: JSON.stringify([
|
||||
{ type: "local", id: wrapperStyleSourceId },
|
||||
{ type: "local", id: divStyleSourceId },
|
||||
{ type: "local", id: headingStyleSourceId },
|
||||
...slotPairs.flatMap((pair) => pair.styleSources),
|
||||
]),
|
||||
styleSourceSelections: JSON.stringify([
|
||||
{ instanceId: wrapperId, values: [wrapperStyleSourceId] },
|
||||
{ instanceId: divId, values: [divStyleSourceId] },
|
||||
{ instanceId: headingId, values: [headingStyleSourceId] },
|
||||
...slotPairs.flatMap((pair) => pair.styleSourceSelections),
|
||||
]),
|
||||
styles: JSON.stringify([
|
||||
{
|
||||
@@ -138,24 +175,7 @@ const createSlotKeyboardBuildData = ({
|
||||
property: "gap",
|
||||
value: { type: "unit", unit: "px", value: 32 },
|
||||
},
|
||||
{
|
||||
styleSourceId: divStyleSourceId,
|
||||
breakpointId: baseBreakpointId,
|
||||
property: "minHeight",
|
||||
value: { type: "unit", unit: "px", value: 120 },
|
||||
},
|
||||
{
|
||||
styleSourceId: divStyleSourceId,
|
||||
breakpointId: baseBreakpointId,
|
||||
property: "padding",
|
||||
value: { type: "unit", unit: "px", value: 24 },
|
||||
},
|
||||
{
|
||||
styleSourceId: headingStyleSourceId,
|
||||
breakpointId: baseBreakpointId,
|
||||
property: "marginTop",
|
||||
value: { type: "unit", unit: "px", value: 24 },
|
||||
},
|
||||
...slotPairs.flatMap((pair) => pair.styles),
|
||||
]),
|
||||
dataSources: JSON.stringify([]),
|
||||
resources: JSON.stringify([]),
|
||||
@@ -168,11 +188,13 @@ export const createSlotKeyboardProject = async ({
|
||||
email = "slot-keyboard-e2e@webstudio.test",
|
||||
title = "Slot Keyboard E2E",
|
||||
builderToken = "slot-keyboard-e2e-builder-token",
|
||||
additionalPairSuffixes = [],
|
||||
}: {
|
||||
context: BrowserContext;
|
||||
email?: string;
|
||||
title?: string;
|
||||
builderToken?: string;
|
||||
additionalPairSuffixes?: string[];
|
||||
}): Promise<SeededSlotKeyboardProject> => {
|
||||
return await createSeededBuilderProject({
|
||||
context,
|
||||
@@ -183,6 +205,7 @@ export const createSlotKeyboardProject = async ({
|
||||
createSlotKeyboardBuildData({
|
||||
pages: build.pages,
|
||||
breakpoints: build.breakpoints,
|
||||
additionalPairSuffixes,
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const reactGlobalPath = fileURLToPath(
|
||||
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
|
||||
);
|
||||
const cliTsconfigPath = fileURLToPath(
|
||||
new URL("../../../../packages/cli/tsconfig.local.json", import.meta.url)
|
||||
);
|
||||
|
||||
export const runFormAuthor = (
|
||||
author: string,
|
||||
projectId: string,
|
||||
...args: string[]
|
||||
) =>
|
||||
execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
"tsx",
|
||||
"--import",
|
||||
reactGlobalPath,
|
||||
"--conditions=webstudio",
|
||||
fileURLToPath(new URL(`../fixtures/${author}.ts`, import.meta.url)),
|
||||
projectId,
|
||||
...args,
|
||||
],
|
||||
{
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, TSX_TSCONFIG_PATH: cliTsconfigPath },
|
||||
}
|
||||
);
|
||||
@@ -1,4 +1,5 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
@@ -87,6 +88,13 @@ const startClient = () => {
|
||||
let client: ReturnType<typeof startClient> | undefined;
|
||||
let queue = Promise.resolve();
|
||||
|
||||
export const startPreviewFormMcpClient = async () => {
|
||||
if (client === undefined) {
|
||||
client = startClient();
|
||||
await once(client.child, "spawn");
|
||||
}
|
||||
};
|
||||
|
||||
export const closePreviewFormMcpClient = async () => {
|
||||
await queue;
|
||||
const activeClient = client;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { insertAssetFolders } from "../db";
|
||||
import {
|
||||
createAssetFolder,
|
||||
openAssetsPanel,
|
||||
@@ -150,6 +152,18 @@ test("Dragging an asset auto-scrolls a long folder list", async ({
|
||||
builderToken: "asset-folder-autoscroll-e2e-builder-token",
|
||||
});
|
||||
|
||||
// The long list is a precondition for the drag, so seed its filler folders together.
|
||||
const createdAt = new Date().toISOString();
|
||||
await insertAssetFolders(
|
||||
Array.from({ length: 24 }, (_, index) => ({
|
||||
id: randomUUID(),
|
||||
projectId: fixture.projectId,
|
||||
name: `Filler ${String(index).padStart(2, "0")}`,
|
||||
parentId: null,
|
||||
createdAt,
|
||||
}))
|
||||
);
|
||||
|
||||
await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
@@ -162,18 +176,6 @@ test("Dragging an asset auto-scrolls a long folder list", async ({
|
||||
filename: "upload-image.svg",
|
||||
});
|
||||
const scrollArea = page.locator("[data-asset-manager-scroll-area]");
|
||||
for (let index = 0; index < 24; index += 1) {
|
||||
await createAssetFolder({
|
||||
page,
|
||||
name: `Filler ${String(index).padStart(2, "0")}`,
|
||||
});
|
||||
const overflows = await scrollArea.evaluate(
|
||||
(element) => element.scrollHeight > element.clientHeight + 80
|
||||
);
|
||||
if (overflows) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
const destination = await createAssetFolder({
|
||||
page,
|
||||
name: "Destination",
|
||||
|
||||
@@ -43,6 +43,7 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
const builderToken = `${fixture.projectId}-mcp-builder-token`;
|
||||
const directories = {
|
||||
editor: directory,
|
||||
editorRead: freshDirectory,
|
||||
viewer: viewerDirectory,
|
||||
builder: builderDirectory,
|
||||
};
|
||||
@@ -72,30 +73,19 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
};
|
||||
const call = async (
|
||||
tool: string,
|
||||
input: object,
|
||||
{
|
||||
fresh = false,
|
||||
role = "editor",
|
||||
}: { fresh?: boolean; role?: keyof typeof directories } = {}
|
||||
input: Record<string, unknown>,
|
||||
role: keyof typeof directories = "editor"
|
||||
) => {
|
||||
const client = fresh
|
||||
? await connect(freshDirectory, directories[role])
|
||||
: (clients.get(role) ??
|
||||
(await connect(directories[role], directories[role])));
|
||||
if (fresh === false) {
|
||||
let client = clients.get(role);
|
||||
if (client === undefined) {
|
||||
client = await connect(
|
||||
directories[role],
|
||||
role === "editorRead" ? directories.editor : directories[role]
|
||||
);
|
||||
clients.set(role, client);
|
||||
}
|
||||
try {
|
||||
const result = await client.callTool({
|
||||
name: tool,
|
||||
arguments: input as Record<string, unknown>,
|
||||
});
|
||||
return JSON.parse(JSON.stringify(result.structuredContent));
|
||||
} finally {
|
||||
if (fresh) {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
const result = await client.callTool({ name: tool, arguments: input });
|
||||
return JSON.parse(JSON.stringify(result.structuredContent));
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -155,7 +145,7 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
expect(updated.ok, updated.error?.message).toBe(true);
|
||||
expect(updated.meta.session.commitStatus).toBe("committed");
|
||||
|
||||
const reloaded = await call("get-page", { pageId }, { fresh: true });
|
||||
const reloaded = await call("get-page", { pageId }, "editorRead");
|
||||
expect(reloaded.ok).toBe(true);
|
||||
expect(reloaded.data).toMatchObject({
|
||||
id: pageId,
|
||||
@@ -165,20 +155,6 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
meta: { description: '"Edited MCP description"' },
|
||||
});
|
||||
|
||||
await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.editorToken,
|
||||
mode: "content",
|
||||
});
|
||||
await openPage({
|
||||
page,
|
||||
pageName: "Edited MCP content page",
|
||||
canvasText: fixture.pageTemplateText,
|
||||
});
|
||||
await openPageSettings({ page, pageName: "Edited MCP content page" });
|
||||
await expect(page.getByLabel("Title")).toHaveValue("Edited MCP title");
|
||||
|
||||
const beforeDenied = await loadDevBuild({ projectId: fixture.projectId });
|
||||
const denied = await call("update-page-settings", {
|
||||
pageId,
|
||||
@@ -207,13 +183,20 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
expect(uploaded.meta.session.commitStatus).toBe("committed");
|
||||
const assetId = uploaded.data.uploaded[0].id;
|
||||
|
||||
const asset = await call("get-asset", { assetId }, { fresh: true });
|
||||
const refreshed = await call(
|
||||
"refresh",
|
||||
{ namespaces: ["assets", "assetFolders"] },
|
||||
"editorRead"
|
||||
);
|
||||
expect(refreshed.ok, refreshed.error?.message).toBe(true);
|
||||
|
||||
const asset = await call("get-asset", { assetId }, "editorRead");
|
||||
expect(asset.ok).toBe(true);
|
||||
expect(asset.data.asset).toMatchObject({
|
||||
id: assetId,
|
||||
folderId,
|
||||
});
|
||||
const folders = await call("list-asset-folders", {}, { fresh: true });
|
||||
const folders = await call("list-asset-folders", {}, "editorRead");
|
||||
expect(folders.ok).toBe(true);
|
||||
expect(folders.data.folders).toEqual(
|
||||
expect.arrayContaining([
|
||||
@@ -227,6 +210,14 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
authToken: fixture.editorToken,
|
||||
mode: "content",
|
||||
});
|
||||
await openPage({
|
||||
page,
|
||||
pageName: "Edited MCP content page",
|
||||
canvasText: fixture.pageTemplateText,
|
||||
});
|
||||
await openPageSettings({ page, pageName: "Edited MCP content page" });
|
||||
await expect(page.getByLabel("Title")).toHaveValue("Edited MCP title");
|
||||
|
||||
await openAssetsPanel({ page });
|
||||
await page
|
||||
.getByRole("button", { name: "Folder Editor MCP assets" })
|
||||
@@ -236,7 +227,7 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
const beforeViewerWrites = await loadDevBuild({
|
||||
projectId: fixture.projectId,
|
||||
});
|
||||
expect((await call("list-pages", {}, { role: "viewer" })).ok).toBe(true);
|
||||
expect((await call("list-pages", {}, "viewer")).ok).toBe(true);
|
||||
for (const [tool, input] of [
|
||||
[
|
||||
"create-page-from-template",
|
||||
@@ -251,7 +242,7 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
},
|
||||
],
|
||||
] as const) {
|
||||
const denied = await call(tool, input, { role: "viewer" });
|
||||
const denied = await call(tool, input, "viewer");
|
||||
expect(denied.ok, tool).toBe(false);
|
||||
expect(denied.error.code, `${tool}: ${denied.error.message}`).toBe(
|
||||
"FORBIDDEN"
|
||||
@@ -266,10 +257,10 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
const builderWrite = await call(
|
||||
"update-page-settings",
|
||||
{ pageId, values: { status: "302" } },
|
||||
{ role: "builder" }
|
||||
"builder"
|
||||
);
|
||||
expect(builderWrite.ok, builderWrite.error?.message).toBe(true);
|
||||
const builderPage = await call("get-page", { pageId }, { role: "builder" });
|
||||
const builderPage = await call("get-page", { pageId }, "builder");
|
||||
expect(builderPage.data.meta.status).toBe("302");
|
||||
} finally {
|
||||
await Promise.all(Array.from(clients.values(), (client) => client.close()));
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect } from "@playwright/test";
|
||||
import { loadDevBuild } from "../db";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import {
|
||||
startLocalEmailReceiver,
|
||||
withMcpEmailPreview,
|
||||
} from "../flows/mcp-email-preview";
|
||||
import { test } from "../test";
|
||||
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const authorPath = fileURLToPath(
|
||||
new URL("../fixtures/mcp-managed-form-author.ts", import.meta.url)
|
||||
);
|
||||
const reactGlobalPath = fileURLToPath(
|
||||
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
|
||||
);
|
||||
const cliTsconfigPath = fileURLToPath(
|
||||
new URL("../../../../packages/cli/tsconfig.local.json", import.meta.url)
|
||||
);
|
||||
|
||||
test("MCP-authored Email Resources deliver multiple files and honor attachment opt-out", async ({
|
||||
context,
|
||||
}) => {
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email: "mcp-email-attachments@webstudio.test",
|
||||
title: "MCP Email attachments",
|
||||
assetNamePrefix: "mcp-email-attachments-",
|
||||
builderToken: "mcp-email-attachments-builder-token",
|
||||
});
|
||||
const { stdout } = await execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
"tsx",
|
||||
"--import",
|
||||
reactGlobalPath,
|
||||
"--conditions=webstudio",
|
||||
authorPath,
|
||||
fixture.projectId,
|
||||
"email-attachments",
|
||||
],
|
||||
{
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, TSX_TSCONFIG_PATH: cliTsconfigPath },
|
||||
}
|
||||
);
|
||||
const { formId, emailResourceIds } = JSON.parse(stdout) as {
|
||||
formId: string;
|
||||
emailResourceIds: string[];
|
||||
};
|
||||
expect(emailResourceIds).toHaveLength(2);
|
||||
const build = await loadDevBuild({ projectId: fixture.projectId });
|
||||
const resources = JSON.parse(build.resources) as Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
email?: { includeAttachments?: boolean };
|
||||
}>;
|
||||
const ownerResource = resources.find(
|
||||
({ id, name }) => emailResourceIds.includes(id) && name === "Email to owner"
|
||||
);
|
||||
const visitorResource = resources.find(
|
||||
({ id, name }) =>
|
||||
emailResourceIds.includes(id) && name === "Email to visitor"
|
||||
);
|
||||
expect(ownerResource?.email?.includeAttachments).toBe(true);
|
||||
expect(visitorResource?.email?.includeAttachments).toBe(false);
|
||||
|
||||
const files = [
|
||||
{
|
||||
name: "café-notes.txt",
|
||||
mimeType: "text/plain",
|
||||
buffer: Buffer.from("First attachment: café\n", "utf8"),
|
||||
},
|
||||
{
|
||||
name: "sample.bin",
|
||||
mimeType: "application/octet-stream",
|
||||
buffer: Buffer.from([0, 1, 127, 128, 254, 255]),
|
||||
},
|
||||
];
|
||||
const receiver = await startLocalEmailReceiver();
|
||||
try {
|
||||
await withMcpEmailPreview({
|
||||
projectId: fixture.projectId,
|
||||
emailPort: receiver.port,
|
||||
callback: async ({ url }) => {
|
||||
const submission = await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: `[data-ws-managed-form-id="${formId}"]`,
|
||||
values: [
|
||||
{ name: "name", value: "Ada Lovelace" },
|
||||
{ name: "email", value: "ada@example.test" },
|
||||
{ name: "subject", value: "Attachment opt-out test" },
|
||||
{
|
||||
name: "message",
|
||||
value: "Checking separate file delivery settings.",
|
||||
},
|
||||
...files.map((file) => ({
|
||||
name: "upload",
|
||||
file: {
|
||||
name: file.name,
|
||||
type: file.mimeType,
|
||||
base64: file.buffer.toString("base64"),
|
||||
},
|
||||
})),
|
||||
],
|
||||
submitter: "button[type=submit]",
|
||||
timeout: 30_000,
|
||||
},
|
||||
});
|
||||
expect(submission.data).toMatchObject({
|
||||
status: "submitted",
|
||||
formState: "success",
|
||||
errors: [],
|
||||
});
|
||||
expect(submission.data.results).toEqual([
|
||||
expect.objectContaining({
|
||||
resourceId: emailResourceIds[0],
|
||||
status: 200,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
resourceId: emailResourceIds[1],
|
||||
status: 200,
|
||||
}),
|
||||
]);
|
||||
expect(receiver.messages).toHaveLength(2);
|
||||
|
||||
const owner = receiver.messages.find((message) =>
|
||||
message.to.some(({ address }) => address === "owner@mcp.test")
|
||||
);
|
||||
const visitor = receiver.messages.find((message) =>
|
||||
message.to.some(({ address }) => address === "ada@example.test")
|
||||
);
|
||||
expect(owner).toBeDefined();
|
||||
expect(visitor).toBeDefined();
|
||||
expect(owner?.attachments).toHaveLength(files.length);
|
||||
for (const [index, file] of files.entries()) {
|
||||
const attachment = owner?.attachments?.[index];
|
||||
expect(attachment?.filename).toBe(file.name);
|
||||
expect(attachment?.contentType).toBe(file.mimeType);
|
||||
expect(
|
||||
Buffer.from(attachment?.contentBase64 ?? "", "base64")
|
||||
).toEqual(file.buffer);
|
||||
}
|
||||
expect(visitor?.attachments).toBeUndefined();
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await receiver.close();
|
||||
}
|
||||
});
|
||||
@@ -1,54 +1,23 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect } from "@playwright/test";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { runFormAuthor } from "../flows/mcp-form-author";
|
||||
import {
|
||||
startLocalEmailReceiver,
|
||||
withMcpEmailPreview,
|
||||
} from "../flows/mcp-email-preview";
|
||||
import { test } from "../test";
|
||||
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
|
||||
import {
|
||||
startPreviewFormMcpClient,
|
||||
submitPreviewFormViaMcp,
|
||||
} from "../flows/mcp-preview-submit";
|
||||
|
||||
// Both tests run two MCP authoring and generated preview phases.
|
||||
const twoPhaseTimeout = 240_000;
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const reactGlobalPath = fileURLToPath(
|
||||
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
|
||||
);
|
||||
const cliTsconfigPath = fileURLToPath(
|
||||
new URL("../../../../packages/cli/tsconfig.local.json", import.meta.url)
|
||||
);
|
||||
const initialAuthorPath = fileURLToPath(
|
||||
new URL("../fixtures/mcp-managed-form-author.ts", import.meta.url)
|
||||
);
|
||||
const bindingAuthorPath = fileURLToPath(
|
||||
new URL("../fixtures/mcp-email-binding-author.ts", import.meta.url)
|
||||
);
|
||||
const author = async (
|
||||
projectId: string,
|
||||
path: string,
|
||||
mode: string,
|
||||
formId?: string
|
||||
) => {
|
||||
const { stdout } = await execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
"tsx",
|
||||
"--import",
|
||||
reactGlobalPath,
|
||||
"--conditions=webstudio",
|
||||
path,
|
||||
projectId,
|
||||
mode,
|
||||
...(formId === undefined ? [] : [formId]),
|
||||
],
|
||||
{
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, TSX_TSCONFIG_PATH: cliTsconfigPath },
|
||||
}
|
||||
const createForm = async (projectId: string) => {
|
||||
const { stdout } = await runFormAuthor(
|
||||
"mcp-managed-form-author",
|
||||
projectId,
|
||||
"email"
|
||||
);
|
||||
return JSON.parse(stdout) as { formId: string };
|
||||
};
|
||||
@@ -57,6 +26,7 @@ test("MCP Email binding changes share two production Preview phases", async ({
|
||||
context,
|
||||
}) => {
|
||||
test.setTimeout(twoPhaseTimeout);
|
||||
await startPreviewFormMcpClient();
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email: "mcp-email-binding-scenarios@webstudio.test",
|
||||
@@ -64,11 +34,16 @@ test("MCP Email binding changes share two production Preview phases", async ({
|
||||
assetNamePrefix: "mcp-email-binding-scenarios-",
|
||||
builderToken: "mcp-email-binding-scenarios-builder-token",
|
||||
});
|
||||
const bound = await author(fixture.projectId, initialAuthorPath, "email");
|
||||
const partial = await author(fixture.projectId, initialAuthorPath, "email");
|
||||
const bound = await createForm(fixture.projectId);
|
||||
const partial = await createForm(fixture.projectId);
|
||||
expect(bound.formId).not.toBe(partial.formId);
|
||||
await author(fixture.projectId, bindingAuthorPath, "bind", bound.formId);
|
||||
await author(fixture.projectId, bindingAuthorPath, "partial", partial.formId);
|
||||
await runFormAuthor(
|
||||
"mcp-email-binding-author",
|
||||
fixture.projectId,
|
||||
"initial",
|
||||
bound.formId,
|
||||
partial.formId
|
||||
);
|
||||
|
||||
const receiver = await startLocalEmailReceiver();
|
||||
const submit = async (url: string, formId: string, withUpload: boolean) => {
|
||||
@@ -143,8 +118,13 @@ test("MCP Email binding changes share two production Preview phases", async ({
|
||||
},
|
||||
});
|
||||
|
||||
await author(fixture.projectId, bindingAuthorPath, "reset", bound.formId);
|
||||
await author(fixture.projectId, bindingAuthorPath, "empty", partial.formId);
|
||||
await runFormAuthor(
|
||||
"mcp-email-binding-author",
|
||||
fixture.projectId,
|
||||
"updated",
|
||||
bound.formId,
|
||||
partial.formId
|
||||
);
|
||||
await withMcpEmailPreview({
|
||||
projectId: fixture.projectId,
|
||||
emailPort: receiver.port,
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import { expect } from "@playwright/test";
|
||||
import { loadDevBuild } from "../db";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { startFormDeliveryReceiver } from "../flows/generated-form-delivery";
|
||||
import { withMcpEmailHttpPreview } from "../flows/mcp-email-http-preview";
|
||||
import { startLocalEmailReceiver } from "../flows/mcp-email-preview";
|
||||
import { runFormAuthor } from "../flows/mcp-form-author";
|
||||
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
|
||||
import { test } from "../test";
|
||||
|
||||
test("MCP-authored Forms deliver email attachments and ordered HTTP Actions in generated Preview", async ({
|
||||
context,
|
||||
}) => {
|
||||
// Author the HTTP and Email scenarios before building their shared Preview.
|
||||
test.setTimeout(180_000);
|
||||
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email: "mcp-email-attachments@webstudio.test",
|
||||
title: "MCP Form delivery",
|
||||
assetNamePrefix: "mcp-email-attachments-",
|
||||
builderToken: "mcp-email-attachments-builder-token",
|
||||
});
|
||||
await runFormAuthor(
|
||||
"mcp-form-callbacks-author",
|
||||
fixture.projectId,
|
||||
"managed",
|
||||
"https://mcp-delivery.example/submit",
|
||||
"field-change"
|
||||
);
|
||||
const { stdout: actionsOutput } = await runFormAuthor(
|
||||
"mcp-form-action-combination-author",
|
||||
fixture.projectId,
|
||||
"ten-actions"
|
||||
);
|
||||
const { formId, resourceIds, rejectedResourceId } = JSON.parse(
|
||||
actionsOutput
|
||||
) as {
|
||||
formId: string;
|
||||
resourceIds: string[];
|
||||
rejectedResourceId: string;
|
||||
};
|
||||
expect(resourceIds).toHaveLength(10);
|
||||
expect(new Set([...resourceIds, rejectedResourceId]).size).toBe(11);
|
||||
|
||||
const { stdout: emailOutput } = await runFormAuthor(
|
||||
"mcp-managed-form-author",
|
||||
fixture.projectId,
|
||||
"email-attachments"
|
||||
);
|
||||
const { formId: emailFormId, emailResourceIds } = JSON.parse(emailOutput) as {
|
||||
formId: string;
|
||||
emailResourceIds: string[];
|
||||
};
|
||||
expect(emailResourceIds).toHaveLength(2);
|
||||
const build = await loadDevBuild({ projectId: fixture.projectId });
|
||||
const resources = JSON.parse(build.resources) as Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
email?: { includeAttachments?: boolean };
|
||||
}>;
|
||||
const ownerResource = resources.find(
|
||||
({ id, name }) => emailResourceIds.includes(id) && name === "Email to owner"
|
||||
);
|
||||
const visitorResource = resources.find(
|
||||
({ id, name }) =>
|
||||
emailResourceIds.includes(id) && name === "Email to visitor"
|
||||
);
|
||||
expect(ownerResource?.email?.includeAttachments).toBe(true);
|
||||
expect(visitorResource?.email?.includeAttachments).toBe(false);
|
||||
|
||||
const files = [
|
||||
{
|
||||
name: "café-notes.txt",
|
||||
mimeType: "text/plain",
|
||||
buffer: Buffer.from("First attachment: café\n", "utf8"),
|
||||
},
|
||||
{
|
||||
name: "sample.bin",
|
||||
mimeType: "application/octet-stream",
|
||||
buffer: Buffer.from([0, 1, 127, 128, 254, 255]),
|
||||
},
|
||||
];
|
||||
const emailReceiver = await startLocalEmailReceiver();
|
||||
try {
|
||||
const receiver = await startFormDeliveryReceiver();
|
||||
try {
|
||||
await withMcpEmailHttpPreview({
|
||||
projectId: fixture.projectId,
|
||||
emailPort: emailReceiver.port,
|
||||
httpPort: receiver.port,
|
||||
callback: async ({ url }) => {
|
||||
await test.step("authored field-change effect runs before submission", async () => {
|
||||
const callbackSubmission = (
|
||||
await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: "#callback-form",
|
||||
values: [{ name: "outcome", value: "success" }],
|
||||
submitter: "button[type=submit]",
|
||||
timeout: 30_000,
|
||||
},
|
||||
})
|
||||
).data;
|
||||
expect(callbackSubmission).toMatchObject({
|
||||
status: "submitted",
|
||||
formState: "success",
|
||||
});
|
||||
expect(
|
||||
receiver.deliveries.map(({ body }) => JSON.parse(body))
|
||||
).toEqual([{ outcome: "success", changeCount: "1" }]);
|
||||
});
|
||||
receiver.deliveries.length = 0;
|
||||
|
||||
await test.step("ten Actions run in order and an eleventh is rejected", async () => {
|
||||
const submission = (
|
||||
await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: `[data-ws-managed-form-id="${formId}"]`,
|
||||
values: [
|
||||
{ name: "name", value: "Ada" },
|
||||
{ name: "email", value: "ada@example.com" },
|
||||
{ name: "subject", value: "Ten actions" },
|
||||
{ name: "message", value: "All actions" },
|
||||
],
|
||||
submitter: "button[type=submit]",
|
||||
timeout: 30_000,
|
||||
},
|
||||
})
|
||||
).data;
|
||||
expect(submission).toMatchObject({
|
||||
status: "submitted",
|
||||
formState: "success",
|
||||
errors: [],
|
||||
});
|
||||
expect(submission.exchanges).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
status: 200,
|
||||
url: expect.stringContaining("/__ws-form"),
|
||||
}),
|
||||
])
|
||||
);
|
||||
expect(submission.results).toEqual(
|
||||
resourceIds.map((resourceId, index) =>
|
||||
expect.objectContaining({
|
||||
resourceId,
|
||||
resourceName: `HTTP action ${index + 1}`,
|
||||
status: 200,
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(JSON.stringify(submission)).not.toContain(
|
||||
rejectedResourceId
|
||||
);
|
||||
expect(receiver.deliveries).toHaveLength(10);
|
||||
expect(
|
||||
receiver.deliveries
|
||||
.map(
|
||||
({ body }) =>
|
||||
JSON.parse(body) as { index: number; name: string }
|
||||
)
|
||||
.sort((left, right) => left.index - right.index)
|
||||
).toEqual(
|
||||
Array.from({ length: 10 }, (_, index) => ({
|
||||
index: index + 1,
|
||||
name: "Ada",
|
||||
}))
|
||||
);
|
||||
});
|
||||
|
||||
await test.step("email Resources deliver multiple files and honor attachment opt-out", async () => {
|
||||
const submission = await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: `[data-ws-managed-form-id="${emailFormId}"]`,
|
||||
values: [
|
||||
{ name: "name", value: "Ada Lovelace" },
|
||||
{ name: "email", value: "ada@example.test" },
|
||||
{ name: "subject", value: "Attachment opt-out test" },
|
||||
{
|
||||
name: "message",
|
||||
value: "Checking separate file delivery settings.",
|
||||
},
|
||||
...files.map((file) => ({
|
||||
name: "upload",
|
||||
file: {
|
||||
name: file.name,
|
||||
type: file.mimeType,
|
||||
base64: file.buffer.toString("base64"),
|
||||
},
|
||||
})),
|
||||
],
|
||||
submitter: "button[type=submit]",
|
||||
timeout: 30_000,
|
||||
},
|
||||
});
|
||||
expect(submission.data).toMatchObject({
|
||||
status: "submitted",
|
||||
formState: "success",
|
||||
errors: [],
|
||||
});
|
||||
expect(submission.data.results).toEqual([
|
||||
expect.objectContaining({
|
||||
resourceId: emailResourceIds[0],
|
||||
status: 200,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
resourceId: emailResourceIds[1],
|
||||
status: 200,
|
||||
}),
|
||||
]);
|
||||
expect(emailReceiver.messages).toHaveLength(2);
|
||||
|
||||
const owner = emailReceiver.messages.find((message) =>
|
||||
message.to.some(({ address }) => address === "owner@mcp.test")
|
||||
);
|
||||
const visitor = emailReceiver.messages.find((message) =>
|
||||
message.to.some(({ address }) => address === "ada@example.test")
|
||||
);
|
||||
expect(owner).toBeDefined();
|
||||
expect(visitor).toBeDefined();
|
||||
expect(owner?.attachments).toHaveLength(files.length);
|
||||
for (const [index, file] of files.entries()) {
|
||||
const attachment = owner?.attachments?.[index];
|
||||
expect(attachment?.filename).toBe(file.name);
|
||||
expect(attachment?.contentType).toBe(file.mimeType);
|
||||
expect(
|
||||
Buffer.from(attachment?.contentBase64 ?? "", "base64")
|
||||
).toEqual(file.buffer);
|
||||
}
|
||||
expect(visitor?.attachments).toBeUndefined();
|
||||
});
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await receiver.close();
|
||||
}
|
||||
} finally {
|
||||
await emailReceiver.close();
|
||||
}
|
||||
});
|
||||
@@ -1,184 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect } from "@playwright/test";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import {
|
||||
startFormDeliveryReceiver,
|
||||
withGeneratedFormDeliveryPreview,
|
||||
} from "../flows/generated-form-delivery";
|
||||
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
|
||||
import { test } from "../test";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const authorPath = fileURLToPath(
|
||||
new URL("../fixtures/mcp-form-action-combination-author.ts", import.meta.url)
|
||||
);
|
||||
const callbackAuthorPath = fileURLToPath(
|
||||
new URL("../fixtures/mcp-form-callbacks-author.ts", import.meta.url)
|
||||
);
|
||||
const reactGlobalPath = fileURLToPath(
|
||||
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
|
||||
);
|
||||
|
||||
test("MCP field changes and ten ordered Form Actions share one generated Preview", async ({
|
||||
context,
|
||||
}) => {
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email: "mcp-form-ten-actions@webstudio.test",
|
||||
title: "MCP Form ten Actions",
|
||||
assetNamePrefix: "mcp-form-ten-actions-",
|
||||
builderToken: "mcp-form-ten-actions-builder-token",
|
||||
});
|
||||
await execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
"tsx",
|
||||
"--import",
|
||||
reactGlobalPath,
|
||||
"--conditions=webstudio",
|
||||
callbackAuthorPath,
|
||||
fixture.projectId,
|
||||
"managed",
|
||||
"https://mcp-delivery.example/submit",
|
||||
"field-change",
|
||||
],
|
||||
{
|
||||
timeout: 60_000,
|
||||
env: {
|
||||
...process.env,
|
||||
TSX_TSCONFIG_PATH: fileURLToPath(
|
||||
new URL(
|
||||
"../../../../packages/cli/tsconfig.local.json",
|
||||
import.meta.url
|
||||
)
|
||||
),
|
||||
},
|
||||
}
|
||||
);
|
||||
const { stdout } = await execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
"tsx",
|
||||
"--import",
|
||||
reactGlobalPath,
|
||||
"--conditions=webstudio",
|
||||
authorPath,
|
||||
fixture.projectId,
|
||||
"ten-actions",
|
||||
],
|
||||
{
|
||||
timeout: 60_000,
|
||||
env: {
|
||||
...process.env,
|
||||
TSX_TSCONFIG_PATH: fileURLToPath(
|
||||
new URL(
|
||||
"../../../../packages/cli/tsconfig.local.json",
|
||||
import.meta.url
|
||||
)
|
||||
),
|
||||
},
|
||||
}
|
||||
);
|
||||
const { formId, resourceIds, rejectedResourceId } = JSON.parse(stdout) as {
|
||||
formId: string;
|
||||
resourceIds: string[];
|
||||
rejectedResourceId: string;
|
||||
};
|
||||
expect(resourceIds).toHaveLength(10);
|
||||
expect(new Set([...resourceIds, rejectedResourceId]).size).toBe(11);
|
||||
|
||||
const receiver = await startFormDeliveryReceiver();
|
||||
try {
|
||||
await withGeneratedFormDeliveryPreview({
|
||||
projectId: fixture.projectId,
|
||||
receiverPort: receiver.port,
|
||||
callback: async ({ url }) => {
|
||||
await test.step("authored field-change effect runs before submission", async () => {
|
||||
const callbackSubmission = (
|
||||
await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: "#callback-form",
|
||||
values: [{ name: "outcome", value: "success" }],
|
||||
submitter: "button[type=submit]",
|
||||
timeout: 30_000,
|
||||
},
|
||||
})
|
||||
).data;
|
||||
expect(callbackSubmission).toMatchObject({
|
||||
status: "submitted",
|
||||
formState: "success",
|
||||
});
|
||||
expect(
|
||||
receiver.deliveries.map(({ body }) => JSON.parse(body))
|
||||
).toEqual([{ outcome: "success", changeCount: "1" }]);
|
||||
});
|
||||
receiver.deliveries.length = 0;
|
||||
|
||||
await test.step("ten Actions run in order and an eleventh is rejected", async () => {
|
||||
const submission = (
|
||||
await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: `[data-ws-managed-form-id="${formId}"]`,
|
||||
values: [
|
||||
{ name: "name", value: "Ada" },
|
||||
{ name: "email", value: "ada@example.com" },
|
||||
{ name: "subject", value: "Ten actions" },
|
||||
{ name: "message", value: "All actions" },
|
||||
],
|
||||
submitter: "button[type=submit]",
|
||||
timeout: 30_000,
|
||||
},
|
||||
})
|
||||
).data;
|
||||
expect(submission).toMatchObject({
|
||||
status: "submitted",
|
||||
formState: "success",
|
||||
errors: [],
|
||||
});
|
||||
expect(submission.exchanges).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
status: 200,
|
||||
url: expect.stringContaining("/__ws-form"),
|
||||
}),
|
||||
])
|
||||
);
|
||||
expect(submission.results).toEqual(
|
||||
resourceIds.map((resourceId, index) =>
|
||||
expect.objectContaining({
|
||||
resourceId,
|
||||
resourceName: `HTTP action ${index + 1}`,
|
||||
status: 200,
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(JSON.stringify(submission)).not.toContain(rejectedResourceId);
|
||||
expect(receiver.deliveries).toHaveLength(10);
|
||||
expect(
|
||||
receiver.deliveries
|
||||
.map(
|
||||
({ body }) =>
|
||||
JSON.parse(body) as { index: number; name: string }
|
||||
)
|
||||
.sort((left, right) => left.index - right.index)
|
||||
).toEqual(
|
||||
Array.from({ length: 10 }, (_, index) => ({
|
||||
index: index + 1,
|
||||
name: "Ada",
|
||||
}))
|
||||
);
|
||||
});
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await receiver.close();
|
||||
}
|
||||
});
|
||||
@@ -5,7 +5,10 @@ import { expect } from "@playwright/test";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { withGeneratedPreview } from "../flows/generated-app";
|
||||
import { startLegacyFormRouteReceiver } from "../flows/legacy-form-route-receiver";
|
||||
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
|
||||
import {
|
||||
startPreviewFormMcpClient,
|
||||
submitPreviewFormViaMcp,
|
||||
} from "../flows/mcp-preview-submit";
|
||||
import { test } from "../test";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -16,6 +19,7 @@ test("MCP-edited saved deprecated Webhook Form action uses current dynamic route
|
||||
}) => {
|
||||
const receiver = await startLegacyFormRouteReceiver();
|
||||
try {
|
||||
await startPreviewFormMcpClient();
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email: "mcp-legacy-form-route@webstudio.test",
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect } from "@playwright/test";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { withGeneratedPreview } from "../flows/generated-app";
|
||||
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
|
||||
import { test } from "../test";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const authorPath = fileURLToPath(
|
||||
new URL("../fixtures/mcp-managed-form-author.ts", import.meta.url)
|
||||
);
|
||||
const reactGlobalPath = fileURLToPath(
|
||||
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
|
||||
);
|
||||
|
||||
test("MCP-authored Form validates required fields and reports submission errors in generated Preview", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email: "mcp-preview-form@webstudio.test",
|
||||
title: "MCP Preview Form",
|
||||
assetNamePrefix: "mcp-preview-form-",
|
||||
builderToken: "mcp-preview-form-builder-token",
|
||||
});
|
||||
const { stdout } = await execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
"tsx",
|
||||
"--import",
|
||||
reactGlobalPath,
|
||||
"--conditions=webstudio",
|
||||
authorPath,
|
||||
fixture.projectId,
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
TSX_TSCONFIG_PATH: fileURLToPath(
|
||||
new URL(
|
||||
"../../../../packages/cli/tsconfig.local.json",
|
||||
import.meta.url
|
||||
)
|
||||
),
|
||||
},
|
||||
timeout: 60_000,
|
||||
}
|
||||
);
|
||||
const { formId } = JSON.parse(stdout) as { formId: string };
|
||||
await withGeneratedPreview({
|
||||
projectId: fixture.projectId,
|
||||
callback: async ({ url }) => {
|
||||
await page.route("**/*", (route) => {
|
||||
const target = new URL(route.request().url());
|
||||
return target.hostname === "127.0.0.1"
|
||||
? route.continue()
|
||||
: route.abort();
|
||||
});
|
||||
await page.goto(url);
|
||||
const rendered = page.locator(`[data-ws-managed-form-id="${formId}"]`);
|
||||
await rendered.getByRole("button", { name: "Submit" }).click();
|
||||
expect(
|
||||
await rendered
|
||||
.locator('input[name="name"]')
|
||||
.evaluate((input: HTMLInputElement) => input.validity.valueMissing)
|
||||
).toBe(true);
|
||||
const bytes = Buffer.from([0, 1, 127, 128, 255]);
|
||||
const submission = (
|
||||
await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: `[data-ws-managed-form-id="${formId}"]`,
|
||||
values: [
|
||||
{ name: "name", value: "Ada" },
|
||||
{ name: "email", value: "ada@example.com" },
|
||||
{ name: "subject", value: "MCP Preview" },
|
||||
{ name: "message", value: "Hello from MCP" },
|
||||
{ name: "tag", value: "first tag" },
|
||||
{ name: "tag", value: "second tag" },
|
||||
{
|
||||
name: "upload",
|
||||
file: {
|
||||
name: "sample.bin",
|
||||
type: "application/octet-stream",
|
||||
base64: bytes.toString("base64"),
|
||||
},
|
||||
},
|
||||
],
|
||||
submitter: "button[type=submit]",
|
||||
timeout: 30_000,
|
||||
},
|
||||
})
|
||||
).data;
|
||||
expect(submission).toMatchObject({
|
||||
status: "submitted",
|
||||
formState: "error",
|
||||
results: [],
|
||||
});
|
||||
expect(submission.errors).toEqual([
|
||||
expect.objectContaining({ status: 400 }),
|
||||
]);
|
||||
expect(submission.exchanges).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
status: 400,
|
||||
url: expect.stringContaining("/__ws-form"),
|
||||
}),
|
||||
])
|
||||
);
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import { createServer } from "node:http";
|
||||
import { expect } from "@playwright/test";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { withGeneratedPreview } from "../flows/generated-app";
|
||||
import { runFormAuthor } from "../flows/mcp-form-author";
|
||||
import {
|
||||
closePreviewFormMcpClient,
|
||||
submitPreviewFormViaMcp,
|
||||
} from "../flows/mcp-preview-submit";
|
||||
import { test } from "../test";
|
||||
|
||||
test("MCP-authored managed and native Forms validate and submit in generated Preview", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
test.setTimeout(240_000);
|
||||
|
||||
const requests: Array<{ method: string; url: string }> = [];
|
||||
const server = createServer((request, response) => {
|
||||
if (new URL(request.url ?? "", "http://127.0.0.1").pathname === "/search") {
|
||||
requests.push({ method: request.method ?? "", url: request.url ?? "" });
|
||||
}
|
||||
response.writeHead(200, { "content-type": "text/html" });
|
||||
response.end('<!doctype html><p id="received">Received</p>');
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
try {
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string") {
|
||||
throw new Error("Expected local receiver port");
|
||||
}
|
||||
const receiverUrl = `http://127.0.0.1:${address.port}/search`;
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email: "mcp-preview-form@webstudio.test",
|
||||
title: "MCP Preview Forms",
|
||||
assetNamePrefix: "mcp-preview-form-",
|
||||
builderToken: "mcp-preview-form-builder-token",
|
||||
});
|
||||
const { stdout } = await runFormAuthor(
|
||||
"mcp-managed-form-author",
|
||||
fixture.projectId
|
||||
);
|
||||
const { formId } = JSON.parse(stdout) as { formId: string };
|
||||
await runFormAuthor(
|
||||
"mcp-native-get-form-author",
|
||||
fixture.projectId,
|
||||
receiverUrl
|
||||
);
|
||||
|
||||
await withGeneratedPreview({
|
||||
projectId: fixture.projectId,
|
||||
callback: async ({ url }) => {
|
||||
await page.route("**/*", (route) =>
|
||||
new URL(route.request().url()).hostname === "127.0.0.1"
|
||||
? route.continue()
|
||||
: route.abort()
|
||||
);
|
||||
await page.goto(url);
|
||||
|
||||
await test.step("Managed Form requires fields and reports a blocked HTTP action", async () => {
|
||||
const rendered = page.locator(
|
||||
`[data-ws-managed-form-id="${formId}"]`
|
||||
);
|
||||
await rendered.getByRole("button", { name: "Submit" }).click();
|
||||
expect(
|
||||
await rendered
|
||||
.locator('input[name="name"]')
|
||||
.evaluate(
|
||||
(input: HTMLInputElement) => input.validity.valueMissing
|
||||
)
|
||||
).toBe(true);
|
||||
const bytes = Buffer.from([0, 1, 127, 128, 255]);
|
||||
const submission = (
|
||||
await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: `[data-ws-managed-form-id="${formId}"]`,
|
||||
values: [
|
||||
{ name: "name", value: "Ada" },
|
||||
{ name: "email", value: "ada@example.com" },
|
||||
{ name: "subject", value: "MCP Preview" },
|
||||
{ name: "message", value: "Hello from MCP" },
|
||||
{ name: "tag", value: "first tag" },
|
||||
{ name: "tag", value: "second tag" },
|
||||
{
|
||||
name: "upload",
|
||||
file: {
|
||||
name: "sample.bin",
|
||||
type: "application/octet-stream",
|
||||
base64: bytes.toString("base64"),
|
||||
},
|
||||
},
|
||||
],
|
||||
submitter: "button[type=submit]",
|
||||
timeout: 30_000,
|
||||
},
|
||||
})
|
||||
).data;
|
||||
expect(submission).toMatchObject({
|
||||
status: "submitted",
|
||||
formState: "error",
|
||||
results: [],
|
||||
});
|
||||
expect(submission.errors).toEqual([
|
||||
expect.objectContaining({ status: 400 }),
|
||||
]);
|
||||
expect(submission.exchanges).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
status: 400,
|
||||
url: expect.stringContaining("/__ws-form"),
|
||||
}),
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
await test.step("Native GET form submits repeated fields to a local receiver", async () => {
|
||||
const form = page.locator("#native-get-form");
|
||||
await expect(form).toHaveAttribute("method", "get");
|
||||
await expect(form).toHaveAttribute("action", receiverUrl);
|
||||
const invalid = await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: "#native-get-form",
|
||||
values: [],
|
||||
submitter: 'button[type="submit"]',
|
||||
timeout: 30_000,
|
||||
},
|
||||
});
|
||||
expect(invalid.ok).toBe(true);
|
||||
expect(invalid.data).toMatchObject({
|
||||
status: "validation_failed",
|
||||
formState: "invalid",
|
||||
results: [],
|
||||
exchanges: [],
|
||||
});
|
||||
await expect(page).toHaveURL(url);
|
||||
expect(requests).toHaveLength(0);
|
||||
|
||||
const submitted = await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: "#native-get-form",
|
||||
values: [
|
||||
{ name: "tag", value: "second" },
|
||||
{ name: "tag", value: "first" },
|
||||
],
|
||||
submitter: 'button[type="submit"]',
|
||||
timeout: 30_000,
|
||||
},
|
||||
});
|
||||
expect(submitted.ok).toBe(true);
|
||||
expect(submitted.data).toMatchObject({
|
||||
status: "submitted",
|
||||
results: [],
|
||||
errors: [],
|
||||
redirect: receiverUrl,
|
||||
});
|
||||
expect(submitted.data.exchanges).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ status: 200 })])
|
||||
);
|
||||
expect(submitted.data.pageUrl).toBe(receiverUrl);
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0].method).toBe("GET");
|
||||
expect(
|
||||
new URL(requests[0].url, receiverUrl).searchParams.getAll("tag")
|
||||
).toEqual(["second", "first"]);
|
||||
});
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
try {
|
||||
await closePreviewFormMcpClient();
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,150 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createServer } from "node:http";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect } from "@playwright/test";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { withGeneratedPreview } from "../flows/generated-app";
|
||||
import {
|
||||
closePreviewFormMcpClient,
|
||||
submitPreviewFormViaMcp,
|
||||
} from "../flows/mcp-preview-submit";
|
||||
import { test } from "../test";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
test("MCP-authored native GET form submits repeated fields to a local receiver", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
// Generate the app and run two submissions through isolated MCP clients.
|
||||
test.setTimeout(240_000);
|
||||
|
||||
const requests: Array<{ method: string; url: string }> = [];
|
||||
const server = createServer((request, response) => {
|
||||
if (new URL(request.url ?? "", "http://127.0.0.1").pathname === "/search") {
|
||||
requests.push({ method: request.method ?? "", url: request.url ?? "" });
|
||||
}
|
||||
response.writeHead(200, { "content-type": "text/html" });
|
||||
response.end('<!doctype html><p id="received">Received</p>');
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string") {
|
||||
throw new Error("Expected local receiver port");
|
||||
}
|
||||
const receiverUrl = `http://127.0.0.1:${address.port}/search`;
|
||||
|
||||
try {
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email: "mcp-native-get-form@webstudio.test",
|
||||
title: "MCP native GET Form",
|
||||
assetNamePrefix: "mcp-native-get-form-",
|
||||
});
|
||||
await execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
"tsx",
|
||||
"--import",
|
||||
fileURLToPath(
|
||||
new URL(
|
||||
"../../../../scripts/register-react-global.ts",
|
||||
import.meta.url
|
||||
)
|
||||
),
|
||||
"--conditions=webstudio",
|
||||
fileURLToPath(
|
||||
new URL("../fixtures/mcp-native-get-form-author.ts", import.meta.url)
|
||||
),
|
||||
fixture.projectId,
|
||||
receiverUrl,
|
||||
],
|
||||
{
|
||||
timeout: 30_000,
|
||||
env: {
|
||||
...process.env,
|
||||
TSX_TSCONFIG_PATH: fileURLToPath(
|
||||
new URL(
|
||||
"../../../../packages/cli/tsconfig.local.json",
|
||||
import.meta.url
|
||||
)
|
||||
),
|
||||
},
|
||||
}
|
||||
);
|
||||
await withGeneratedPreview({
|
||||
projectId: fixture.projectId,
|
||||
callback: async ({ url }) => {
|
||||
await page.route("**/*", (route) =>
|
||||
new URL(route.request().url()).hostname === "127.0.0.1"
|
||||
? route.continue()
|
||||
: route.abort()
|
||||
);
|
||||
await page.goto(url);
|
||||
const form = page.locator("#native-get-form");
|
||||
await expect(form).toHaveAttribute("method", "get");
|
||||
await expect(form).toHaveAttribute("action", receiverUrl);
|
||||
const invalid = await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: "#native-get-form",
|
||||
values: [],
|
||||
submitter: 'button[type="submit"]',
|
||||
timeout: 30_000,
|
||||
},
|
||||
});
|
||||
expect(invalid.ok).toBe(true);
|
||||
expect(invalid.data).toMatchObject({
|
||||
status: "validation_failed",
|
||||
formState: "invalid",
|
||||
results: [],
|
||||
exchanges: [],
|
||||
});
|
||||
await expect(page).toHaveURL(url);
|
||||
expect(requests).toHaveLength(0);
|
||||
|
||||
const submitted = await submitPreviewFormViaMcp({
|
||||
url,
|
||||
input: {
|
||||
path: "/",
|
||||
selector: "#native-get-form",
|
||||
values: [
|
||||
{ name: "tag", value: "second" },
|
||||
{ name: "tag", value: "first" },
|
||||
],
|
||||
submitter: 'button[type="submit"]',
|
||||
timeout: 30_000,
|
||||
},
|
||||
});
|
||||
expect(submitted.ok).toBe(true);
|
||||
expect(submitted.data).toMatchObject({
|
||||
status: "submitted",
|
||||
results: [],
|
||||
errors: [],
|
||||
redirect: receiverUrl,
|
||||
});
|
||||
expect(submitted.data.exchanges).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ status: 200 })])
|
||||
);
|
||||
expect(submitted.data.pageUrl).toBe(receiverUrl);
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0].method).toBe("GET");
|
||||
expect(
|
||||
new URL(requests[0].url, receiverUrl).searchParams.getAll("tag")
|
||||
).toEqual(["second", "first"]);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
try {
|
||||
await closePreviewFormMcpClient();
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -6,10 +6,7 @@ import {
|
||||
} from "../flows/builder";
|
||||
import { selectCanvasTextInstance } from "../flows/canvas-selection";
|
||||
import { openNavigatorPanel } from "../flows/navigator";
|
||||
import {
|
||||
waitForChangeToBeSaved,
|
||||
waitForSyncStatus,
|
||||
} from "../flows/sync-status";
|
||||
import { waitForChangeToBeSaved } from "../flows/sync-status";
|
||||
import { insertTemplateAfterCanvasText } from "../flows/template-insertion";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import type { SeededContentModeProject } from "../fixtures/content-mode-project";
|
||||
@@ -18,6 +15,8 @@ import { measure } from "../perf";
|
||||
import { e2ePaidPlanName } from "../plans";
|
||||
import { loadDevBuild } from "../db";
|
||||
|
||||
test.describe.configure({ mode: "parallel" });
|
||||
|
||||
let fixture: SeededContentModeProject;
|
||||
|
||||
const getInstanceComponentCount = async ({
|
||||
@@ -65,29 +64,17 @@ const selectAppMenuItem = async ({
|
||||
await menuItem.click();
|
||||
};
|
||||
|
||||
const undoShortcut = async ({
|
||||
const selectSavedAppMenuItem = async ({
|
||||
page,
|
||||
waitForSave = true,
|
||||
name,
|
||||
}: {
|
||||
page: Page;
|
||||
waitForSave?: boolean;
|
||||
name: "Undo" | "Redo";
|
||||
}) => {
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
const save =
|
||||
waitForSave === true
|
||||
? waitForChangeToBeSaved({ page, timeout: 30_000 })
|
||||
: undefined;
|
||||
await selectAppMenuItem({ page, name: "Undo" });
|
||||
await save;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
};
|
||||
|
||||
const redoShortcut = async ({ page }: { page: Page }) => {
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
const save = waitForChangeToBeSaved({ page, timeout: 30_000 });
|
||||
await selectAppMenuItem({ page, name: "Redo" });
|
||||
await save;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
await Promise.all([
|
||||
waitForChangeToBeSaved({ page, timeout: 30_000 }),
|
||||
selectAppMenuItem({ page, name }),
|
||||
]);
|
||||
};
|
||||
|
||||
const openComponentsPanel = async ({ page }: { page: Page }) => {
|
||||
@@ -127,8 +114,10 @@ const insertComponentPanelOption = async ({
|
||||
name: string;
|
||||
}) => {
|
||||
await searchComponentsPanel({ page, text: name });
|
||||
await page.getByRole("option", { name, exact: true }).click();
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
await Promise.all([
|
||||
waitForChangeToBeSaved({ page }),
|
||||
page.getByRole("option", { name, exact: true }).click(),
|
||||
]);
|
||||
};
|
||||
|
||||
const getNavigatorButtonSummary = async ({
|
||||
@@ -190,11 +179,10 @@ const selectNavigatorContextAction = async ({
|
||||
`Expected Navigator ${action} action to be enabled. aria-disabled=${ariaDisabled}, data-disabled=${dataDisabled}`
|
||||
);
|
||||
}
|
||||
await menuItem.click();
|
||||
await waitForChangeToBeSaved({ page });
|
||||
await Promise.all([waitForChangeToBeSaved({ page }), menuItem.click()]);
|
||||
};
|
||||
|
||||
test.beforeAll(async ({ browser }) => {
|
||||
test.beforeEach(async ({ browser }) => {
|
||||
fixture = await withBrowserContext(browser, (context) =>
|
||||
createContentModeProject({
|
||||
context,
|
||||
@@ -235,7 +223,7 @@ test("Builder can insert through the engine bridge, undo, redo, and reload", asy
|
||||
});
|
||||
|
||||
await measure("pages actions undo bridge insert", async () => {
|
||||
await undoShortcut({ page, waitForSave: false });
|
||||
await selectSavedAppMenuItem({ page, name: "Undo" });
|
||||
});
|
||||
await waitForCanvasTextHidden({
|
||||
page,
|
||||
@@ -243,7 +231,7 @@ test("Builder can insert through the engine bridge, undo, redo, and reload", asy
|
||||
});
|
||||
|
||||
await measure("pages actions redo bridge insert", async () => {
|
||||
await redoShortcut({ page });
|
||||
await selectSavedAppMenuItem({ page, name: "Redo" });
|
||||
});
|
||||
await waitForCanvasText({
|
||||
page,
|
||||
@@ -344,8 +332,10 @@ test("Builder can duplicate a component through the engine bridge, undo, redo, a
|
||||
}
|
||||
|
||||
await measure("pages actions duplicate inserted component", async () => {
|
||||
await page.keyboard.press("ControlOrMeta+D");
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
await Promise.all([
|
||||
waitForChangeToBeSaved({ page }),
|
||||
page.keyboard.press("ControlOrMeta+D"),
|
||||
]);
|
||||
});
|
||||
const duplicatedCount = await getInstanceComponentCount({
|
||||
fixture,
|
||||
@@ -358,7 +348,7 @@ test("Builder can duplicate a component through the engine bridge, undo, redo, a
|
||||
}
|
||||
|
||||
await measure("pages actions undo duplicate command", async () => {
|
||||
await undoShortcut({ page });
|
||||
await selectSavedAppMenuItem({ page, name: "Undo" });
|
||||
});
|
||||
const undoCount = await getInstanceComponentCount({
|
||||
fixture,
|
||||
@@ -371,7 +361,7 @@ test("Builder can duplicate a component through the engine bridge, undo, redo, a
|
||||
}
|
||||
|
||||
await measure("pages actions redo duplicate command", async () => {
|
||||
await redoShortcut({ page });
|
||||
await selectSavedAppMenuItem({ page, name: "Redo" });
|
||||
});
|
||||
const redoCount = await getInstanceComponentCount({
|
||||
fixture,
|
||||
@@ -463,7 +453,7 @@ test("Builder can duplicate and delete a component from Navigator context menu",
|
||||
}
|
||||
|
||||
await measure("pages actions undo navigator duplicate", async () => {
|
||||
await undoShortcut({ page });
|
||||
await selectSavedAppMenuItem({ page, name: "Undo" });
|
||||
});
|
||||
const undoDuplicateCount = await getInstanceComponentCount({
|
||||
fixture,
|
||||
@@ -476,7 +466,7 @@ test("Builder can duplicate and delete a component from Navigator context menu",
|
||||
}
|
||||
|
||||
await measure("pages actions redo navigator duplicate", async () => {
|
||||
await redoShortcut({ page });
|
||||
await selectSavedAppMenuItem({ page, name: "Redo" });
|
||||
});
|
||||
const redoDuplicateCount = await getInstanceComponentCount({
|
||||
fixture,
|
||||
@@ -507,7 +497,7 @@ test("Builder can duplicate and delete a component from Navigator context menu",
|
||||
}
|
||||
|
||||
await measure("pages actions undo navigator delete", async () => {
|
||||
await undoShortcut({ page });
|
||||
await selectSavedAppMenuItem({ page, name: "Undo" });
|
||||
});
|
||||
const undoDeleteCount = await getInstanceComponentCount({
|
||||
fixture,
|
||||
|
||||
@@ -9,10 +9,7 @@ import {
|
||||
openPage,
|
||||
openPageSettings,
|
||||
} from "../flows/pages-panel";
|
||||
import {
|
||||
waitForChangeToBeSaved,
|
||||
waitForSyncStatus,
|
||||
} from "../flows/sync-status";
|
||||
import { waitForChangeToBeSaved } from "../flows/sync-status";
|
||||
import {
|
||||
expectGeneratedAppRedirect,
|
||||
expectGeneratedRedirects,
|
||||
@@ -90,7 +87,6 @@ const saveSiteName = async ({
|
||||
.getByRole("textbox", { name: "Site name", exact: true })
|
||||
.fill(siteName);
|
||||
await save;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
};
|
||||
|
||||
const setAtomicStyles = async ({
|
||||
@@ -108,7 +104,6 @@ const setAtomicStyles = async ({
|
||||
const save = waitForChangeToBeSaved({ page });
|
||||
await checkbox.click();
|
||||
await save;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
};
|
||||
if ((await checkbox.isChecked()) === checked) {
|
||||
await toggle();
|
||||
@@ -130,33 +125,13 @@ const addRedirect = async ({
|
||||
await page.getByPlaceholder("/old-path or /old/*").fill(from);
|
||||
await page.getByPlaceholder("/to-path or URL").fill(to);
|
||||
await page.keyboard.press("Escape");
|
||||
const save = waitForChangeToBeSaved({ page });
|
||||
await page
|
||||
.getByPlaceholder("/to-path or URL")
|
||||
.locator("xpath=following::button[2]")
|
||||
.click();
|
||||
await page.getByText(from, { exact: true }).waitFor();
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
};
|
||||
|
||||
const addBasicAuth = async ({
|
||||
page,
|
||||
route,
|
||||
login,
|
||||
password,
|
||||
}: {
|
||||
page: PlaywrightPage;
|
||||
route: string;
|
||||
login: string;
|
||||
password: string;
|
||||
}) => {
|
||||
await page.getByRole("option", { name: "Authentication" }).click();
|
||||
await page.getByPlaceholder("/private or /docs/*").fill(route);
|
||||
await page.getByPlaceholder("Login").fill(login);
|
||||
await page.getByPlaceholder("Password").fill(password);
|
||||
const save = waitForChangeToBeSaved({ page });
|
||||
await page.getByRole("button", { name: "Add" }).click();
|
||||
await save;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
};
|
||||
|
||||
const deleteBasicAuth = async ({
|
||||
@@ -173,7 +148,6 @@ const deleteBasicAuth = async ({
|
||||
.click();
|
||||
await page.getByRole("button", { name: "Delete", exact: true }).click();
|
||||
await save;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
};
|
||||
|
||||
const expectPersistedBasicAuth = async ({
|
||||
@@ -216,7 +190,6 @@ const deleteRedirect = async ({
|
||||
.getByRole("button", { name: `Delete redirect from ${from}` })
|
||||
.click();
|
||||
await save;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
};
|
||||
|
||||
const expectPersistedProjectSettings = async ({
|
||||
@@ -260,15 +233,16 @@ const expectPersistedProjectSettings = async ({
|
||||
}
|
||||
};
|
||||
|
||||
test("Project settings site name and redirects persist after reload", async ({
|
||||
test("Project settings for site name, CSS, email, and redirects persist after reload", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const email = "project-settings-runtime@webstudio.test";
|
||||
const fixture = await createContentModeProject({
|
||||
context: context,
|
||||
context,
|
||||
email,
|
||||
title: "Project Settings Runtime",
|
||||
devPlan: e2eEmailPlanName,
|
||||
assetNamePrefix: "project-settings-runtime-",
|
||||
editorToken: "project-settings-runtime-editor-token",
|
||||
builderToken: "project-settings-runtime-builder-token",
|
||||
@@ -279,7 +253,11 @@ test("Project settings site name and redirects persist after reload", async ({
|
||||
to: "/",
|
||||
};
|
||||
|
||||
await loginWithSecret({ page, email });
|
||||
const recipients =
|
||||
'"Team, West" <team@example.com>, Owner <owner@example.com>';
|
||||
const sender = "Project Team <sender@example.com>";
|
||||
|
||||
await loginWithSecret({ page, email, devPlan: e2eEmailPlanName });
|
||||
|
||||
await measure("project settings runtime open builder", async () => {
|
||||
await openProjectBuilder({
|
||||
@@ -301,6 +279,30 @@ test("Project settings site name and redirects persist after reload", async ({
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("Save named email recipients and Reply to", async () => {
|
||||
await page.getByRole("option", { name: "Emails" }).click();
|
||||
|
||||
let save = waitForChangeToBeSaved({ page });
|
||||
await page.getByRole("textbox", { name: "Recipients" }).fill(recipients);
|
||||
await save;
|
||||
|
||||
save = waitForChangeToBeSaved({ page });
|
||||
await page.getByRole("textbox", { name: "Reply to" }).fill(sender);
|
||||
await save;
|
||||
|
||||
const persisted = await getPersistedProjectSettings({
|
||||
projectId: fixture.projectId,
|
||||
});
|
||||
if (
|
||||
persisted.meta.contactEmail !== recipients ||
|
||||
persisted.meta.emailSender !== sender
|
||||
) {
|
||||
throw new Error(
|
||||
`Expected saved Project Emails settings, received ${JSON.stringify(persisted.meta)}.`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
await expectPersistedProjectSettings({
|
||||
projectId: fixture.projectId,
|
||||
siteName,
|
||||
@@ -356,6 +358,17 @@ test("Project settings site name and redirects persist after reload", async ({
|
||||
"Expected atomic CSS setting to remain disabled after reload."
|
||||
);
|
||||
}
|
||||
await test.step("Verify email settings after reload", async () => {
|
||||
await page.getByRole("option", { name: "Emails" }).click();
|
||||
if (
|
||||
(await page.getByRole("textbox", { name: "Recipients" }).inputValue()) !==
|
||||
recipients ||
|
||||
(await page.getByRole("textbox", { name: "Reply to" }).inputValue()) !==
|
||||
sender
|
||||
) {
|
||||
throw new Error("Expected Project Emails settings to survive reload.");
|
||||
}
|
||||
});
|
||||
await page.getByRole("option", { name: "Redirects" }).click();
|
||||
|
||||
await measure("project settings runtime delete redirect", async () => {
|
||||
@@ -393,81 +406,13 @@ test("Project settings site name and redirects persist after reload", async ({
|
||||
});
|
||||
});
|
||||
|
||||
test("Project Emails Reply to and named recipients persist after reload", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const email = "project-emails-runtime@webstudio.test";
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email,
|
||||
title: "Project Emails Runtime",
|
||||
devPlan: e2eEmailPlanName,
|
||||
assetNamePrefix: "project-emails-runtime-",
|
||||
editorToken: "project-emails-runtime-editor-token",
|
||||
builderToken: "project-emails-runtime-builder-token",
|
||||
});
|
||||
const recipients =
|
||||
'"Team, West" <team@example.com>, Owner <owner@example.com>';
|
||||
const sender = "Project Team <sender@example.com>";
|
||||
|
||||
await loginWithSecret({ page, email, devPlan: e2eEmailPlanName });
|
||||
await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
await waitForCanvasText({ page, text: "Initial content" });
|
||||
await openProjectSettings({ page });
|
||||
await page.getByRole("option", { name: "Emails" }).click();
|
||||
|
||||
let save = waitForChangeToBeSaved({ page });
|
||||
await page.getByRole("textbox", { name: "Recipients" }).fill(recipients);
|
||||
await save;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
save = waitForChangeToBeSaved({ page });
|
||||
await page.getByRole("textbox", { name: "Reply to" }).fill(sender);
|
||||
await save;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
const persisted = await getPersistedProjectSettings({
|
||||
projectId: fixture.projectId,
|
||||
});
|
||||
if (
|
||||
persisted.meta.contactEmail !== recipients ||
|
||||
persisted.meta.emailSender !== sender
|
||||
) {
|
||||
throw new Error(
|
||||
`Expected saved Project Emails settings, received ${JSON.stringify(persisted.meta)}.`
|
||||
);
|
||||
}
|
||||
|
||||
await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
await waitForCanvasText({ page, text: "Initial content" });
|
||||
await openProjectSettings({ page });
|
||||
await page.getByRole("option", { name: "Emails" }).click();
|
||||
if (
|
||||
(await page.getByRole("textbox", { name: "Recipients" }).inputValue()) !==
|
||||
recipients ||
|
||||
(await page.getByRole("textbox", { name: "Reply to" }).inputValue()) !==
|
||||
sender
|
||||
) {
|
||||
throw new Error("Expected Project Emails settings to survive reload.");
|
||||
}
|
||||
});
|
||||
|
||||
test("Marketplace page settings persist after reload", async ({
|
||||
test("Marketplace page settings and project authentication routes persist after reload", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const email = "marketplace-page-settings-runtime@webstudio.test";
|
||||
const fixture = await createContentModeProject({
|
||||
context: context,
|
||||
context,
|
||||
email,
|
||||
title: "Marketplace Page Settings Runtime",
|
||||
assetNamePrefix: "marketplace-page-settings-runtime-",
|
||||
@@ -476,6 +421,9 @@ test("Marketplace page settings persist after reload", async ({
|
||||
});
|
||||
const pageName = "Marketplace Runtime Page";
|
||||
const category = "Runtime Examples";
|
||||
const route = "/private";
|
||||
const login = "editor";
|
||||
const password = "e2e-secret";
|
||||
|
||||
await updateProject(fixture.projectId, {
|
||||
marketplaceApprovalStatus: "PENDING",
|
||||
@@ -492,6 +440,33 @@ test("Marketplace page settings persist after reload", async ({
|
||||
await waitForCanvasText({ page, text: "Initial content" });
|
||||
});
|
||||
|
||||
await measure("project auth runtime add route", async () => {
|
||||
await openProjectSettings({ page });
|
||||
await page.getByRole("option", { name: "Authentication" }).click();
|
||||
await page.getByPlaceholder("/private or /docs/*").fill("private");
|
||||
await page.getByPlaceholder("Login").fill(login);
|
||||
await page.getByPlaceholder("Password").fill(password);
|
||||
if (
|
||||
(await page.getByRole("button", { name: "Add" }).isDisabled()) === false
|
||||
) {
|
||||
throw new Error("Expected invalid auth route to disable Add.");
|
||||
}
|
||||
await page.getByPlaceholder("/private or /docs/*").fill(route);
|
||||
const save = waitForChangeToBeSaved({ page });
|
||||
await page.getByRole("button", { name: "Add" }).click();
|
||||
await save;
|
||||
});
|
||||
await expectPersistedBasicAuth({
|
||||
projectId: fixture.projectId,
|
||||
route,
|
||||
login,
|
||||
exists: true,
|
||||
});
|
||||
await page
|
||||
.getByRole("dialog", { name: "Project settings" })
|
||||
.getByRole("button", { name: "Close", exact: true })
|
||||
.click();
|
||||
|
||||
await measure("marketplace page settings create page", async () => {
|
||||
await createPageFromTemplate({
|
||||
page,
|
||||
@@ -508,13 +483,11 @@ test("Marketplace page settings persist after reload", async ({
|
||||
const includeSave = waitForChangeToBeSaved({ page });
|
||||
await page.getByLabel("Include in the marketplace").click();
|
||||
await includeSave;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
const categorySave = waitForChangeToBeSaved({ page });
|
||||
await page.getByLabel("Category").fill(category);
|
||||
await page.getByLabel("Category").blur();
|
||||
await categorySave;
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
}
|
||||
);
|
||||
|
||||
@@ -571,61 +544,11 @@ test("Marketplace page settings persist after reload", async ({
|
||||
)}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("Project authentication routes persist after reload and deletion", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const email = "project-auth-runtime@webstudio.test";
|
||||
const fixture = await createContentModeProject({
|
||||
context: context,
|
||||
email,
|
||||
title: "Project Auth Runtime",
|
||||
assetNamePrefix: "project-auth-runtime-",
|
||||
editorToken: "project-auth-runtime-editor-token",
|
||||
builderToken: "project-auth-runtime-builder-token",
|
||||
});
|
||||
const route = "/private";
|
||||
const login = "editor";
|
||||
const password = "e2e-secret";
|
||||
|
||||
await loginWithSecret({ page, email });
|
||||
await measure("project auth runtime open builder", async () => {
|
||||
await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
await waitForCanvasText({ page, text: "Initial content" });
|
||||
});
|
||||
|
||||
await measure("project auth runtime add route", async () => {
|
||||
await openProjectSettings({ page });
|
||||
await page.getByRole("option", { name: "Authentication" }).click();
|
||||
await page.getByPlaceholder("/private or /docs/*").fill("private");
|
||||
if (
|
||||
(await page.getByRole("button", { name: "Add" }).isDisabled()) === false
|
||||
) {
|
||||
throw new Error("Expected invalid auth route to disable Add.");
|
||||
}
|
||||
await addBasicAuth({ page, route, login, password });
|
||||
});
|
||||
await expectPersistedBasicAuth({
|
||||
projectId: fixture.projectId,
|
||||
route,
|
||||
login,
|
||||
exists: true,
|
||||
});
|
||||
|
||||
await measure("project auth runtime reload builder", async () => {
|
||||
await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
await waitForCanvasText({ page, text: "Initial content" });
|
||||
});
|
||||
await page
|
||||
.getByRole("group", { name: `Page ${pageName}`, exact: true })
|
||||
.getByRole("button", { name: "Close page settings" })
|
||||
.click();
|
||||
await openProjectSettings({ page });
|
||||
await page.getByRole("option", { name: "Authentication" }).click();
|
||||
await page.getByText(route, { exact: true }).waitFor();
|
||||
|
||||
@@ -1,737 +1,232 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Frame, Page } from "@playwright/test";
|
||||
import {
|
||||
expect,
|
||||
type BrowserContext,
|
||||
type Frame,
|
||||
type Page,
|
||||
} from "@playwright/test";
|
||||
import {
|
||||
getCanvasInstance,
|
||||
getCanvasInstanceSelector,
|
||||
openProjectBuilder,
|
||||
waitForCanvasFrame,
|
||||
} from "../flows/builder";
|
||||
import { openNavigatorPanel } from "../flows/navigator";
|
||||
import { waitForSyncStatus } from "../flows/sync-status";
|
||||
import {
|
||||
createSlotKeyboardProject,
|
||||
type SeededSlotKeyboardProject,
|
||||
} from "../fixtures/slot-keyboard-project";
|
||||
import { waitForChangeToBeSaved } from "../flows/sync-status";
|
||||
import { createSlotKeyboardProject } from "../fixtures/slot-keyboard-project";
|
||||
import { test } from "../test";
|
||||
import { measure } from "../perf";
|
||||
|
||||
test.describe.configure({ mode: "parallel" });
|
||||
|
||||
let fixture: SeededSlotKeyboardProject;
|
||||
|
||||
const slotASelector = getCanvasInstanceSelector([
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
]);
|
||||
|
||||
const expectCanvasInstanceVisible = async ({
|
||||
canvas,
|
||||
instanceSelector,
|
||||
}: {
|
||||
canvas: Frame;
|
||||
instanceSelector: string[];
|
||||
}) => {
|
||||
await getCanvasInstance({ canvas, instanceSelector }).waitFor({
|
||||
state: "visible",
|
||||
timeout: 30_000,
|
||||
});
|
||||
const wrapper = ["slot-keyboard-wrapper", "slot-keyboard-body"];
|
||||
const box = "slot-keyboard-div";
|
||||
const heading = "slot-keyboard-heading";
|
||||
const getSlotPair = (suffix = "") => {
|
||||
const slotA = [`slot-keyboard-slot-a${suffix}`, ...wrapper];
|
||||
const slotB = [`slot-keyboard-slot-b${suffix}`, ...wrapper];
|
||||
return {
|
||||
slotA,
|
||||
slotB,
|
||||
fragmentA: [`slot-keyboard-fragment${suffix}`, ...slotA],
|
||||
fragmentB: [`slot-keyboard-fragment${suffix}`, ...slotB],
|
||||
};
|
||||
};
|
||||
|
||||
test.beforeEach(async ({ context }) => {
|
||||
const { fragmentA, fragmentB } = getSlotPair();
|
||||
|
||||
// Each move starts with the same two children in a separate shared fragment.
|
||||
const canvasDetachMoves = [
|
||||
{ key: "ArrowLeft", suffix: "-outdent", id: heading, position: "after" },
|
||||
{ key: "ArrowUp", suffix: "-above", id: box, position: "before" },
|
||||
{ key: "ArrowDown", suffix: "-below", id: heading, position: "after" },
|
||||
] as const;
|
||||
|
||||
const expectInstanceOrder = async (
|
||||
canvas: Frame,
|
||||
before: string[],
|
||||
after: string[]
|
||||
) => {
|
||||
const ordered = canvas.locator(
|
||||
`${getCanvasInstanceSelector(before)}, ${getCanvasInstanceSelector(after)}`
|
||||
);
|
||||
await expect(ordered).toHaveCount(2);
|
||||
await expect(ordered.first()).toHaveAttribute(
|
||||
"data-ws-selector",
|
||||
before.join(",")
|
||||
);
|
||||
await expect(ordered.last()).toHaveAttribute(
|
||||
"data-ws-selector",
|
||||
after.join(",")
|
||||
);
|
||||
};
|
||||
|
||||
const saveShortcut = async (page: Page, key: string) => {
|
||||
await Promise.all([
|
||||
waitForChangeToBeSaved({ page, timeout: 30_000 }),
|
||||
page.keyboard.press(`Control+${key}`),
|
||||
]);
|
||||
};
|
||||
|
||||
const createFixture = async (
|
||||
context: BrowserContext,
|
||||
additionalPairSuffixes: string[] = []
|
||||
) => {
|
||||
const id = randomUUID();
|
||||
fixture = await createSlotKeyboardProject({
|
||||
return await createSlotKeyboardProject({
|
||||
context,
|
||||
email: `slot-keyboard-${id}@webstudio.test`,
|
||||
builderToken: `slot-keyboard-${id}-builder-token`,
|
||||
additionalPairSuffixes,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const expectCanvasInstancePrecedes = async ({
|
||||
canvas,
|
||||
beforeSelector,
|
||||
afterSelector,
|
||||
}: {
|
||||
canvas: Frame;
|
||||
beforeSelector: string[];
|
||||
afterSelector: string[];
|
||||
}) => {
|
||||
const beforeLocator = getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: beforeSelector,
|
||||
});
|
||||
const afterLocator = getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: afterSelector,
|
||||
});
|
||||
await beforeLocator.waitFor({ state: "visible", timeout: 30_000 });
|
||||
await afterLocator.waitFor({ state: "visible", timeout: 30_000 });
|
||||
const precedes = await beforeLocator.evaluate((beforeElement, after) => {
|
||||
const afterElement = document.querySelector(after);
|
||||
if (afterElement === null) {
|
||||
return false;
|
||||
}
|
||||
return Boolean(
|
||||
beforeElement.compareDocumentPosition(afterElement) &
|
||||
Node.DOCUMENT_POSITION_FOLLOWING
|
||||
);
|
||||
}, getCanvasInstanceSelector(afterSelector));
|
||||
if (precedes === false) {
|
||||
throw new Error(
|
||||
`Expected ${beforeSelector.join(",")} to precede ${afterSelector.join(",")}`
|
||||
);
|
||||
const expectIndented = async (canvas: Frame) => {
|
||||
await expect(
|
||||
getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: [heading, box, ...fragmentA],
|
||||
})
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: [heading, box, ...fragmentB],
|
||||
})
|
||||
).toBeVisible();
|
||||
};
|
||||
|
||||
const expectDetached = async (
|
||||
canvas: Frame,
|
||||
{
|
||||
id,
|
||||
suffix = "",
|
||||
position,
|
||||
}: {
|
||||
id: string;
|
||||
suffix?: string;
|
||||
position: "before" | "after";
|
||||
}
|
||||
};
|
||||
|
||||
const getFocusedTreeButtonText = async ({ page }: { page: Page }) => {
|
||||
return await page.evaluate(() => {
|
||||
const activeElement = document.activeElement;
|
||||
if (activeElement?.hasAttribute("data-tree-button") === false) {
|
||||
return;
|
||||
}
|
||||
return activeElement?.textContent?.trim();
|
||||
});
|
||||
};
|
||||
|
||||
const getSelectedTreeButtonTexts = async ({ page }: { page: Page }) => {
|
||||
return await page
|
||||
.locator("[data-tree-button][aria-selected='true']")
|
||||
.evaluateAll((buttons) =>
|
||||
buttons.map((button) => button.textContent?.trim() ?? "")
|
||||
);
|
||||
};
|
||||
|
||||
const expectSelectedTreeButtonTexts = async ({
|
||||
page,
|
||||
expectedTexts,
|
||||
}: {
|
||||
page: Page;
|
||||
expectedTexts: string[];
|
||||
}) => {
|
||||
await page.waitForFunction(
|
||||
(expected) => {
|
||||
const selectedTexts = Array.from(
|
||||
document.querySelectorAll("[data-tree-button][aria-selected='true']")
|
||||
).map((button) => button.textContent?.trim() ?? "");
|
||||
return (
|
||||
selectedTexts.length === expected.length &&
|
||||
expected.every((expectedText) =>
|
||||
selectedTexts.some((selectedText) =>
|
||||
selectedText.includes(expectedText)
|
||||
)
|
||||
)
|
||||
);
|
||||
},
|
||||
expectedTexts,
|
||||
{ timeout: 10_000 }
|
||||
);
|
||||
};
|
||||
|
||||
test("Keyboard shortcut moves a shared slot child into the previous sibling", async ({
|
||||
page,
|
||||
}) => {
|
||||
const canvas = await measure("slot keyboard open builder", async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
});
|
||||
|
||||
const headingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: headingSelector,
|
||||
});
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: headingSelector,
|
||||
}).click();
|
||||
|
||||
await page.keyboard.press("Control+ArrowRight");
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
],
|
||||
});
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-b",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("Keyboard shortcut keeps Navigator arrows working after outdenting a row", async ({
|
||||
page,
|
||||
}) => {
|
||||
const canvas = await measure(
|
||||
"slot keyboard navigator outdent open builder",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const slotAHeadingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
}).click();
|
||||
await openNavigatorPanel({ page });
|
||||
await page.getByRole("button", { name: "Slot Heading" }).first().click();
|
||||
|
||||
await page.keyboard.press("Control+ArrowLeft");
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
const focusedTextAfterMove = await getFocusedTreeButtonText({ page });
|
||||
if (focusedTextAfterMove?.includes("Slot Heading") !== true) {
|
||||
throw new Error(
|
||||
`Expected moved Navigator row to keep focus, received ${focusedTextAfterMove}`
|
||||
);
|
||||
) => {
|
||||
const { slotA, slotB, fragmentA, fragmentB } = getSlotPair(suffix);
|
||||
const movedSelector = [`${id}${suffix}`, ...wrapper];
|
||||
for (const fragment of [fragmentA, fragmentB]) {
|
||||
await expect(
|
||||
getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: [`${id}${suffix}`, ...fragment],
|
||||
})
|
||||
).toBeHidden();
|
||||
}
|
||||
|
||||
await page.keyboard.press("ArrowUp");
|
||||
const focusedTextAfterArrow = await getFocusedTreeButtonText({ page });
|
||||
if (
|
||||
focusedTextAfterArrow === undefined ||
|
||||
focusedTextAfterArrow === focusedTextAfterMove
|
||||
) {
|
||||
throw new Error(
|
||||
`Expected ArrowUp to move Navigator focus from ${focusedTextAfterMove}, received ${focusedTextAfterArrow}`
|
||||
);
|
||||
await expect(
|
||||
getCanvasInstance({ canvas, instanceSelector: movedSelector })
|
||||
).toBeVisible();
|
||||
if (position === "before") {
|
||||
await expectInstanceOrder(canvas, movedSelector, slotA);
|
||||
return;
|
||||
}
|
||||
});
|
||||
await expectInstanceOrder(canvas, slotA, movedSelector);
|
||||
await expectInstanceOrder(canvas, movedSelector, slotB);
|
||||
};
|
||||
|
||||
test("Shift+ArrowDown in Navigator selects exactly one additional row", async ({
|
||||
test("Canvas shortcuts select shared Slot siblings and persist keyboard moves", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const canvas = await measure(
|
||||
"slot keyboard navigator multi-select open builder",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
const { projectId, builderToken } = await createFixture(
|
||||
context,
|
||||
canvasDetachMoves.map(({ suffix }) => suffix)
|
||||
);
|
||||
|
||||
const slotADivSelector = [
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotADivSelector,
|
||||
}).click();
|
||||
await openNavigatorPanel({ page });
|
||||
await page.getByRole("button", { name: "Drop Div" }).first().click();
|
||||
await expectSelectedTreeButtonTexts({
|
||||
const canvas = await openProjectBuilder({
|
||||
page,
|
||||
expectedTexts: ["Drop Div"],
|
||||
projectId,
|
||||
authToken: builderToken,
|
||||
});
|
||||
|
||||
await page.keyboard.press("Shift+ArrowDown");
|
||||
|
||||
await expectSelectedTreeButtonTexts({
|
||||
page,
|
||||
expectedTexts: ["Drop Div", "Slot Heading"],
|
||||
});
|
||||
const focusedText = await getFocusedTreeButtonText({ page });
|
||||
if (focusedText?.includes("Slot Heading") !== true) {
|
||||
throw new Error(
|
||||
`Expected Shift+ArrowDown to focus Slot Heading, received ${focusedText}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("Control/Command+A after canvas selection selects sibling rows", async ({
|
||||
page,
|
||||
}) => {
|
||||
const canvas = await measure(
|
||||
"slot keyboard canvas multi-select open builder",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const slotAHeadingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await getCanvasInstance({
|
||||
const canvasHeading = getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
}).click();
|
||||
instanceSelector: [heading, ...fragmentA],
|
||||
});
|
||||
|
||||
await canvasHeading.click();
|
||||
await page.keyboard.press("Control+A");
|
||||
|
||||
await openNavigatorPanel({ page });
|
||||
await expectSelectedTreeButtonTexts({
|
||||
await expect(
|
||||
page.locator("[data-tree-button][aria-selected='true']")
|
||||
).toHaveText([/Drop Div/, /Slot Heading/]);
|
||||
|
||||
// Refocus the canvas and select just the heading before moving it.
|
||||
await canvasHeading.click();
|
||||
await saveShortcut(page, "ArrowRight");
|
||||
await expectIndented(canvas);
|
||||
|
||||
for (const move of canvasDetachMoves) {
|
||||
await test.step(`Canvas ${move.key} moves a child out of both Slots`, async () => {
|
||||
const { fragmentA } = getSlotPair(move.suffix);
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: [`${move.id}${move.suffix}`, ...fragmentA],
|
||||
}).click();
|
||||
await saveShortcut(page, move.key);
|
||||
await expectDetached(canvas, move);
|
||||
});
|
||||
}
|
||||
|
||||
await page.reload();
|
||||
const reloadedCanvas = await waitForCanvasFrame({ page });
|
||||
await expectIndented(reloadedCanvas);
|
||||
for (const move of canvasDetachMoves) {
|
||||
await expectDetached(reloadedCanvas, move);
|
||||
}
|
||||
});
|
||||
|
||||
test("Navigator shortcuts reorder and outdent shared Slot children while keeping keyboard focus", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const { projectId, builderToken } = await createFixture(context);
|
||||
const canvas = await openProjectBuilder({
|
||||
page,
|
||||
expectedTexts: ["Drop Div", "Slot Heading"],
|
||||
});
|
||||
|
||||
const selectedTexts = await getSelectedTreeButtonTexts({ page });
|
||||
if (selectedTexts.some((selectedText) => selectedText.includes("Slot A"))) {
|
||||
throw new Error(
|
||||
`Expected Command+A to select only siblings, received ${selectedTexts.join(", ")}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("Keyboard shortcut moves a direct shared slot child out of all slot occurrences", async ({
|
||||
page,
|
||||
}) => {
|
||||
const canvas = await measure(
|
||||
"slot keyboard detach open builder",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const slotAHeadingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
projectId,
|
||||
authToken: builderToken,
|
||||
});
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
}).click();
|
||||
|
||||
await page.keyboard.press("Control+ArrowLeft");
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-b",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
],
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("Keyboard shortcut moves the first shared slot child above all slot occurrences", async ({
|
||||
page,
|
||||
}) => {
|
||||
const canvas = await measure(
|
||||
"slot keyboard top child open builder",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const slotADivSelector = [
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: slotADivSelector,
|
||||
});
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotADivSelector,
|
||||
}).click();
|
||||
|
||||
await page.keyboard.press("Control+ArrowUp");
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotADivSelector,
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: [
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-b",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
],
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
|
||||
const movedDivSelector = [
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: movedDivSelector,
|
||||
});
|
||||
|
||||
const movedDivPrecedesSlotA = await canvas
|
||||
.locator(getCanvasInstanceSelector(movedDivSelector))
|
||||
.evaluate((movedElement, selector) => {
|
||||
const slotA = document.querySelector(selector);
|
||||
if (slotA === null) {
|
||||
return false;
|
||||
}
|
||||
return Boolean(
|
||||
movedElement.compareDocumentPosition(slotA) &
|
||||
Node.DOCUMENT_POSITION_FOLLOWING
|
||||
);
|
||||
}, slotASelector);
|
||||
if (movedDivPrecedesSlotA === false) {
|
||||
throw new Error("Expected moved div to be positioned before Slot A");
|
||||
}
|
||||
});
|
||||
|
||||
test("Keyboard shortcut moves the last shared slot child below all slot occurrences", async ({
|
||||
page,
|
||||
}) => {
|
||||
const canvas = await measure(
|
||||
"slot keyboard bottom child open builder",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const slotAHeadingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
});
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
}).click();
|
||||
|
||||
await page.keyboard.press("Control+ArrowDown");
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-b",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
],
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
|
||||
const movedHeadingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: movedHeadingSelector,
|
||||
});
|
||||
|
||||
const slotAPrecedesMovedHeading = await canvas
|
||||
.locator(slotASelector)
|
||||
.evaluate((slotA, movedSelector) => {
|
||||
const movedElement = document.querySelector(movedSelector);
|
||||
if (movedElement === null) {
|
||||
return false;
|
||||
}
|
||||
return Boolean(
|
||||
slotA.compareDocumentPosition(movedElement) &
|
||||
Node.DOCUMENT_POSITION_FOLLOWING
|
||||
);
|
||||
}, getCanvasInstanceSelector(movedHeadingSelector));
|
||||
if (slotAPrecedesMovedHeading === false) {
|
||||
throw new Error("Expected moved heading to be positioned after Slot A");
|
||||
}
|
||||
});
|
||||
|
||||
test("Keyboard shortcut reorders a shared slot child from navigator focus", async ({
|
||||
page,
|
||||
}) => {
|
||||
const canvas = await measure(
|
||||
"slot keyboard navigator open builder",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const slotAHeadingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
instanceSelector: [heading, ...fragmentA],
|
||||
}).click();
|
||||
await openNavigatorPanel({ page });
|
||||
await page.getByRole("button", { name: "Slot Heading" }).first().click();
|
||||
await page.keyboard.press("Control+ArrowUp");
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
const slotADivSelector = [
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
const slotBHeadingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-b",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
const slotBDivSelector = [
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-b",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
|
||||
await expectCanvasInstancePrecedes({
|
||||
canvas,
|
||||
beforeSelector: slotAHeadingSelector,
|
||||
afterSelector: slotADivSelector,
|
||||
});
|
||||
await expectCanvasInstancePrecedes({
|
||||
canvas,
|
||||
beforeSelector: slotBHeadingSelector,
|
||||
afterSelector: slotBDivSelector,
|
||||
});
|
||||
});
|
||||
|
||||
test("Keyboard shortcut moves the first shared slot child above all slot occurrences from navigator focus", async ({
|
||||
page,
|
||||
}) => {
|
||||
const canvas = await measure(
|
||||
"slot keyboard navigator top child open builder",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const slotADivSelector = [
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotADivSelector,
|
||||
}).click();
|
||||
await openNavigatorPanel({ page });
|
||||
await page.getByRole("button", { name: "Drop Div" }).first().click();
|
||||
|
||||
await page.keyboard.press("Control+ArrowUp");
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotADivSelector,
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: [
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-b",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
],
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
|
||||
const movedDivSelector = [
|
||||
"slot-keyboard-div",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: movedDivSelector,
|
||||
});
|
||||
|
||||
const movedDivPrecedesSlotA = await canvas
|
||||
.locator(getCanvasInstanceSelector(movedDivSelector))
|
||||
.evaluate((movedElement, selector) => {
|
||||
const slotA = document.querySelector(selector);
|
||||
if (slotA === null) {
|
||||
return false;
|
||||
}
|
||||
return Boolean(
|
||||
movedElement.compareDocumentPosition(slotA) &
|
||||
Node.DOCUMENT_POSITION_FOLLOWING
|
||||
);
|
||||
}, slotASelector);
|
||||
if (movedDivPrecedesSlotA === false) {
|
||||
throw new Error("Expected moved div to be positioned before Slot A");
|
||||
const navigator = page.locator("[data-navigator-tree]");
|
||||
const row = navigator
|
||||
.getByRole("button", { name: "Slot Heading", exact: true })
|
||||
.first();
|
||||
await row.click();
|
||||
await saveShortcut(page, "ArrowUp");
|
||||
for (const fragment of [fragmentA, fragmentB]) {
|
||||
const headingSelector = [heading, ...fragment];
|
||||
const boxSelector = [box, ...fragment];
|
||||
await expect(
|
||||
getCanvasInstance({ canvas, instanceSelector: headingSelector })
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
getCanvasInstance({ canvas, instanceSelector: boxSelector })
|
||||
).toBeVisible();
|
||||
await expectInstanceOrder(canvas, headingSelector, boxSelector);
|
||||
}
|
||||
});
|
||||
await expect(row).toBeFocused();
|
||||
|
||||
test("Keyboard shortcut moves the last shared slot child below all slot occurrences from navigator focus", async ({
|
||||
page,
|
||||
}) => {
|
||||
const canvas = await measure(
|
||||
"slot keyboard navigator bottom child open builder",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
await saveShortcut(page, "ArrowLeft");
|
||||
await expectDetached(canvas, { id: heading, position: "before" });
|
||||
await expect(row).toBeFocused();
|
||||
await page.keyboard.press("ArrowUp");
|
||||
await expect(
|
||||
navigator.getByRole("button", {
|
||||
name: "Slot Keyboard Wrapper",
|
||||
exact: true,
|
||||
})
|
||||
).toBeFocused();
|
||||
|
||||
const slotAHeadingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-a",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
}).click();
|
||||
await openNavigatorPanel({ page });
|
||||
await page.getByRole("button", { name: "Slot Heading" }).first().click();
|
||||
|
||||
await page.keyboard.press("Control+ArrowDown");
|
||||
await waitForSyncStatus({ page, status: "idle" });
|
||||
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: slotAHeadingSelector,
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
await getCanvasInstance({
|
||||
canvas,
|
||||
instanceSelector: [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-fragment",
|
||||
"slot-keyboard-slot-b",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
],
|
||||
}).waitFor({ state: "hidden", timeout: 30_000 });
|
||||
|
||||
const movedHeadingSelector = [
|
||||
"slot-keyboard-heading",
|
||||
"slot-keyboard-wrapper",
|
||||
"slot-keyboard-body",
|
||||
];
|
||||
await expectCanvasInstanceVisible({
|
||||
canvas,
|
||||
instanceSelector: movedHeadingSelector,
|
||||
await page.reload();
|
||||
await expectDetached(await waitForCanvasFrame({ page }), {
|
||||
id: heading,
|
||||
position: "before",
|
||||
});
|
||||
|
||||
const slotAPrecedesMovedHeading = await canvas
|
||||
.locator(slotASelector)
|
||||
.evaluate((slotA, movedSelector) => {
|
||||
const movedElement = document.querySelector(movedSelector);
|
||||
if (movedElement === null) {
|
||||
return false;
|
||||
}
|
||||
return Boolean(
|
||||
slotA.compareDocumentPosition(movedElement) &
|
||||
Node.DOCUMENT_POSITION_FOLLOWING
|
||||
);
|
||||
}, getCanvasInstanceSelector(movedHeadingSelector));
|
||||
if (slotAPrecedesMovedHeading === false) {
|
||||
throw new Error("Expected moved heading to be positioned after Slot A");
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user