Files
site-builder/craft/scripts/e2e-sitesmith-delete.mjs
shadowdaoandClaude Opus 5.5 11cd967c90 fix(editor): generated columns/cards can be deleted; a refused delete says why
Sitesmith layouts put their cards/columns as Container children of a
ColumnLayout, which the flattener turns into Craft LINKED nodes (col-N).
Craft never deletes a linked node (isDeletable() is false), and
findDeletableTarget returned null for a populated column, so the context
menu, Delete/Backspace, command palette and mobile toolbar all silently did
nothing -- 100% of generated column containers in both captured Sitesmith
responses were undeletable.

- planDelete/runDelete (craft-helpers): one rule set for every delete route.
  A column of a Columns layout is removed by rebuilding the layout (minus the
  column subtree, slots renumbered col-0.., columns decremented, split
  rescaled) in one undo step; the rebuilt layout gets a new id so Craft's
  <Element> remounts. Last column -> the layout goes (as before).
- A Section/BackgroundSection/Form content area is still protected but now
  shows a notice explaining why with a "Delete <Section>" action; ROOT stays
  protected. No delete is a silent no-op any more.
- Sitesmith patch delete_node uses the same path (a card delete no longer
  fails with only a console warning).
- Tests: src/utils/sitesmith-delete.test.ts (real Craft editor + the two
  captured Sitesmith responses), updated core-commands test, and a
  real-browser check: npm run test:browser:sitesmith-delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXjXyosSkunDsdWz3mb
2026-11-08 06:54:00 -08:00

178 lines
9.8 KiB
JavaScript

#!/usr/bin/env node
/**
* Real-browser (Chromium, headless) regression for "Sitesmith layout: containers cannot be deleted".
*
* Applies REAL captured Sitesmith page responses (src/utils/__fixtures__/sitesmith-*-response.json)
* through the real modal (mock backend, scripts/e2e-sitesmith-mock-server.mjs), then tries to delete
* every generated column Container (ColumnLayout linked columns) and every Section inner area by
* the context menu and by the Delete key. Each delete must either remove something or show a
* visible notice -- never a silent no-op.
*
* npm run test:browser:sitesmith-delete
*
* Env: CHROMIUM_PATH, SITESMITH_E2E_DIST, SITESMITH_E2E_SKIP_BUILD=1, SITESMITH_SHOTS=<dir>
*/
import { chromium } from '@playwright/test';
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createMockServer } from './e2e-sitesmith-mock-server.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const distDir = path.resolve(process.env.SITESMITH_E2E_DIST || fs.mkdtempSync(path.join(os.tmpdir(), 'sitesmith-del-')));
const shotsDir = path.resolve(process.env.SITESMITH_SHOTS || path.join(os.tmpdir(), 'sitesmith-delete-shots'));
fs.mkdirSync(shotsDir, { recursive: true });
if (!(process.env.SITESMITH_E2E_SKIP_BUILD && fs.existsSync(path.join(distDir, 'index.html')))) {
console.log(`building editor -> ${distDir}`);
const b = spawnSync('npx', ['vite', 'build', '--outDir', distDir, '--emptyOutDir'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
if (b.status !== 0) { console.error(b.stdout, b.stderr); process.exit(2); }
}
const srv = await createMockServer({ distDir });
const fixtures = ['sitesmith-ols-home-response.json', 'sitesmith-ttm-likes-response.json'];
let failures = 0;
const ok = (label, cond, detail) => { if (!cond) failures++; console.log(`${cond ? 'PASS' : 'FAIL'} ${label}${!cond && detail !== undefined ? ` -- ${detail}` : ''}`); };
const browser = await chromium.launch({ headless: true, ...(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}) });
async function loadFixture(fx) {
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
await ctx.route(/^https?:\/\/(?!127\.0\.0\.1)/, (route) => {
const u = route.request().url();
if (/\.css(\?|$)|fonts\.googleapis/.test(u)) return route.fulfill({ status: 200, contentType: 'text/css', body: '/* offline */' });
return route.abort();
});
await ctx.addInitScript(() => { try { localStorage.setItem('sitesmith.selfReview', 'off'); } catch (e) {} });
const page = await ctx.newPage();
page.__errors = [];
page.on('pageerror', (e) => page.__errors.push(String(e)));
page.on('console', (m) => { if (m.type() === 'error') page.__errors.push(m.text()); });
await page.goto(srv.url + '/');
await page.waitForSelector('.canvas-device-frame [data-craft-container]', { timeout: 20000 });
const resp = JSON.parse(fs.readFileSync(path.join(root, 'src/utils/__fixtures__', fx), 'utf8'));
srv.setNextResult(resp);
await page.click('button.sitesmith-btn');
await page.waitForSelector('textarea.sitesmith-textarea:not([disabled])', { timeout: 10000 });
await page.fill('textarea.sitesmith-textarea', 'Build me a home page');
await page.click('[role=dialog] button:has-text("→")');
await page.waitForSelector('[data-wsb-cols]', { timeout: 30000 });
await page.waitForTimeout(800);
// close the modal
await page.click('[role=dialog] button[aria-label=Close]');
await page.waitForSelector('[role=dialog]', { state: 'detached', timeout: 5000 }).catch(() => {});
await page.waitForTimeout(300);
return page;
}
/** Ids of every generated column Container (ColumnLayout children) and Section inner area, read
* from the fixture itself (the flattener keeps `node_id` as the Craft id; Section inner = `<id>__section-inner`). */
function targetsOf(resp) {
const cols = [], inners = [];
const walk = (n) => {
const t = n?.type?.resolvedName;
const kids = n?.nodes || [];
if (t === 'ColumnLayout') cols.push({ layout: n.props.node_id, cols: kids.map((k) => k.props.node_id) });
if (t === 'Section' && kids.length) inners.push(`${n.props.node_id}__section-inner`);
kids.forEach(walk);
};
resp.pages.forEach((p) => walk(p.tree));
return { cols, inners };
}
const exists = (page, id) => page.locator(`[data-layer-id="${id}"]`).count().then((c) => c > 0);
const notices = (page) => page.evaluate(() => [...document.querySelectorAll('[role=status],[role=alert]')].map((n) => n.textContent.trim()).filter(Boolean).join(' | '));
const layerCount = (page) => page.locator('[data-layer-id]').count();
async function selectViaLayers(page, id) {
const row = page.locator(`[data-layer-id="${id}"]`);
await row.scrollIntoViewIfNeeded();
await row.click();
await page.waitForTimeout(120);
}
async function deleteVia(page, route) {
if (route === 'delete-key') {
await page.keyboard.press('Delete');
} else {
// Right-click on the canvas without a mousedown (which would re-select whatever is under the cursor).
const box = await page.locator('.canvas-device-frame').boundingBox();
await page.dispatchEvent('.canvas-device-frame', 'contextmenu', { clientX: box.x + 40, clientY: box.y + 40, bubbles: true });
await page.waitForSelector('button:has-text("Select Parent")', { timeout: 3000 });
const del = page.locator('button', { has: page.locator('span', { hasText: /^Delete$/ }) }).last();
if (await del.isDisabled()) { await page.keyboard.press('Escape'); return 'disabled'; }
await del.click();
}
await page.waitForTimeout(300);
return 'clicked';
}
for (const fx of fixtures) {
const resp = JSON.parse(fs.readFileSync(path.join(root, 'src/utils/__fixtures__', fx), 'utf8'));
const { cols, inners } = targetsOf(resp);
const short = fx.replace(/sitesmith-|-response\.json/g, '');
for (const route of ['context-menu', 'delete-key']) {
const page = await loadFixture(fx);
await page.click('button:has-text("Layers")');
await page.waitForSelector('[data-layer-id]', { timeout: 5000 });
if (route === 'context-menu') await page.screenshot({ path: path.join(shotsDir, `${short}-applied.png`) });
const tag = `${short} ${route}`;
let attempts = 0, removed = 0, explained = 0, silent = 0;
const rows = [];
// Columns: delete the LAST column, then the FIRST, of every layout (each has content in the others).
for (const { layout, cols: ids } of cols) {
const order = ids.length > 1 ? [ids[ids.length - 1], ids[0]] : [ids[0]];
for (const id of order) {
if (!(await exists(page, id))) { console.log(` (skip ${id}: not on canvas)`); continue; }
await selectViaLayers(page, id);
const n0 = await notices(page);
const r = await deleteVia(page, route);
attempts++;
const gone = !(await exists(page, id));
const n1 = await notices(page);
if (gone) removed++; else if (n1 && n1 !== n0) explained++; else silent++;
if (gone && route === 'delete-key' && ids.length >= 3 && id === ids[ids.length - 1]) {
await page.locator(`[data-layer-id="${ids[0]}"]`).click();
await page.waitForTimeout(200);
await page.screenshot({ path: path.join(shotsDir, `${short}-${ids.length}to${ids.length - 1}-cols.png`) });
}
rows.push(`${id} (${ids.length} cols in ${layout}): ${gone ? `DELETED (canvas column boxes now ${await page.evaluate(() => [...document.querySelectorAll('.canvas-device-frame [data-wsb-cols]')].map((c) => c.children.length).join(','))})` : r === 'disabled' ? 'menu item disabled' : n1 && n1 !== n0 ? `notice "${n1}"` : 'SILENT NO-OP'}`);
}
}
for (const id of inners) {
if (!(await exists(page, id))) continue;
const owner = id.replace(/__section-inner$/, '');
await selectViaLayers(page, id);
const n0 = await notices(page);
const before = await layerCount(page);
const r = await deleteVia(page, route);
attempts++;
const gone = !(await exists(page, id));
const n1 = await notices(page);
if (gone) removed++; else if (n1 && n1 !== n0) explained++; else silent++;
if (!gone) await page.screenshot({ path: path.join(shotsDir, `${short}-${route}-inner-notice.png`) });
rows.push(`${id} (Section inner): ${gone ? `DELETED (section gone=${!(await exists(page, owner))}, layers ${before}->${await layerCount(page)})` : r === 'disabled' ? 'menu item disabled' : n1 && n1 !== n0 ? `notice "${n1}"` : 'SILENT NO-OP'}`);
break; // one Section is enough
}
rows.forEach((r) => console.log(' ' + r));
await page.screenshot({ path: path.join(shotsDir, `${short}-${route}-after.png`) });
ok(`${tag}: no silent no-op deletes (${attempts} tries, ${removed} deleted, ${explained} explained, ${silent} silent)`, silent === 0);
ok(`${tag}: every generated column Container could be deleted`, rows.filter((r) => /cols in/.test(r)).every((r) => /DELETED/.test(r)));
// Undo brings a deleted column back (one history step per delete).
if (removed) {
const before = await layerCount(page);
await page.click('.canvas-device-frame', { position: { x: 5, y: 5 } }).catch(() => {});
await page.keyboard.press('Control+z');
await page.waitForTimeout(300);
ok(`${tag}: undo restores the last delete`, (await layerCount(page)) > before, `${before} -> ${await layerCount(page)}`);
}
const fatal = page.__errors.filter((e) => /Invariant|Cannot delete|top-level|Delete failed|does not exist in resolver/i.test(e));
ok(`${tag}: no delete errors in console`, fatal.length === 0, fatal.slice(0, 3).join(' || '));
await page.context().close();
}
}
await browser.close();
srv.close?.();
console.log(failures ? `\n${failures} FAILED` : '\nALL PASS');
process.exit(failures ? 1 : 0);