diff --git a/craft/package.json b/craft/package.json index 2f4f453..421d7d1 100644 --- a/craft/package.json +++ b/craft/package.json @@ -23,6 +23,7 @@ "test:browser:sitesmith": "node scripts/e2e-sitesmith.mjs", "test:browser:sitesmith-editor-assets": "node scripts/e2e-sitesmith-editor-assets.mjs", "test:browser:sitesmith-cleaned": "node scripts/e2e-sitesmith-cleaned.mjs", + "test:browser:sitesmith-delete": "node scripts/e2e-sitesmith-delete.mjs", "test:browser:preview-assets": "node scripts/e2e-preview-assets.mjs", "test:unit:watch": "vitest" }, diff --git a/craft/scripts/e2e-sitesmith-delete.mjs b/craft/scripts/e2e-sitesmith-delete.mjs new file mode 100644 index 0000000..3634105 --- /dev/null +++ b/craft/scripts/e2e-sitesmith-delete.mjs @@ -0,0 +1,177 @@ +#!/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= + */ +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 = `__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); diff --git a/craft/src/components/layout/ColumnLayout.tsx b/craft/src/components/layout/ColumnLayout.tsx index ab7cfd1..b4d284c 100644 --- a/craft/src/components/layout/ColumnLayout.tsx +++ b/craft/src/components/layout/ColumnLayout.tsx @@ -41,7 +41,7 @@ const splitToWidths: Record = { '16-16-16-16-16-16': ['16.666%', '16.666%', '16.666%', '16.666%', '16.666%', '16.666%'], }; -function getWidths(split: SplitOption, columns: number): string[] { +export function getWidths(split: SplitOption, columns: number): string[] { // Check predefined splits first if (split !== 'equal') { const defined = splitToWidths[split]; diff --git a/craft/src/editor/core-commands.test.tsx b/craft/src/editor/core-commands.test.tsx index 2c64415..dd088a1 100644 --- a/craft/src/editor/core-commands.test.tsx +++ b/craft/src/editor/core-commands.test.tsx @@ -66,11 +66,36 @@ describe('multi-select', () => { expect(topLevelSelection(h.query, ['ROOT', 'sec', 'b1', 'sec2'])).toEqual(['sec', 'sec2']); }); - test('a selected node plus its own child resolves to the ancestor only (a populated column is refused)', () => { - h.act(() => { cmd('edit.delete').run(ctx(['b1', 'col-0'])); }); + test('a selected node plus its own child resolves to the ancestor only (the column is removed)', () => { + const notify = vi.fn(); + h.act(() => { cmd('edit.delete').run(ctx(['b1', 'col-0'], { notify })); }); + const nodes = h.query.getNodes(); + expect(nodes['col-0']).toBeUndefined(); + expect(nodes.b1).toBeUndefined(); + expect(nodes.b2).toBeUndefined(); + const layoutId = kids('sec-in')[0]; + const layout = h.query.node(layoutId).get().data; + expect(layout.linkedNodes).toEqual({ 'col-0': 'col-1' }); + expect(layout.props.columns).toBe(1); + expect(notify).not.toHaveBeenCalled(); + // one undo step brings the column and its content back + h.act(() => { cmd('edit.undo').run(ctx([])); }); expect(kids('col-0')).toEqual(['b1', 'b2']); }); + test('deleting a Section content area is refused with a visible reason and offers the Section', () => { + const notify = vi.fn(); + const before = h.getSerialized(); + h.act(() => { cmd('edit.delete').run(ctx(['sec-in'], { notify })); }); + expect(h.getSerialized()).toBe(before); + expect(notify).toHaveBeenCalledTimes(1); + const n = notify.mock.calls[0][0]; + expect(n.message).toMatch(/content area of the Section/); + expect(n.actionLabel).toBe('Delete Section'); + h.act(() => n.onAction()); + expect(h.query.getNodes().sec).toBeUndefined(); + }); + test('delete of two siblings', () => { h.act(() => { cmd('edit.delete').run(ctx(['b1', 'b2'])); }); expect(kids('col-0')).toEqual([]); diff --git a/craft/src/editor/core-commands.ts b/craft/src/editor/core-commands.ts index 8b5c7bd..80403e7 100644 --- a/craft/src/editor/core-commands.ts +++ b/craft/src/editor/core-commands.ts @@ -1,6 +1,7 @@ import { registerCommands, type Command, type CommandContext } from './commands'; import { insertTargetOutsideInstance, isInsideInstance } from '../utils/global-sections'; -import { findDeletableTarget, getAncestorIds, getParentId } from '../utils/craft-helpers'; +import { planDelete, removeColumn, getAncestorIds, getParentId, type DeletePlan } from '../utils/craft-helpers'; +import { reportBlockedDelete } from '../hooks/useNodeActions'; import { regenerateTreeIds } from '../utils/craft-tree'; import { getClipboardTree, setClipboardTree } from '../hooks/clipboard'; import type { DeviceMode } from '../types'; @@ -76,20 +77,28 @@ function duplicateAll({ query, actions, selectedIds }: CommandContext): void { if (created.length) actions.selectNode(created.length === 1 ? created[0] : created); } -function deleteAll({ query, actions, selectedIds }: CommandContext): void { - const targets = new Set(); - for (const id of topLevelSelection(query, selectedIds)) { - const t = findDeletableTarget(query, id); - if (t) targets.add(t); +function deleteAll({ query, actions, selectedIds, notify }: CommandContext): void { + const plans: DeletePlan[] = topLevelSelection(query, selectedIds).map((id) => planDelete(query, id)); + let ran = false; + const step = () => { if (ran) return actions.history.merge(); ran = true; return actions; }; + const done = new Set(); + let blocked: { reason: string; ownerId?: string } | null = null; + // Plain deletes first; column removals rebuild their layout, so run them one at a time after + // (re-planned against the live tree, since an earlier removal renumbers the columns). + for (const p of plans) { + if (p.kind !== 'node' || done.has(p.id)) continue; + done.add(p.id); + try { step().delete(p.id); } catch (err) { console.error('Delete failed:', err); blocked = { reason: 'That element could not be deleted.' }; } } - const step = groupedActions(actions); - targets.forEach((t) => { - try { - step().delete(t); - } catch (err) { - console.error('Delete failed:', err); - } - }); + for (const p of plans) { + if (p.kind !== 'column') continue; + const again = planDelete(query, p.columnId); + if (again.kind !== 'column') continue; + try { removeColumn(actions, query, again.layoutId, again.columnId, { mergeWithPrevious: ran }); ran = true; } catch (err) { console.error('Delete failed:', err); blocked = { reason: 'That column could not be deleted.' }; } + } + const firstBlocked = plans.find((p) => p.kind === 'blocked'); + if (!blocked && firstBlocked && firstBlocked.kind === 'blocked') blocked = { reason: firstBlocked.reason, ownerId: firstBlocked.ownerId }; + if (blocked) reportBlockedDelete(notify, actions, query, blocked); } function pasteClipboard({ query, actions, selectedIds }: CommandContext): void { diff --git a/craft/src/hooks/useNodeActions.ts b/craft/src/hooks/useNodeActions.ts index 2773143..467cd05 100644 --- a/craft/src/hooks/useNodeActions.ts +++ b/craft/src/hooks/useNodeActions.ts @@ -1,7 +1,8 @@ import { useEditor } from '@craftjs/core'; import { isInsideInstance } from '../utils/global-sections'; import { regenerateTreeIds } from '../utils/craft-tree'; -import { findDeletableTarget } from '../utils/craft-helpers'; +import { planDelete, runDelete, getNodeLabel } from '../utils/craft-helpers'; +import { useNotices } from '../state/NoticeContext'; export interface NodeActions { moveUp: () => void; @@ -20,9 +21,9 @@ export interface NodeActions { /** True if `nodeId` has a later sibling under the same parent (so * `moveDown` would actually move it). False for ROOT/null/no-parent. */ canMoveDown: boolean; - /** True if `findDeletableTarget` resolves to a real, deletable node (either - * `nodeId` itself, or an ancestor when `nodeId` is an empty linked-node - * slot whose siblings are all also empty -- see `craft-helpers.ts`). */ + /** True if a delete would act (see `planDelete` in `craft-helpers.ts`): the + * node itself, a column of a Columns layout, the owner of an all-empty + * linked slot, or a content area whose notice offers deleting its owner. */ canDelete: boolean; /** True if `nodeId` has a real parent to select -- i.e. the parent is * neither ROOT nor missing. `selectParent` on a top-level section (whose @@ -81,6 +82,7 @@ export interface NodeActions { */ export function useNodeActions(nodeId: string | null | undefined): NodeActions { const { actions, query } = useEditor(); + const { notify } = useNotices(); const isRootOrNull = !nodeId || nodeId === 'ROOT'; @@ -104,7 +106,10 @@ export function useNodeActions(nodeId: string | null | undefined): NodeActions { } } - const canDelete = !isRootOrNull && !!findDeletableTarget(query, nodeId); + // Also true for a content area with an owner to offer (Section inner): the tap then explains and + // offers deleting the Section, instead of a disabled button that never says why. + const plan = isRootOrNull ? null : planDelete(query, nodeId); + const canDelete = !!plan && (plan.kind !== 'blocked' || !!plan.ownerId); const getParentId = (): string | null => { if (!nodeId) return null; @@ -202,13 +207,8 @@ export function useNodeActions(nodeId: string | null | undefined): NodeActions { }; const deleteNode = () => { - const target = findDeletableTarget(query, nodeId); - if (!target) return; - try { - actions.delete(target); - } catch (e) { - console.error('Delete failed:', e); - } + if (isRootOrNull) return; + reportBlockedDelete(notify, actions, query, runDelete(actions, query, nodeId)); }; return { @@ -223,3 +223,27 @@ export function useNodeActions(nodeId: string | null | undefined): NodeActions { canSelectParent, }; } + +/** + * A delete that did nothing must say why (never a silent no-op). When there is an element to + * delete instead (the Section around its content area), the notice offers it. + */ +export function reportBlockedDelete( + notify: (n: { id?: string; kind: 'info' | 'success' | 'error'; message: string; actionLabel?: string; onAction?(): void; timeoutMs?: number }) => string, + actions: any, + query: any, + blocked: { reason: string; ownerId?: string } | null, +): void { + if (!blocked) return; + const ownerId = blocked.ownerId; + notify({ + id: 'delete-blocked', + kind: 'info', + message: blocked.reason, + timeoutMs: 8000, + ...(ownerId ? { + actionLabel: `Delete ${getNodeLabel(query, ownerId)}`, + onAction: () => reportBlockedDelete(notify, actions, query, runDelete(actions, query, ownerId)), + } : {}), + }); +} diff --git a/craft/src/utils/apply-ai-response.ts b/craft/src/utils/apply-ai-response.ts index bd69ed2..205ea3a 100644 --- a/craft/src/utils/apply-ai-response.ts +++ b/craft/src/utils/apply-ai-response.ts @@ -5,6 +5,7 @@ import { fullBleedPageRoots } from '../sitesmith/replace-plan'; import { canvasFingerprint, type CanvasFingerprint } from './canvas-fingerprint'; import { SitesmithResponse, SerializedTreeNode, SitesmithPatchOp } from '../types/sitesmith'; import { sanitizeAiTree, buildNodeTree } from './craft-tree'; +import { runDelete } from './craft-helpers'; import { cleanAiResponse } from '../sitesmith/clean-ai-response'; import { useSiteDesign, type SiteDesign } from '../state/SiteDesignContext'; import { effectiveBackgroundOf } from './effective-background'; @@ -350,14 +351,14 @@ function applyPatch( break; } - case 'delete_node': - try { - actions.delete(id); - changed++; - } catch (e) { - console.warn('sitesmith patch: delete_node failed', e); - } + case 'delete_node': { + // Same rules as the editor's own delete: a card/column of a Columns layout is a Craft linked + // node that `actions.delete` refuses, so it is removed by rebuilding the layout (runDelete). + const blocked = runDelete(actions, query, id); + if (blocked) console.warn('sitesmith patch: delete_node not applied:', op.node_id, blocked.reason); + else changed++; break; + } default: // Every SitesmithPatchOp variant is handled above, so `op` is typed diff --git a/craft/src/utils/craft-helpers.ts b/craft/src/utils/craft-helpers.ts index e5dccba..439d7d3 100644 --- a/craft/src/utils/craft-helpers.ts +++ b/craft/src/utils/craft-helpers.ts @@ -1,29 +1,173 @@ +import { getRandomId } from '@craftjs/utils'; +import { getWidths } from '../components/layout/ColumnLayout'; +import { isInsideInstance } from './global-sections'; + /** - * Find the actual deletable target for a node. Linked nodes (owned by parent - * components like ColumnLayout columns or Section inner) are structurally - * non-deletable in Craft.js — actions.delete() throws on them. When the - * selected node is an empty linked node and all its linked siblings are also - * empty (i.e., the whole layout is empty), redirect deletion to the owning - * parent so the layout itself goes away. Otherwise return null to refuse - * deletion — protects against nuking a layout that has content in other cols. + * What a delete of `nodeId` would do (shared by the context menu, the Delete key / command palette + * and the mobile toolbar, so they agree): + * + * - `node`: delete that node (the selection itself, or the layout it is the last empty slot of). + * - `column`: the node is a column of a Columns layout (a Craft LINKED node, `col-N`). Craft can + * never delete a linked node (`isDeletable()` is false -> `actions.delete` throws), so the column + * is removed by rebuilding the layout with one column fewer (`removeColumn`). Every Sitesmith + * layout puts its cards/columns here (ColumnLayout children become linked columns in + * `flattenTreeForCraft`), which is why generated containers looked undeletable. + * - `blocked`: nothing is deleted and `reason` says why, in words the owner can act on; `ownerId` + * (when set) is the element to delete instead. A delete never silently does nothing. */ -export function findDeletableTarget(query: any, nodeId: string | null | undefined): string | null { - if (!nodeId || nodeId === 'ROOT') return null; +export type DeletePlan = + | { kind: 'node'; id: string } + | { kind: 'column'; layoutId: string; columnId: string } + | { kind: 'blocked'; reason: string; ownerId?: string }; + +const isColumnLayout = (data: any): boolean => + data?.name === 'ColumnLayout' || data?.displayName === 'Columns' || + (data?.type && (data.type as any).resolvedName === 'ColumnLayout'); + +export function planDelete(query: any, nodeId: string | null | undefined): DeletePlan { + if (!nodeId || nodeId === 'ROOT') return { kind: 'blocked', reason: 'The page itself cannot be deleted.' }; try { const node = query.node(nodeId).get(); + if (!node) return { kind: 'blocked', reason: 'That element is no longer on the page.' }; const parentId: string | null | undefined = node?.data?.parent; - if (!parentId) return nodeId; + if (!parentId) return { kind: 'node', id: nodeId }; const parent = query.node(parentId).get(); const linkedIds = Object.values((parent?.data?.linkedNodes || {}) as Record); - if (!linkedIds.includes(nodeId)) return nodeId; + if (!linkedIds.includes(nodeId)) return { kind: 'node', id: nodeId }; + // A linked slot. When every slot of the owner is empty, the owner itself goes (old behaviour). const allEmpty = linkedIds.every((id) => { const sib = query.node(id).get(); return ((sib?.data?.nodes as string[] | undefined) || []).length === 0; }); - if (!allEmpty) return null; - return findDeletableTarget(query, parentId); + if (allEmpty) return planDelete(query, parentId); + if (isColumnLayout(parent?.data)) { + if (linkedIds.length <= 1) return planDelete(query, parentId); + if (isInsideInstance(query, parentId)) { + return { kind: 'blocked', reason: 'This column is part of a global section. Edit the global section to remove it.' }; + } + return { kind: 'column', layoutId: parentId, columnId: nodeId }; + } + // Section / Background section / Form inner area: the owner's only content area. + const ownerLabel = getNodeLabel(query, parentId); + return { + kind: 'blocked', + reason: `This is the content area of the ${ownerLabel}. Delete the elements inside it, or delete the whole ${ownerLabel}.`, + ownerId: parentId, + }; } catch { - return null; + return { kind: 'blocked', reason: 'That element could not be deleted.' }; + } +} + +/** + * Back-compat wrapper: the id `actions.delete` can be called on, or null. A column of a Columns + * layout returns its own id (it is deletable, through `runDelete`). + */ +export function findDeletableTarget(query: any, nodeId: string | null | undefined): string | null { + const plan = planDelete(query, nodeId); + if (plan.kind === 'node') return plan.id; + if (plan.kind === 'column') return plan.columnId; + return null; +} + +/** Widths (numbers, %) left after dropping column `index`, rescaled to 100, as a split string. */ +export function splitWithoutColumn(split: string | undefined, columns: number, index: number): string { + const widths = getWidths((split || 'equal') as any, columns).map((w) => parseFloat(w)); + widths.splice(index, 1); + if (widths.length === 0) return 'equal'; + if (widths.every((w) => Math.abs(w - widths[0]) < 0.5)) return 'equal'; + const sum = widths.reduce((a, b) => a + b, 0) || 1; + const scaled = widths.map((w) => Math.max(1, Math.round((w / sum) * 100))); + return scaled.join('-'); +} + +function subtreeIds(nodes: Record, id: string, out: Set = new Set()): Set { + if (out.has(id) || !nodes[id]) return out; + out.add(id); + const d = nodes[id].data; + for (const c of (d.nodes || []) as string[]) subtreeIds(nodes, c, out); + for (const c of Object.values((d.linkedNodes || {}) as Record)) subtreeIds(nodes, c, out); + return out; +} + +/** + * Remove one column from a Columns layout. Craft cannot delete a linked node, so the layout is + * rebuilt: its node tree minus the column's subtree, linked slots renumbered `col-0..col-(n-2)` in + * order, `columns` decremented and `split` rescaled; then the old layout is replaced in place (one + * undo step; `mergeWithPrevious` folds it into the history step before it). Throws when the layout cannot be replaced (caller reports it). + */ +export function removeColumn(actions: any, query: any, layoutId: string, columnId: string, opts: { mergeWithPrevious?: boolean } = {}): string { + const layout = query.node(layoutId).get(); + const grandId: string | null | undefined = layout?.data?.parent; + if (!grandId) throw new Error('layout has no parent'); + const grand = query.node(grandId).get(); + const index = ((grand?.data?.nodes || []) as string[]).indexOf(layoutId); + if (index === -1) throw new Error('layout is not a regular child of its parent'); + + const tree = query.node(layoutId).toNodeTree(); + const linked = Object.entries((layout.data.linkedNodes || {}) as Record) + .sort(([a], [b]) => (parseInt(a.replace(/\D+/g, ''), 10) || 0) - (parseInt(b.replace(/\D+/g, ''), 10) || 0)); + const removedIndex = linked.findIndex(([, id]) => id === columnId); + if (removedIndex === -1) throw new Error('column is not in the layout'); + const keep = linked.filter(([, id]) => id !== columnId).map(([, id]) => id); + const drop = subtreeIds(tree.nodes, columnId); + + const props = layout.data.props || {}; + const oldCount = linked.length; + const newCount = keep.length; + const split = splitWithoutColumn(props.split, oldCount, removedIndex); + const gap = typeof props.gap === 'string' && props.gap ? props.gap : '16px'; + const newWidths = getWidths(split as any, newCount); + + // The rebuilt layout gets a NEW id: Craft's resolves its linked node id once, on mount, + // so a layout re-added under the same id keeps rendering the removed column (crash). A new id + // remounts it. Columns and content keep their ids (and Sitesmith `node_id` props). + const newLayoutId = getRandomId(); + const nodes: Record = {}; + for (const [id, n0] of Object.entries(tree.nodes as Record)) { + if (drop.has(id)) continue; + const n = n0.data?.parent === layoutId ? { ...n0, data: { ...n0.data, parent: newLayoutId } } : n0; + if (id === layoutId) { + nodes[newLayoutId] = { + ...n, + id: newLayoutId, + data: { + ...n.data, + props: { ...n.data.props, columns: newCount, split }, + linkedNodes: Object.fromEntries(keep.map((cid, i) => [`col-${i}`, cid])), + }, + }; + continue; + } + const col = keep.indexOf(id); + const flex = n.data?.props?.style?.flex; + // A column made by the Columns block carries its width as `flex: 0 0 calc( - )` + // (the editor shows that; export overrides it). Keep the editor in step with the new split. + if (col !== -1 && typeof flex === 'string' && /^0 0 calc\(/.test(flex)) { + nodes[id] = { ...n, data: { ...n.data, props: { ...n.data.props, style: { ...n.data.props.style, flex: `0 0 calc(${newWidths[col]} - ${gap})` } } } }; + continue; + } + nodes[id] = n; + } + + (opts.mergeWithPrevious ? actions.history.merge() : actions).delete(layoutId); + actions.history.merge().addNodeTree({ rootNodeId: newLayoutId, nodes }, grandId, index); + return newLayoutId; +} + +/** + * Carry out `planDelete` for one node. Returns null when something was deleted, otherwise the + * reason it was not (for a visible notice) plus the element to delete instead, when there is one. + */ +export function runDelete(actions: any, query: any, nodeId: string | null | undefined): { reason: string; ownerId?: string } | null { + const plan = planDelete(query, nodeId); + try { + if (plan.kind === 'node') { actions.delete(plan.id); return null; } + if (plan.kind === 'column') { removeColumn(actions, query, plan.layoutId, plan.columnId); return null; } + return { reason: plan.reason, ownerId: plan.ownerId }; + } catch (e) { + console.error('Delete failed:', e); + return { reason: 'That element could not be deleted. Try selecting the element around it.' }; } } diff --git a/craft/src/utils/sitesmith-delete.test.ts b/craft/src/utils/sitesmith-delete.test.ts new file mode 100644 index 0000000..dd6fc37 --- /dev/null +++ b/craft/src/utils/sitesmith-delete.test.ts @@ -0,0 +1,139 @@ +/** + * Regression: "when Sitesmith creates a layout, some containers cannot be deleted" (2026-11-08). + * + * Every Sitesmith layout puts its cards/columns as Container children of a ColumnLayout. The + * flattener turns those into Craft LINKED nodes (`col-N`), which Craft never deletes + * (`isDeletable()` is false), and the old `findDeletableTarget` returned null for a populated + * column -> every delete route silently did nothing. Uses the REAL captured Sitesmith responses. + */ +import { describe, test, expect, afterEach } from 'vitest'; +import olsHome from './__fixtures__/sitesmith-ols-home-response.json'; +import ttmLikes from './__fixtures__/sitesmith-ttm-likes-response.json'; +import { renderEditorHarness, EditorHarness } from '../test-utils/editorHarness'; +import { buildNodeTree } from './craft-tree'; +import { planDelete, runDelete, splitWithoutColumn } from './craft-helpers'; +import { exportBodyHtml } from './html-export'; + +const FIXTURES = ['sitesmith-ols-home-response.json', 'sitesmith-ttm-likes-response.json']; +const RESPONSES: Record = { 'sitesmith-ols-home-response.json': olsHome, 'sitesmith-ttm-likes-response.json': ttmLikes }; +const load = (f: string) => RESPONSES[f]; + +let h: EditorHarness | null = null; +afterEach(() => { h?.unmount(); h = null; }); + +function mount(fixture: string) { + h = renderEditorHarness(); + const tree = buildNodeTree(h.query, load(fixture).pages[0].tree); + h.act(() => h!.actions.addNodeTree(tree, 'ROOT')); + return h; +} + +const nodesOf = (hh: EditorHarness) => hh.query.getNodes() as Record; +const columnsOf = (hh: EditorHarness) => + Object.entries(nodesOf(hh)) + .filter(([, n]) => n.data.name === 'ColumnLayout') + .map(([id, n]) => ({ id, cols: Object.values(n.data.linkedNodes as Record) })); + +describe.each(FIXTURES)('Sitesmith layout %s', (fixture) => { + test('every generated column Container is deletable (none is a silent no-op)', () => { + const hh = mount(fixture); + const layouts = columnsOf(hh); + expect(layouts.length).toBeGreaterThan(0); + for (const { cols } of layouts) { + for (const col of cols) { + // Craft itself refuses (linked node) -- that is the trap. + expect(hh.query.node(col).isDeletable()).toBe(false); + expect(planDelete(hh.query, col).kind).toBe('column'); + } + } + }); + + test('deleting the last and then the first column of every layout removes exactly that column', () => { + const hh = mount(fixture); + for (const { id: layoutId0, cols } of columnsOf(hh)) { + const first = cols[0]; + const last = cols[cols.length - 1]; + let blocked: unknown = 'x'; + hh.act(() => { blocked = runDelete(hh.actions, hh.query, last); }); + expect(blocked).toBeNull(); + expect(nodesOf(hh)[last]).toBeUndefined(); + expect(nodesOf(hh)[layoutId0]).toBeUndefined(); // rebuilt under a new id + const parentOfFirst = nodesOf(hh)[first].data.parent; + const layout = nodesOf(hh)[parentOfFirst].data; + expect(layout.name).toBe('ColumnLayout'); + expect(layout.props.columns).toBe(cols.length - 1); + expect(Object.keys(layout.linkedNodes)).toEqual(cols.slice(0, -1).map((_, i) => `col-${i}`)); + expect(Object.values(layout.linkedNodes)).toEqual(cols.slice(0, -1)); + if (cols.length > 2) { + hh.act(() => { blocked = runDelete(hh.actions, hh.query, first); }); + expect(blocked).toBeNull(); + expect(nodesOf(hh)[first]).toBeUndefined(); + } else { + // one column left: deleting it deletes the (now one-column) layout + hh.act(() => { blocked = runDelete(hh.actions, hh.query, first); }); + expect(blocked).toBeNull(); + expect(nodesOf(hh)[first]).toBeUndefined(); + expect(nodesOf(hh)[parentOfFirst]).toBeUndefined(); + } + } + // Still a valid, exportable page with no dangling ids. + const state = JSON.parse(hh.getSerialized()); + for (const [id, n] of Object.entries(state as Record)) { + for (const c of [...n.nodes, ...Object.values(n.linkedNodes as Record)]) { + expect(state[c as string], `${id} -> ${c}`).toBeDefined(); + } + } + expect(exportBodyHtml(hh.getSerialized()).html.length).toBeGreaterThan(100); + }); + + test('one undo brings a removed column back with its content', () => { + const hh = mount(fixture); + const before = hh.getSerialized(); + const { cols } = columnsOf(hh)[0]; + hh.act(() => { runDelete(hh.actions, hh.query, cols[0]); }); + expect(nodesOf(hh)[cols[0]]).toBeUndefined(); + hh.act(() => hh.actions.history.undo()); + expect(nodesOf(hh)[cols[0]]).toBeDefined(); + expect(JSON.parse(hh.getSerialized())).toEqual(JSON.parse(before)); + }); + + test('a Section content area is not deleted alone but says why and names the Section', () => { + const hh = mount(fixture); + const [secId, sec] = Object.entries(nodesOf(hh)).find(([, n]) => n.data.name === 'Section')!; + const inner = (sec.data.linkedNodes as Record)['section-inner']; + const before = hh.getSerialized(); + let res: { reason: string; ownerId?: string } | null = null; + hh.act(() => { res = runDelete(hh.actions, hh.query, inner); }); + expect(hh.getSerialized()).toBe(before); + expect(res!.reason).toMatch(/content area/); + expect(res!.ownerId).toBe(secId); + }); +}); + +describe('splitWithoutColumn', () => { + test.each([ + ['50-50', 2, 0, 'equal'], + ['33-33-33', 3, 1, 'equal'], + ['25-50-25', 3, 0, '67-33'], + ['30-70', 2, 1, 'equal'], + ['equal', 4, 3, 'equal'], + ['40-30-30', 3, 0, 'equal'], + ['20-30-50', 3, 1, '29-71'], + ])('%s (%i cols) minus #%i -> %s', (split, n, i, want) => { + expect(splitWithoutColumn(split, n as number, i as number)).toBe(want); + }); +}); + +describe('Sitesmith patch delete_node on a generated card', () => { + test('removes the card (a linked column) instead of failing silently', async () => { + const { __test } = await import('./apply-ai-response'); + const hh = mount('sitesmith-ttm-likes-response.json'); + const { cols } = columnsOf(hh).find((l) => l.cols.length === 4)!; + let out: any; + hh.act(() => { out = __test.applyPatch(hh.actions, hh.query, [{ op: 'delete_node', node_id: cols[2] } as any]); }); + expect(out.changed).toBe(1); + expect(nodesOf(hh)[cols[2]]).toBeUndefined(); + const layout = nodesOf(hh)[nodesOf(hh)[cols[0]].data.parent].data; + expect(Object.values(layout.linkedNodes)).toEqual([cols[0], cols[1], cols[3]]); + }); +});