Reduce E2E shard work and remove duplicate CI discovery

This commit is contained in:
Oleg Isonen committed 2026-11-16 00:22:20 +00:00
1 parent c0572f35c2
commit 83abffabb8
33 files changed
+1297 -1483

No files matched your search

+2 -1
View File
@@ -106,7 +106,8 @@ runs:
E2E_TEST_SHARD: ${{ inputs.shard }}
E2E_TEST_PARTITION: ${{ inputs.partition }}
run: |
args=(--workers=3)
# Select only the E2E test files. Playwright runs setup as a dependency.
args=(--workers=3 'e2e/tests/')
if [ -n "$E2E_TEST_PARTITION" ]; then
args+=(--shard="$E2E_TEST_PARTITION")
fi
@@ -0,0 +1,92 @@
import { randomUUID } from "node:crypto";
import type { BrowserContext } from "@playwright/test";
import {
migratePages,
serializePages,
} from "@webstudio-is/project-migrations/pages";
import type { Instance } from "@webstudio-is/sdk";
import { createSeededBuilderProject } from "./builder-project";
export const pageTemplateName = "Content Page Template";
export const pageTemplateText = "Content page template heading";
export const createBuilderEditingProject = ({
context,
name,
includePageTemplate = false,
}: {
context: BrowserContext;
name: string;
includePageTemplate?: boolean;
}) =>
createSeededBuilderProject({
context,
email: `${name}@webstudio.test`,
title: name,
builderToken: `${name}-${randomUUID()}-builder-token`,
createBuildUpdate: (build) => {
const pages = migratePages(JSON.parse(build.pages));
const home = pages.pages.get(pages.homePageId);
if (home === undefined) {
throw new Error("Expected the fixture home page");
}
home.rootInstanceId = "body";
const instances: Instance[] = [
{
type: "instance",
id: "body",
component: "ws:element",
tag: "body",
children: [{ type: "id", value: "initial-content" }],
},
{
type: "instance",
id: "initial-content",
component: "ws:element",
tag: "p",
children: [{ type: "text", value: "Initial content" }],
},
];
if (includePageTemplate) {
const rootInstanceId = "page-template-body";
pages.pageTemplates = new Map([
[
"content-page-template",
{
id: "content-page-template",
rootInstanceId,
name: pageTemplateName,
title: JSON.stringify(pageTemplateName),
meta: {},
},
],
]);
instances.push(
{
type: "instance",
id: rootInstanceId,
component: "ws:element",
tag: "body",
children: [{ type: "id", value: "page-template-heading" }],
},
{
type: "instance",
id: "page-template-heading",
component: "ws:element",
tag: "h1",
children: [{ type: "text", value: pageTemplateText }],
}
);
}
return {
pages: JSON.stringify(serializePages(pages)),
instances: JSON.stringify(instances),
dataSources: "[]",
props: "[]",
resources: "[]",
styleSources: "[]",
styleSourceSelections: "[]",
styles: "[]",
};
},
});
@@ -62,7 +62,8 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
export const authorFormActionCombination = async (
projectId: string,
mode?: string
mode?: string,
deliveryPath = "/submit"
) => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
@@ -338,12 +339,12 @@ export const authorFormActionCombination = async (
}
const graphql = await createAction(
"First GraphQL action",
"/submit",
deliveryPath,
"graphql",
`{ query: "mutation Record($name: String!) { record(name: $name) }", variables: { name: ${formData}.name } }`
);
const middle = await createAction("Middle HTTP action", "/submit");
const http = await createAction("Last HTTP action", "/submit");
const middle = await createAction("Middle HTTP action", deliveryPath);
const http = await createAction("Last HTTP action", deliveryPath);
const actions = [
{ dataSourceId: graphql.dataSourceId },
{ dataSourceId: middle.dataSourceId },
@@ -0,0 +1,30 @@
import { authorFormActionCombination } from "./mcp-form-action-combination-author";
import { authorFormCallbacks } from "./mcp-form-callbacks-author";
import { authorQuerySearch } from "./mcp-query-search-author";
const [, , projectId, managedPath, concurrencyPath] = process.argv;
if (
projectId === undefined ||
managedPath === undefined ||
concurrencyPath === undefined
) {
throw new Error(
"Expected a project ID and managed callback and concurrency paths"
);
}
const receiverUrl = "https://mcp-delivery.example/submit";
await authorFormCallbacks({ projectId, mode: "legacy", receiverUrl });
await authorFormCallbacks({
projectId,
mode: "managed",
receiverUrl,
path: managedPath,
});
await authorQuerySearch(projectId);
const actions = await authorFormActionCombination(
projectId,
undefined,
concurrencyPath
);
process.stdout.write(`${JSON.stringify(actions)}\n`);
+19 -7
View File
@@ -1,6 +1,6 @@
import path from "node:path";
import type { Page } from "@playwright/test";
import { waitForChangeToBeSaved } from "./sync-status";
import { waitForChangeToBeSaved, waitForSyncComplete } from "./sync-status";
import { dragPointer } from "./drag";
const assetFixturePath = (filename: string) =>
@@ -93,24 +93,36 @@ export const dragAssetToFolder = async ({
await asset.waitFor({ state: "hidden" });
};
export const uploadAsset = async ({
export const uploadAssets = async ({
page,
filename,
filenames,
}: {
page: Page;
filename: string;
filenames: [string, ...string[]];
}) => {
const fileChooserPromise = page.waitForEvent("filechooser");
await openAddAssetMenu(page);
await page.getByRole("menuitem", { name: "Upload", exact: true }).click();
const fileChooser = await fileChooserPromise;
const save = waitForChangeToBeSaved({ page });
await fileChooser.setFiles(assetFixturePath(filename));
const title = await waitForAsset({ page, filename });
await fileChooser.setFiles(filenames.map(assetFixturePath));
const titles = await Promise.all(
filenames.map((filename) => waitForAsset({ page, filename }))
);
await save;
return title;
// A slow upload can enqueue another save after the first one completes.
await waitForSyncComplete({ page });
return titles;
};
export const uploadAsset = async ({
page,
filename,
}: {
page: Page;
filename: string;
}) => (await uploadAssets({ page, filenames: [filename] }))[0]!;
export const openAssetSettings = async ({
page,
filename,
@@ -1,19 +1,63 @@
import { createServer } from "node:http";
import { createServer, type ServerResponse } from "node:http";
export const concurrencyPath = "/submit?tag=concurrency";
export const startFormCallbackReceiver = async () => {
const deliveries: Array<Record<string, unknown>> = [];
const server = createServer(async (request, response) => {
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.from(chunk));
}
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
deliveries.push(body);
const success = body.outcome !== "failure";
const actionDeliveries: string[] = [];
const pending: ServerResponse[] = [];
let barrierReached = false;
let timeout: ReturnType<typeof setTimeout> | undefined;
const respond = (response: ServerResponse, success: boolean) => {
response.writeHead(success ? 200 : 503, {
"content-type": "application/json",
});
response.end(JSON.stringify({ delivered: success }));
};
const server = createServer(async (request, response) => {
if (
request.method !== "POST" ||
(request.url !== "/submit" && request.url !== concurrencyPath)
) {
response.writeHead(404).end();
return;
}
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.from(chunk));
}
const body = Buffer.concat(chunks).toString("utf8");
if (request.url === "/submit") {
const callback = JSON.parse(body);
deliveries.push(callback);
respond(response, callback.outcome !== "failure");
return;
}
actionDeliveries.push(body);
if (actionDeliveries.length > 3) {
response.writeHead(409).end();
return;
}
if (barrierReached) {
respond(response, true);
return;
}
pending.push(response);
if (pending.length === 1) {
// A serial dispatcher can never get the second response before the first.
timeout = setTimeout(() => {
for (const waiting of pending.splice(0)) {
waiting.writeHead(504).end("Second Action did not arrive");
}
}, 10_000);
} else {
barrierReached = true;
clearTimeout(timeout);
for (const waiting of pending.splice(0)) {
respond(waiting, true);
}
}
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
@@ -24,9 +68,18 @@ export const startFormCallbackReceiver = async () => {
throw new Error("Expected local Form receiver port");
}
return {
url: `http://127.0.0.1:${address.port}/submit`,
port: address.port,
deliveries,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
actionDeliveries,
get barrierReached() {
return barrierReached;
},
close: async () => {
clearTimeout(timeout);
for (const waiting of pending.splice(0)) {
waiting.writeHead(503).end();
}
await new Promise<void>((resolve) => server.close(() => resolve()));
},
};
};
@@ -23,22 +23,27 @@ const cliTsconfigPath = fileURLToPath(
);
export const withMcpEmailHttpPreview = async <Result>({
projectId,
emailPort,
httpPort,
callback,
...source
}: {
projectId: string;
emailPort: number;
httpPort: number;
callback: ({ url }: { url: string }) => Promise<Result>;
}) => {
} & (
| { projectId: string }
| { build: Awaited<ReturnType<typeof loadDevBuild>> }
)) => {
const tempDir = await mkdtemp(
join(tmpdir(), "webstudio-e2e-mcp-email-http-")
);
let preview: ChildProcess | undefined;
try {
const build = await loadDevBuild({ projectId });
const build =
"build" in source
? source.build
: await loadDevBuild({ projectId: source.projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
+127 -134
View File
@@ -5,7 +5,7 @@ import { measure } from "../perf";
import { test } from "../test";
import { openProjectBuilder, waitForCanvasText } from "./builder";
import { expectGeneratedRedirects } from "./generated-app";
import { waitForChangeToBeSaved } from "./sync-status";
import { waitForChangeToBeSaved, waitForSyncComplete } from "./sync-status";
type PersistedPages = {
redirects?: Array<{
@@ -54,20 +54,6 @@ export const openProjectSettings = async ({
await page.getByRole("dialog", { name: "Project settings" }).waitFor();
};
const saveSiteName = async ({
page,
siteName,
}: {
page: PlaywrightPage;
siteName: string;
}) => {
const save = waitForChangeToBeSaved({ page });
await page
.getByRole("textbox", { name: "Site name", exact: true })
.fill(siteName);
await save;
};
const setAtomicStyles = async ({
page,
checked,
@@ -79,15 +65,10 @@ const setAtomicStyles = async ({
const checkbox = page.getByRole("checkbox", {
name: "Generate atomic CSS when publishing",
});
const toggle = async () => {
const save = waitForChangeToBeSaved({ page });
await checkbox.click();
await save;
};
if ((await checkbox.isChecked()) === checked) {
await toggle();
await checkbox.click();
}
await toggle();
await checkbox.click();
};
const addRedirect = async ({
@@ -104,13 +85,11 @@ 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 save;
};
const deleteRedirect = async ({
@@ -128,17 +107,19 @@ const deleteRedirect = async ({
await save;
};
const expectPersistedProjectSettings = async ({
projectId,
const expectPersistedProjectSettings = ({
build,
siteName,
redirect,
}: {
projectId: string;
build: Awaited<ReturnType<typeof loadDevBuild>>;
siteName: string;
redirect?: { from: string; to: string; status?: string };
}) => {
const pages = await getPersistedPages({ projectId });
const settings = await getPersistedProjectSettings({ projectId });
const pages = JSON.parse(build.pages) as PersistedPages;
const settings = JSON.parse(
build.projectSettings
) as PersistedProjectSettings;
if (settings.meta.siteName !== siteName) {
throw new Error(
`Expected siteName "${siteName}", received ${JSON.stringify(settings.meta)}.`
@@ -176,7 +157,10 @@ export const withSavedProjectRedirect = async ({
}: {
page: PlaywrightPage;
fixture: { projectId: string; builderToken: string };
verifyPreview: (redirect: { from: string; to: string }) => Promise<void>;
verifyPreview: (options: {
redirect: { from: string; to: string };
build: Awaited<ReturnType<typeof loadDevBuild>>;
}) => Promise<void>;
}) => {
const siteName = "Runtime Settings Site";
const redirect = {
@@ -198,7 +182,9 @@ export const withSavedProjectRedirect = async ({
await measure("project settings runtime update settings", async () => {
await openProjectSettings({ page });
await saveSiteName({ page, siteName });
await page
.getByRole("textbox", { name: "Site name", exact: true })
.fill(siteName);
await setAtomicStyles({ page, checked: false });
await addRedirect({
page,
@@ -210,120 +196,127 @@ export const withSavedProjectRedirect = 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 waitForSyncComplete({ page });
});
await expectPersistedProjectSettings({
projectId: fixture.projectId,
siteName,
redirect,
});
if (
(await getPersistedProjectSettings({ projectId: fixture.projectId }))
.compiler.atomicStyles !== false
) {
const savedBuild = await loadDevBuild({ projectId: fixture.projectId });
expectPersistedProjectSettings({ build: savedBuild, siteName, redirect });
const settings = JSON.parse(
savedBuild.projectSettings
) as PersistedProjectSettings;
if (settings.compiler.atomicStyles !== false) {
throw new Error("Expected atomic CSS setting to persist as disabled.");
}
const reloadAndPreview = await Promise.allSettled([
verifyPreview(redirect),
measure("project settings runtime reload with redirect", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
if (
settings.meta.contactEmail !== recipients ||
settings.meta.emailSender !== sender
) {
throw new Error(
`Expected saved Project Emails settings, received ${JSON.stringify(settings.meta)}.`
);
}
// Preview uses this saved version while Builder verifies and deletes the
// redirect. The export after deletion still reads a fresh build from storage.
const checks = await Promise.allSettled([
measure("project settings runtime production Preview", () =>
verifyPreview({ redirect, build: savedBuild })
),
test.step("Verify saved settings and delete redirect in Builder", async () => {
await measure(
"project settings runtime reload with redirect",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
}
);
await openProjectSettings({ page });
await page
.getByRole("textbox", { name: "Site name", exact: true })
.waitFor();
const persistedSiteName = await page
.getByRole("textbox", { name: "Site name", exact: true })
.inputValue();
if (persistedSiteName !== siteName) {
throw new Error(
`Expected project settings site name "${siteName}", received "${persistedSiteName}".`
);
}
await page.getByRole("option", { name: "Redirects" }).click();
await page.getByText(redirect.from, { exact: true }).waitFor();
await page.getByRole("option", { name: "Publish" }).click();
if (
await page
.getByRole("checkbox", {
name: "Generate atomic CSS when publishing",
})
.isChecked()
) {
throw new Error(
"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 () => {
await deleteRedirect({ page, from: redirect.from });
});
expectPersistedProjectSettings({
build: await loadDevBuild({ projectId: fixture.projectId }),
siteName,
});
await Promise.all([
measure(
"project settings runtime generated redirects after delete",
() =>
expectGeneratedRedirects({
projectId: fixture.projectId,
expectedRedirects: [],
})
),
measure(
"project settings runtime reload after redirect delete",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
}
),
]);
await openProjectSettings({ page });
await page.getByRole("option", { name: "Redirects" }).click();
await page.getByText(redirect.from, { exact: true }).waitFor({
state: "hidden",
});
await waitForCanvasText({ page, text: "Initial content" });
}),
]);
for (const check of reloadAndPreview) {
for (const check of checks) {
if (check.status === "rejected") {
throw check.reason;
}
}
await openProjectSettings({ page });
await page.getByRole("textbox", { name: "Site name", exact: true }).waitFor();
const persistedSiteName = await page
.getByRole("textbox", { name: "Site name", exact: true })
.inputValue();
if (persistedSiteName !== siteName) {
throw new Error(
`Expected project settings site name "${siteName}", received "${persistedSiteName}".`
);
}
await page.getByRole("option", { name: "Redirects" }).click();
await page.getByText(redirect.from, { exact: true }).waitFor();
await page.getByRole("option", { name: "Publish" }).click();
if (
await page
.getByRole("checkbox", {
name: "Generate atomic CSS when publishing",
})
.isChecked()
) {
throw new Error(
"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 () => {
await deleteRedirect({ page, from: redirect.from });
});
await expectPersistedProjectSettings({
projectId: fixture.projectId,
siteName,
});
await Promise.all([
measure("project settings runtime generated redirects after delete", () =>
expectGeneratedRedirects({
projectId: fixture.projectId,
expectedRedirects: [],
})
),
measure(
"project settings runtime reload after redirect delete",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
}
),
]);
await openProjectSettings({ page });
await page.getByRole("option", { name: "Redirects" }).click();
await page.getByText(redirect.from, { exact: true }).waitFor({
state: "hidden",
});
};
@@ -8,7 +8,7 @@ import { loadDevBuild, updateBuild } from "../db";
import { measure } from "../perf";
import { openProjectBuilder, waitForCanvasText } from "./builder";
import { selectNavigatorItem } from "./navigator";
import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";
import { waitForChangeToBeSaved } from "./sync-status";
const seedSavedWebhookForm = async (projectId: string) => {
const build = await loadDevBuild({ projectId });
@@ -253,7 +253,6 @@ const updateResourceActionUrl = async ({
const save = waitForChangeToBeSaved({ page });
await input.press("Enter");
await save;
await waitForSyncStatus({ page, status: "idle" });
};
const expectPersistedActionResource = async ({
+1 -1
View File
@@ -192,7 +192,7 @@ configure_database_urls() {
export DIRECT_URL="${E2E_DIRECT_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${db_port}/${POSTGRES_DB}}"
}
if [ "$E2E_RUN_TESTS" = "true" ] && [ "$mode" != "ci-shard-prepare" ]; then
if [ "$E2E_RUN_TESTS" = "true" ] && [[ "$mode" != ci-shard-* ]]; then
run_step "validate builder e2e test selection" \
"$E2E_TEST_SELECTION_TIMEOUT_SECONDS" validate_builder_e2e_selection
fi
@@ -0,0 +1,218 @@
import { expect } from "@playwright/test";
import { randomUUID } from "node:crypto";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import {
createAssetFolder,
deleteSelectedAsset,
openAssetSettings,
openAssetsPanel,
replaceSelectedAsset,
uploadAsset,
waitForAsset,
} from "../flows/assets-panel";
import { openProjectBuilder, waitForCanvasFrame } from "../flows/builder";
import {
selectCanvasImage,
waitForCanvasImage,
waitForCanvasImageSourceName,
} from "../flows/canvas-media";
import { chooseSelectedAssetProperty } from "../flows/props-panel";
import {
waitForChangeToBeSaved,
waitForSyncComplete,
} from "../flows/sync-status";
import { insertTemplateAfterCanvasText } from "../flows/template-insertion";
import { measure } from "../perf";
import { e2ePaidPlanName } from "../plans";
import { test } from "../test";
test("Editor can save assets, folders, and collection entries in content mode", async ({
context,
page,
}) => {
const fixture = await createContentModeProject({
context,
devPlan: e2ePaidPlanName,
email: `content-mode-assets-${randomUUID()}@webstudio.test`,
});
const uploadFilename = "large-image.svg";
const replacementFilename = "replacement-image.svg";
const collectionName = "Content collection entries";
const folderName = "Editor ordinary assets";
const entryTitle = "Content collection entry";
const entryFilename = "content-collection-entry.mdx";
const assetsPanel = page.getByRole("tabpanel", { name: "Assets" });
const browseRoot = () =>
assetsPanel.getByRole("button", { name: "Root", exact: true }).click();
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForSyncComplete({ page });
await openAssetsPanel({ page });
const collection = await createAssetFolder({
page,
name: collectionName,
useAsContentCollection: true,
});
await collection.dblclick();
await page.getByRole("button", { name: "Collection settings" }).waitFor();
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await waitForSyncComplete({ page });
await openAssetsPanel({ page });
// The last folder is remembered for this project, including across modes.
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByRole("button", { name: "Add asset" }).click();
await page.getByRole("menuitem", { name: "New entry" }).click();
const dialog = page.getByRole("dialog", { name: "New entry" });
await dialog.getByLabel("Title *").fill(entryTitle);
await Promise.all([
waitForChangeToBeSaved({ page }),
dialog.getByRole("button", { name: "Create entry" }).click(),
]);
await waitForAsset({ page, filename: entryFilename });
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByTitle("template.mdx").waitFor({ state: "visible" });
await browseRoot();
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.imageReplacementTemplateName,
});
await waitForCanvasImage({
page,
alt: fixture.imageReplacementTemplateImageAlt,
});
let uploadedAssetTitle = "";
await measure("content mode upload image source asset", async () => {
await openAssetsPanel({ page });
uploadedAssetTitle = await uploadAsset({
page,
filename: uploadFilename,
});
});
await selectCanvasImage({
page,
alt: fixture.imageReplacementTemplateImageAlt,
});
await measure("content mode choose image source asset", async () => {
await chooseSelectedAssetProperty({
page,
label: "Source",
assetFilename: uploadFilename,
});
});
await waitForCanvasImageSourceName({ page, sourceName: "large-image_" });
const canvas = await waitForCanvasFrame({ page });
const uploadedImage = canvas.locator('img[src*="large-image_"]');
await expect(uploadedImage).toHaveAttribute("width", "240");
await expect(uploadedImage).toHaveAttribute("height", "160");
let replacementAssetTitle = "";
await measure("content mode replace used image source asset", async () => {
await openAssetsPanel({ page });
await openAssetSettings({
page,
filename: uploadedAssetTitle,
});
replacementAssetTitle = await replaceSelectedAsset({
page,
filename: replacementFilename,
});
});
await waitForCanvasImageSourceName({
page,
sourceName: "replacement-image_",
});
await waitForSyncComplete({ page });
const folder = await createAssetFolder({ page, name: folderName });
await folder.dblclick();
const deletedAsset =
await test.step("Upload, replace and delete an unused asset in the ordinary folder", async () => {
const uploadFilename = "upload-image.svg";
const replacementFilename = "large-image.svg";
let uploadedAssetTitle = "";
await measure("content mode upload asset", async () => {
uploadedAssetTitle = await uploadAsset({
page,
filename: uploadFilename,
});
});
let replacementAssetTitle = "";
await measure("content mode replace asset", async () => {
await openAssetSettings({ page, filename: uploadedAssetTitle });
const assetId = await page.locator("#asset-manager-id").inputValue();
if (assetId.length === 0) {
throw new Error(
"Expected Asset settings to expose the uploaded asset id"
);
}
await page.getByText("0 uses", { exact: true }).waitFor();
replacementAssetTitle = await replaceSelectedAsset({
page,
filename: replacementFilename,
});
});
await measure("content mode delete asset", async () => {
await openAssetSettings({ page, filename: replacementAssetTitle });
await deleteSelectedAsset({
page,
filename: replacementAssetTitle,
});
});
return { uploadedAssetTitle, replacementAssetTitle };
});
await browseRoot();
await collection.dblclick();
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await openAssetsPanel({ page });
await waitForAsset({ page, filename: entryFilename });
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByTitle("template.mdx").waitFor({ state: "visible" });
await browseRoot();
const expectDeletedAssetAbsent = async () => {
await expect(
assetsPanel.getByTitle(deletedAsset.uploadedAssetTitle)
).toHaveCount(0);
await expect(
assetsPanel.getByTitle(deletedAsset.replacementAssetTitle)
).toHaveCount(0);
};
await expectDeletedAssetAbsent();
await waitForCanvasImageSourceName({
page,
sourceName: "replacement-image_",
});
await page.getByTitle(replacementAssetTitle).waitFor();
await waitForSyncComplete({ page });
const reloadedCanvas = await waitForCanvasFrame({ page });
const replacementImage = reloadedCanvas.locator(
'img[src*="replacement-image_"]'
);
await expect(replacementImage).toHaveAttribute("width", "120");
await expect(replacementImage).toHaveAttribute("height", "80");
await folder.dblclick();
await expectDeletedAssetAbsent();
});
@@ -3,7 +3,7 @@ import { insertAssetFolders } from "../db";
import {
createAssetFolder,
openAssetsPanel,
uploadAsset,
uploadAssets,
} from "../flows/assets-panel";
import { openProjectBuilder } from "../flows/builder";
import {
@@ -45,13 +45,9 @@ test("Asset selection and drag work across a long folder list", async ({
});
await waitForSyncStatus({ page, status: "idle" });
await openAssetsPanel({ page });
const firstAssetTitle = await uploadAsset({
const [firstAssetTitle, secondAssetTitle] = await uploadAssets({
page,
filename: "upload-image.svg",
});
const secondAssetTitle = await uploadAsset({
page,
filename: "replacement-image.svg",
filenames: ["upload-image.svg", "replacement-image.svg"],
});
const firstAsset = page.getByTitle(firstAssetTitle);
const secondAsset = page.getByTitle(secondAssetTitle);
@@ -7,11 +7,8 @@ import {
setSelectedBooleanProperty,
waitForSelectedBooleanPropertyValue,
} from "../flows/props-panel";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
} from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { waitForChangeToBeSaved } from "../flows/sync-status";
import { createBuilderEditingProject } from "../fixtures/builder-editing-project";
import { test } from "../test";
import { measure } from "../perf";
@@ -35,8 +32,9 @@ const insertComponentPanelOption = async ({
component === undefined
? page.getByRole("option", { name, exact: true })
: page.locator(`[data-drag-component="${component}"]`);
const save = waitForChangeToBeSaved({ page });
await option.click();
await waitForSyncStatus({ page, status: "idle" });
await save;
};
const selectNavigatorItem = async ({
@@ -96,7 +94,6 @@ const pastePlainTextFromClipboardShortcut = async ({
);
}, text);
await save;
await waitForSyncStatus({ page, status: "idle" });
};
const bindSelectedPropertyToExpression = async ({
@@ -129,7 +126,6 @@ const bindSelectedPropertyToExpression = async ({
const save = waitForChangeToBeSaved({ page });
await page.keyboard.press("ControlOrMeta+Enter");
await save;
await waitForSyncStatus({ page, status: "idle" });
await page.keyboard.press("Escape");
};
@@ -279,13 +275,9 @@ test("Props panel expression bindings and checkbox state persist after reload",
page,
context,
}) => {
const fixture = await createContentModeProject({
context: context,
email: "props-runtime@webstudio.test",
title: "Props Runtime",
assetNamePrefix: "props-runtime-",
editorToken: "props-runtime-editor-token",
builderToken: "props-runtime-builder-token",
const fixture = await createBuilderEditingProject({
context,
name: "props-runtime",
});
const anchorText = "Expression-bound link";
const expression = '"/props-expression-link"';
@@ -231,6 +231,7 @@ test("Share links enforce viewer, editor, builder, admin, and owner permissions"
page: editor.page,
currentText: fixture.shareLinkEditableText,
text: editedText,
waitForProjectSync: false,
});
await replaceCanvasText({
@@ -252,6 +253,10 @@ test("Share links enforce viewer, editor, builder, admin, and owner permissions"
(async () => {
await openBuilderUrl({ page: editor.page, url: editorUrl });
await waitForCanvasText({ page: editor.page, text: editedText });
await waitForCanvasText({
page: editor.page,
text: collaborativeText,
});
await waitForSyncComplete({ page: editor.page });
await expectShareUnavailable({ page: editor.page });
@@ -2,7 +2,7 @@ import { createServer } from "node:http";
import { expect } from "@playwright/test";
import { encodeDataSourceVariable } from "@webstudio-is/sdk";
import { formDataParameterName } from "@webstudio-is/sdk/runtime";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { createProjectThroughApi } from "../fixtures/create-project";
import { loadDevBuild } from "../db";
import type { CapturedEmail } from "../flows/mcp-email-preview";
import { withMcpEmailHttpPreview } from "../flows/mcp-email-http-preview";
@@ -62,12 +62,10 @@ test("Generated Preview delivers MCP-authored forms with readable email and brow
page,
}) => {
await startPreviewFormMcpClient();
const fixture = await createContentModeProject({
const projectId = await createProjectThroughApi({
context,
email: "mcp-default-contact@webstudio.test",
title: "MCP default contact Form",
assetNamePrefix: "mcp-default-contact-",
builderToken: "mcp-default-contact-builder-token",
});
const {
formData: {
@@ -77,9 +75,9 @@ test("Generated Preview delivers MCP-authored forms with readable email and brow
},
contact: { formId, ownerResourceId, visitorResourceId },
context: { formId: contextFormId },
} = await authorForms(fixture.projectId);
} = await authorForms(projectId);
expect(formDataExpression).toContain(".toString()");
const build = await loadDevBuild({ projectId: fixture.projectId });
const build = await loadDevBuild({ projectId });
const resources = JSON.parse(build.resources) as Array<{
id: string;
email?: Record<string, unknown>;
@@ -164,7 +162,7 @@ test("Generated Preview delivers MCP-authored forms with readable email and brow
const receiver = await startFormContextReceiver();
try {
await withMcpEmailHttpPreview({
projectId: fixture.projectId,
projectId,
emailPort: address.port,
httpPort: receiver.port,
callback: async ({ url }) => {
@@ -1,8 +1,15 @@
import { expect, type Page } from "@playwright/test";
import type { StyleSource, StyleSourceSelection } from "@webstudio-is/sdk";
import type {
StyleDecl,
StyleSource,
StyleSourceSelection,
} from "@webstudio-is/sdk";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import { selectCanvasTextInstance } from "../flows/canvas-selection";
import { waitForCanvasTextStyle } from "../flows/canvas-style";
import {
waitForCanvasTextStyle,
waitForHoveredCanvasTextStyle,
} from "../flows/canvas-style";
import { openNavigatorPanel } from "../flows/navigator";
import { addCssDeclaration } from "../flows/css-declaration";
import { waitForChangeToBeSaved } from "../flows/sync-status";
@@ -16,18 +23,52 @@ const setCssValue = async ({
page,
property,
value,
waitForSave = true,
}: {
page: Page;
property: string;
value: string;
waitForSave?: boolean;
}) => {
const input = page.getByLabel(property, { exact: true }).first();
await input.fill(value);
const save = waitForChangeToBeSaved({ page });
const save = waitForSave ? waitForChangeToBeSaved({ page }) : undefined;
await input.press("Enter");
await save;
};
const resetCssValue = async ({
page,
property,
}: {
page: Page;
property: string;
}) => {
const input = page.getByLabel(property, { exact: true }).first();
const labelText = `${property.slice(0, 1).toUpperCase()}${property.slice(1)}`;
const control = input.locator(
`xpath=ancestor::*[.//*[normalize-space()=${JSON.stringify(labelText)}]][1]`
);
const label = control.getByText(labelText, { exact: true });
await label.waitFor({ state: "visible", timeout: 10_000 });
const save = waitForChangeToBeSaved({ page });
await label.click({ modifiers: ["Alt"] });
await save;
};
const selectStyleSourceState = async ({
page,
state,
}: {
page: Page;
state: string;
}) => {
await page
.getByLabel("Style source menu Local", { exact: true })
.click({ force: true });
await page.getByRole("menuitem", { name: state, exact: true }).click();
};
const selectNavigatorItem = async ({
page,
itemName,
@@ -69,24 +110,24 @@ const getInstanceChildCount = async ({
);
};
test("Builder grid, design tokens, and custom breakpoint styles persist", async ({
test("Builder style properties, grid, tokens, and custom breakpoints persist", async ({
page,
context,
}) => {
const fixture = await createContentModeProject({
context,
email: "style-panel-layout-e2e@webstudio.test",
title: "Style Panel Layout E2E",
assetNamePrefix: "style-panel-layout-e2e-",
email: "style-panel-e2e@webstudio.test",
title: "Style Panel E2E",
assetNamePrefix: "style-panel-e2e-",
});
const bodyInstanceId = "body";
const breakpointText = "Initial content";
const styledText = "Initial content";
const tokenText = fixture.shareLinkEditableText;
const tokenInstanceId = "share-link-editable-content";
const breakpointName = "E2E Tablet";
const updatedBreakpointName = "E2E Tablet Updated";
const tokenName = "E2E Brand Token";
const openLayoutProject = () =>
const openStyleProject = () =>
openProjectBuilder({
page,
projectId: fixture.projectId,
@@ -109,8 +150,50 @@ test("Builder grid, design tokens, and custom breakpoint styles persist", async
expect(selection?.values).toContain(token?.id);
};
await openLayoutProject();
await waitForCanvasText({ page, text: breakpointText });
const representativeStyles = [
{ property: "font-size", value: "44px", computed: "44px" },
{ property: "line-height", value: "1.25", computed: "55px" },
{ property: "letter-spacing", value: "2px", computed: "2px" },
{ property: "color", value: "#2255ff", computed: "rgb(34, 85, 255)" },
];
const expectRepresentativeCanvasStyles = async () => {
for (const { property, computed } of representativeStyles) {
await waitForCanvasTextStyle({
page,
text: styledText,
property,
value: computed,
});
}
};
const expectHoverCanvasStyle = () =>
waitForHoveredCanvasTextStyle({
page,
text: styledText,
property: "color",
value: "rgb(202, 18, 107)",
});
const readSavedInstanceStyles = async () => {
const build = await loadDevBuild({ projectId: fixture.projectId });
const styles: StyleDecl[] = JSON.parse(build.styles);
const selections: StyleSourceSelection[] = JSON.parse(
build.styleSourceSelections
);
const selection = selections.find(
({ instanceId }) => instanceId === fixture.listItemInstanceId
);
return styles.filter(({ styleSourceId }) =>
selection?.values.includes(styleSourceId)
);
};
const hoverColor = expect.objectContaining({
state: ":hover",
property: "color",
});
const width = expect.objectContaining({ property: "width" });
await openStyleProject();
await waitForCanvasText({ page, text: styledText });
const initialBodyChildCount = await getInstanceChildCount({
fixture,
@@ -139,6 +222,37 @@ test("Builder grid, design tokens, and custom breakpoint styles persist", async
await expectSavedToken();
});
await test.step("edit and reset representative style properties", async () => {
await selectCanvasTextInstance({ page, text: styledText });
await page.getByRole("tab", { name: "Style" }).click();
for (const { property, value } of representativeStyles) {
await setCssValue({ page, property, value, waitForSave: false });
}
await setCssValue({
page,
property: "width",
value: "420px",
waitForSave: false,
});
await selectStyleSourceState({ page, state: ":hover" });
await setCssValue({ page, property: "color", value: "#ca126b" });
await selectStyleSourceState({ page, state: ":hover" });
await expectRepresentativeCanvasStyles();
await waitForCanvasTextStyle({
page,
text: styledText,
property: "width",
value: "420px",
});
await expectHoverCanvasStyle();
expect(await readSavedInstanceStyles()).toContainEqual(hoverColor);
await page.getByRole("tab", { name: "Style" }).click();
await resetCssValue({ page, property: "width" });
expect(await readSavedInstanceStyles()).not.toContainEqual(width);
});
await test.step("fill the selected grid", async () => {
await selectNavigatorItem({ page, itemName: "Body" });
await page.getByRole("tab", { name: "Style" }).click();
@@ -196,20 +310,20 @@ test("Builder grid, design tokens, and custom breakpoint styles persist", async
.click();
await page.getByText(updatedBreakpointName, { exact: true }).click();
await selectCanvasTextInstance({ page, text: breakpointText });
await selectCanvasTextInstance({ page, text: styledText });
await page.getByRole("tab", { name: "Style" }).click();
await setCssValue({ page, property: "font-size", value: "31px" });
await waitForCanvasTextStyle({
page,
text: breakpointText,
text: styledText,
property: "font-size",
value: "31px",
});
});
await openLayoutProject();
await waitForCanvasText({ page, text: breakpointText });
await openStyleProject();
await waitForCanvasText({ page, text: styledText });
await test.step("verify the reloaded design token and grid", async () => {
await selectCanvasTextInstance({ page, text: tokenText });
@@ -245,7 +359,7 @@ test("Builder grid, design tokens, and custom breakpoint styles persist", async
await page.getByText(updatedBreakpointName, { exact: true }).click();
await waitForCanvasTextStyle({
page,
text: breakpointText,
text: styledText,
property: "font-size",
value: "31px",
});
@@ -262,7 +376,7 @@ test("Builder grid, design tokens, and custom breakpoint styles persist", async
await deleteSave;
});
await openLayoutProject();
await openStyleProject();
await page
.getByRole("button", { name: "Breakpoints with custom conditions" })
.click();
@@ -270,4 +384,16 @@ test("Builder grid, design tokens, and custom breakpoint styles persist", async
await page.getByText(updatedBreakpointName, { exact: true }).waitFor({
state: "hidden",
});
await page.keyboard.press("Escape");
// The new breakpoint has a minimum width of 0. Check the base font size
// once its override has been removed.
await test.step("verify the reloaded style properties", async () => {
await expectRepresentativeCanvasStyles();
await expectHoverCanvasStyle();
await page.mouse.move(0, 0);
const styles = await readSavedInstanceStyles();
expect(styles).toContainEqual(hoverColor);
expect(styles).not.toContainEqual(width);
});
});
@@ -1,57 +1,35 @@
import { expect } from "@playwright/test";
import { randomUUID } from "node:crypto";
import {
createAssetFolder,
deleteSelectedAsset,
openAssetSettings,
openAssetsPanel,
replaceSelectedAsset,
uploadAsset,
waitForAsset,
} from "../flows/assets-panel";
import {
openProjectBuilder,
waitForCanvasFrame,
waitForCanvasText,
} from "../flows/builder";
import { loadDevBuild } from "../db";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import {
selectCanvasImage,
waitForCanvasImage,
waitForCanvasImageCount,
waitForCanvasImageSourceName,
waitForCanvasVideoSource,
} from "../flows/canvas-media";
import {
waitForCanvasTextStyle,
waitForCanvasTextStyleCount,
} from "../flows/canvas-style";
import { chooseSelectedAssetProperty } from "../flows/props-panel";
import {
waitForChangeToBeSaved,
waitForSyncComplete,
} 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";
import { test } from "../test";
import { measure } from "../perf";
import { e2ePaidPlanName } from "../plans";
import { loadDevBuild } from "../db";
import { test } from "../test";
let fixture: SeededContentModeProject;
test.describe.configure({ mode: "parallel" });
test.beforeEach(async ({ context }) => {
fixture = await createContentModeProject({
test("Content templates persist with styles and assets, including after Builder copy/paste", async ({
context,
page,
}) => {
const fixture = await createContentModeProject({
context,
devPlan: e2ePaidPlanName,
email: `content-mode-assets-${randomUUID()}@webstudio.test`,
});
});
test("Content templates persist with styles and assets, including after Builder copy/paste", async ({
page,
}) => {
const getImageAssetReferenceCount = async () => {
const build = await loadDevBuild({ projectId: fixture.projectId });
const props = JSON.parse(build.props) as Array<{
@@ -81,11 +59,14 @@ test("Content templates persist with styles and assets, including after Builder
const initialAssetReferenceCount = await getImageAssetReferenceCount();
// Check each insertion on the canvas, then wait for the final save before
// opening the project as Builder and checking persistence across reloads.
await measure("content mode insert asset template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.assetTemplateName,
waitForProjectSync: false,
});
});
await waitForCanvasImage({
@@ -102,6 +83,7 @@ test("Content templates persist with styles and assets, including after Builder
page,
anchorText: "Initial content",
templateName: fixture.styledHeadingTemplateName,
waitForProjectSync: false,
});
});
await waitForCanvasText({
@@ -120,6 +102,7 @@ test("Content templates persist with styles and assets, including after Builder
page,
anchorText: "Initial content",
templateName: fixture.tokenTemplateLabel,
waitForProjectSync: false,
});
});
await waitForCanvasText({
@@ -138,6 +121,7 @@ test("Content templates persist with styles and assets, including after Builder
page,
anchorText: "Initial content",
templateName: fixture.isolatedLocalTemplateName,
waitForProjectSync: false,
});
await insertTemplateAfterCanvasText({
page,
@@ -236,188 +220,3 @@ test("Content templates persist with styles and assets, including after Builder
}
});
});
test("Editor can save assets, folders, and collection entries in content mode", async ({
page,
}) => {
const uploadFilename = "large-image.svg";
const replacementFilename = "replacement-image.svg";
const collectionName = "Content collection entries";
const folderName = "Editor ordinary assets";
const entryTitle = "Content collection entry";
const entryFilename = "content-collection-entry.mdx";
const assetsPanel = page.getByRole("tabpanel", { name: "Assets" });
const browseRoot = () =>
assetsPanel.getByRole("button", { name: "Root", exact: true }).click();
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForSyncComplete({ page });
await openAssetsPanel({ page });
const collection = await createAssetFolder({
page,
name: collectionName,
useAsContentCollection: true,
});
await collection.dblclick();
await page.getByRole("button", { name: "Collection settings" }).waitFor();
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await waitForSyncComplete({ page });
await openAssetsPanel({ page });
// The last folder is remembered for this project, including across modes.
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByRole("button", { name: "Add asset" }).click();
await page.getByRole("menuitem", { name: "New entry" }).click();
const dialog = page.getByRole("dialog", { name: "New entry" });
await dialog.getByLabel("Title *").fill(entryTitle);
await Promise.all([
waitForChangeToBeSaved({ page }),
dialog.getByRole("button", { name: "Create entry" }).click(),
]);
await waitForAsset({ page, filename: entryFilename });
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByTitle("template.mdx").waitFor({ state: "visible" });
await browseRoot();
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.imageReplacementTemplateName,
});
await waitForCanvasImage({
page,
alt: fixture.imageReplacementTemplateImageAlt,
});
let uploadedAssetTitle = "";
await measure("content mode upload image source asset", async () => {
await openAssetsPanel({ page });
uploadedAssetTitle = await uploadAsset({
page,
filename: uploadFilename,
});
});
await selectCanvasImage({
page,
alt: fixture.imageReplacementTemplateImageAlt,
});
await measure("content mode choose image source asset", async () => {
await chooseSelectedAssetProperty({
page,
label: "Source",
assetFilename: uploadFilename,
});
});
await waitForCanvasImageSourceName({ page, sourceName: "large-image_" });
const canvas = await waitForCanvasFrame({ page });
const uploadedImage = canvas.locator('img[src*="large-image_"]');
await expect(uploadedImage).toHaveAttribute("width", "240");
await expect(uploadedImage).toHaveAttribute("height", "160");
let replacementAssetTitle = "";
await measure("content mode replace used image source asset", async () => {
await openAssetsPanel({ page });
await openAssetSettings({
page,
filename: uploadedAssetTitle,
});
replacementAssetTitle = await replaceSelectedAsset({
page,
filename: replacementFilename,
});
});
await waitForCanvasImageSourceName({
page,
sourceName: "replacement-image_",
});
await waitForSyncComplete({ page });
const folder = await createAssetFolder({ page, name: folderName });
await folder.dblclick();
const deletedAsset =
await test.step("Upload, replace and delete an unused asset in the ordinary folder", async () => {
const uploadFilename = "upload-image.svg";
const replacementFilename = "large-image.svg";
let uploadedAssetTitle = "";
await measure("content mode upload asset", async () => {
uploadedAssetTitle = await uploadAsset({
page,
filename: uploadFilename,
});
});
let replacementAssetTitle = "";
await measure("content mode replace asset", async () => {
await openAssetSettings({ page, filename: uploadedAssetTitle });
const assetId = await page.locator("#asset-manager-id").inputValue();
if (assetId.length === 0) {
throw new Error(
"Expected Asset settings to expose the uploaded asset id"
);
}
await page.getByText("0 uses", { exact: true }).waitFor();
replacementAssetTitle = await replaceSelectedAsset({
page,
filename: replacementFilename,
});
});
await measure("content mode delete asset", async () => {
await openAssetSettings({ page, filename: replacementAssetTitle });
await deleteSelectedAsset({
page,
filename: replacementAssetTitle,
});
});
return { uploadedAssetTitle, replacementAssetTitle };
});
await browseRoot();
await collection.dblclick();
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await openAssetsPanel({ page });
await waitForAsset({ page, filename: entryFilename });
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByTitle("template.mdx").waitFor({ state: "visible" });
await browseRoot();
const expectDeletedAssetAbsent = async () => {
await expect(
assetsPanel.getByTitle(deletedAsset.uploadedAssetTitle)
).toHaveCount(0);
await expect(
assetsPanel.getByTitle(deletedAsset.replacementAssetTitle)
).toHaveCount(0);
};
await expectDeletedAssetAbsent();
await waitForCanvasImageSourceName({
page,
sourceName: "replacement-image_",
});
await page.getByTitle(replacementAssetTitle).waitFor();
await waitForSyncComplete({ page });
const reloadedCanvas = await waitForCanvasFrame({ page });
const replacementImage = reloadedCanvas.locator(
'img[src*="replacement-image_"]'
);
await expect(replacementImage).toHaveAttribute("width", "120");
await expect(replacementImage).toHaveAttribute("height", "80");
await folder.dblclick();
await expectDeletedAssetAbsent();
});
@@ -1,4 +1,4 @@
import { expect, type Page } from "@playwright/test";
import { expect } from "@playwright/test";
import { deleteContentBlockChildAfterCanvasText } from "../flows/block-outline";
import {
openProjectBuilder,
@@ -144,19 +144,6 @@ const getElementHrefWithText = async ({
return href.value;
};
const applyHistoryShortcut = async ({
page,
shortcut,
}: {
page: Page;
shortcut: "ControlOrMeta+Z" | "ControlOrMeta+Shift+Z";
}) => {
const save = waitForChangeToBeSaved({ page });
save.catch(() => undefined);
await page.keyboard.press(shortcut);
await save;
};
let fixture: SeededContentModeProject;
test.describe.configure({ mode: "parallel" });
@@ -188,6 +175,7 @@ test("Editor can paste, format and delete text while protected content remains",
page,
anchorText: "Initial content",
templateName: fixture.deletableTemplateName,
waitForProjectSync: false,
});
});
await waitForCanvasText({
@@ -247,14 +235,18 @@ test("Editor can paste, format and delete text while protected content remains",
}
await measure("content mode undo rich text formatting", async () => {
await applyHistoryShortcut({ page, shortcut: "ControlOrMeta+Z" });
await Promise.all([
waitForChangeToBeSaved({ page }),
page.keyboard.press("ControlOrMeta+Z"),
]);
await waitForCanvasTextHidden({ page, text: formattedText });
await waitForCanvasText({ page, text: fixture.shareLinkEditableText });
});
await waitForCanvasTextHidden({ page, text: formattedText });
await measure("content mode redo rich text formatting", async () => {
await applyHistoryShortcut({ page, shortcut: "ControlOrMeta+Shift+Z" });
await page.keyboard.press("ControlOrMeta+Shift+Z");
await waitForCanvasText({ page, text: formattedText });
});
await waitForCanvasText({ page, text: formattedText });
await selectCanvasTextInstanceForProps({
page,
@@ -369,14 +361,13 @@ test("Editor can paste, format and delete text while protected content remains",
page,
anchorText: "Initial content",
templateName: fixture.nestedTemplateName,
waitForProjectSync: false,
});
});
await waitForCanvasText({
page,
text: fixture.nestedTemplateText,
});
await waitForSyncComplete({ page });
await measure("content mode try nested delete", async () => {
const canvas = await waitForCanvasFrame({ page });
await page.keyboard.down("Alt");
@@ -433,6 +424,7 @@ test("Editor can edit text and content props but not design props", async ({
page,
anchorText: "Initial content",
templateName: fixture.styledHeadingTemplateName,
waitForProjectSync: false,
});
const styledTemplateHeading = canvas
.locator("h2")
@@ -463,13 +455,13 @@ test("Editor can edit text and content props but not design props", async ({
});
await page.keyboard.press("Enter");
await expect(canvas.locator("[contenteditable]")).toHaveCount(0);
await waitForSyncComplete({ page });
await expect(protectedImage).toBeVisible();
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.editableTextTemplateName,
waitForProjectSync: false,
});
await waitForCanvasText({
page,
@@ -480,6 +472,7 @@ test("Editor can edit text and content props but not design props", async ({
page,
anchorText: fixture.editableTextTemplateText,
templateName: fixture.contentPropsTemplateName,
waitForProjectSync: false,
});
await waitForCanvasText({
page,
@@ -502,6 +495,7 @@ test("Editor can edit text and content props but not design props", async ({
page,
currentText: fixture.editableTextTemplateText,
text: editedContent,
waitForProjectSync: false,
});
});
@@ -529,41 +523,33 @@ test("Editor can edit text and content props but not design props", async ({
text: fixture.contentPropsTemplateLinkText,
propertyLabel: "Href",
});
await fillSelectedStringProperty({
page,
label: "Href",
control: "url",
value: editedHref,
});
const urlInput = page.getByPlaceholder("https://www.url.com").first();
await urlInput.fill(editedHref);
await urlInput.blur();
await selectCanvasImage({
page,
alt: fixture.contentPropsTemplateImageAlt,
});
await fillSelectedStringProperty({
page,
label: "Source",
control: "url",
value: editedImageSrc,
});
await fillSelectedStringProperty({
page,
label: "Alt",
control: "text",
value: editedImageAlt,
});
await expect(page.getByText("Source", { exact: true }).first()).toBeVisible();
await urlInput.fill(editedImageSrc);
await urlInput.blur();
await expect(page.getByText("Alt", { exact: true }).first()).toBeVisible();
const altInput = page.locator("textarea").first();
await altInput.fill(editedImageAlt);
await altInput.blur();
await expectTextHidden({ page, text: "Width" });
await selectCanvasVideoSource({
page,
sourceName: fixture.contentPropsTemplateVideoName,
});
await fillSelectedStringProperty({
page,
label: "Source",
control: "url",
value: editedVideoSrc,
});
await expect(page.getByText("Source", { exact: true }).first()).toBeVisible();
await urlInput.fill(editedVideoSrc);
await urlInput.blur();
// Verify each edit after a single save barrier and reload.
await waitForSyncComplete({ page });
await measure("content mode reload editor for props", async () => {
await openProjectBuilder({
@@ -1,3 +1,4 @@
import { createReadStream } from "node:fs";
import { expect } from "@playwright/test";
import {
blockBodyComponent,
@@ -11,18 +12,14 @@ import type {
StyleSource,
StyleSourceSelection,
} from "@webstudio-is/sdk";
import { loadDevBuild, updateBuild } from "../db";
import { createAssetClient } from "../../app/shared/asset-client";
import { insertAsset, insertFile, loadDevBuild, updateBuild } from "../db";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import {
openProjectBuilder,
waitForCanvasFrame,
waitForCanvasText,
} from "../flows/builder";
import {
getAssetIdByFilename,
openAssetsPanel,
uploadAsset,
} from "../flows/assets-panel";
import { selectCanvasImage } from "../flows/canvas-media";
import { replaceCanvasText } from "../flows/content-editing";
import { fillSelectedStringProperty } from "../flows/props-panel";
@@ -231,31 +228,40 @@ test("Editor can edit legacy document bindings before a Builder visits", async (
browser,
}) => {
const filename = "content-source.mdx";
const { fixture, assetId } = await withBrowserContext(
browser,
async (context) => {
const fixture = await createContentModeProject({
context,
devPlan: e2ePaidPlanName,
email: "legacy-bindings@webstudio.test",
title: "Legacy document bindings",
});
const setupPage = await context.newPage();
await openProjectBuilder({
page: setupPage,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await openAssetsPanel({ page: setupPage });
await uploadAsset({ page: setupPage, filename });
return {
fixture,
assetId: await getAssetIdByFilename({ page: setupPage, filename }),
};
}
const fixture = await withBrowserContext(browser, (context) =>
createContentModeProject({
context,
devPlan: e2ePaidPlanName,
email: "legacy-bindings@webstudio.test",
title: "Legacy document bindings",
})
);
// Seed the old representation only after the setup browser has closed.
const build = await loadDevBuild({ projectId: fixture.projectId });
// Seed the document before opening Builder so the Editor is its first reader.
const name = `${fixture.projectId}-${filename}`;
const [assetData, build] = await Promise.all([
createAssetClient().uploadFile(
name,
"file",
createReadStream(
new URL(`../fixtures/assets/${filename}`, import.meta.url)
),
undefined
),
loadDevBuild({ projectId: fixture.projectId }),
]);
await insertFile({
name,
...assetData,
meta: JSON.stringify(assetData.meta),
status: "UPLOADED",
uploaderProjectId: fixture.projectId,
});
const { id: assetId } = await insertAsset({
id: `${fixture.projectId}-legacy-document`,
projectId: fixture.projectId,
name,
filename,
});
const instances: Instance[] = JSON.parse(build.instances);
const props: Prop[] = JSON.parse(build.props);
const dataSources: DataSource[] = JSON.parse(build.dataSources);
@@ -214,55 +214,66 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
])
);
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");
// Verify both read paths before the Builder role changes the saved page.
const readResults = await Promise.allSettled([
test.step("verify saved MCP edits in Builder", async () => {
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");
await openAssetsPanel({ page });
await page
.getByRole("button", { name: "Folder Editor MCP assets" })
.dblclick();
await waitForAsset({ page, filename });
const beforeViewerWrites = await loadDevBuild({
projectId: fixture.projectId,
});
expect((await call("list-pages", {}, "viewer")).ok).toBe(true);
for (const [tool, input] of [
[
"create-page-from-template",
{ templateId: template.id, name: "Denied", path: "/denied" },
],
["create-asset-folder", { name: "Denied folder" }],
[
"upload-asset",
{
asset: { name: filename, type: "file", format: "txt" },
assetsDir: directory,
},
],
] as const) {
const denied = await call(tool, input, "viewer");
expect(denied.ok, tool).toBe(false);
expect(denied.error.code, `${tool}: ${denied.error.message}`).toBe(
"FORBIDDEN"
);
await openAssetsPanel({ page });
await page
.getByRole("button", { name: "Folder Editor MCP assets" })
.dblclick();
await waitForAsset({ page, filename });
}),
test.step("verify the MCP viewer cannot write", async () => {
const beforeViewerWrites = await loadDevBuild({
projectId: fixture.projectId,
});
expect((await call("list-pages", {}, "viewer")).ok).toBe(true);
for (const [tool, input] of [
[
"create-page-from-template",
{ templateId: template.id, name: "Denied", path: "/denied" },
],
["create-asset-folder", { name: "Denied folder" }],
[
"upload-asset",
{
asset: { name: filename, type: "file", format: "txt" },
assetsDir: directory,
},
],
] as const) {
const denied = await call(tool, input, "viewer");
expect(denied.ok, tool).toBe(false);
expect(denied.error.code, `${tool}: ${denied.error.message}`).toBe(
"FORBIDDEN"
);
}
const afterViewerWrites = await loadDevBuild({
projectId: fixture.projectId,
});
expect(afterViewerWrites.version).toBe(beforeViewerWrites.version);
expect(afterViewerWrites.pages).toEqual(beforeViewerWrites.pages);
}),
]);
for (const result of readResults) {
if (result.status === "rejected") {
throw result.reason;
}
}
const afterViewerWrites = await loadDevBuild({
projectId: fixture.projectId,
});
expect(afterViewerWrites.version).toBe(beforeViewerWrites.version);
expect(afterViewerWrites.pages).toEqual(beforeViewerWrites.pages);
const builderWrite = await call(
"update-page-settings",
@@ -1,6 +1,6 @@
import { createServer } from "node:http";
import { expect } from "@playwright/test";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { createBuilderEditingProject } from "../fixtures/builder-editing-project";
import { loadDevBuild } from "../db";
import { startFormDeliveryReceiver } from "../flows/generated-form-delivery";
import { withMcpEmailHttpPreview } from "../flows/mcp-email-http-preview";
@@ -23,12 +23,9 @@ test("Builder and MCP Form actions deliver from generated Preview", async ({
}) => {
test.setTimeout(240_000);
await startPreviewFormMcpClient();
const fixture = await createContentModeProject({
const fixture = await createBuilderEditingProject({
context,
email: "mcp-email-scenarios@webstudio.test",
title: "MCP Email scenarios",
assetNamePrefix: "mcp-email-scenarios-",
builderToken: "mcp-email-scenarios-builder-token",
name: "mcp-email-scenarios",
});
await test.step("save the legacy Webhook Form action through Builder", async () => {
await configureSavedWebhookForm({ page, fixture });
@@ -1,191 +0,0 @@
import { execFile } from "node:child_process";
import { createServer, type ServerResponse } 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 { withGeneratedFormDeliveryPreview } from "../flows/generated-form-delivery";
import {
startPreviewFormMcpClient,
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 reactGlobalPath = fileURLToPath(
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
);
const startBarrierReceiver = async () => {
const deliveries: string[] = [];
const pending: ServerResponse[] = [];
let barrierReached = false;
let timeout: ReturnType<typeof setTimeout> | undefined;
const receiver = createServer(async (request, response) => {
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.from(chunk));
}
if (request.method !== "POST" || request.url !== "/submit") {
response.writeHead(404).end();
return;
}
deliveries.push(Buffer.concat(chunks).toString("utf8"));
if (deliveries.length > 3) {
response.writeHead(409).end();
return;
}
if (barrierReached) {
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({ delivered: true }));
return;
}
pending.push(response);
if (pending.length === 1) {
// A serial dispatcher can never get the second response before the first.
timeout = setTimeout(() => {
for (const waiting of pending.splice(0)) {
waiting.writeHead(504).end("Second Action did not arrive");
}
}, 10_000);
} else {
barrierReached = true;
clearTimeout(timeout);
for (const waiting of pending.splice(0)) {
waiting.writeHead(200, { "content-type": "application/json" });
waiting.end(JSON.stringify({ delivered: true }));
}
}
});
await new Promise<void>((resolve, reject) => {
receiver.once("error", reject);
receiver.listen(0, "127.0.0.1", resolve);
});
const address = receiver.address();
if (address === null || typeof address === "string") {
throw new Error("Expected a local receiver port");
}
return {
port: address.port,
deliveries,
get barrierReached() {
return barrierReached;
},
close: async () => {
clearTimeout(timeout);
for (const waiting of pending.splice(0)) {
waiting.writeHead(503).end();
}
await new Promise<void>((resolve) => receiver.close(() => resolve()));
},
};
};
test("MCP-authored Form starts connected Actions concurrently and runs all three", async ({
context,
}) => {
await startPreviewFormMcpClient();
const fixture = await createContentModeProject({
context,
email: "mcp-form-action-concurrency@webstudio.test",
title: "MCP Form Action concurrency",
assetNamePrefix: "mcp-form-action-concurrency-",
builderToken: "mcp-form-action-concurrency-builder-token",
});
const { stdout } = await execFileAsync(
process.execPath,
[
"--import",
"tsx",
"--import",
reactGlobalPath,
"--conditions=webstudio",
authorPath,
fixture.projectId,
],
{
timeout: 60_000,
env: {
...process.env,
TSX_TSCONFIG_PATH: fileURLToPath(
new URL(
"../../../../packages/cli/tsconfig.local.json",
import.meta.url
)
),
},
}
);
const { formId, graphqlResourceId, httpResourceId, middleResourceId } =
JSON.parse(stdout) as {
formId: string;
graphqlResourceId: string;
httpResourceId: string;
middleResourceId: string;
};
const receiver = await startBarrierReceiver();
try {
await withGeneratedFormDeliveryPreview({
projectId: fixture.projectId,
receiverPort: receiver.port,
callback: async ({ url }) => {
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: "Parallel Actions" },
{ name: "message", value: "Both receivers" },
],
submitter: "button[type=submit]",
timeout: 30_000,
},
})
).data;
expect(receiver.barrierReached).toBe(true);
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([
expect.objectContaining({
resourceId: graphqlResourceId,
status: 200,
}),
expect.objectContaining({
resourceId: middleResourceId,
status: 200,
}),
expect.objectContaining({ resourceId: httpResourceId, status: 200 }),
]);
expect(receiver.deliveries).toHaveLength(3);
expect(
receiver.deliveries.some((body) => body.includes("mutation Record"))
).toBe(true);
expect(
receiver.deliveries.some((body) =>
body.includes('"subject":"Parallel Actions"')
)
).toBe(true);
},
});
} finally {
await receiver.close();
}
});
@@ -1,6 +1,9 @@
import { expect } from "@playwright/test";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { startFormCallbackReceiver } from "../flows/form-callback-receiver";
import {
concurrencyPath,
startFormCallbackReceiver,
} from "../flows/form-callback-receiver";
import { withGeneratedPreview } from "../flows/generated-app";
import { runFormAuthor } from "../flows/mcp-form-author";
import {
@@ -11,7 +14,7 @@ import { test } from "../test";
const managedPath = "/managed-callbacks";
test("Generated Preview runs legacy and managed Form callbacks and preserves query values", async ({
test("Generated Preview runs Form callbacks, concurrent Actions, and query navigation", async ({
page,
context,
}) => {
@@ -24,13 +27,19 @@ test("Generated Preview runs legacy and managed Form callbacks and preserves que
});
const receiver = await startFormCallbackReceiver();
try {
await runFormAuthor(
"mcp-form-callbacks-author",
const { stdout } = await runFormAuthor(
"mcp-form-callbacks-and-actions-author",
fixture.projectId,
"legacy-and-managed",
"https://mcp-delivery.example/submit",
managedPath
managedPath,
concurrencyPath
);
const { formId, graphqlResourceId, httpResourceId, middleResourceId } =
JSON.parse(stdout) as {
formId: string;
graphqlResourceId: string;
httpResourceId: string;
middleResourceId: string;
};
await withGeneratedPreview({
projectId: fixture.projectId,
evaluationReceiverPort: String(receiver.port),
@@ -206,6 +215,65 @@ test("Generated Preview runs legacy and managed Form callbacks and preserves que
)
.toBe(documentMarker);
});
await test.step("managed Form starts the connected Actions concurrently and runs all three", 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: "Parallel Actions" },
{ name: "message", value: "Both receivers" },
],
submitter: "button[type=submit]",
timeout: 30_000,
},
})
).data;
expect(receiver.barrierReached).toBe(true);
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([
expect.objectContaining({
resourceId: graphqlResourceId,
status: 200,
}),
expect.objectContaining({
resourceId: middleResourceId,
status: 200,
}),
expect.objectContaining({
resourceId: httpResourceId,
status: 200,
}),
]);
expect(receiver.actionDeliveries).toHaveLength(3);
expect(
receiver.actionDeliveries.some((body) =>
body.includes("mutation Record")
)
).toBe(true);
expect(
receiver.actionDeliveries.some((body) =>
body.includes('"subject":"Parallel Actions"')
)
).toBe(true);
});
},
});
} finally {
@@ -119,9 +119,11 @@ test("Project redirects and MCP-authored Forms run in the same generated product
try {
const receiver = await startFormDeliveryReceiver();
try {
const verifyPreview = (redirect: { from: string; to: string }) =>
const verifyPreview: Parameters<
typeof withSavedProjectRedirect
>[0]["verifyPreview"] = ({ redirect, build }) =>
withMcpEmailHttpPreview({
projectId: fixture.projectId,
build,
emailPort: emailReceiver.port,
httpPort: receiver.port,
callback: async ({ url }) => {
@@ -2,7 +2,7 @@ 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 { createBuilderEditingProject } from "../fixtures/builder-editing-project";
import { waitForCanvasFrame } from "../flows/builder";
import { startFormDeliveryReceiver } from "../flows/generated-form-delivery";
import { selectCanvasTextInstance } from "../flows/canvas-selection";
@@ -52,12 +52,9 @@ test("MCP-authored Form submission exposes its saved HTTP exchange without anoth
page,
context,
}) => {
const fixture = await createContentModeProject({
const fixture = await createBuilderEditingProject({
context,
email: "mcp-form-resource-snapshot@webstudio.test",
title: "MCP Form Resource submission snapshot",
assetNamePrefix: "mcp-form-resource-snapshot-",
builderToken: "mcp-form-resource-snapshot-builder-token",
name: "mcp-form-resource-snapshot",
});
const receiver = await startFormDeliveryReceiver();
const actionUrl = `http://127.0.0.1:${receiver.port}/submit`;
@@ -2,7 +2,7 @@ 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 { createProjectThroughApi } from "../fixtures/create-project";
import {
startFormDeliveryReceiver,
withGeneratedFormDeliveryPreview,
@@ -197,16 +197,14 @@ test("MCP Forms preserve action order, redirect, and feedback in generated Previ
}) => {
test.setTimeout(240_000);
await startPreviewFormMcpClient();
const fixture = await createContentModeProject({
const projectId = await createProjectThroughApi({
context,
email: "mcp-form-redirect-combined@webstudio.test",
title: "MCP Form redirect outcomes",
assetNamePrefix: "mcp-form-redirect-combined-",
builderToken: "mcp-form-redirect-combined-builder-token",
});
const { successful, failed, feedback, combination } = await measure(
"MCP author Form outcomes",
() => authorForms(fixture.projectId)
() => authorForms(projectId)
);
const { formId, graphqlResourceId, middleResourceId, httpResourceId } =
combination;
@@ -217,7 +215,7 @@ test("MCP Forms preserve action order, redirect, and feedback in generated Previ
const receiver = await startFormDeliveryReceiver();
try {
await withGeneratedFormDeliveryPreview({
projectId: fixture.projectId,
projectId,
receiverPort: receiver.port,
callback: async ({ url }) => {
await test.step("MCP Form dispatches Actions in configured result order", async () => {
@@ -8,7 +8,11 @@ import {
prepareMdxEditorPages,
} from "../fixtures/mdx-content-block-project";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { openAssetsPanel, uploadAsset } from "../flows/assets-panel";
import {
openAssetsPanel,
uploadAsset,
uploadAssets,
} from "../flows/assets-panel";
import {
openProjectBuilder,
waitForCanvasFrame,
@@ -35,7 +39,7 @@ import { openNavigatorPanel } from "../flows/navigator";
import { openPage } from "../flows/pages-panel";
import { selectCanvasTextInstanceForProps } from "../flows/canvas-selection";
import { fillSelectedStringProperty } from "../flows/props-panel";
import { getProjectBuilderUrl, test } from "../test";
import { getProjectBuilderUrl, newIsolatedPage, test } from "../test";
import { e2ePaidPlanName } from "../plans";
test.describe.configure({ mode: "parallel" });
@@ -188,9 +192,18 @@ const openFixture = async ({
await waitForSyncComplete({ page });
};
const openMdxEditor = async (page: Page) => {
await selectContentBlock({ page });
await page.getByRole("button", { name: "Open", exact: true }).click();
const editor = page.getByRole("dialog").locator(".cm-content");
await editor.waitFor({ state: "visible" });
return editor;
};
test("Content Block MDX source lifecycle persists edits and resets to empty", async ({
page,
context,
browser,
}) => {
// This full lifecycle repeatedly reloads Builder across two roles. CI can
// exhaust the default two-minute budget at the final reload assertion.
@@ -209,8 +222,7 @@ test("Content Block MDX source lifecycle persists edits and resets to empty", as
authToken: fixture.builderToken,
});
await openAssetsPanel({ page });
await uploadAsset({ page, filename: sourceFilename });
await uploadAsset({ page, filename: alternateFilename });
await uploadAssets({ page, filenames: [sourceFilename, alternateFilename] });
await selectContentBlock({ page });
await chooseContentBlockSource({ page, filename: sourceFilename });
@@ -292,37 +304,25 @@ test("Content Block MDX source lifecycle persists edits and resets to empty", as
"Editing a plain Content Block template must persist as Markdown"
);
}
await openFixture({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await selectContentBlock({ page });
await page.getByRole("button", { name: "Open", exact: true }).click();
const fileEditor = page.getByRole("dialog").locator(".cm-content");
await fileEditor.waitFor({ state: "visible" });
if ((await fileEditor.textContent())?.includes(editedTemplateText) !== true) {
throw new Error(
"Opening an MDX Asset after a canvas save must show the latest content"
);
}
const rawEditorHeading = "Raw editor heading";
const rawEditorWrite = waitForAssetWrite(page, (source) =>
source.includes(`## ${rawEditorHeading}`)
);
await fileEditor.click();
await page.keyboard.press("ControlOrMeta+End");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type(`## ${rawEditorHeading}`);
await page.keyboard.press("Escape");
await waitForCanvasText({ page, text: rawEditorHeading });
await rawEditorWrite;
await openFixture({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
await test.step("A fresh Builder reads the saved template edit", async () => {
const { page: builderPage, close } = await newIsolatedPage(browser);
try {
await openFixture({
page: builderPage,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
const fileEditor = await openMdxEditor(builderPage);
if (
(await fileEditor.textContent())?.includes(editedTemplateText) !== true
) {
throw new Error(
"Opening an MDX asset after a canvas save must show the saved template edit"
);
}
} finally {
await close();
}
});
await Promise.all([
waitForAssetWrite(page),
@@ -425,8 +425,31 @@ test("Content Block MDX source lifecycle persists edits and resets to empty", as
});
await waitForCanvasText({ page, text: editedHeading });
await waitForCanvasTextHidden({ page, text: editedTemplateText });
await selectContentBlock({ page });
const fileEditor = await openMdxEditor(page);
const savedSource = await fileEditor.textContent();
if (savedSource?.includes(editedHeading) !== true) {
throw new Error(
"Opening an MDX Asset after a canvas save must show the latest content"
);
}
if (savedSource.includes(editedTemplateText)) {
throw new Error("Opening the MDX asset must omit the deleted template");
}
const rawEditorHeading = "Raw editor heading";
const rawEditorWrite = waitForAssetWrite(page, (source) =>
source.includes(`## ${rawEditorHeading}`)
);
await fileEditor.click();
await page.keyboard.press("ControlOrMeta+End");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type(`## ${rawEditorHeading}`);
await page.keyboard.press("Escape");
await waitForCanvasText({ page, text: rawEditorHeading });
await rawEditorWrite;
await selectContentBlock({ page });
await chooseContentBlockSource({
page,
filename: alternateFilename,
@@ -436,10 +459,7 @@ test("Content Block MDX source lifecycle persists edits and resets to empty", as
await waitForCanvasText({ page, text: alternateHeading });
await waitForCanvasTextHidden({ page, text: editedHeading });
await selectContentBlock({ page });
await page.getByRole("button", { name: "Open", exact: true }).click();
const alternateEditor = page.getByRole("dialog").locator(".cm-content");
await alternateEditor.waitFor({ state: "visible" });
const alternateEditor = await openMdxEditor(page);
if (
(await alternateEditor.textContent())?.includes(alternateHeading) !== true
) {
@@ -812,7 +832,7 @@ test("MDX template warnings and renamed templates resolve in the right modes", a
await chooseContentBlockSource({ page, filename: namedTemplateFilename });
await confirmContentBlockConnection({ page });
await waitForCanvasText({ page, text: "Authored lifecycle card" });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
await waitForCanvasText({ page, text: "Valid MDX sibling" });
await waitForCanvasText({
@@ -1,4 +1,4 @@
import type { Page } from "@playwright/test";
import { expect, type Page } from "@playwright/test";
import {
openProjectBuilder,
waitForCanvasText,
@@ -6,7 +6,10 @@ import {
} from "../flows/builder";
import { selectCanvasTextInstance } from "../flows/canvas-selection";
import { openNavigatorPanel } from "../flows/navigator";
import { waitForChangeToBeSaved } from "../flows/sync-status";
import {
waitForChangeToBeSaved,
waitForSyncComplete,
} 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";
@@ -114,10 +117,7 @@ const insertComponentPanelOption = async ({
name: string;
}) => {
await searchComponentsPanel({ page, text: name });
await Promise.all([
waitForChangeToBeSaved({ page }),
page.getByRole("option", { name, exact: true }).click(),
]);
await page.getByRole("option", { name, exact: true }).click();
};
const getNavigatorButtonSummary = async ({
@@ -179,7 +179,7 @@ const selectNavigatorContextAction = async ({
`Expected Navigator ${action} action to be enabled. aria-disabled=${ariaDisabled}, data-disabled=${dataDisabled}`
);
}
await Promise.all([waitForChangeToBeSaved({ page }), menuItem.click()]);
await menuItem.click();
};
test.beforeEach(async ({ browser }) => {
@@ -276,69 +276,42 @@ test("Builder filters the catalog and persists component actions from shortcuts
});
await selectCanvasTextInstance({ page, text: "Initial content" });
const initialCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
const readComponentCount = () =>
getInstanceComponentCount({ fixture, component: componentName });
const initialCount = await readComponentCount();
// The persisted count is available before the sync indicator returns to idle.
const expectSavedComponentCount = (count: number, action: string) =>
expect
.poll(readComponentCount, {
message: action,
intervals: [100, 250],
timeout: 10_000,
})
.toBe(count);
await measure(
"pages actions insert component before command duplicate",
async () => {
await openComponentsPanel({ page });
await insertComponentPanelOption({ page, name: componentName });
await expectSavedComponentCount(initialCount + 1, "Insert one Image");
}
);
const insertedCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (insertedCount !== initialCount + 1) {
throw new Error(
`Expected components panel to insert one ${componentName}. Before ${initialCount}, after ${insertedCount}`
);
}
await measure("pages actions duplicate inserted component", async () => {
await Promise.all([
waitForChangeToBeSaved({ page }),
page.keyboard.press("ControlOrMeta+D"),
]);
await page.keyboard.press("ControlOrMeta+D");
await expectSavedComponentCount(initialCount + 2, "Duplicate the Image");
});
const duplicatedCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (duplicatedCount !== initialCount + 2) {
throw new Error(
`Expected duplicate command to add one ${componentName}. Before ${initialCount}, after ${duplicatedCount}`
);
}
await measure("pages actions undo duplicate command", async () => {
await selectSavedAppMenuItem({ page, name: "Undo" });
await selectAppMenuItem({ page, name: "Undo" });
await expectSavedComponentCount(initialCount + 1, "Undo the shortcut");
});
const undoCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (undoCount !== initialCount + 1) {
throw new Error(
`Expected undo to remove duplicated ${componentName}. Before ${initialCount}, after ${undoCount}`
);
}
await measure("pages actions redo duplicate command", async () => {
await selectSavedAppMenuItem({ page, name: "Redo" });
await selectAppMenuItem({ page, name: "Redo" });
await expectSavedComponentCount(initialCount + 2, "Redo the shortcut");
});
const redoCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (redoCount !== initialCount + 2) {
throw new Error(
`Expected redo to restore duplicated ${componentName}. Before ${initialCount}, after ${redoCount}`
);
}
await measure(
"pages actions duplicate component from navigator",
@@ -349,43 +322,35 @@ test("Builder filters the catalog and persists component actions from shortcuts
itemName: componentName,
action: "Duplicate",
});
try {
await expectSavedComponentCount(
initialCount + 3,
"Duplicate from Navigator"
);
} catch (error) {
throw new Error(
`Components: ${await getInstanceComponentCountSummary(fixture)}. Navigator: ${JSON.stringify(await getNavigatorButtonSummary({ page, text: componentName }))}`,
{ cause: error }
);
}
}
);
const navigatorDuplicateCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (navigatorDuplicateCount !== redoCount + 1) {
throw new Error(
`Expected Navigator duplicate to add one ${componentName}. Before ${redoCount}, after ${navigatorDuplicateCount}. Components: ${await getInstanceComponentCountSummary(fixture)}. Navigator: ${JSON.stringify(await getNavigatorButtonSummary({ page, text: componentName }))}`
);
}
await measure("pages actions undo navigator duplicate", async () => {
await selectSavedAppMenuItem({ page, name: "Undo" });
});
const undoDuplicateCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (undoDuplicateCount !== redoCount) {
throw new Error(
`Expected undo to remove Navigator duplicate ${componentName}. Before ${redoCount}, after ${undoDuplicateCount}`
await selectAppMenuItem({ page, name: "Undo" });
await expectSavedComponentCount(
initialCount + 2,
"Undo Navigator duplicate"
);
}
});
await measure("pages actions redo navigator duplicate", async () => {
await selectSavedAppMenuItem({ page, name: "Redo" });
});
const redoDuplicateCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (redoDuplicateCount !== redoCount + 1) {
throw new Error(
`Expected redo to restore Navigator duplicate ${componentName}. Before ${redoCount}, after ${redoDuplicateCount}`
await selectAppMenuItem({ page, name: "Redo" });
await expectSavedComponentCount(
initialCount + 3,
"Redo Navigator duplicate"
);
}
});
await measure("pages actions delete component from navigator", async () => {
await openNavigatorPanel({ page });
@@ -394,29 +359,14 @@ test("Builder filters the catalog and persists component actions from shortcuts
itemName: componentName,
action: "Delete",
});
await expectSavedComponentCount(initialCount + 2, "Delete from Navigator");
});
const deletedCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (deletedCount !== redoCount) {
throw new Error(
`Expected Navigator delete to remove one ${componentName}. Before ${redoCount}, after ${deletedCount}`
);
}
await measure("pages actions undo navigator delete", async () => {
await selectSavedAppMenuItem({ page, name: "Undo" });
await selectAppMenuItem({ page, name: "Undo" });
await expectSavedComponentCount(initialCount + 3, "Undo Navigator delete");
await waitForSyncComplete({ page });
});
const undoDeleteCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (undoDeleteCount !== redoCount + 1) {
throw new Error(
`Expected undo to restore Navigator-deleted ${componentName}. Before ${redoCount}, after ${undoDeleteCount}`
);
}
await measure("pages actions reload component mutations", async () => {
await openProjectBuilder({
@@ -426,13 +376,5 @@ test("Builder filters the catalog and persists component actions from shortcuts
});
});
await waitForCanvasText({ page, text: insertedButtonText });
const reloadedCount = await getInstanceComponentCount({
fixture,
component: componentName,
});
if (reloadedCount !== initialCount + 3) {
throw new Error(
`Expected reload to preserve component actions for ${componentName}. Before ${initialCount}, after ${reloadedCount}`
);
}
expect(await readComponentCount()).toBe(initialCount + 3);
});
@@ -1,4 +1,4 @@
import { expect, type Page } from "@playwright/test";
import { expect, type Browser, type Page } from "@playwright/test";
import { expectTextHidden } from "../flows/assertions";
import {
getCanvasFrame,
@@ -15,16 +15,16 @@ import {
openPagesPanel,
openTemplateSettings,
} from "../flows/pages-panel";
import { waitForChangeToBeSaved } from "../flows/sync-status";
import {
waitForChangeToBeSaved,
waitForSyncComplete,
} from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import type { SeededContentModeProject } from "../fixtures/content-mode-project";
import { test, withBrowserContext } from "../test";
import { measure } from "../perf";
import { loadDevBuild, updateBuild } from "../db";
let fixture: SeededContentModeProject;
let pasteFixture: SeededContentModeProject;
test.describe.configure({ mode: "parallel" });
const copiedPageTransferMarker = "@webstudio/page/v0.1";
@@ -79,14 +79,26 @@ const waitForTemplate = async ({
await getTreeButton({ page, itemName: templateName }).waitFor();
};
const waitForCopiedPageTransferData = async ({ page }: { page: Page }) => {
await page.waitForFunction(async (marker) => {
try {
return (await navigator.clipboard.readText()).includes(marker as string);
} catch {
return false;
}
}, copiedPageTransferMarker);
const waitForCopiedPageTransferData = async ({
page,
type,
name,
}: {
page: Page;
type: "page" | "folder" | "template";
name: string;
}) => {
await page.waitForFunction(
async ({ marker, type, name }) => {
try {
const data = JSON.parse(await navigator.clipboard.readText())[marker];
return data?.type === type && data[type]?.name === name;
} catch {
return false;
}
},
{ marker: copiedPageTransferMarker, type, name }
);
};
const getDataResourceCounts = async (fixture: SeededContentModeProject) => {
@@ -205,27 +217,15 @@ const confirmDialogAction = async ({
await button.waitFor({ state: "hidden" });
};
test.beforeAll(async ({ browser }, workerInfo) => {
const workerSuffix = `worker-${workerInfo.parallelIndex}`;
await withBrowserContext(browser, async (context) => {
fixture = await createContentModeProject({
const createPagesFixture = (browser: Browser, scenario: string) =>
withBrowserContext(browser, (context) =>
createContentModeProject({
context,
email: `pages-actions-pages-${workerSuffix}@webstudio.test`,
email: `pages-actions-${scenario}@webstudio.test`,
title: "Pages Actions E2E",
assetNamePrefix: `pages-actions-pages-${workerSuffix}-`,
editorToken: `pages-actions-pages-${workerSuffix}-editor-token`,
builderToken: `pages-actions-pages-${workerSuffix}-builder-token`,
});
pasteFixture = await createContentModeProject({
context,
email: `pages-actions-pages-paste-${workerSuffix}@webstudio.test`,
title: "Pages Actions Paste E2E",
assetNamePrefix: `pages-actions-pages-paste-${workerSuffix}-`,
editorToken: `pages-actions-pages-paste-${workerSuffix}-editor-token`,
builderToken: `pages-actions-pages-paste-${workerSuffix}-builder-token`,
});
});
});
assetNamePrefix: `pages-actions-${scenario}-`,
})
);
test("Canvas switches away from an AnimateText page without reloading", async ({
browser,
@@ -322,8 +322,10 @@ test("Canvas switches away from an AnimateText page without reloading", async ({
});
test("Builder can draft, stage, copy, duplicate, and delete a page from the header menu", async ({
browser,
page,
}) => {
const fixture = await createPagesFixture(browser, "page");
const pageName = "Actions Menu Page";
const renamedPageName = "Renamed Actions Menu Page";
const copiedPageName = `${renamedPageName} (1)`;
@@ -404,7 +406,11 @@ test("Builder can draft, stage, copy, duplicate, and delete a page from the head
menuLabel: "Page actions",
action: "Copy",
});
await waitForCopiedPageTransferData({ page });
await waitForCopiedPageTransferData({
page,
type: "page",
name: renamedPageName,
});
await pasteFromClipboardShortcut({ page });
await waitForPageRow({ page, pageName: copiedPageName });
@@ -479,148 +485,124 @@ test("Builder can draft, stage, copy, duplicate, and delete a page from the head
await expectDataResourceCopies(fixture, dataResourceCountsBefore);
});
test("Builder can copy, duplicate, and delete a folder from the context menu", async ({
test("Builder can rename, copy, duplicate, and delete folders and page templates", async ({
browser,
page,
}) => {
const fixture = await createPagesFixture(browser, "folder-template");
const folderName = "Actions Menu Folder";
const renamedFolderName = "Renamed Actions Menu Folder";
const copiedFolderName = `${renamedFolderName} (1)`;
const duplicatedFolderName = `${renamedFolderName} (2)`;
await measure("pages actions open builder for folder actions", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await createFolder({ page, folderName });
await openFolderSettings({ page, folderName });
const renameSave = waitForChangeToBeSaved({ page });
await page.getByLabel("Folder name", { exact: true }).fill(renamedFolderName);
await page.getByLabel("Folder name", { exact: true }).blur();
await renameSave;
await waitForFolderRow({ page, folderName: renamedFolderName });
await expectTextHidden({ page, text: folderName });
await selectContextAction({
page,
itemName: renamedFolderName,
action: "Copy",
});
await waitForCopiedPageTransferData({ page });
const pasteSave = waitForChangeToBeSaved({ page });
await selectContextAction({ page, itemName: "Home", action: "Paste" });
await pasteSave;
await waitForFolderRow({ page, folderName: copiedFolderName });
const duplicateSave = waitForChangeToBeSaved({ page });
await selectContextAction({
page,
itemName: renamedFolderName,
action: "Duplicate",
});
await duplicateSave;
await waitForFolderRow({ page, folderName: duplicatedFolderName });
await selectContextAction({
page,
itemName: duplicatedFolderName,
action: "Delete",
});
const deleteSave = waitForChangeToBeSaved({ page });
await confirmDialogAction({ page, action: "Delete" });
await deleteSave;
await expectTextHidden({ page, text: duplicatedFolderName });
await measure(
"pages actions reload for folder action persistence",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
}
);
await openPagesPanel({ page });
await waitForFolderRow({ page, folderName: renamedFolderName });
await expectTextHidden({ page, text: folderName });
await waitForFolderRow({ page, folderName: copiedFolderName });
await openFolderSettings({ page, folderName: copiedFolderName });
await expectTextHidden({ page, text: duplicatedFolderName });
});
test("Builder can copy, duplicate, and delete a page template from actions menus", async ({
page,
}) => {
const templateName = fixture.pageTemplateName;
const renamedTemplateName = "Renamed Content Page Template";
const copiedTemplateName = `${renamedTemplateName} (1)`;
const duplicatedTemplateName = `${renamedTemplateName} (2)`;
await measure("pages actions open builder for template actions", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await test.step("Folder context menu actions", async () => {
await createFolder({ page, folderName });
await openFolderSettings({ page, folderName });
await page
.getByLabel("Folder name", { exact: true })
.fill(renamedFolderName);
await page.getByLabel("Folder name", { exact: true }).blur();
await waitForFolderRow({ page, folderName: renamedFolderName });
await expectTextHidden({ page, text: folderName });
await selectContextAction({
page,
itemName: renamedFolderName,
action: "Copy",
});
await waitForCopiedPageTransferData({
page,
type: "folder",
name: renamedFolderName,
});
await selectContextAction({ page, itemName: "Home", action: "Paste" });
await waitForFolderRow({ page, folderName: copiedFolderName });
await selectContextAction({
page,
itemName: renamedFolderName,
action: "Duplicate",
});
await waitForFolderRow({ page, folderName: duplicatedFolderName });
await selectContextAction({
page,
itemName: duplicatedFolderName,
action: "Delete",
});
await confirmDialogAction({ page, action: "Delete" });
await expectTextHidden({ page, text: duplicatedFolderName });
});
await test.step("Template header and context menu actions", async () => {
await openTemplateSettings({ page, templateName });
await page
.getByLabel("Template name", { exact: true })
.fill(renamedTemplateName);
await page.getByLabel("Template name", { exact: true }).blur();
await waitForTemplate({ page, templateName: renamedTemplateName });
await openTemplateSettings({ page, templateName: renamedTemplateName });
await selectHeaderAction({
page,
menuLabel: "Template actions",
action: "Copy",
});
await waitForCopiedPageTransferData({
page,
type: "template",
name: renamedTemplateName,
});
await page.keyboard.press("ControlOrMeta+V");
await waitForTemplate({ page, templateName: copiedTemplateName });
await openTemplateSettings({ page, templateName: renamedTemplateName });
await selectHeaderAction({
page,
menuLabel: "Template actions",
action: "Duplicate",
});
await waitForTemplate({ page, templateName: duplicatedTemplateName });
await selectContextAction({
page,
itemName: duplicatedTemplateName,
action: "Delete",
});
const save = waitForChangeToBeSaved({ page });
await confirmDialogAction({ page, action: "Delete Template" });
await save;
await expectTextHidden({ page, text: duplicatedTemplateName });
});
await test.step("Folder and template changes persist after reopening Builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await openPagesPanel({ page });
await waitForFolderRow({ page, folderName: renamedFolderName });
await expectTextHidden({ page, text: folderName });
await waitForFolderRow({ page, folderName: copiedFolderName });
await openFolderSettings({ page, folderName: copiedFolderName });
await expectTextHidden({ page, text: duplicatedFolderName });
await waitForTemplate({ page, templateName: renamedTemplateName });
await waitForTemplate({ page, templateName: copiedTemplateName });
await expectTextHidden({ page, text: duplicatedTemplateName });
});
await openPagesPanel({ page });
await openTemplateSettings({ page, templateName });
const renameSave = waitForChangeToBeSaved({ page });
await page
.getByLabel("Template name", { exact: true })
.fill(renamedTemplateName);
await page.getByLabel("Template name", { exact: true }).blur();
await renameSave;
await waitForTemplate({ page, templateName: renamedTemplateName });
await openTemplateSettings({ page, templateName: renamedTemplateName });
await selectHeaderAction({
page,
menuLabel: "Template actions",
action: "Copy",
});
await waitForCopiedPageTransferData({ page });
await pasteFromClipboardShortcut({ page });
await waitForTemplate({ page, templateName: copiedTemplateName });
await openTemplateSettings({ page, templateName: renamedTemplateName });
await selectHeaderAction({
page,
menuLabel: "Template actions",
action: "Duplicate",
});
await waitForTemplate({ page, templateName: duplicatedTemplateName });
await selectContextAction({
page,
itemName: duplicatedTemplateName,
action: "Delete",
});
const deleteSave = waitForChangeToBeSaved({ page });
await confirmDialogAction({ page, action: "Delete Template" });
await deleteSave;
await expectTextHidden({ page, text: duplicatedTemplateName });
await measure(
"pages actions reload for template action persistence",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
}
);
await openPagesPanel({ page });
await waitForTemplate({ page, templateName: renamedTemplateName });
await waitForTemplate({ page, templateName: copiedTemplateName });
await expectTextHidden({ page, text: duplicatedTemplateName });
});
const createInstanceTransfer = ({ id, text }: { id: string; text: string }) =>
@@ -667,7 +649,6 @@ const pasteClipboardData = async ({
page: Page;
data: Record<string, string>;
}) => {
const save = waitForChangeToBeSaved({ page });
await page.evaluate((data) => {
const clipboardData = new DataTransfer();
for (const [mimeType, value] of Object.entries(data)) {
@@ -681,59 +662,13 @@ const pasteClipboardData = async ({
})
);
}, data);
await save;
};
const countPastedElements = async ({
tag,
text,
}: {
tag: string;
text: string;
}) => {
const build = await loadDevBuild({ projectId: pasteFixture.projectId });
const instances = JSON.parse(build.instances) as Array<{
component?: string;
tag?: string;
children?: Array<{ type: string; value?: string }>;
}>;
return instances.filter(
(instance) =>
instance.component === "ws:element" &&
instance.tag === tag &&
instance.children?.some(
(child) => child.type === "text" && child.value?.includes(text)
)
).length;
};
const countBuildInstancesWithText = async (text: string) => {
const build = await loadDevBuild({ projectId: pasteFixture.projectId });
const instances = JSON.parse(build.instances) as Array<{
id: string;
children?: Array<{ type: string; value?: string }>;
}>;
const instancesById = new Map(
instances.map((instance) => [instance.id, instance])
);
const containsText = (instanceId: string): boolean => {
const instance = instancesById.get(instanceId);
return (
instance?.children?.some(
(child) =>
(child.type === "text" && child.value?.includes(text)) ||
(child.type === "id" &&
child.value !== undefined &&
containsText(child.value))
) ?? false
);
};
return instances.filter((instance) => containsText(instance.id)).length;
};
test("Builder runs paste plugins through generic browser paste events", async ({
browser,
page,
}) => {
const fixture = await createPagesFixture(browser, "paste");
const entries = [
[
"application/json",
@@ -791,29 +726,38 @@ test("Builder runs paste plugins through generic browser paste events", async ({
await openProjectBuilder({
page,
projectId: pasteFixture.projectId,
authToken: pasteFixture.builderToken,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
for (const [mimeType, value, text, tag] of entries) {
for (const [mimeType, value, text] of entries) {
await selectPasteBody({ page });
await pasteClipboardData({ page, data: { [mimeType]: value } });
await waitForCanvasText({ page, text });
}
await waitForSyncComplete({ page });
const build = await loadDevBuild({ projectId: fixture.projectId });
const instances = JSON.parse(build.instances) as Array<{
component: string;
tag?: string;
children: Array<{ type: string; value: string }>;
}>;
for (const [, , text, tag] of entries) {
// The Webflow plugin can wrap its text in a generated instance.
const matches = instances.filter(
(instance) =>
(tag === undefined ||
(instance.component === "ws:element" && instance.tag === tag)) &&
instance.children.some(
(child) => child.type === "text" && child.value.includes(text)
)
);
if (tag === undefined) {
const count = await countBuildInstancesWithText(text);
if (count === 0) {
throw new Error(
`Expected generic Webflow paste to persist ${JSON.stringify(text)}`
);
}
continue;
}
const count = await countPastedElements({ tag, text });
if (count !== 1) {
throw new Error(
`Expected one ${tag} containing ${JSON.stringify(text)}, found ${count}`
);
expect(matches.length, text).toBeGreaterThan(0);
} else {
expect(matches, text).toHaveLength(1);
}
}
});
@@ -9,16 +9,18 @@ import { openNavigatorPanel } from "../flows/navigator";
import { openPage } from "../flows/pages-panel";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
waitForSyncComplete,
} from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import type { SeededContentModeProject } from "../fixtures/content-mode-project";
import { test, withBrowserContext } from "../test";
import {
createBuilderEditingProject,
pageTemplateName,
pageTemplateText,
} from "../fixtures/builder-editing-project";
import { test } from "../test";
import { measure } from "../perf";
import { loadDevBuild } from "../db";
let fixture: SeededContentModeProject;
let navigatorStructuralFixture: SeededContentModeProject;
type Project = Awaited<ReturnType<typeof createBuilderEditingProject>>;
test.describe.configure({ mode: "parallel" });
@@ -64,7 +66,7 @@ const createInstanceTransfer = ({ id, text }: { id: string; text: string }) =>
},
});
const loadBuildInstances = async (fixture: SeededContentModeProject) => {
const loadBuildInstances = async (fixture: Project) => {
const build = await loadDevBuild({ projectId: fixture.projectId });
return JSON.parse(build.instances) as BuildInstance[];
};
@@ -197,14 +199,14 @@ const createBuildInspector = (instances: BuildInstance[]) => {
};
};
const inspectBuild = async (fixture: SeededContentModeProject) =>
const inspectBuild = async (fixture: Project) =>
createBuildInspector(await loadBuildInstances(fixture));
const getElementTagCount = async ({
fixture,
tag,
}: {
fixture: SeededContentModeProject;
fixture: Project;
tag: string;
}) => {
return (await inspectBuild(fixture)).countElementTag(tag);
@@ -215,7 +217,7 @@ const getElementTagWithTextCount = async ({
tag,
text,
}: {
fixture: SeededContentModeProject;
fixture: Project;
tag: string;
text: string;
}) => {
@@ -226,7 +228,7 @@ const getExactTextChildCount = async ({
fixture,
text,
}: {
fixture: SeededContentModeProject;
fixture: Project;
text: string;
}) => {
return (await inspectBuild(fixture)).countExactTextChildren(text);
@@ -237,7 +239,7 @@ const getElementWithTextParentTag = async ({
tag,
text,
}: {
fixture: SeededContentModeProject;
fixture: Project;
tag: string;
text: string;
}) => {
@@ -252,7 +254,7 @@ const getDirectChildTextOrder = async ({
parentTag,
texts,
}: {
fixture: SeededContentModeProject;
fixture: Project;
parentTag: string;
texts: string[];
}) => {
@@ -266,7 +268,7 @@ const getInstanceLabelCount = async ({
fixture,
label,
}: {
fixture: SeededContentModeProject;
fixture: Project;
label: string;
}) => {
return (await inspectBuild(fixture)).countLabel(label);
@@ -285,21 +287,18 @@ const pastePlainTextFromClipboardShortcut = async ({
const save = waitForChangeToBeSaved({ page });
await page.keyboard.press("ControlOrMeta+V");
await save;
await waitForSyncStatus({ page, status: "idle" });
};
const pasteFromClipboardShortcut = async ({ page }: { page: Page }) => {
const save = waitForChangeToBeSaved({ page }).catch(() => undefined);
const save = waitForChangeToBeSaved({ page });
await page.keyboard.press("ControlOrMeta+V");
await save;
await waitForSyncStatus({ page, status: "idle" });
};
const cutSelectedInstanceShortcut = async ({ page }: { page: Page }) => {
const save = waitForChangeToBeSaved({ page });
await page.keyboard.press("ControlOrMeta+X");
await save;
await waitForSyncStatus({ page, status: "idle" });
};
const pasteTextFromClipboardShortcutWithoutSave = async ({
@@ -313,7 +312,7 @@ const pasteTextFromClipboardShortcutWithoutSave = async ({
await navigator.clipboard.writeText(text);
}, text);
await page.keyboard.press("ControlOrMeta+V");
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
};
const waitForClipboardTextIncludes = async ({
@@ -335,13 +334,11 @@ const waitForClipboardTextIncludes = async ({
const pasteClipboardData = async ({
page,
data,
waitForSave = true,
}: {
page: Page;
data: Record<string, string>;
waitForSave?: boolean;
}) => {
const save = waitForSave ? waitForChangeToBeSaved({ page }) : undefined;
const save = waitForChangeToBeSaved({ page });
await page.evaluate((data) => {
const clipboardData = new DataTransfer();
for (const [mimeType, value] of Object.entries(data)) {
@@ -356,7 +353,6 @@ const pasteClipboardData = async ({
);
}, data);
await save;
await waitForSyncStatus({ page, status: "idle" });
};
const moveSelectedNavigatorInstance = async ({
@@ -369,7 +365,6 @@ const moveSelectedNavigatorInstance = async ({
const save = waitForChangeToBeSaved({ page });
await page.keyboard.press(shortcut);
await save;
await waitForSyncStatus({ page, status: "idle" });
};
const openComponentsPanel = async ({ page }: { page: Page }) => {
@@ -396,8 +391,9 @@ const insertComponentPanelOption = async ({
name: string;
}) => {
await searchComponentsPanel({ page, text: name });
const save = waitForChangeToBeSaved({ page });
await page.getByRole("option", { name, exact: true }).click();
await waitForSyncStatus({ page, status: "idle" });
await save;
};
const openCommandPanel = async ({ page }: { page: Page }) => {
@@ -520,31 +516,14 @@ const editSelectedNavigatorLabel = async ({
await waitForChangeToBeSaved({ page });
};
test.beforeAll(async ({ browser }, workerInfo) => {
const workerSuffix = `worker-${workerInfo.parallelIndex}`;
await withBrowserContext(browser, async (context) => {
fixture = await createContentModeProject({
context,
email: `pages-actions-${workerSuffix}@webstudio.test`,
title: "Pages Actions E2E",
assetNamePrefix: `pages-actions-${workerSuffix}-`,
editorToken: `pages-actions-${workerSuffix}-editor-token`,
builderToken: `pages-actions-${workerSuffix}-builder-token`,
});
navigatorStructuralFixture = await createContentModeProject({
context,
email: `pages-actions-navigator-structural-${workerSuffix}@webstudio.test`,
title: "Pages Actions Navigator Structural E2E",
assetNamePrefix: `pages-actions-navigator-structural-${workerSuffix}-`,
editorToken: `pages-actions-navigator-structural-${workerSuffix}-editor-token`,
builderToken: `pages-actions-navigator-structural-${workerSuffix}-builder-token`,
});
});
});
test("Builder Navigator keyboard move, reparent, and reorder persist after reload", async ({
page,
context,
}) => {
const fixture = await createBuilderEditingProject({
context,
name: "navigator-keyboard",
});
const sectionText = "Navigator move section";
const asideText = "Navigator move aside";
const html = `
@@ -561,8 +540,8 @@ test("Builder Navigator keyboard move, reparent, and reorder persist after reloa
async () => {
await openProjectBuilder({
page,
projectId: navigatorStructuralFixture.projectId,
authToken: navigatorStructuralFixture.builderToken,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
}
);
@@ -588,7 +567,7 @@ test("Builder Navigator keyboard move, reparent, and reorder persist after reloa
}
);
const reparentedParentTag = await getElementWithTextParentTag({
fixture: navigatorStructuralFixture,
fixture,
tag: "aside",
text: asideText,
});
@@ -607,7 +586,7 @@ test("Builder Navigator keyboard move, reparent, and reorder persist after reloa
});
});
const outdentedParentTag = await getElementWithTextParentTag({
fixture: navigatorStructuralFixture,
fixture,
tag: "aside",
text: asideText,
});
@@ -629,7 +608,7 @@ test("Builder Navigator keyboard move, reparent, and reorder persist after reloa
}
);
const reorderedTextOrder = await getDirectChildTextOrder({
fixture: navigatorStructuralFixture,
fixture,
parentTag: "body",
texts: [sectionText, asideText],
});
@@ -642,19 +621,19 @@ test("Builder Navigator keyboard move, reparent, and reorder persist after reloa
await measure("pages actions reload navigator keyboard moves", async () => {
await openProjectBuilder({
page,
projectId: navigatorStructuralFixture.projectId,
authToken: navigatorStructuralFixture.builderToken,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasText({ page, text: sectionText });
await waitForCanvasText({ page, text: asideText });
const reloadedParentTag = await getElementWithTextParentTag({
fixture: navigatorStructuralFixture,
fixture,
tag: "aside",
text: asideText,
});
const reloadedTextOrder = await getDirectChildTextOrder({
fixture: navigatorStructuralFixture,
fixture,
parentTag: "body",
texts: [sectionText, asideText],
});
@@ -672,7 +651,12 @@ test("Builder Navigator keyboard move, reparent, and reorder persist after reloa
test("Builder Navigator and command panel edits persist after reload", async ({
page,
context,
}) => {
const fixture = await createBuilderEditingProject({
context,
name: "navigator-commands",
});
const anchorText = "Initial content";
const componentName = "Image";
const renamedLabel = "Hero media";
@@ -768,7 +752,13 @@ test("Builder Navigator and command panel edits persist after reload", async ({
test("Builder clipboard shortcuts and paste targets preserve saved content", async ({
page,
context,
}) => {
const fixture = await createBuilderEditingProject({
context,
name: "builder-clipboard",
includePageTemplate: true,
});
await measure("pages actions open builder for clipboard cases", async () => {
await openProjectBuilder({
page,
@@ -811,13 +801,7 @@ test("Builder clipboard shortcuts and paste targets preserve saved content", asy
await navigator.clipboard.writeText(text);
}, pastedText);
await page.keyboard.press("ControlOrMeta+V");
await commandInput.waitFor();
const value = await commandInput.inputValue();
if (value !== pastedText) {
throw new Error(
`Expected native input paste to preserve text "${pastedText}", got "${value}"`
);
}
await expect(commandInput).toHaveValue(pastedText);
await page.keyboard.press("Escape");
await waitForCanvasTextHidden({ page, text: pastedText });
});
@@ -826,7 +810,7 @@ test("Builder clipboard shortcuts and paste targets preserve saved content", asy
const text = "Initial content";
await waitForCanvasText({ page, text });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
const initialTextCount = await getExactTextChildCount({ fixture, text });
await selectCanvasTextInstance({ page, text });
@@ -941,8 +925,8 @@ test("Builder clipboard shortcuts and paste targets preserve saved content", asy
await openPage({
page,
pageName: fixture.pageTemplateName,
canvasText: fixture.pageTemplateText,
pageName: pageTemplateName,
canvasText: pageTemplateText,
});
await selectBodyInNavigator({ page });
@@ -1,10 +1,5 @@
import { randomUUID } from "node:crypto";
import {
expect,
type BrowserContext,
type Frame,
type Page,
} from "@playwright/test";
import { expect, type BrowserContext, type Frame } from "@playwright/test";
import {
getCanvasInstance,
getCanvasInstanceSelector,
@@ -12,7 +7,7 @@ import {
waitForCanvasFrame,
} from "../flows/builder";
import { openNavigatorPanel } from "../flows/navigator";
import { waitForChangeToBeSaved } from "../flows/sync-status";
import { waitForSyncComplete } from "../flows/sync-status";
import { createSlotKeyboardProject } from "../fixtures/slot-keyboard-project";
import { test } from "../test";
@@ -60,13 +55,6 @@ const expectInstanceOrder = async (
);
};
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[] = []
@@ -155,7 +143,7 @@ test("Canvas shortcuts select shared Slot siblings and persist keyboard moves",
// Refocus the canvas and select just the heading before moving it.
await canvasHeading.click();
await saveShortcut(page, "ArrowRight");
await page.keyboard.press("Control+ArrowRight");
await expectIndented(canvas);
for (const move of canvasDetachMoves) {
@@ -165,11 +153,12 @@ test("Canvas shortcuts select shared Slot siblings and persist keyboard moves",
canvas,
instanceSelector: [`${move.id}${move.suffix}`, ...fragmentA],
}).click();
await saveShortcut(page, move.key);
await page.keyboard.press(`Control+${move.key}`);
await expectDetached(canvas, move);
});
}
await waitForSyncComplete({ page, timeout: 30_000 });
await page.reload();
const reloadedCanvas = await waitForCanvasFrame({ page });
await expectIndented(reloadedCanvas);
@@ -199,7 +188,7 @@ test("Navigator shortcuts reorder and outdent shared Slot children while keeping
.getByRole("button", { name: "Slot Heading", exact: true })
.first();
await row.click();
await saveShortcut(page, "ArrowUp");
await page.keyboard.press("Control+ArrowUp");
for (const fragment of [fragmentA, fragmentB]) {
const headingSelector = [heading, ...fragment];
const boxSelector = [box, ...fragment];
@@ -213,7 +202,7 @@ test("Navigator shortcuts reorder and outdent shared Slot children while keeping
}
await expect(row).toBeFocused();
await saveShortcut(page, "ArrowLeft");
await page.keyboard.press("Control+ArrowLeft");
await expectDetached(canvas, { id: heading, position: "before" });
await expect(row).toBeFocused();
await page.keyboard.press("ArrowUp");
@@ -224,6 +213,7 @@ test("Navigator shortcuts reorder and outdent shared Slot children while keeping
})
).toBeFocused();
await waitForSyncComplete({ page, timeout: 30_000 });
await page.reload();
await expectDetached(await waitForCanvasFrame({ page }), {
id: heading,
@@ -1,260 +0,0 @@
import type { BrowserContext, Page } from "@playwright/test";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import { selectCanvasTextInstance } from "../flows/canvas-selection";
import {
waitForCanvasTextStyle,
waitForHoveredCanvasTextStyle,
} from "../flows/canvas-style";
import { waitForChangeToBeSaved } from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import type { SeededContentModeProject } from "../fixtures/content-mode-project";
import { test } from "../test";
import { measure } from "../perf";
import { loadDevBuild } from "../db";
const createStylePanelRuntimeProject = async (
context: BrowserContext,
name: string
) => {
return await createContentModeProject({
context,
email: `style-panel-runtime-${name}@webstudio.test`,
title: `Style Panel Runtime ${name}`,
assetNamePrefix: `style-panel-runtime-${name}-`,
editorToken: `style-panel-runtime-${name}-editor-token`,
builderToken: `style-panel-runtime-${name}-builder-token`,
});
};
const setCssValue = async ({
page,
property,
value,
waitForSave = true,
}: {
page: Page;
property: string;
value: string;
waitForSave?: boolean;
}) => {
const input = page.getByLabel(property, { exact: true }).first();
await input.fill(value);
const save = waitForSave ? waitForChangeToBeSaved({ page }) : undefined;
await input.press("Enter");
await save;
};
const resetCssValue = async ({
page,
property,
}: {
page: Page;
property: string;
}) => {
const input = page.getByLabel(property, { exact: true }).first();
const labelText = `${property.slice(0, 1).toUpperCase()}${property.slice(1)}`;
const control = input.locator(
`xpath=ancestor::*[.//*[normalize-space()=${JSON.stringify(labelText)}]][1]`
);
const label = control.getByText(labelText, { exact: true });
await label.waitFor({ state: "visible", timeout: 10_000 });
const save = waitForChangeToBeSaved({ page });
await label.click({ modifiers: ["Alt"] });
await save;
};
const selectStyleSourceState = async ({
page,
state,
}: {
page: Page;
state: string;
}) => {
await page
.getByLabel("Style source menu Local", { exact: true })
.click({ force: true });
await page.getByRole("menuitem", { name: state, exact: true }).click();
};
const readBuildStylesText = async (fixture: SeededContentModeProject) => {
const build = await loadDevBuild({ projectId: fixture.projectId });
return JSON.stringify(JSON.parse(build.styles));
};
const expectBuildStylesToContain = async ({
fixture,
text,
}: {
fixture: SeededContentModeProject;
text: string;
}) => {
const styles = await readBuildStylesText(fixture);
if (styles.includes(text) === false) {
throw new Error(`Expected build styles to contain "${text}".`);
}
};
const expectBuildStylesNotToContain = async ({
fixture,
text,
}: {
fixture: SeededContentModeProject;
text: string;
}) => {
const styles = await readBuildStylesText(fixture);
if (styles.includes(text)) {
throw new Error(`Expected build styles not to contain "${text}".`);
}
};
test("Builder style panel edits representative styles and persists after reload", async ({
page,
context,
}) => {
const fixture = await createStylePanelRuntimeProject(context, "styles");
const text = "Initial content";
await measure("style panel runtime open builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasText({ page, text });
await selectCanvasTextInstance({ page, text });
await page.getByRole("tab", { name: "Style" }).click();
await measure("style panel runtime edit css values", async () => {
await setCssValue({
page,
property: "font-size",
value: "44px",
waitForSave: false,
});
await setCssValue({
page,
property: "line-height",
value: "1.25",
waitForSave: false,
});
await setCssValue({
page,
property: "letter-spacing",
value: "2px",
waitForSave: false,
});
await setCssValue({
page,
property: "color",
value: "#2255ff",
waitForSave: false,
});
await setCssValue({
page,
property: "width",
value: "420px",
waitForSave: false,
});
await selectStyleSourceState({ page, state: ":hover" });
await setCssValue({ page, property: "color", value: "#ca126b" });
await selectStyleSourceState({ page, state: ":hover" });
});
await waitForCanvasTextStyle({
page,
text,
property: "font-size",
value: "44px",
});
await waitForCanvasTextStyle({
page,
text,
property: "line-height",
value: "55px",
});
await waitForCanvasTextStyle({
page,
text,
property: "letter-spacing",
value: "2px",
});
await waitForCanvasTextStyle({
page,
text,
property: "color",
value: "rgb(34, 85, 255)",
});
await waitForCanvasTextStyle({
page,
text,
property: "width",
value: "420px",
});
await waitForHoveredCanvasTextStyle({
page,
text,
property: "color",
value: "rgb(202, 18, 107)",
});
await expectBuildStylesToContain({
fixture,
text: `"state":":hover"`,
});
await page.getByRole("tab", { name: "Style" }).click();
await measure("style panel runtime reset css value", async () => {
await resetCssValue({ page, property: "width" });
});
await expectBuildStylesNotToContain({
fixture,
text: `"property":"width"`,
});
await measure("style panel runtime reload builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasTextStyle({
page,
text,
property: "font-size",
value: "44px",
});
await waitForCanvasTextStyle({
page,
text,
property: "line-height",
value: "55px",
});
await waitForCanvasTextStyle({
page,
text,
property: "letter-spacing",
value: "2px",
});
await waitForCanvasTextStyle({
page,
text,
property: "color",
value: "rgb(34, 85, 255)",
});
await waitForHoveredCanvasTextStyle({
page,
text,
property: "color",
value: "rgb(202, 18, 107)",
});
await expectBuildStylesNotToContain({
fixture,
text: `"property":"width"`,
});
await expectBuildStylesToContain({
fixture,
text: `"state":":hover"`,
});
});