Compare commits

..
Author SHA1 Message Date
shadowdaoandClaude Opus 4.8 c712a69c4a test(topbar): cover publish() warnings wiring into PublishWarnings banner
PublishWarnings.tsx had unit tests for the presentational banner, but
nothing asserted that result.warnings from publish() actually flows
through TopBar's handlePublish into it. That 3-line seam is exactly what
this feature exists to fix -- the backend always returned warnings, and
TopBar discarded them by only checking result.success, so the
contact-form-relay warning was dead code for its entire life.

Adds TopBar.test.tsx asserting: warnings render after a successful
publish with warnings, no banner renders when warnings is absent, a
warning doesn't present as a publish failure, warnings survive the 3s
"Published" flash (fake timers, advanced past 3000ms), and a fresh
publish clears stale warnings from the previous one.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 22:12:31 -07:00
shadowdaoandClaude Opus 4.8 d460e8ac33 topbar: surface publish warnings instead of discarding them
handlePublish's JSON response has always included a `warnings` array
(e.g. the contact-form relay's "submissions will not be delivered"
notice), but nothing in the editor ever read it. Adds a PublishWarnings
banner, held in its own state independent of the 3s publishStatus
flash so the customer has time to read it, rendered in both the
desktop and mobile TopBar branches.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 21:52:11 -07:00
jknapp 2b1569202a Merge PR #25: bounce + image crop/resize fix 2026-07-14 23:07:58 +00:00
shadowdaoandClaude Opus 4.8 5c44dd545c fix(site-builder): bounce stays visible + springier; image/video crop fills (cover) + resize shrinks footprint
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 16:04:50 -07:00
jknapp 2ac62c4e9e Merge PR #24: fix animation delay unit 2026-07-14 19:36:51 +00:00
shadowdaoandClaude Opus 4.8 25dfcbb725 fix(site-builder): coerce bare-number animation delay to a valid CSS time (2 -> 2s)
data-animation-delay is stored as a plain seconds string (e.g. '2'); the reveal
script assigned it raw to el.style.animationDelay, which is invalid CSS and no-ops.
Suffix 's' onto bare numbers (leaving '2s'/'200ms' alone) so entrance-animation
delays actually apply. Backend generateCompiledHTML gets the byte-identical change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 12:34:51 -07:00
jknapp 9bf78fd72d Merge PR #23: fix entrance-animation output 2026-07-14 19:16:59 +00:00
shadowdaoandClaude Opus 4.8 2dcc2b4d21 fix(site-builder): entrance-animation reveal script survives Preview + well-formed void-tag attrs + no-JS fallback
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 12:12:01 -07:00
jknapp 4e0fc78a30 Merge PR #22: enh pages productivity + cross-page clipboard 2026-07-14 14:48:25 +00:00
shadowdaoandClaude Opus 4.8 85dfe181aa fix(pages): duplicatePage must save outgoing active canvas before teardown (avoid dropping live edits)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 07:47:44 -07:00
shadowdaoandClaude Opus 4.8 a698f014b0 feat(site-builder): page duplicate/reorder/set-landing + fix cross-page node copy/paste
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 07:36:00 -07:00
jknapp 204ea5e078 Merge PR #21: enh output/seo/tokens (frontend) 2026-07-14 14:21:10 +00:00
20 changed files with 1950 additions and 125 deletions
+78 -12
View File
@@ -1,29 +1,95 @@
import { describe, test, expect, afterEach } from 'vitest'; import { describe, test, expect, afterEach } from 'vitest';
import { getClipboardNodeId, setClipboardNodeId } from './clipboard'; import type { NodeTree } from '@craftjs/core';
import { getClipboardTree, setClipboardTree } from './clipboard';
function makeTree(rootId: string, props: Record<string, unknown> = {}): NodeTree {
return {
rootNodeId: rootId,
nodes: {
[rootId]: {
id: rootId,
data: {
type: { resolvedName: 'Container' },
name: 'Container',
displayName: 'Container',
props,
custom: {},
isCanvas: false,
parent: 'wherever-it-originally-lived',
nodes: [],
linkedNodes: {},
hidden: false,
},
info: {},
events: { selected: false, dragged: false, hovered: false },
dom: null,
related: {},
rules: {},
_hydrationTimestamp: 0,
} as unknown as NodeTree['nodes'][string],
},
};
}
describe('clipboard', () => { describe('clipboard', () => {
afterEach(() => { afterEach(() => {
setClipboardNodeId(null); setClipboardTree(null);
}); });
test('starts empty', () => { test('starts empty', () => {
expect(getClipboardNodeId()).toBeNull(); expect(getClipboardTree()).toBeNull();
}); });
test('set then get returns the stored node id', () => { test('set then get returns a tree with the same root id and shape', () => {
setClipboardNodeId('node-123'); const tree = makeTree('node-123', { text: 'hello' });
expect(getClipboardNodeId()).toBe('node-123'); setClipboardTree(tree);
const got = getClipboardTree();
expect(got).not.toBeNull();
expect(got!.rootNodeId).toBe('node-123');
expect(got!.nodes['node-123'].data.props).toEqual({ text: 'hello' });
}); });
test('is a shared module-level store -- overwriting replaces the previous value', () => { test('is a shared module-level store -- overwriting replaces the previous value', () => {
setClipboardNodeId('first'); setClipboardTree(makeTree('first'));
setClipboardNodeId('second'); setClipboardTree(makeTree('second'));
expect(getClipboardNodeId()).toBe('second'); expect(getClipboardTree()!.rootNodeId).toBe('second');
}); });
test('can be cleared back to null', () => { test('can be cleared back to null', () => {
setClipboardNodeId('node-123'); setClipboardTree(makeTree('node-123'));
setClipboardNodeId(null); setClipboardTree(null);
expect(getClipboardNodeId()).toBeNull(); expect(getClipboardTree()).toBeNull();
});
test('deep-clones on set: mutating the original tree after set does not affect the stored snapshot', () => {
const original = makeTree('node-123', { text: 'original' });
setClipboardTree(original);
// Mutate the original tree's props object directly (as if the source
// node were edited, or the same live node got copied again).
(original.nodes['node-123'].data.props as Record<string, unknown>).text = 'mutated';
expect(getClipboardTree()!.nodes['node-123'].data.props).toEqual({ text: 'original' });
});
test('deep-clones nested props (arrays/objects), not just the top-level props object', () => {
const original = makeTree('node-123', { links: [{ url: 'https://example.com' }] });
setClipboardTree(original);
(original.nodes['node-123'].data.props as any).links[0].url = 'https://mutated.example.com';
expect((getClipboardTree()!.nodes['node-123'].data.props as any).links[0].url).toBe(
'https://example.com',
);
});
test('survives the original tree object being discarded entirely (detached copy, not a live reference)', () => {
let tree: NodeTree | null = makeTree('node-abc', { text: 'snapshot' });
setClipboardTree(tree);
tree = null; // simulate the original page's node/tree going away entirely
const got = getClipboardTree();
expect(got).not.toBeNull();
expect(got!.nodes['node-abc'].data.props).toEqual({ text: 'snapshot' });
}); });
}); });
+65 -7
View File
@@ -1,3 +1,5 @@
import type { Node, NodeId, NodeTree } from '@craftjs/core';
/** /**
* Tiny shared clipboard for canvas node copy/paste. * Tiny shared clipboard for canvas node copy/paste.
* *
@@ -9,15 +11,71 @@
* Deliberately not React state -- nothing in the UI needs to re-render * Deliberately not React state -- nothing in the UI needs to re-render
* reactively when the clipboard changes; consumers just read the current * reactively when the clipboard changes; consumers just read the current
* value at the moment they need it (on paste, or when a menu opens). * value at the moment they need it (on paste, or when a menu opens).
*
* Historical bug (cross-page copy/paste): this used to store only the copied
* node's bare id (`clipboardNodeId`) and re-resolve it via `query.node(id)`
* at paste time. That works fine same-page, but the moment the user switches
* pages the canvas is re-deserialized to the target page's Craft.js state --
* the copied id no longer exists in `query` at all -- so a cross-page paste
* silently no-op'd (or threw, caught, and swallowed). Storing a detached
* TREE SNAPSHOT at copy time instead means paste never needs to look the
* source id up again: it just hands the snapshot to `regenerateTreeIds` +
* `actions.addNodeTree`, which works identically regardless of which page's
* state is currently loaded on the canvas.
*/ */
let clipboardNodeId: string | null = null; let clipboardTree: NodeTree | null = null;
/** Returns the id of the node currently on the clipboard, or null if empty. */ /**
export function getClipboardNodeId(): string | null { * Deep, detached clone of a live Craft.js `NodeTree` (as returned by
return clipboardNodeId; * `query.node(id).toNodeTree()`).
*
* Not a plain `structuredClone(tree)`: for a REAL (live) Craft.js node,
* `data.type` is the actual component function/class reference (not a
* serializable `{resolvedName}` wrapper) -- `structuredClone` cannot clone a
* function and throws `DataCloneError` (see the identical note on
* `regenerateTreeIds` in `utils/craft-tree.ts`, which hit this exact bug
* historically). `type` is a stable reference shared by every node of that
* component across the whole app (it doesn't change per page), so it's safe
* to keep by reference -- only the mutable per-node data (`props`, `custom`,
* `nodes`, `linkedNodes`) needs an actual deep copy so a later mutation (a
* subsequent paste's `setProp`, or a fresh copy of the same live node)
* can never reach back into this stored snapshot.
*/
function cloneNodeTree(tree: NodeTree): NodeTree {
const nodes: Record<NodeId, Node> = {};
for (const [id, node] of Object.entries(tree.nodes)) {
nodes[id] = {
...node,
data: {
...node.data,
props: structuredClone(node.data.props),
custom: structuredClone(node.data.custom),
nodes: [...(node.data.nodes || [])],
linkedNodes: { ...(node.data.linkedNodes || {}) },
},
};
}
return { rootNodeId: tree.rootNodeId, nodes };
} }
/** Sets (or clears, with `null`) the node id on the clipboard. */ /**
export function setClipboardNodeId(nodeId: string | null): void { * Returns the tree snapshot currently on the clipboard, or null if empty.
clipboardNodeId = nodeId; * The returned tree is safe to hand straight to `regenerateTreeIds` --
* `regenerateTreeIds` never mutates its input, so repeated pastes of the
* same clipboard contents (including across a page switch) all work off the
* same untouched snapshot.
*/
export function getClipboardTree(): NodeTree | null {
return clipboardTree;
}
/**
* Sets (or clears, with `null`) the tree snapshot on the clipboard. The tree
* is deep-cloned before being stored (see `cloneNodeTree`) so it is fully
* detached from the live Craft.js node it was captured from -- it survives
* that node being deleted, mutated, or (the whole point) the canvas being
* re-deserialized to a different page entirely.
*/
export function setClipboardTree(tree: NodeTree | null): void {
clipboardTree = tree ? cloneNodeTree(tree) : null;
} }
+53 -17
View File
@@ -4,7 +4,7 @@ import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils'; import { act } from 'react-dom/test-utils';
import type { NodeTree, Node } from '@craftjs/core'; import type { NodeTree, Node } from '@craftjs/core';
import { useKeyboardShortcuts } from './useKeyboardShortcuts'; import { useKeyboardShortcuts } from './useKeyboardShortcuts';
import { getClipboardNodeId, setClipboardNodeId } from './clipboard'; import { getClipboardTree, setClipboardTree } from './clipboard';
/** /**
* Regression coverage: Ctrl/Cmd+V must run the copied subtree through * Regression coverage: Ctrl/Cmd+V must run the copied subtree through
@@ -15,6 +15,13 @@ import { getClipboardNodeId, setClipboardNodeId } from './clipboard';
* ROOT-fallback targeting, the empty-clipboard no-op, and the existing * ROOT-fallback targeting, the empty-clipboard no-op, and the existing
* input-focus guard. * input-focus guard.
* *
* Also covers the cross-page clipboard fix: copy stores a detached TREE
* SNAPSHOT (`setClipboardTree`), not a bare node id -- so paste never needs
* to re-resolve the original node via `query.node(id)`, which is exactly
* what breaks once the canvas has been re-deserialized to a different page
* (see `hooks/clipboard.ts` and the cross-page integration test in
* `test-utils/integration/duplicate-paste.integration.test.tsx`).
*
* Mock pattern mirrors PageContext.pure-updaters.test.tsx / * Mock pattern mirrors PageContext.pure-updaters.test.tsx /
* PageContext.slug.test.tsx: a fake `useEditor` exposing `query`/`actions`, * PageContext.slug.test.tsx: a fake `useEditor` exposing `query`/`actions`,
* mounted via a bare consumer component, with REAL `keydown` events * mounted via a bare consumer component, with REAL `keydown` events
@@ -27,6 +34,7 @@ import { getClipboardNodeId, setClipboardNodeId } from './clipboard';
*/ */
const addNodeTreeMock = vi.fn(); const addNodeTreeMock = vi.fn();
const selectNodeMock = vi.fn();
let selectedIds: string[] = []; let selectedIds: string[] = [];
function makeNode(id: string, parent: string | null, children: string[] = []): Node { function makeNode(id: string, parent: string | null, children: string[] = []): Node {
@@ -62,9 +70,10 @@ const COPIED_TREE: NodeTree = {
}, },
}; };
const nodeStore: Record<string, { data: { parent: string | null } }> = { const nodeStore: Record<string, { data: { parent: string | null; nodes?: string[] } }> = {
'selected-1': { data: { parent: 'parent-container-1' } }, 'selected-1': { data: { parent: 'parent-container-1' } },
ROOT: { data: { parent: null } }, 'parent-container-1': { data: { parent: null, nodes: ['other-sibling', 'selected-1'] } },
ROOT: { data: { parent: null, nodes: [] } },
'copied-root-1': { data: { parent: 'wherever-it-originally-lived' } }, 'copied-root-1': { data: { parent: 'wherever-it-originally-lived' } },
}; };
@@ -88,6 +97,7 @@ vi.mock('@craftjs/core', () => ({
}, },
actions: { actions: {
addNodeTree: addNodeTreeMock, addNodeTree: addNodeTreeMock,
selectNode: selectNodeMock,
history: { undo: vi.fn(), redo: vi.fn() }, history: { undo: vi.fn(), redo: vi.fn() },
delete: vi.fn(), delete: vi.fn(),
clearEvents: vi.fn(), clearEvents: vi.fn(),
@@ -145,44 +155,51 @@ const Consumer: React.FC = () => {
beforeEach(() => { beforeEach(() => {
selectedIds = []; selectedIds = [];
addNodeTreeMock.mockClear(); addNodeTreeMock.mockClear();
selectNodeMock.mockClear();
regenerateTreeIdsMock.mockClear(); regenerateTreeIdsMock.mockClear();
setClipboardNodeId(null); setClipboardTree(null);
}); });
afterEach(() => { afterEach(() => {
setClipboardNodeId(null); setClipboardTree(null);
if (root) unmount(); if (root) unmount();
}); });
describe('useKeyboardShortcuts: Ctrl/Cmd+C / Ctrl/Cmd+V', () => { describe('useKeyboardShortcuts: Ctrl/Cmd+C / Ctrl/Cmd+V', () => {
test('Ctrl+C copies the selected node id to the clipboard', () => { test('Ctrl+C copies the selected node`s subtree (a tree snapshot, not a bare id) to the clipboard', () => {
render(<Consumer />); render(<Consumer />);
selectedIds = ['selected-1']; selectedIds = ['copied-root-1'];
pressKey('c'); pressKey('c');
expect(getClipboardNodeId()).toBe('selected-1'); const clip = getClipboardTree();
expect(clip).not.toBeNull();
expect(clip!.rootNodeId).toBe('copied-root-1');
expect(Object.keys(clip!.nodes).sort()).toEqual(['copied-child-1', 'copied-root-1']);
}); });
test('Ctrl+V pastes as a sibling of the selection (selected node`s data.parent) with FRESH ids', () => { test('Ctrl+V pastes as a sibling of the selection, immediately after it, with FRESH ids', () => {
render(<Consumer />); render(<Consumer />);
selectedIds = ['copied-root-1']; selectedIds = ['copied-root-1'];
pressKey('c'); pressKey('c');
expect(getClipboardNodeId()).toBe('copied-root-1'); expect(getClipboardTree()!.rootNodeId).toBe('copied-root-1');
selectedIds = ['selected-1']; selectedIds = ['selected-1'];
pressKey('v'); pressKey('v');
// regenerateTreeIds actually ran before the tree was handed to Craft.js. // regenerateTreeIds actually ran before the tree was handed to Craft.js.
expect(regenerateTreeIdsMock).toHaveBeenCalledTimes(1); expect(regenerateTreeIdsMock).toHaveBeenCalledTimes(1);
expect(regenerateTreeIdsMock).toHaveBeenCalledWith(COPIED_TREE); expect(regenerateTreeIdsMock).toHaveBeenCalledWith(getClipboardTree());
expect(addNodeTreeMock).toHaveBeenCalledTimes(1); expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
const [pastedTree, targetParent] = addNodeTreeMock.mock.calls[0]; const [pastedTree, targetParent, insertIndex] = addNodeTreeMock.mock.calls[0];
// Sibling of the current selection: selected-1's data.parent. // Sibling of the current selection: selected-1's data.parent.
expect(targetParent).toBe('parent-container-1'); expect(targetParent).toBe('parent-container-1');
// Immediately after selected-1 (index 1 among parent-container-1's
// children), matching duplicate()'s "insert right after" UX.
expect(insertIndex).toBe(2);
// The regression this guards: pasted ids must be fresh, never reuse the // The regression this guards: pasted ids must be fresh, never reuse the
// ids the copied node already occupies in the live Craft.js tree. // ids the copied node already occupies in the live Craft.js tree.
@@ -193,9 +210,12 @@ describe('useKeyboardShortcuts: Ctrl/Cmd+C / Ctrl/Cmd+V', () => {
for (const id of pastedIds) { for (const id of pastedIds) {
expect(originalIds.has(id)).toBe(false); expect(originalIds.has(id)).toBe(false);
} }
// The new copy is selected, same as duplicate()'s existing UX.
expect(selectNodeMock).toHaveBeenCalledWith(pastedTree.rootNodeId);
}); });
test('Ctrl+V with selection at ROOT falls back to ROOT as the insertion parent', () => { test('Ctrl+V with selection at ROOT falls back to appending into ROOT', () => {
render(<Consumer />); render(<Consumer />);
selectedIds = ['copied-root-1']; selectedIds = ['copied-root-1'];
@@ -205,8 +225,24 @@ describe('useKeyboardShortcuts: Ctrl/Cmd+C / Ctrl/Cmd+V', () => {
pressKey('v'); pressKey('v');
expect(addNodeTreeMock).toHaveBeenCalledTimes(1); expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
const [, targetParent] = addNodeTreeMock.mock.calls[0]; const [, targetParent, insertIndex] = addNodeTreeMock.mock.calls[0];
expect(targetParent).toBe('ROOT'); expect(targetParent).toBe('ROOT');
expect(insertIndex).toBeUndefined();
});
test('Ctrl+V with nothing selected falls back to appending into ROOT', () => {
render(<Consumer />);
selectedIds = ['copied-root-1'];
pressKey('c');
selectedIds = [];
pressKey('v');
expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
const [, targetParent, insertIndex] = addNodeTreeMock.mock.calls[0];
expect(targetParent).toBe('ROOT');
expect(insertIndex).toBeUndefined();
}); });
test('Ctrl+V with an empty clipboard is a no-op', () => { test('Ctrl+V with an empty clipboard is a no-op', () => {
@@ -229,9 +265,9 @@ describe('useKeyboardShortcuts: Ctrl/Cmd+C / Ctrl/Cmd+V', () => {
selectedIds = ['selected-1']; selectedIds = ['selected-1'];
pressKey('c'); pressKey('c');
expect(getClipboardNodeId()).toBeNull(); expect(getClipboardTree()).toBeNull();
setClipboardNodeId('copied-root-1'); setClipboardTree(COPIED_TREE);
pressKey('v'); pressKey('v');
expect(addNodeTreeMock).not.toHaveBeenCalled(); expect(addNodeTreeMock).not.toHaveBeenCalled();
@@ -252,7 +288,7 @@ describe('useKeyboardShortcuts: Ctrl/Cmd+C / Ctrl/Cmd+V', () => {
selectedIds = ['selected-1']; selectedIds = ['selected-1'];
pressKey('c'); pressKey('c');
expect(getClipboardNodeId()).toBeNull(); expect(getClipboardTree()).toBeNull();
activeElementSpy.mockRestore(); activeElementSpy.mockRestore();
}); });
+35 -13
View File
@@ -2,7 +2,7 @@ import { useEffect } from 'react';
import { useEditor } from '@craftjs/core'; import { useEditor } from '@craftjs/core';
import { findDeletableTarget } from '../utils/craft-helpers'; import { findDeletableTarget } from '../utils/craft-helpers';
import { regenerateTreeIds } from '../utils/craft-tree'; import { regenerateTreeIds } from '../utils/craft-tree';
import { getClipboardNodeId, setClipboardNodeId } from './clipboard'; import { getClipboardTree, setClipboardTree } from './clipboard';
function isInputFocused(): boolean { function isInputFocused(): boolean {
const el = document.activeElement; const el = document.activeElement;
@@ -86,13 +86,16 @@ export function useKeyboardShortcuts() {
return; return;
} }
// Ctrl+C: copy selected node id to the shared clipboard // Ctrl+C: copy the selected node's subtree (a detached snapshot, not
// just its id -- see clipboard.ts for why: an id-based clipboard can't
// survive a page switch, since the copied id no longer exists in
// `query` once the canvas is re-deserialized to a different page).
if (ctrl && (e.key === 'c' || e.key === 'C')) { if (ctrl && (e.key === 'c' || e.key === 'C')) {
e.preventDefault(); e.preventDefault();
try { try {
const selected = query.getEvent('selected').all(); const selected = query.getEvent('selected').all();
if (selected.length > 0 && selected[0] !== 'ROOT') { if (selected.length > 0 && selected[0] !== 'ROOT') {
setClipboardNodeId(selected[0]); setClipboardTree(query.node(selected[0]).toNodeTree());
} }
} catch (err) { } catch (err) {
console.error('Copy failed:', err); console.error('Copy failed:', err);
@@ -100,25 +103,44 @@ export function useKeyboardShortcuts() {
return; return;
} }
// Ctrl+V: paste the clipboard node as a sibling of the current selection // Ctrl+V: paste the clipboard tree as a sibling of the current
// selection (immediately after it, matching duplicate()'s UX), or
// append to ROOT when nothing is selected. Works regardless of which
// page is currently on the canvas -- the clipboard tree is a detached
// snapshot, not a reference to a node that may no longer exist here.
if (ctrl && (e.key === 'v' || e.key === 'V')) { if (ctrl && (e.key === 'v' || e.key === 'V')) {
e.preventDefault(); e.preventDefault();
try { try {
const sourceId = getClipboardNodeId(); const clip = getClipboardTree();
if (!sourceId || !query.node(sourceId).get()) return; if (!clip) return;
const selected = query.getEvent('selected').all(); const selected = query.getEvent('selected').all();
if (selected.length === 0) return; const selectedId = selected.length > 0 ? selected[0] : null;
const selectedId = selected[0];
let targetParent = 'ROOT'; let targetParentId = 'ROOT';
if (selectedId !== 'ROOT') { let insertIndex: number | undefined;
if (selectedId && selectedId !== 'ROOT') {
const node = query.node(selectedId).get(); const node = query.node(selectedId).get();
targetParent = node?.data?.parent || 'ROOT'; const parentId: string | null | undefined = node?.data?.parent;
if (parentId) {
targetParentId = parentId;
try {
const siblings: string[] = query.node(parentId).get()?.data?.nodes || [];
const idx = siblings.indexOf(selectedId);
if (idx !== -1) insertIndex = idx + 1;
} catch {
// Leave insertIndex undefined -- addNodeTree appends when omitted.
}
}
} }
const tree = regenerateTreeIds(query.node(sourceId).toNodeTree()); const tree = regenerateTreeIds(clip);
actions.addNodeTree(tree, targetParent); if (insertIndex !== undefined) {
actions.addNodeTree(tree, targetParentId, insertIndex);
} else {
actions.addNodeTree(tree, targetParentId);
}
actions.selectNode(tree.rootNodeId);
} catch (err) { } catch (err) {
console.error('Paste failed:', err); console.error('Paste failed:', err);
} }
+35 -16
View File
@@ -3,7 +3,7 @@ import { useEditor } from '@craftjs/core';
import { useSitesmithModal } from '../../state/SitesmithContext'; import { useSitesmithModal } from '../../state/SitesmithContext';
import { buildSitesmithTarget } from '../../utils/sitesmith-target'; import { buildSitesmithTarget } from '../../utils/sitesmith-target';
import { regenerateTreeIds } from '../../utils/craft-tree'; import { regenerateTreeIds } from '../../utils/craft-tree';
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard'; import { getClipboardTree, setClipboardTree } from '../../hooks/clipboard';
import { useNodeActions } from '../../hooks/useNodeActions'; import { useNodeActions } from '../../hooks/useNodeActions';
interface ContextMenuProps { interface ContextMenuProps {
@@ -79,35 +79,54 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
const copyNode = useCallback(() => { const copyNode = useCallback(() => {
if (!nodeId || nodeId === 'ROOT') return; if (!nodeId || nodeId === 'ROOT') return;
try { try {
setClipboardNodeId(nodeId); // Store a detached subtree snapshot, not just the id -- an id-based
// clipboard can't survive a page switch (the copied id no longer
// exists in `query` once the canvas is re-deserialized to a different
// page's Craft.js state). See clipboard.ts.
setClipboardTree(query.node(nodeId).toNodeTree());
} catch (e) { } catch (e) {
console.error('Copy failed:', e); console.error('Copy failed:', e);
} }
onClose(); onClose();
}, [nodeId, onClose]); }, [nodeId, query, onClose]);
const pasteNode = useCallback(() => { const pasteNode = useCallback(() => {
const sourceId = getClipboardNodeId(); const clip = getClipboardTree();
if (!sourceId) { if (!clip) {
onClose(); onClose();
return; return;
} }
try { try {
if (!query.node(sourceId).get()) { // Paste as a SIBLING of the right-clicked node (immediately after it,
onClose(); // matching duplicate()'s UX), not as its child -- using the clicked
return; // node itself as the parent throws when it's a leaf. Falls back to
} // appending into ROOT when nothing valid was right-clicked. This works
// regardless of which page is on the canvas -- the clipboard tree is a
// Paste as a SIBLING of the right-clicked node, not as its child -- // detached snapshot, not a reference to a node that may not exist here.
// using the clicked node itself as the parent throws when it's a leaf.
let targetParent = 'ROOT'; let targetParent = 'ROOT';
let insertIndex: number | undefined;
if (nodeId && nodeId !== 'ROOT') { if (nodeId && nodeId !== 'ROOT') {
const clickedNode = query.node(nodeId).get(); const clickedNode = query.node(nodeId).get();
targetParent = clickedNode?.data?.parent || 'ROOT'; const parentId: string | null | undefined = clickedNode?.data?.parent;
if (parentId) {
targetParent = parentId;
try {
const siblings: string[] = query.node(parentId).get()?.data?.nodes || [];
const idx = siblings.indexOf(nodeId);
if (idx !== -1) insertIndex = idx + 1;
} catch {
// Leave insertIndex undefined -- addNodeTree appends when omitted.
}
}
} }
const tree = regenerateTreeIds(query.node(sourceId).toNodeTree()); const tree = regenerateTreeIds(clip);
actions.addNodeTree(tree, targetParent); if (insertIndex !== undefined) {
actions.addNodeTree(tree, targetParent, insertIndex);
} else {
actions.addNodeTree(tree, targetParent);
}
actions.selectNode(tree.rootNodeId);
} catch (e) { } catch (e) {
console.error('Paste failed:', e); console.error('Paste failed:', e);
} }
@@ -176,7 +195,7 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
icon: 'clipboard', icon: 'clipboard',
shortcut: 'Ctrl+V', shortcut: 'Ctrl+V',
action: pasteNode, action: pasteNode,
disabled: !getClipboardNodeId(), disabled: !getClipboardTree(),
dividerAfter: true, dividerAfter: true,
}, },
{ {
+78 -40
View File
@@ -15,6 +15,9 @@ export const PagesPanel: React.FC = () => {
addPage, addPage,
deletePage, deletePage,
renamePage, renamePage,
duplicatePage,
movePage,
setLandingPage,
updatePageSeo, updatePageSeo,
} = usePages(); } = usePages();
const [isAdding, setIsAdding] = useState(false); const [isAdding, setIsAdding] = useState(false);
@@ -68,6 +71,33 @@ export const PagesPanel: React.FC = () => {
* differently-colored category. The active/editing state reuses the same * differently-colored category. The active/editing state reuses the same
* accent-outline treatment the page list already uses for the active page, * accent-outline treatment the page list already uses for the active page,
* so there's one consistent "this is what's currently open" affordance. */ * so there's one consistent "this is what's currently open" affordance. */
/* ---------- Per-page-row icon button ----------
* Shared 24x24 icon-button styling used by every action in the page row
* (SEO settings, rename, duplicate, reorder, set-as-home, delete) so a new
* action slots in looking identical to the pre-existing gear/pencil/trash
* buttons -- same dark-theme neutral treatment, `disabled` dims the icon
* (matching how `disabled` already reads elsewhere in this panel, e.g. the
* "Add Page" button), and `danger` reuses the existing delete-button
* accent color. */
const pageActionBtnStyle = (opts: { disabled?: boolean; danger?: boolean } = {}): React.CSSProperties => ({
width: 24,
height: 24,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 11,
color: opts.disabled
? 'var(--color-text-dim)'
: opts.danger
? 'var(--color-danger)'
: 'var(--color-text-muted)',
background: 'transparent',
border: 'none',
borderRadius: 'var(--radius-sm)',
cursor: opts.disabled ? 'default' : 'pointer',
opacity: opts.disabled ? 0.5 : 1,
});
const zoneRowStyle = (isActive: boolean): React.CSSProperties => ({ const zoneRowStyle = (isActive: boolean): React.CSSProperties => ({
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
@@ -344,26 +374,58 @@ export const PagesPanel: React.FC = () => {
</div> </div>
</div> </div>
<div <div
style={{ display: 'flex', gap: 4, flexShrink: 0 }} style={{ display: 'flex', gap: 2, flexShrink: 0, flexWrap: 'wrap', justifyContent: 'flex-end', maxWidth: 96 }}
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
> >
<button
onClick={() => movePage(page.id, 'up')}
disabled={pageIndex === 0}
data-tooltip="Move up"
aria-label={`Move ${page.name} up`}
style={pageActionBtnStyle({ disabled: pageIndex === 0 })}
>
<i className="fa fa-arrow-up" aria-hidden="true" />
</button>
<button
onClick={() => movePage(page.id, 'down')}
disabled={pageIndex === pages.length - 1}
data-tooltip="Move down"
aria-label={`Move ${page.name} down`}
style={pageActionBtnStyle({ disabled: pageIndex === pages.length - 1 })}
>
<i className="fa fa-arrow-down" aria-hidden="true" />
</button>
<button
onClick={() => duplicatePage(page.id)}
data-tooltip="Duplicate"
aria-label={`Duplicate ${page.name}`}
style={pageActionBtnStyle()}
>
<i className="fa fa-clone" aria-hidden="true" />
</button>
{isLanding ? (
<span
data-tooltip="This is the home page"
aria-label={`${page.name} is the home page`}
style={pageActionBtnStyle({ disabled: true })}
>
<i className="fa fa-home" aria-hidden="true" />
</span>
) : (
<button
onClick={() => setLandingPage(page.id)}
data-tooltip="Set as home page"
aria-label={`Set ${page.name} as the home page`}
style={pageActionBtnStyle()}
>
<i className="fa fa-home" aria-hidden="true" />
</button>
)}
<button <button
onClick={() => setSeoSettingsPageId(page.id)} onClick={() => setSeoSettingsPageId(page.id)}
data-tooltip="Page Settings (SEO)" data-tooltip="Page Settings (SEO)"
aria-label={`Page settings for ${page.name}`} aria-label={`Page settings for ${page.name}`}
style={{ style={pageActionBtnStyle()}
width: 24,
height: 24,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 11,
color: 'var(--color-text-muted)',
background: 'transparent',
border: 'none',
borderRadius: 'var(--radius-sm)',
cursor: 'pointer',
}}
> >
<i className="fa fa-cog" aria-hidden="true" /> <i className="fa fa-cog" aria-hidden="true" />
</button> </button>
@@ -371,19 +433,7 @@ export const PagesPanel: React.FC = () => {
onClick={() => startEditing(page)} onClick={() => startEditing(page)}
data-tooltip="Rename" data-tooltip="Rename"
aria-label={`Rename ${page.name}`} aria-label={`Rename ${page.name}`}
style={{ style={pageActionBtnStyle()}
width: 24,
height: 24,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 11,
color: 'var(--color-text-muted)',
background: 'transparent',
border: 'none',
borderRadius: 'var(--radius-sm)',
cursor: 'pointer',
}}
> >
<i className="fa fa-pencil" aria-hidden="true" /> <i className="fa fa-pencil" aria-hidden="true" />
</button> </button>
@@ -392,19 +442,7 @@ export const PagesPanel: React.FC = () => {
onClick={() => setDeleteConfirmId(page.id)} onClick={() => setDeleteConfirmId(page.id)}
data-tooltip="Delete" data-tooltip="Delete"
aria-label={`Delete ${page.name}`} aria-label={`Delete ${page.name}`}
style={{ style={pageActionBtnStyle({ danger: true })}
width: 24,
height: 24,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 11,
color: 'var(--color-text-muted)',
background: 'transparent',
border: 'none',
borderRadius: 'var(--radius-sm)',
cursor: 'pointer',
}}
> >
<i className="fa fa-trash" aria-hidden="true" /> <i className="fa fa-trash" aria-hidden="true" />
</button> </button>
@@ -0,0 +1,133 @@
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
/* Same DOM-harness pattern as MediaStylePanel.video.test.tsx -- mock
@craftjs/core's useEditor so setProp calls can be observed without
mounting a real <Editor> tree, and mock utils/assets so AssetPicker
doesn't hit the network. */
const setPropSpy = vi.fn((_id: string, updater: (p: any) => void) => {
updater(lastProps);
});
let lastProps: any;
vi.mock('@craftjs/core', () => ({
useEditor: () => ({ actions: { setProp: setPropSpy } }),
}));
vi.mock('../../../utils/assets', () => ({
uploadAsset: vi.fn(),
listAssets: vi.fn(),
}));
import { ImageStylePanel } from './ImageStylePanel';
let container: HTMLDivElement;
let root: Root;
function render(ui: React.ReactElement) {
container = document.createElement('div');
document.body.appendChild(container);
act(() => {
root = createRoot(container);
root.render(ui);
});
}
function unmount() {
act(() => { root.unmount(); });
container.remove();
}
function q<T extends Element = Element>(testId: string): T | null {
return container.querySelector(`[data-testid="${testId}"]`);
}
function qAll<T extends Element = Element>(testId: string): T[] {
return Array.from(container.querySelectorAll(`[data-testid="${testId}"]`));
}
/** Click the preset button with this exact label inside a given data-testid
* root (AspectRatioControl / PresetButtonGrid render plain buttons keyed by
* label, no per-button testid). */
function clickPresetByLabel(root: Element | null, label: string) {
const btn = Array.from(root?.querySelectorAll('button') ?? []).find((b) => b.textContent === label);
expect(btn).toBeTruthy();
act(() => { btn!.dispatchEvent(new MouseEvent('click', { bubbles: true })); });
}
beforeEach(() => {
setPropSpy.mockClear();
});
afterEach(() => {
if (container) unmount();
});
describe('ImageStylePanel crop-fills-by-default (fix-anim-image B)', () => {
test('applying a non-empty aspect ratio with objectFit unset also sets objectFit to cover', () => {
lastProps = { src: '/uploads/photo.jpg', alt: '', style: {} };
render(<ImageStylePanel selectedId="img-1" nodeProps={lastProps} />);
clickPresetByLabel(q('aspect-ratio-control'), '1:1');
expect(lastProps.style.aspectRatio).toBe('1 / 1');
expect(lastProps.style.objectFit).toBe('cover');
});
test('applying a ratio when objectFit is already "contain" leaves it as contain (no forced override)', () => {
lastProps = { src: '/uploads/photo.jpg', alt: '', style: { objectFit: 'contain' } };
render(<ImageStylePanel selectedId="img-1" nodeProps={lastProps} />);
clickPresetByLabel(q('aspect-ratio-control'), '16:9');
expect(lastProps.style.aspectRatio).toBe('16 / 9');
expect(lastProps.style.objectFit).toBe('contain');
});
test('clearing the ratio (Original) does not force-clear objectFit', () => {
lastProps = { src: '/uploads/photo.jpg', alt: '', style: { aspectRatio: '1 / 1', objectFit: 'cover' } };
render(<ImageStylePanel selectedId="img-1" nodeProps={lastProps} />);
clickPresetByLabel(q('aspect-ratio-control'), 'Original');
expect(lastProps.style.aspectRatio).toBe('');
expect(lastProps.style.objectFit).toBe('cover');
});
test('the Object Fit control (Cover/Contain/Fill/None) remains present and usable', () => {
lastProps = { src: '/uploads/photo.jpg', alt: '', style: { aspectRatio: '1 / 1', objectFit: 'cover' } };
render(<ImageStylePanel selectedId="img-1" nodeProps={lastProps} />);
// PresetButtonGrid buttons have no dedicated per-button testid; find by label text.
const containBtn = Array.from(container.querySelectorAll('button')).find((b) => b.textContent === 'Contain');
expect(containBtn).toBeTruthy();
act(() => { containBtn!.dispatchEvent(new MouseEvent('click', { bubbles: true })); });
expect(lastProps.style.objectFit).toBe('contain');
});
});
describe('ImageStylePanel Height control gated on aspect-ratio (fix-anim-image C)', () => {
test('no aspect-ratio set: both Width and Height SizeControls render', () => {
lastProps = { src: '/uploads/photo.jpg', alt: '', style: {} };
render(<ImageStylePanel selectedId="img-1" nodeProps={lastProps} />);
expect(qAll('size-control').length).toBe(2);
});
test('aspect-ratio set: only the Width SizeControl renders (Height is hidden)', () => {
lastProps = { src: '/uploads/photo.jpg', alt: '', style: { aspectRatio: '1 / 1', objectFit: 'cover' } };
render(<ImageStylePanel selectedId="img-1" nodeProps={lastProps} />);
expect(qAll('size-control').length).toBe(1);
});
test('applying an aspect ratio clears a stale height so it cannot linger and conflict', () => {
lastProps = { src: '/uploads/photo.jpg', alt: '', style: { height: '50%' } };
render(<ImageStylePanel selectedId="img-1" nodeProps={lastProps} />);
clickPresetByLabel(q('aspect-ratio-control'), '9:16');
expect(lastProps.style.aspectRatio).toBe('9 / 16');
expect(lastProps.style.height).toBe('');
});
});
@@ -25,6 +25,19 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
const { setProp, setPropStyle } = useNodeProp(selectedId); const { setProp, setPropStyle } = useNodeProp(selectedId);
// Applying an aspect-ratio crop should FILL the frame by default (object-fit:
// cover) rather than leave letterboxed empty bands, and width + ratio + cover
// fully determine the box -- so a stale `height` can't linger and conflict
// (kills the %-height no-op that made resize look like it wasn't working).
// Clearing the ratio (back to 'Original') leaves objectFit as the user left it.
const applyAspectRatio = (v: string) => {
setPropStyle('aspectRatio', v);
if (v) {
if (!style.objectFit) setPropStyle('objectFit', 'cover');
setPropStyle('height', '');
}
};
return ( return (
<> <>
{/* Image source */} {/* Image source */}
@@ -54,18 +67,24 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
value={(style.maxWidth as string) || ''} value={(style.maxWidth as string) || ''}
onChange={(v) => setPropStyle('maxWidth', v)} onChange={(v) => setPropStyle('maxWidth', v)}
/> />
<SizeControl {/* Height is only meaningful when there's no aspect-ratio crop -- once a
label="Height" ratio is set, Width + ratio + cover fully determine the box, so a
value={(style.height as string) || ''} separate Height control would only conflict/mislead (see
onChange={(v) => setPropStyle('height', v)} applyAspectRatio, which clears any stale height at that moment). */}
/> {!style.aspectRatio && (
<SizeControl
label="Height"
value={(style.height as string) || ''}
onChange={(v) => setPropStyle('height', v)}
/>
)}
{/* Crop & Framing -- aspect-ratio + object-fit + object-position on the {/* Crop & Framing -- aspect-ratio + object-fit + object-position on the
<img> itself is a CSS framing crop (no server-side image processing <img> itself is a CSS framing crop (no server-side image processing
needed). */} needed). */}
<AspectRatioControl <AspectRatioControl
value={(style.aspectRatio as string) || ''} value={(style.aspectRatio as string) || ''}
onChange={(v) => setPropStyle('aspectRatio', v)} onChange={applyAspectRatio}
/> />
<div className="guided-section"> <div className="guided-section">
<SectionLabel>Object Fit</SectionLabel> <SectionLabel>Object Fit</SectionLabel>
@@ -37,6 +37,18 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
const style = nodeProps.style || {}; const style = nodeProps.style || {};
// Same crop-fills-by-default + no stale-height-conflict treatment as
// ImageStylePanel (see there for the full rationale): applying a ratio
// defaults objectFit to 'cover' when unset, and clears height so Width +
// ratio + cover is the single source of truth for the box.
const applyAspectRatio = (v: string) => {
setPropStyle('aspectRatio', v);
if (v) {
if (!style.objectFit) setPropStyle('objectFit', 'cover');
setPropStyle('height', '');
}
};
return ( return (
<> <>
{/* Video source -- upload/browse/paste-URL (paste-URL still handles {/* Video source -- upload/browse/paste-URL (paste-URL still handles
@@ -63,9 +75,14 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
value={(style.width as string) || ''} value={(style.width as string) || ''}
onChange={(v) => setPropStyle('width', v)} onChange={(v) => setPropStyle('width', v)}
/> />
{/* NOTE: unlike ImageStylePanel, there is no separate Height control
here to gate on aspect-ratio -- VideoBlock's <video>/iframe size
themselves from `width` + `aspectRatio` directly (see
VideoBlock.tsx), not from an outer-wrapper height, so adding one
would reintroduce the exact empty-space bug this fix targets. */}
<AspectRatioControl <AspectRatioControl
value={(style.aspectRatio as string) || ''} value={(style.aspectRatio as string) || ''}
onChange={(v) => setPropStyle('aspectRatio', v)} onChange={applyAspectRatio}
/> />
</> </>
)} )}
@@ -121,6 +121,58 @@ describe('MediaStylePanel Video size controls (Width + Aspect Ratio) are gated o
expect(q('size-control')).toBeNull(); expect(q('size-control')).toBeNull();
expect(q('aspect-ratio-control')).toBeNull(); expect(q('aspect-ratio-control')).toBeNull();
}); });
test('a video-shaped selection only renders one SizeControl (Width) -- no separate Height control', () => {
// See MediaStylePanel.tsx's note: VideoBlock sizes its <video>/iframe from
// width + aspectRatio directly, not from an outer-wrapper height, so a
// Height control would reintroduce the empty-space bug this fix targets.
lastProps = { videoUrl: 'https://example.com/clip.mp4', poster: '', style: {} };
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
expect(qAll('size-control').length).toBe(1);
});
});
/* FIX (fix-anim-image contract, B+C): applying a crop aspect-ratio to a video
should fill by default (objectFit defaults to 'cover' when unset) and clear
any stale height, matching ImageStylePanel's treatment -- for prop-schema
consistency even though VideoBlock's file-type <video> already hardcodes
object-fit: cover today. */
describe('MediaStylePanel Video AspectRatioControl applies crop-fills-by-default treatment (fix-anim-image B+C)', () => {
function clickPresetByLabel(root: Element | null, label: string) {
const btn = Array.from(root?.querySelectorAll('button') ?? []).find((b) => b.textContent === label);
expect(btn).toBeTruthy();
act(() => { btn!.dispatchEvent(new MouseEvent('click', { bubbles: true })); });
}
test('applying a non-empty ratio with objectFit unset also sets objectFit to cover', () => {
lastProps = { videoUrl: 'https://example.com/clip.mp4', poster: '', style: {} };
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
clickPresetByLabel(q('aspect-ratio-control'), '1:1');
expect(lastProps.style.aspectRatio).toBe('1 / 1');
expect(lastProps.style.objectFit).toBe('cover');
});
test('applying a ratio clears a stale height', () => {
lastProps = { videoUrl: 'https://example.com/clip.mp4', poster: '', style: { height: '50%' } };
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
clickPresetByLabel(q('aspect-ratio-control'), '16:9');
expect(lastProps.style.aspectRatio).toBe('16 / 9');
expect(lastProps.style.height).toBe('');
});
test('clearing the ratio (Original) does not force-clear objectFit', () => {
lastProps = { videoUrl: 'https://example.com/clip.mp4', poster: '', style: { aspectRatio: '1 / 1', objectFit: 'cover' } };
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
clickPresetByLabel(q('aspect-ratio-control'), 'Original');
expect(lastProps.style.aspectRatio).toBe('');
expect(lastProps.style.objectFit).toBe('cover');
});
}); });
function openCollapsibleByTitle(title: string) { function openCollapsibleByTitle(title: string) {
@@ -0,0 +1,57 @@
import { describe, test, expect, vi, afterEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import { PublishWarnings } from './PublishWarnings';
/* ---------- DOM test harness (no @testing-library/react in this repo, see
src/ui/AssetPicker.test.tsx for the same pattern: react-dom/client +
react-dom/test-utils `act`, both transitive deps of react-dom already). ---------- */
let container: HTMLDivElement;
let root: Root;
function render(ui: React.ReactElement) {
container = document.createElement('div');
document.body.appendChild(container);
act(() => {
root = createRoot(container);
root.render(ui);
});
}
function click(el: Element | null) {
if (!el) throw new Error('element not found');
act(() => { (el as HTMLElement).dispatchEvent(new MouseEvent('click', { bubbles: true })); });
}
afterEach(() => {
if (container) {
act(() => { root.unmount(); });
container.remove();
}
});
describe('PublishWarnings', () => {
test('renders nothing when there are no warnings', () => {
render(<PublishWarnings warnings={[]} onDismiss={() => {}} />);
expect(container.innerHTML).toBe('');
});
test('renders each warning', () => {
render(
<PublishWarnings
warnings={['First problem.', 'Second problem.']}
onDismiss={() => {}}
/>,
);
expect(container.textContent).toContain('First problem.');
expect(container.textContent).toContain('Second problem.');
});
test('dismiss fires the callback', () => {
const onDismiss = vi.fn();
render(<PublishWarnings warnings={['A problem.']} onDismiss={onDismiss} />);
click(container.querySelector('[data-testid="publish-warnings-dismiss"]'));
expect(onDismiss).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,31 @@
import React from 'react';
export interface PublishWarningsProps {
warnings: string[];
onDismiss: () => void;
}
/** Non-blocking banner shown after a successful publish. The site IS live --
* these are things the customer should fix and re-publish, not failures. */
export const PublishWarnings: React.FC<PublishWarningsProps> = ({ warnings, onDismiss }) => {
if (!warnings.length) return null;
return (
<div className="publish-warnings" role="status" data-testid="publish-warnings">
<i className="fa fa-exclamation-triangle" aria-hidden="true" />
<ul>
{warnings.map((w, i) => (
<li key={i}>{w}</li>
))}
</ul>
<button
type="button"
onClick={onDismiss}
aria-label="Dismiss"
data-testid="publish-warnings-dismiss"
>
<i className="fa fa-times" aria-hidden="true" />
</button>
</div>
);
};
+191
View File
@@ -0,0 +1,191 @@
import { describe, test, expect, vi, afterEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
/**
* Closes the gap flagged by the whole-branch review: PublishWarnings.test.tsx
* covers the presentational banner in isolation, but nothing asserted that
* `result.warnings` from `publish()` actually reaches it through TopBar. That
* 3-line seam (handlePublish -> setPublishWarnings -> <PublishWarnings>) is
* exactly what regressed before this feature existed: the backend has always
* returned `warnings`, and TopBar discarded them by only checking
* `result.success` -- so the contact-form-relay warning was dead code for its
* entire life. This suite drives the real `<TopBar>` through a real button
* click and asserts the warnings show up, survive the 3s "Published" flash,
* don't taint the success/error status, and get cleared by a fresh publish.
*
* Mocks (same DOM-harness + `vi.mock('@craftjs/core', ...)` pattern as
* RenderNode.test.tsx / useWhpApi.load.test.tsx -- no @testing-library/react
* in this repo):
* - `@craftjs/core`'s `useEditor`: TopBar only needs inert undo/redo/query
* stubs, not a real Craft.js tree.
* - `useWhpApi`: this IS the seam under test -- `publish` is a controllable
* mock so each test can choose exactly what the "backend" returns.
* - TemplateModal / HeadCodeModal / SitesmithButton: sibling chrome
* unrelated to the warnings seam (portals, CodeMirror lazy-load,
* useSitesmith's own fetch calls) -- stubbed out so this suite stays
* focused, same as MobilePanelBar.test.tsx stubbing its sibling panels.
* `usePages`/`useSiteDesign`/`useMobileChrome` are left un-mocked and
* un-provided -- their default context values (defined in each context
* module) are harmless no-op stubs, and TopBar's desktop render path never
* needs more than that.
*/
vi.mock('@craftjs/core', () => ({
useEditor: (collector?: (state: unknown, query: unknown) => Record<string, unknown>) => {
const query = {
serialize: () => '{}',
history: { canUndo: () => false, canRedo: () => false },
};
const actions = { history: { undo: vi.fn(), redo: vi.fn() } };
const collected = collector ? collector({}, query) : {};
return { actions, query, ...collected };
},
}));
const publishMock = vi.fn();
vi.mock('../../hooks/useWhpApi', () => ({
useWhpApi: () => ({
save: vi.fn().mockResolvedValue({ success: true }),
publish: publishMock,
load: vi.fn().mockResolvedValue(null),
uploadAsset: vi.fn(),
isWHP: true,
}),
}));
vi.mock('./TemplateModal', () => ({ TemplateModal: () => null }));
vi.mock('./HeadCodeModal', () => ({ HeadCodeModal: () => null }));
vi.mock('../sitesmith/SitesmithButton', () => ({ SitesmithButton: () => null }));
import { TopBar } from './TopBar';
import { EditorConfigProvider } from '../../state/EditorConfigContext';
import { WhpConfig } from '../../types';
const whpConfig: WhpConfig = {
user: 'testuser',
apiUrl: '/panel/api/site-builder',
csrfToken: 'tok',
siteId: 1,
siteDomain: 'example.com',
siteName: 'Example Site',
backUrl: '/panel/sites',
isRoot: false,
};
let container: HTMLDivElement;
let root: Root;
function render() {
container = document.createElement('div');
document.body.appendChild(container);
act(() => {
root = createRoot(container);
root.render(
<EditorConfigProvider config={whpConfig}>
<TopBar device="desktop" onDeviceChange={() => {}} showGuides={false} onToggleGuides={() => {}} />
</EditorConfigProvider>,
);
});
}
function publishButton(): HTMLButtonElement {
const btn = container.querySelector<HTMLButtonElement>('.topbar-btn.publish');
if (!btn) throw new Error('Publish button not found');
return btn;
}
/** handlePublish does exactly one `await publish()` before touching state;
* two microtask flushes inside the same act() batch is enough to carry that
* through to the resulting re-render. */
async function clickPublish() {
await act(async () => {
publishButton().dispatchEvent(new MouseEvent('click', { bubbles: true }));
await Promise.resolve();
await Promise.resolve();
});
}
afterEach(() => {
if (container) {
act(() => { root.unmount(); });
container.remove();
}
publishMock.mockReset();
vi.useRealTimers();
});
describe('TopBar publish-warnings wiring', () => {
test('warnings from publish() flow through into the rendered banner', async () => {
publishMock.mockResolvedValue({ success: true, warnings: ['Warning one.', 'Warning two.'] });
render();
await clickPublish();
expect(container.textContent).toContain('Warning one.');
expect(container.textContent).toContain('Warning two.');
});
test('a clean publish (no warnings key) renders no banner at all', async () => {
publishMock.mockResolvedValue({ success: true });
render();
await clickPublish();
expect(container.querySelector('[data-testid="publish-warnings"]')).toBeNull();
});
test('a warning is non-blocking -- publish still reports success, not a failure', async () => {
publishMock.mockResolvedValue({
success: true,
warnings: ['Submissions will not be delivered until an administrator enables it.'],
});
render();
await clickPublish();
expect(container.querySelector('.publish-badge.published')).not.toBeNull();
expect(container.querySelector('.save-indicator.error')).toBeNull();
expect(container.textContent).toContain('Submissions will not be delivered until an administrator enables it.');
});
test('warnings survive the 3-second "Published" flash timer', async () => {
vi.useFakeTimers();
publishMock.mockResolvedValue({ success: true, warnings: ['Sticks around after the flash.'] });
render();
await act(async () => {
publishButton().dispatchEvent(new MouseEvent('click', { bubbles: true }));
await Promise.resolve();
await Promise.resolve();
});
// Sanity: both the flash and the warning are up before the timer fires.
expect(container.querySelector('.publish-badge.published')).not.toBeNull();
expect(container.textContent).toContain('Sticks around after the flash.');
act(() => {
vi.advanceTimersByTime(3000);
});
// The 3s timer resets publishStatus -> the "Published" flash is gone...
expect(container.querySelector('.publish-badge.published')).toBeNull();
// ...but publishWarnings lives in its own state and must NOT have been
// cleared by that same timer.
expect(container.textContent).toContain('Sticks around after the flash.');
});
test('a new publish attempt clears warnings left over from the previous one', async () => {
publishMock.mockResolvedValueOnce({ success: true, warnings: ['Old warning.'] });
render();
await clickPublish();
expect(container.textContent).toContain('Old warning.');
publishMock.mockResolvedValueOnce({ success: true });
await clickPublish();
expect(container.textContent).not.toContain('Old warning.');
expect(container.querySelector('[data-testid="publish-warnings"]')).toBeNull();
});
});
+22 -3
View File
@@ -10,6 +10,7 @@ import { DeviceMode } from '../../types';
import { TemplateModal } from './TemplateModal'; import { TemplateModal } from './TemplateModal';
import { HeadCodeModal } from './HeadCodeModal'; import { HeadCodeModal } from './HeadCodeModal';
import { TopBarOverflowMenu } from './TopBarOverflowMenu'; import { TopBarOverflowMenu } from './TopBarOverflowMenu';
import { PublishWarnings } from './PublishWarnings';
import { SitesmithButton } from '../sitesmith/SitesmithButton'; import { SitesmithButton } from '../sitesmith/SitesmithButton';
import { useSitesmithModal } from '../../state/SitesmithContext'; import { useSitesmithModal } from '../../state/SitesmithContext';
@@ -33,6 +34,7 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle'); const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
const [publishStatus, setPublishStatus] = useState<'idle' | 'publishing' | 'published' | 'error'>('idle'); const [publishStatus, setPublishStatus] = useState<'idle' | 'publishing' | 'published' | 'error'>('idle');
const [publishWarnings, setPublishWarnings] = useState<string[]>([]);
const [isDraft, setIsDraft] = useState(false); const [isDraft, setIsDraft] = useState(false);
// Mobile-A2: lifted from private useState into MobileChromeContext so // Mobile-A2: lifted from private useState into MobileChromeContext so
// opening a mobile sheet can close these modals (item 3) -- behavior is // opening a mobile sheet can close these modals (item 3) -- behavior is
@@ -100,11 +102,16 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
const handlePublish = useCallback(async () => { const handlePublish = useCallback(async () => {
setPublishStatus('publishing'); setPublishStatus('publishing');
setPublishWarnings([]);
try { try {
const result = await publish(); const result = await publish();
if (result?.success) { if (result?.success) {
setPublishStatus('published'); setPublishStatus('published');
setIsDraft(false); setIsDraft(false);
// The site published; these are fixable problems, not failures. Held
// independently of publishStatus so the 3s "Published" flash doesn't
// take the warning down with it.
setPublishWarnings(Array.isArray(result.warnings) ? result.warnings : []);
if (publishTimeoutRef.current) clearTimeout(publishTimeoutRef.current); if (publishTimeoutRef.current) clearTimeout(publishTimeoutRef.current);
publishTimeoutRef.current = setTimeout(() => setPublishStatus('idle'), 3000); publishTimeoutRef.current = setTimeout(() => setPublishStatus('idle'), 3000);
} else { } else {
@@ -133,7 +140,7 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
const handlePreview = useCallback(() => { const handlePreview = useCallback(() => {
try { try {
const serialized = query.serialize(); const serialized = query.serialize();
import('../../utils/html-export').then(({ exportToHtml, exportBodyHtml }) => { import('../../utils/html-export').then(({ exportToHtml, exportBodyHtml, buildAnimationScript }) => {
// Get header HTML // Get header HTML
let headerHtml = ''; let headerHtml = '';
try { try {
@@ -154,8 +161,18 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
} }
} catch (e) { console.warn('Footer export failed:', e); } } catch (e) { console.warn('Footer export failed:', e); }
// Compose full page: header + body + footer // Compose full page: header + body + footer. `handlePreview` below
const composedBody = headerHtml + bodyHtml + footerHtml; // replaces the ENTIRE wrapped-doc `<body>` inner (including the
// in-body reveal `<script>` wrapInDocument already emitted) with
// this composed string, so the script would otherwise be clobbered
// and animated elements would stay hidden forever
// ([data-animation]{opacity:0} with no IntersectionObserver to ever
// add `.animated`). Re-append the reveal script here -- built from
// the SAME composed content it will end up living alongside -- so
// it survives the replacement below and fires exactly once.
const composedBody =
headerHtml + bodyHtml + footerHtml +
buildAnimationScript(headerHtml + bodyHtml + footerHtml);
// PKG-H: fold the active page's own SEO overrides + the site-wide // PKG-H: fold the active page's own SEO overrides + the site-wide
// design tokens/favicon into the Preview export so editor Preview // design tokens/favicon into the Preview export so editor Preview
@@ -210,6 +227,7 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
if (isMobile) { if (isMobile) {
return ( return (
<nav className="topbar topbar-mobile"> <nav className="topbar topbar-mobile">
<PublishWarnings warnings={publishWarnings} onDismiss={() => setPublishWarnings([])} />
<div className="topbar-left"> <div className="topbar-left">
{isWHP && ( {isWHP && (
<a <a
@@ -297,6 +315,7 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
return ( return (
<nav className="topbar"> <nav className="topbar">
<PublishWarnings warnings={publishWarnings} onDismiss={() => setPublishWarnings([])} />
<div className="topbar-left"> <div className="topbar-left">
{isWHP && ( {isWHP && (
<a href={whpConfig!.backUrl} className="topbar-btn back-btn" aria-label="Back to Panel"> <a href={whpConfig!.backUrl} className="topbar-btn back-btn" aria-label="Back to Panel">
@@ -0,0 +1,509 @@
import { describe, test, expect, vi, beforeEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import { PageProvider, usePages, applyLandingInvariant } from './PageContext';
import { PageData } from '../types';
/**
* PKG-I: page duplicate / reorder / set-landing.
*
* The landing-page invariant is: `pages[0]` is the landing page, slug
* LOCKED to `'index'`; every other page gets a real, unique slug. This
* suite covers:
* - `applyLandingInvariant` as a pure function (unit tests, no provider).
* - `movePage`/`setLandingPage` re-establishing the invariant after
* reordering, via `PageProvider`.
* - `duplicatePage` inserting a copy right after the source with a copied
* craftState + seo and a unique slug, and switching the canvas to it.
*/
function makePage(overrides: Partial<PageData> & { id: string }): PageData {
return { name: overrides.id, slug: overrides.id, craftState: null, ...overrides };
}
describe('applyLandingInvariant (pure)', () => {
test('page at index 0 gets slug "index" even if it held a different slug', () => {
const pages = [
makePage({ id: 'a', name: 'About', slug: 'about' }),
makePage({ id: 'b', name: 'Home', slug: 'index' }),
];
const result = applyLandingInvariant(pages);
expect(result[0].slug).toBe('index');
expect(result[0].id).toBe('a');
});
test('demotes the old landing page (now at index > 0) to a unique real slug', () => {
const pages = [
makePage({ id: 'a', name: 'About', slug: 'about' }),
makePage({ id: 'b', name: 'Home', slug: 'index' }),
];
const result = applyLandingInvariant(pages);
const demoted = result.find((p) => p.id === 'b')!;
expect(demoted.slug).not.toBe('index');
expect(demoted.slug).toBe('home');
});
test('never produces two pages with slug "index"', () => {
const pages = [
makePage({ id: 'a', name: 'About', slug: 'about' }),
makePage({ id: 'b', name: 'Home', slug: 'index' }),
makePage({ id: 'c', name: 'Contact', slug: 'contact' }),
];
const result = applyLandingInvariant(pages);
const indexSlugs = result.filter((p) => p.slug === 'index');
expect(indexSlugs).toHaveLength(1);
expect(indexSlugs[0].id).toBe('a');
});
test('demoted page slug is deduped against a colliding existing slug elsewhere in the array', () => {
const pages = [
makePage({ id: 'a', name: 'About', slug: 'about' }),
makePage({ id: 'b', name: 'Home', slug: 'index' }), // demoted page, named "Home" -> slugifies to "home"
makePage({ id: 'c', name: 'HomePage', slug: 'home' }), // unrelated page already using slug "home"
];
const result = applyLandingInvariant(pages);
expect(result[0].slug).toBe('index');
const demoted = result.find((p) => p.id === 'b')!;
expect(demoted.slug).toBe('home-2');
const untouched = result.find((p) => p.id === 'c')!;
expect(untouched.slug).toBe('home');
const slugs = result.map((p) => p.slug);
expect(new Set(slugs).size).toBe(slugs.length);
});
test('non-landing pages that already have a real slug are left untouched', () => {
const pages = [
makePage({ id: 'a', name: 'Home', slug: 'index' }),
makePage({ id: 'b', name: 'About', slug: 'about' }),
makePage({ id: 'c', name: 'Contact', slug: 'contact' }),
];
const result = applyLandingInvariant(pages);
expect(result[1]).toEqual(pages[1]);
expect(result[2]).toEqual(pages[2]);
});
test('empty array is a no-op', () => {
expect(applyLandingInvariant([])).toEqual([]);
});
});
/* ---------- PageProvider-mounted coverage ---------- */
let serializeReturn = '{}';
const deserializeMock = vi.fn();
vi.mock('@craftjs/core', () => ({
useEditor: () => ({
query: { serialize: () => serializeReturn },
actions: { deserialize: deserializeMock },
}),
}));
let container: HTMLDivElement;
let root: Root;
function render(ui: React.ReactElement) {
container = document.createElement('div');
document.body.appendChild(container);
act(() => {
root = createRoot(container);
root.render(ui);
});
}
function unmount() {
act(() => {
root.unmount();
});
container.remove();
}
async function flushTimers() {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
});
}
beforeEach(() => {
serializeReturn = '{}';
deserializeMock.mockClear();
});
describe('PageContext.movePage', () => {
test('moves a page up, swapping with its neighbor', () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => ctx!.addPage('About', 'about'));
act(() => ctx!.addPage('Contact', 'contact'));
// pages: [Home(index0), About, Contact]
const contactId = ctx!.pages[2].id;
act(() => ctx!.movePage(contactId, 'up'));
expect(ctx!.pages.map((p) => p.name)).toEqual(['Home', 'Contact', 'About']);
// Landing invariant still holds -- Home untouched at index 0.
expect(ctx!.pages[0].slug).toBe('index');
unmount();
});
test('is a no-op at the top boundary', () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => ctx!.addPage('About', 'about'));
const homeId = ctx!.pages[0].id;
const before = ctx!.pages.map((p) => p.id);
act(() => ctx!.movePage(homeId, 'up'));
expect(ctx!.pages.map((p) => p.id)).toEqual(before);
unmount();
});
test('is a no-op at the bottom boundary', () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => ctx!.addPage('About', 'about'));
const aboutId = ctx!.pages[1].id;
const before = ctx!.pages.map((p) => p.id);
act(() => ctx!.movePage(aboutId, 'down'));
expect(ctx!.pages.map((p) => p.id)).toEqual(before);
unmount();
});
test('moving a non-landing page into index 0 promotes it and demotes the old landing page to a real slug', () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => ctx!.addPage('About', 'about'));
// pages: [Home(index0, slug index), About]
const aboutId = ctx!.pages[1].id;
const homeId = ctx!.pages[0].id;
act(() => ctx!.movePage(aboutId, 'up'));
// pages: [About, Home]
expect(ctx!.pages.map((p) => p.id)).toEqual([aboutId, homeId]);
expect(ctx!.pages[0].slug).toBe('index'); // About is now the landing page
const demotedHome = ctx!.pages.find((p) => p.id === homeId)!;
expect(demotedHome.slug).not.toBe('index');
expect(demotedHome.slug).toBe('home');
// Exactly one 'index' slug, always at index 0.
const indexPages = ctx!.pages.filter((p) => p.slug === 'index');
expect(indexPages).toHaveLength(1);
expect(ctx!.pages.indexOf(indexPages[0])).toBe(0);
// movePage does not touch the canvas.
expect(deserializeMock).not.toHaveBeenCalled();
unmount();
});
test('moving the current landing page down demotes it and promotes its neighbor', () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => ctx!.addPage('About', 'about'));
// pages: [Home(index0, slug index), About]
const homeId = ctx!.pages[0].id;
const aboutId = ctx!.pages[1].id;
act(() => ctx!.movePage(homeId, 'down'));
// pages: [About, Home]
expect(ctx!.pages.map((p) => p.id)).toEqual([aboutId, homeId]);
// Order changed and the landing invariant re-established: index 0
// (now About) gets slug 'index'; the moved page (now at index 1, Home)
// gets a real, non-'index' unique slug.
expect(ctx!.pages[0].id).toBe(aboutId);
expect(ctx!.pages[0].slug).toBe('index');
const demotedHome = ctx!.pages.find((p) => p.id === homeId)!;
expect(demotedHome.slug).not.toBe('index');
expect(demotedHome.slug).toBe('home');
// Exactly one 'index' slug.
const indexPages = ctx!.pages.filter((p) => p.slug === 'index');
expect(indexPages).toHaveLength(1);
unmount();
});
});
describe('PageContext.setLandingPage', () => {
test('promotes an arbitrary page to index 0 and demotes the old landing page', () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => ctx!.addPage('About', 'about'));
act(() => ctx!.addPage('Contact', 'contact'));
const homeId = ctx!.pages[0].id;
const contactId = ctx!.pages[2].id;
act(() => ctx!.setLandingPage(contactId));
expect(ctx!.pages[0].id).toBe(contactId);
expect(ctx!.pages[0].slug).toBe('index');
const demotedHome = ctx!.pages.find((p) => p.id === homeId)!;
expect(demotedHome.slug).toBe('home');
const indexPages = ctx!.pages.filter((p) => p.slug === 'index');
expect(indexPages).toHaveLength(1);
// setLandingPage does not touch the canvas.
expect(deserializeMock).not.toHaveBeenCalled();
unmount();
});
test('is a no-op when the page is already the landing page', () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
const homeId = ctx!.pages[0].id;
const before = ctx!.pages.map((p) => ({ ...p }));
act(() => ctx!.setLandingPage(homeId));
expect(ctx!.pages).toEqual(before);
unmount();
});
});
describe('PageContext.duplicatePage', () => {
test('inserts a copy immediately after the source with a copied craftState, seo, and a unique slug', async () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => ctx!.addPage('About', 'about'));
await flushTimers();
act(() => ctx!.addPage('Contact', 'contact'));
await flushTimers();
// pages: [Home, About, Contact]; Contact is currently active.
const aboutId = ctx!.pages[1].id;
act(() => ctx!.updatePageSeo(aboutId, { metaTitle: 'About Us' }));
act(() => ctx!.duplicatePage(aboutId));
await flushTimers();
const names = ctx!.pages.map((p) => p.name);
expect(names).toEqual(['Home', 'About', 'About copy', 'Contact']);
const copy = ctx!.pages[2];
expect(copy.name).toBe('About copy');
expect(copy.slug).toBe('about-copy');
expect(copy.seo).toEqual({ metaTitle: 'About Us' });
// Every slug in the array is unique.
const slugs = ctx!.pages.map((p) => p.slug);
expect(new Set(slugs).size).toBe(slugs.length);
// Landing invariant untouched -- copy is never index 0.
expect(ctx!.pages[0].slug).toBe('index');
unmount();
});
test('duplicating the ACTIVE page saves the live canvas into the copy (and the original)', async () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
// Home is active by default. Simulate the user having made live edits.
serializeReturn = '{"ROOT":{"live":"edit"}}';
act(() => ctx!.duplicatePage(ctx!.pages[0].id));
await flushTimers();
const copy = ctx!.pages[1];
expect(copy.name).toBe('Home copy');
expect(copy.craftState).toBe('{"ROOT":{"live":"edit"}}');
// Original page's stored state was also refreshed to the live canvas.
expect(ctx!.pages[0].craftState).toBe('{"ROOT":{"live":"edit"}}');
// The canvas switched to the new copy.
expect(ctx!.activePageId).toBe(copy.id);
unmount();
});
test('duplicating a non-active page copies its already-stored craftState (no live-canvas read)', async () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => ctx!.addPage('About', 'about'));
await flushTimers();
// Home is now inactive, stored with whatever it serialized to on switch.
const homeId = ctx!.pages[0].id;
const homeCraftState = ctx!.pages[0].craftState;
// Switch the live serialize() return to something else, to prove
// duplicating an inactive page does NOT read the live canvas.
serializeReturn = '{"ROOT":{"unrelated":"currently-active-page-content"}}';
act(() => ctx!.duplicatePage(homeId));
await flushTimers();
const copy = ctx!.pages.find((p) => p.name === 'Home copy')!;
expect(copy.craftState).toBe(homeCraftState);
unmount();
});
test('duplicating a non-active page does NOT drop the outgoing active page\'s live unsaved edits (regression lock)', async () => {
// Regression test for the Critical bug: duplicatePage(pageId) used to
// call saveCurrentState() ONLY when pageId === the active page, yet
// ALWAYS ended by tearing down the canvas via loadState() + switching
// activePageId to the copy. If the duplicated page was NOT the active
// one, the active page's live canvas edits were never serialized into
// its slot before that teardown -- silently discarded. This asserts the
// outgoing active page ('About') keeps its live-serialized craftState
// after duplicating a DIFFERENT page ('Home').
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => ctx!.addPage('About', 'about'));
await flushTimers();
// pages: [Home, About]; About is active (addPage switches to it).
const homeId = ctx!.pages[0].id;
const aboutId = ctx!.pages[1].id;
expect(ctx!.activePageId).toBe(aboutId);
// Simulate the user having made live, unsaved edits to About (the
// active page) that have not yet been serialized into pages[] state.
const liveAboutEdit = '{"ROOT":{"live":"about-edit-not-yet-saved"}}';
serializeReturn = liveAboutEdit;
// Duplicate a DIFFERENT page (Home), not the active one (About).
act(() => ctx!.duplicatePage(homeId));
await flushTimers();
// The outgoing active page's live edits must have been persisted into
// its own slot before the canvas was torn down and switched away.
const aboutAfter = ctx!.pages.find((p) => p.id === aboutId)!;
expect(aboutAfter.craftState).toBe(liveAboutEdit);
unmount();
});
test('switches the canvas to the new copy (deserialize called with the copy craftState)', async () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
deserializeMock.mockClear();
act(() => ctx!.duplicatePage(ctx!.pages[0].id));
await flushTimers();
expect(deserializeMock).toHaveBeenCalled();
unmount();
});
});
+176
View File
@@ -18,6 +18,28 @@ interface PageContextValue {
addPage: (name: string, slug: string) => void; addPage: (name: string, slug: string) => void;
deletePage: (pageId: string) => void; deletePage: (pageId: string) => void;
renamePage: (pageId: string, name: string, slug: string) => void; renamePage: (pageId: string, name: string, slug: string) => void;
/**
* Duplicates `pageId`, inserting the copy immediately after the source in
* `pages` and switching the canvas to the new copy. If `pageId` is the
* active page, its current on-canvas state is saved first so the copy
* (and the original) both reflect what's actually on screen. The copy
* gets its own unique slug (never `'index'` -- it's never at index 0) and
* a name of `"<source name> copy"`; its `seo` is copied from the source.
*/
duplicatePage: (pageId: string) => void;
/**
* Reorders `pageId` one slot `'up'` or `'down'` within `pages` (swap with
* the adjacent page; no-op at either end). Does NOT touch the live
* canvas -- only list order changes. Re-applies the landing-page
* invariant afterward (see `applyLandingInvariant`) since a reorder can
* move a different page into/out of index 0.
*/
movePage: (pageId: string, direction: 'up' | 'down') => void;
/**
* Moves `pageId` to index 0 (making it the new landing page) and
* re-applies the landing-page invariant. Does NOT touch the live canvas.
*/
setLandingPage: (pageId: string) => void;
/** Merges `seo` fields onto the target page's existing `seo` (creating it if absent). */ /** Merges `seo` fields onto the target page's existing `seo` (creating it if absent). */
updatePageSeo: (pageId: string, seo: Partial<PageSeo>) => void; updatePageSeo: (pageId: string, seo: Partial<PageSeo>) => void;
setHeaderCraftState: (craftState: string) => void; setHeaderCraftState: (craftState: string) => void;
@@ -188,6 +210,9 @@ const PageContext = createContext<PageContextValue>({
addPage: () => {}, addPage: () => {},
deletePage: () => {}, deletePage: () => {},
renamePage: () => {}, renamePage: () => {},
duplicatePage: () => {},
movePage: () => {},
setLandingPage: () => {},
updatePageSeo: () => {}, updatePageSeo: () => {},
setHeaderCraftState: () => {}, setHeaderCraftState: () => {},
setFooterCraftState: () => {}, setFooterCraftState: () => {},
@@ -229,6 +254,59 @@ export function uniqueSlug(base: string, existingSlugs: string[]): string {
return `${base}-${i}`; return `${base}-${i}`;
} }
/**
* Re-establishes the landing-page invariant on a REORDERED pages array: the
* page now at index 0 is the landing page and its slug is locked to
* `'index'` (regardless of whatever slug it held before it was moved there);
* every other page keeps its slug UNLESS it's the page that previously held
* `'index'` and has now been demoted to index > 0 -- that page needs a real,
* unique slug of its own (derived from its name) since a page can no longer
* publish to `index.html` from anywhere but index 0.
*
* Pure function of the array -- used by both `movePage` (swap two adjacent
* pages) and `setLandingPage` (move an arbitrary page to index 0) as the
* shared "fix the invariant up after reordering" step, and directly
* unit-testable without mounting `PageProvider`.
*
* Normally at most one page enters with slug `'index'` (true for any array
* that already satisfied the invariant before the reorder that produced this
* input) -- exactly the case both callers hand it. Defensively, though, a
* STRAY second page with slug `'index'` at index > 0 (e.g. from legacy
* loaded data that predates this invariant) is also demoted rather than left
* as a duplicate -- see the running `usedSlugs` accumulation below.
*/
export function applyLandingInvariant(pages: PageData[]): PageData[] {
if (pages.length === 0) return pages;
// Slugs that must not be collided into: 'index' (reserved for whoever
// ends up at index 0) plus every non-landing page's existing slug except
// any demoted page's (it currently holds 'index' and is about to be given
// a new one). Computed upfront, over the WHOLE array, so a demoted page's
// new slug is checked against every other page regardless of array order
// -- checking only "slugs seen so far" while walking the array would miss
// a collision against a page that appears LATER in the list than the
// demoted one. Mutated (pushed to) as pages are demoted below so that two
// demoted pages in the same pass can't collide with EACH OTHER either.
const usedSlugs: string[] = ['index'];
for (let i = 1; i < pages.length; i++) {
if (pages[i].slug !== 'index') usedSlugs.push(pages[i].slug);
}
return pages.map((page, i) => {
if (i === 0) {
return page.slug === 'index' ? page : { ...page, slug: 'index' };
}
if (page.slug === 'index') {
// Demoted landing page (or a stray extra 'index' page -- see doc
// comment above) -- give it a real, unique slug of its own.
const newSlug = uniqueSlug(slugify(page.name), usedSlugs);
usedSlugs.push(newSlug);
return { ...page, slug: newSlug };
}
return page;
});
}
const DEFAULT_PAGE: PageData = { const DEFAULT_PAGE: PageData = {
id: 'home', id: 'home',
name: 'Home', name: 'Home',
@@ -409,6 +487,101 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
[loadState], [loadState],
); );
/**
* Duplicates `pageId`: inserts a copy immediately after the source in
* `pages` and switches the live canvas to it. See the doc comment on
* `PageContextValue.duplicatePage`.
*/
const duplicatePage = useCallback(
(pageId: string) => {
// Always persist whatever is on the live canvas back into its page
// slot BEFORE any teardown below (same as addPage/switchPage/deletePage
// do unconditionally). Without this, duplicating a page OTHER than the
// active one would tear down and switch the canvas via loadState()
// further down without ever serializing the outgoing active page's
// live edits into its slot -- silently discarding them.
saveCurrentState();
const isActive = pageId === activePageIdRef.current;
const source = pagesRef.current.find((p) => p.id === pageId);
if (!source) return;
// If the source IS the active page, saveCurrentState() above just
// wrote the live canvas into `source.craftState`'s slot -- but
// `pagesRef.current` (captured above) may still be the pre-update
// snapshot depending on render timing, so ask Craft.js directly for
// the same value rather than re-reading the ref. If the source is a
// NON-active page, its stored craftState is untouched by saving the
// (different) active page above, so use it as-is.
const sourceCraftState = isActive ? query.serialize() : source.craftState;
const otherSlugs = pagesRef.current.map((p) => p.slug);
const copyId = nextPageId();
const copyName = `${source.name} copy`;
// The copy is always inserted AFTER the source (index >= 1), so it
// never needs the reserved 'index' slug -- a normal unique slug always
// applies here regardless of whether the source itself is the landing
// page.
const copySlug = uniqueSlug(slugify(copyName), otherSlugs);
const copy: PageData = {
id: copyId,
name: copyName,
slug: copySlug,
craftState: sourceCraftState,
seo: source.seo ? { ...source.seo } : undefined,
};
setPages((prev) => {
const idx = prev.findIndex((p) => p.id === pageId);
if (idx === -1) return prev;
const next = [...prev];
next.splice(idx + 1, 0, copy);
return next;
});
// Switch the canvas to the new copy so the user lands on it, same as
// addPage switching to the freshly created page.
loadState(copy.craftState, EMPTY_CANVAS);
setActivePageId(copyId);
activePageIdRef.current = copyId;
},
[query, saveCurrentState, loadState],
);
/**
* Reorders `pageId` one slot up or down (swap with the adjacent page).
* Pure list-order change -- does not touch the live canvas. See the doc
* comment on `PageContextValue.movePage`.
*/
const movePage = useCallback((pageId: string, direction: 'up' | 'down') => {
setPages((prev) => {
const idx = prev.findIndex((p) => p.id === pageId);
if (idx === -1) return prev;
const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
if (swapIdx < 0 || swapIdx >= prev.length) return prev; // no-op at the ends
const next = [...prev];
[next[idx], next[swapIdx]] = [next[swapIdx], next[idx]];
return applyLandingInvariant(next);
});
}, []);
/**
* Moves `pageId` to index 0, making it the new landing page. Pure list-
* order change -- does not touch the live canvas. See the doc comment on
* `PageContextValue.setLandingPage`.
*/
const setLandingPage = useCallback((pageId: string) => {
setPages((prev) => {
const idx = prev.findIndex((p) => p.id === pageId);
if (idx <= 0) return prev; // already the landing page, or not found
const next = [...prev];
const [moved] = next.splice(idx, 1);
next.unshift(moved);
return applyLandingInvariant(next);
});
}, []);
const renamePage = useCallback((pageId: string, name: string, slug: string) => { const renamePage = useCallback((pageId: string, name: string, slug: string) => {
setPages((prev) => setPages((prev) =>
prev.map((p, i) => { prev.map((p, i) => {
@@ -556,6 +729,9 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
addPage, addPage,
deletePage, deletePage,
renamePage, renamePage,
duplicatePage,
movePage,
setLandingPage,
updatePageSeo, updatePageSeo,
setHeaderCraftState, setHeaderCraftState,
setFooterCraftState, setFooterCraftState,
+35
View File
@@ -106,6 +106,11 @@ body {
border-bottom: 1px solid var(--color-border); border-bottom: 1px solid var(--color-border);
z-index: 100; z-index: 100;
gap: 12px; gap: 12px;
/* Positioned ancestor for .publish-warnings (position: absolute; top:
100%), which is rendered as this <nav>'s first child in both the
desktop and mobile branches -- without this, it would anchor to the
viewport instead of sitting directly under the topbar. */
position: relative;
} }
.topbar-left, .topbar-left,
@@ -1884,3 +1889,33 @@ body {
height: 44px !important; height: 44px !important;
} }
} }
/* --------------------------------------------------------------------------
Publish warnings banner -- non-blocking; the site DID publish. Anchored
to .topbar's `position: relative` (see above) so it drops down directly
beneath the bar in both the desktop and mobile branches.
-------------------------------------------------------------------------- */
.publish-warnings {
position: absolute;
top: 100%;
left: 0;
right: 0;
z-index: 40;
display: flex;
align-items: flex-start;
gap: 8px;
padding: 10px 12px;
background: #422006;
border-bottom: 1px solid #a16207;
color: #fde68a;
font-size: 12px;
}
.publish-warnings ul { margin: 0; padding-left: 16px; flex: 1; }
.publish-warnings li { margin: 2px 0; }
.publish-warnings button {
background: none;
border: none;
color: #fde68a;
cursor: pointer;
padding: 0 4px;
}
@@ -3,7 +3,7 @@ import React from 'react';
import { renderEditorHarness, EditorHarness } from '../editorHarness'; import { renderEditorHarness, EditorHarness } from '../editorHarness';
import { useNodeActions, NodeActions } from '../../hooks/useNodeActions'; import { useNodeActions, NodeActions } from '../../hooks/useNodeActions';
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts'; import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts';
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard'; import { getClipboardTree, setClipboardTree } from '../../hooks/clipboard';
/** /**
* Real-`@craftjs/core` integration coverage for duplicate/paste. * Real-`@craftjs/core` integration coverage for duplicate/paste.
@@ -67,10 +67,39 @@ const INITIAL_STATE = JSON.stringify({
}, },
}); });
// A second, independent "page" state -- distinct node ids from INITIAL_STATE,
// simulating what PageContext.switchPage does: `query.serialize()` the
// current page, then `actions.deserialize()` the target page's stored
// state, replacing the ENTIRE node map. `social-1` (copied from page A)
// does not exist anywhere in this state.
const PAGE_B_STATE = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { style: {}, tag: 'div' },
displayName: 'Container',
custom: {},
hidden: false,
nodes: ['page-b-heading-1'],
linkedNodes: {},
},
'page-b-heading-1': {
type: { resolvedName: 'Heading' },
isCanvas: false,
props: { text: 'Page B Heading', level: 'h2' },
displayName: 'Heading',
custom: {},
hidden: false,
parent: 'ROOT',
nodes: [],
linkedNodes: {},
},
});
let harness: EditorHarness | null = null; let harness: EditorHarness | null = null;
afterEach(() => { afterEach(() => {
setClipboardNodeId(null); setClipboardTree(null);
if (harness) { if (harness) {
harness.unmount(); harness.unmount();
harness = null; harness = null;
@@ -158,7 +187,7 @@ describe('duplicate/paste (real @craftjs/core editor)', () => {
new KeyboardEvent('keydown', { key: 'c', ctrlKey: true, bubbles: true, cancelable: true }), new KeyboardEvent('keydown', { key: 'c', ctrlKey: true, bubbles: true, cancelable: true }),
); );
}); });
expect(getClipboardNodeId()).toBe('social-1'); expect(getClipboardTree()!.rootNodeId).toBe('social-1');
// Select heading-1 (a sibling), then paste -- should land as a sibling // Select heading-1 (a sibling), then paste -- should land as a sibling
// of heading-1's parent (ROOT), with brand-new ids. // of heading-1's parent (ROOT), with brand-new ids.
@@ -190,4 +219,76 @@ describe('duplicate/paste (real @craftjs/core editor)', () => {
expect(pastedProps.links).not.toBe(originalProps.links); expect(pastedProps.links).not.toBe(originalProps.links);
expect(pastedProps).toEqual(originalProps); expect(pastedProps).toEqual(originalProps);
}); });
test('CROSS-PAGE copy/paste: copy on page A, switch to page B, paste -- the node appears on page B', () => {
harness = renderEditorHarness({ initialState: INITIAL_STATE });
const Consumer: React.FC = () => {
useKeyboardShortcuts();
return null;
};
harness.mountChild(<Consumer />);
// --- Page A: select + copy social-1. ---
harness.act(() => {
harness!.actions.selectNode('social-1');
});
harness.act(() => {
document.dispatchEvent(
new KeyboardEvent('keydown', { key: 'c', ctrlKey: true, bubbles: true, cancelable: true }),
);
});
expect(getClipboardTree()!.rootNodeId).toBe('social-1');
// --- Switch to page B: exactly what PageContext.switchPage does --
// serialize (discarded here, a real page switch would stash it) then
// deserialize the target page's state, replacing the ENTIRE node map.
// `social-1` no longer exists anywhere in `query` after this. ---
harness.act(() => {
harness!.actions.deserialize(PAGE_B_STATE);
});
expect(harness.query.getNodes()['social-1']).toBeUndefined();
// Select page B's only node, then paste.
harness.act(() => {
harness!.actions.selectNode('page-b-heading-1');
});
const beforePaste = Object.keys(harness.query.getNodes());
expect(() => {
harness!.act(() => {
document.dispatchEvent(
new KeyboardEvent('keydown', { key: 'v', ctrlKey: true, bubbles: true, cancelable: true }),
);
});
}).not.toThrow();
const afterPaste = Object.keys(harness.query.getNodes());
// The regression this guards against: with the old id-based clipboard,
// `query.node('social-1').get()` returns undefined once page B is
// loaded, so the paste handler's guard silently no-ops -- NOTHING gets
// added. With the tree-snapshot clipboard, the copied subtree is
// detached from any live query and pastes onto page B regardless.
expect(afterPaste.length).toBe(beforePaste.length + 1);
const pastedId = afterPaste.find((id) => !beforePaste.includes(id))!;
expect(pastedId).toBeDefined();
const pastedNode = harness.query.node(pastedId).get();
expect(pastedNode.data.displayName).toBe('Social Links');
expect(pastedNode.data.props.links).toEqual([
{ platform: 'facebook', url: 'https://facebook.com/original' },
]);
// Actually landed on page B's tree, as a sibling of the selected node.
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
expect(rootChildren).toContain(pastedId);
// Real DOM assertion: the pasted SocialLinks component is actually
// rendered on the (now page B) canvas.
expect(
harness.container.querySelectorAll('a[href="https://facebook.com/original"]'),
).toHaveLength(1);
});
}); });
+209 -1
View File
@@ -1,5 +1,5 @@
import { describe, test, expect } from 'vitest'; import { describe, test, expect } from 'vitest';
import { exportBodyHtml, exportToHtml, ExportOptions } from './html-export'; import { exportBodyHtml, exportToHtml, buildAnimationScript, ExportOptions } from './html-export';
import { DEFAULT_SITE_DESIGN, SiteDesign } from '../state/SiteDesignContext'; import { DEFAULT_SITE_DESIGN, SiteDesign } from '../state/SiteDesignContext';
/** /**
@@ -335,3 +335,211 @@ describe('PKG-H: SEO/meta + favicon + design-token <head> emission', () => {
}); });
}); });
}); });
/**
* FIX: entrance-animation broken in Preview. Root causes (see
* .superpowers/sdd/fix-animation-contract.md):
* 1. injectAttrs inserted data-attrs before the tag's first `>`, so a void
* tag (`<img ... />`) became malformed (`<img ... / data-animation="...">`,
* attrs landing AFTER the self-close slash, outside the tag).
* 2. wrapInDocument's in-body reveal <script> was destroyed by TopBar's
* handlePreview, which replaces the whole <body> inner with a
* recomposed header+body+footer string that never carried the script.
*/
describe('injectAttrs well-formed void-tag attrs (animation fix)', () => {
// ImageBlock.toHtml renders `<img src="..." ... />` -- a real void-tag
// producer that goes through injectAttrs via renderNode.
const imageState = (props: Record<string, unknown>) =>
JSON.stringify({
ROOT: {
type: { resolvedName: 'ImageBlock' },
isCanvas: false,
props: { src: '/uploads/photo.jpg', style: {}, ...props },
displayName: 'ImageBlock',
custom: {},
hidden: false,
nodes: [],
linkedNodes: {},
},
});
test('void <img/> gets attrs INSIDE the tag, no " / " sequence before the final >', () => {
const { html } = exportBodyHtml(imageState({ animation: 'bounce' }));
expect(html).toContain('data-animation="bounce"');
// Well-formed: the attribute sits before the self-close slash.
expect(html).toMatch(/data-animation="bounce"\s*\/>/);
// Malformed shape from the bug: attrs landing after the slash.
expect(html).not.toMatch(/\/\s*data-animation="bounce"/);
expect(html).not.toContain('/ data-animation');
});
test('non-void tag (Container div) is unaffected -- attrs still inserted before its only >', () => {
const state = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { tag: 'div', style: {}, animation: 'fade-in' },
displayName: 'Container',
custom: {},
hidden: false,
nodes: [],
linkedNodes: {},
},
});
const { html } = exportBodyHtml(state);
expect(html).toMatch(/^<div[^>]*data-animation="fade-in"[^>]*>/);
expect(html).not.toContain('/>');
});
});
describe('buildAnimationScript (animation fix)', () => {
test('returns the IntersectionObserver reveal script when body contains data-animation', () => {
const body = '<div data-animation="fade-in">Hi</div>';
const script = buildAnimationScript(body);
expect(script).toContain('<script>');
expect(script).toContain('IntersectionObserver');
expect(script).toContain("querySelectorAll('[data-animation]')");
});
test('returns empty string when body has no data-animation', () => {
expect(buildAnimationScript('<div>Hi</div>')).toBe('');
});
test('reveal script coerces a bare-number delay to a valid CSS time (e.g. "2" -> "2s")', () => {
// animationDelay is stored as a plain seconds string ("2"); assigning that raw
// to el.style.animationDelay is invalid CSS and no-ops. The script must suffix a
// unit onto bare numbers while leaving unit-bearing values ("2s"/"200ms") alone.
const script = buildAnimationScript('<div data-animation="fade-in" data-animation-delay="2">Hi</div>');
expect(script).toContain("/^-?[0-9.]+$/.test(delay) ? delay + 's' : delay");
// guard against regressing to the raw (invalid) assignment
expect(script).not.toContain('animationDelay = delay;');
// sanity-check the coercion logic itself against representative inputs
const coerce = (delay: string) => (/^-?[0-9.]+$/.test(delay) ? delay + 's' : delay);
expect(coerce('2')).toBe('2s');
expect(coerce('0.5')).toBe('0.5s');
expect(coerce('2s')).toBe('2s');
expect(coerce('200ms')).toBe('200ms');
});
});
describe('Preview body-replacement keeps exactly one reveal script (animation fix)', () => {
const animatedState = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { tag: 'div', style: {}, animation: 'fade-in' },
displayName: 'Container',
custom: {},
hidden: false,
nodes: [],
linkedNodes: {},
},
});
test('wrapped doc alone already contains exactly one script + the CSS + the noscript fallback', () => {
const { html } = exportToHtml(animatedState, { title: 'Page' });
const scriptCount = (html.match(/IntersectionObserver/g) || []).length;
expect(scriptCount).toBe(1);
expect(html).toContain('[data-animation]{opacity:0}');
expect(html).toContain('<noscript><style>[data-animation]{opacity:1}</style></noscript>');
});
test('simulated handlePreview body-replacement: composed body built WITH buildAnimationScript still yields exactly one reveal script and the head CSS survives', () => {
// Mirror TopBar.tsx handlePreview: exportToHtml gives the wrapped doc
// (head CSS/noscript + its own in-body script); a "composedBody" of
// header+body+footer (no script of its own) is what actually replaces
// the <body> inner. Without appending buildAnimationScript to
// composedBody, the wrapped doc's script would be clobbered and the
// element would never reveal.
const { html: wrapped } = exportToHtml(animatedState, { title: 'Page' });
const headerHtml = '';
const { html: bodyHtml } = exportBodyHtml(animatedState);
const footerHtml = '';
const composedBody =
headerHtml + bodyHtml + footerHtml +
buildAnimationScript(headerHtml + bodyHtml + footerHtml);
const bodyMatch = wrapped.match(/<body[^>]*>([\s\S]*)<\/body>/i);
expect(bodyMatch).toBeTruthy();
const finalHtml = wrapped.replace(bodyMatch![1], () => composedBody);
const scriptCount = (finalHtml.match(/IntersectionObserver/g) || []).length;
expect(scriptCount).toBe(1);
expect(finalHtml).toContain('[data-animation]{opacity:0}');
expect(finalHtml).toContain('data-animation="fade-in"');
// No malformed void-tag artifact should leak into the final assembly.
expect(finalHtml).not.toContain('/ data-animation');
});
test('non-animated body: no animation CSS, no noscript, no reveal script anywhere', () => {
const plainState = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { tag: 'div', style: {} },
displayName: 'Container',
custom: {},
hidden: false,
nodes: [],
linkedNodes: {},
},
});
const { html } = exportToHtml(plainState, { title: 'Page' });
expect(html).not.toContain('[data-animation]');
expect(html).not.toContain('<noscript>');
expect(html).not.toContain('IntersectionObserver');
expect(buildAnimationScript(exportBodyHtml(plainState).html)).toBe('');
});
});
/**
* FIX: bounce entrance-animation disappears after finishing + reads like a
* fade (see .superpowers/sdd/fix-anim-image-contract.md, section A). Root
* cause: the old `@keyframes bounce` set opacity at 0% and 60% but NOT at
* 100% -- with `animation-fill-mode: both`, on finish the element reverted
* to the base `[data-animation]{opacity:0}` rule and vanished. The fix is a
* springier keyframe that ends at `opacity:1`.
*/
describe('bounce keyframe ends at opacity:1 (fix-anim-image A)', () => {
const animatedState = (animation: string) => JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { tag: 'div', style: {}, animation },
displayName: 'Container',
custom: {},
hidden: false,
nodes: [],
linkedNodes: {},
},
});
const NEW_BOUNCE_MINIFIED = '@keyframes bounce{0%{opacity:0;transform:translateY(40px)}40%{opacity:1;transform:translateY(-12px)}60%{transform:translateY(6px)}80%{transform:translateY(-3px)}100%{opacity:1;transform:translateY(0)}}';
const OLD_BOUNCE_TAIL = '100%{transform:translateY(0)}}';
test('minified export contains the new springier bounce substring, byte-identical to the shared contract', () => {
const { html } = exportToHtml(animatedState('bounce'), { title: 'Page' });
expect(html).toContain(NEW_BOUNCE_MINIFIED);
});
test('minified export does NOT contain the old bounce tail (100% with no opacity)', () => {
const { html } = exportToHtml(animatedState('bounce'), { title: 'Page' });
expect(html).not.toContain(OLD_BOUNCE_TAIL);
// Every keyframe's 100% frame in this doc must carry opacity:1 now.
expect(html).toContain('100%{opacity:1;transform:translateY(0)}}');
});
test('pretty (non-minified) export ends the bounce keyframe at 100% { opacity: 1; transform: translateY(0); }', () => {
const { html } = exportToHtml(animatedState('bounce'), { title: 'Page', minifyCss: false });
const NEW_BOUNCE_PRETTY = '@keyframes bounce { 0% { opacity: 0; transform: translateY(40px); } 40% { opacity: 1; transform: translateY(-12px); } 60% { transform: translateY(6px); } 80% { transform: translateY(-3px); } 100% { opacity: 1; transform: translateY(0); } }';
expect(html).toContain(NEW_BOUNCE_PRETTY);
expect(html).not.toContain('100% { transform: translateY(0); } }');
});
test('other keyframes (fadeIn/slideUp/zoomIn) are unchanged', () => {
const { html } = exportToHtml(animatedState('bounce'), { title: 'Page' });
expect(html).toContain('@keyframes fadeIn{from{opacity:0}to{opacity:1}}');
expect(html).toContain('@keyframes slideUp{from{opacity:0;transform:translateY(30px)}to{opacity:1;transform:translateY(0)}}');
expect(html).toContain('@keyframes zoomIn{from{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}');
});
});
+44 -6
View File
@@ -52,12 +52,29 @@ function buildDataAttrs(props: Record<string, any>): string {
/** /**
* Inject data attributes into the first HTML opening tag of a rendered string. * Inject data attributes into the first HTML opening tag of a rendered string.
*
* For a void/self-closing tag (e.g. `<img src="x" />`) the first `>` is
* preceded by a `/` -- naively inserting before the `>` produces the
* malformed `<img ... / data-animation="...">` (attrs land AFTER the
* self-close slash, outside the tag). Detect that trailing `/` and insert
* the attrs before it instead, yielding well-formed `<img ... data-animation="..."/>`.
* Non-void tags (no trailing `/`) are unaffected.
*/ */
function injectAttrs(html: string, attrs: string): string { function injectAttrs(html: string, attrs: string): string {
if (!attrs) return html; if (!attrs) return html;
// Find the first > of the opening tag and inject before it // Find the first > of the opening tag and inject before it
const idx = html.indexOf('>'); const idx = html.indexOf('>');
if (idx === -1) return html; if (idx === -1) return html;
if (idx > 0 && html[idx - 1] === '/') {
// Void/self-closing tag (`<img ... />`): inserting before `>` would land
// the attrs after the `/`, outside the tag (`<img ... / data-x="y">`).
// Insert before the `/` instead -- also trim any whitespace directly
// preceding it so we don't end up with a double space, since `attrs`
// already carries its own leading space(s).
let contentEnd = idx - 1;
while (contentEnd > 0 && /\s/.test(html[contentEnd - 1])) contentEnd--;
return html.slice(0, contentEnd) + attrs + html.slice(idx - 1);
}
return html.slice(0, idx) + attrs + html.slice(idx); return html.slice(0, idx) + attrs + html.slice(idx);
} }
@@ -321,7 +338,7 @@ const ANIMATION_CSS = `
@keyframes slideLeft { from { opacity: 0; transform: translateX(-30px); } to { opacity: 1; transform: translateX(0); } } @keyframes slideLeft { from { opacity: 0; transform: translateX(-30px); } to { opacity: 1; transform: translateX(0); } }
@keyframes slideRight { from { opacity: 0; transform: translateX(30px); } to { opacity: 1; transform: translateX(0); } } @keyframes slideRight { from { opacity: 0; transform: translateX(30px); } to { opacity: 1; transform: translateX(0); } }
@keyframes zoomIn { from { opacity: 0; transform: scale(0.9); } to { opacity: 1; transform: scale(1); } } @keyframes zoomIn { from { opacity: 0; transform: scale(0.9); } to { opacity: 1; transform: scale(1); } }
@keyframes bounce { 0% { opacity: 0; transform: translateY(30px); } 60% { opacity: 1; transform: translateY(-5px); } 100% { transform: translateY(0); } } @keyframes bounce { 0% { opacity: 0; transform: translateY(40px); } 40% { opacity: 1; transform: translateY(-12px); } 60% { transform: translateY(6px); } 80% { transform: translateY(-3px); } 100% { opacity: 1; transform: translateY(0); } }
[data-animation] { opacity: 0; } [data-animation] { opacity: 0; }
[data-animation].animated { animation-duration: 0.6s; animation-fill-mode: both; } [data-animation].animated { animation-duration: 0.6s; animation-fill-mode: both; }
@@ -332,18 +349,34 @@ const ANIMATION_CSS = `
[data-animation="zoom-in"].animated { animation-name: zoomIn; } [data-animation="zoom-in"].animated { animation-name: zoomIn; }
[data-animation="bounce"].animated { animation-name: bounce; }`; [data-animation="bounce"].animated { animation-name: bounce; }`;
const ANIMATION_CSS_MINIFIED = `@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes slideUp{from{opacity:0;transform:translateY(30px)}to{opacity:1;transform:translateY(0)}}@keyframes slideLeft{from{opacity:0;transform:translateX(-30px)}to{opacity:1;transform:translateX(0)}}@keyframes slideRight{from{opacity:0;transform:translateX(30px)}to{opacity:1;transform:translateX(0)}}@keyframes zoomIn{from{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}@keyframes bounce{0%{opacity:0;transform:translateY(30px)}60%{opacity:1;transform:translateY(-5px)}100%{transform:translateY(0)}}[data-animation]{opacity:0}[data-animation].animated{animation-duration:.6s;animation-fill-mode:both}[data-animation="fade-in"].animated{animation-name:fadeIn}[data-animation="slide-up"].animated{animation-name:slideUp}[data-animation="slide-left"].animated{animation-name:slideLeft}[data-animation="slide-right"].animated{animation-name:slideRight}[data-animation="zoom-in"].animated{animation-name:zoomIn}[data-animation="bounce"].animated{animation-name:bounce}`; const ANIMATION_CSS_MINIFIED = `@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes slideUp{from{opacity:0;transform:translateY(30px)}to{opacity:1;transform:translateY(0)}}@keyframes slideLeft{from{opacity:0;transform:translateX(-30px)}to{opacity:1;transform:translateX(0)}}@keyframes slideRight{from{opacity:0;transform:translateX(30px)}to{opacity:1;transform:translateX(0)}}@keyframes zoomIn{from{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}@keyframes bounce{0%{opacity:0;transform:translateY(40px)}40%{opacity:1;transform:translateY(-12px)}60%{transform:translateY(6px)}80%{transform:translateY(-3px)}100%{opacity:1;transform:translateY(0)}}[data-animation]{opacity:0}[data-animation].animated{animation-duration:.6s;animation-fill-mode:both}[data-animation="fade-in"].animated{animation-name:fadeIn}[data-animation="slide-up"].animated{animation-name:slideUp}[data-animation="slide-left"].animated{animation-name:slideLeft}[data-animation="slide-right"].animated{animation-name:slideRight}[data-animation="zoom-in"].animated{animation-name:zoomIn}[data-animation="bounce"].animated{animation-name:bounce}`;
const ANIMATION_SCRIPT = `<script> const ANIMATION_SCRIPT = `<script>
document.querySelectorAll('[data-animation]').forEach(function(el) { document.querySelectorAll('[data-animation]').forEach(function(el) {
var delay = el.getAttribute('data-animation-delay'); var delay = el.getAttribute('data-animation-delay');
if (delay) el.style.animationDelay = delay; if (delay) el.style.animationDelay = /^-?[0-9.]+$/.test(delay) ? delay + 's' : delay;
new IntersectionObserver(function(entries) { new IntersectionObserver(function(entries) {
entries.forEach(function(e) { if (e.isIntersecting) { el.classList.add('animated'); } }); entries.forEach(function(e) { if (e.isIntersecting) { el.classList.add('animated'); } });
}, { threshold: 0.1 }).observe(el); }, { threshold: 0.1 }).observe(el);
}); });
</script>`; </script>`;
// No-JS safety net (contract "No-JS safety"): un-hides animated elements
// when JS is disabled, so `[data-animation]{opacity:0}` never permanently
// hides content that the reveal script would otherwise never run for.
const ANIMATION_NOSCRIPT = `<noscript><style>[data-animation]{opacity:1}</style></noscript>`;
/**
* Returns the reveal `<script>` (byte-identical to the shared contract, and
* to the backend's `generateCompiledHTML` emission) when `bodyHtml` contains
* an animated element, else `''`. Single source of the script string so
* every caller (wrapInDocument's in-body emission, and TopBar's Preview
* body-replacement) stays in sync.
*/
export function buildAnimationScript(bodyHtml: string): string {
return bodyHtml.includes('data-animation') ? ANIMATION_SCRIPT : '';
}
function wrapInDocument(bodyHtml: string, options: ExportOptions): string { function wrapInDocument(bodyHtml: string, options: ExportOptions): string {
const title = options.title || 'Untitled Page'; const title = options.title || 'Untitled Page';
const minify = options.minifyCss !== false; const minify = options.minifyCss !== false;
@@ -361,10 +394,15 @@ function wrapInDocument(bodyHtml: string, options: ExportOptions): string {
const seoMeta = buildSeoMeta(options, title); const seoMeta = buildSeoMeta(options, title);
const tokenCss = buildTokenCss(design); const tokenCss = buildTokenCss(design);
// Only include animation CSS + script if body contains data-animation // Only include animation CSS + noscript fallback + script if body contains
// data-animation (contract gate). `buildAnimationScript` is the single
// source of the reveal-script string -- TopBar's Preview body-replacement
// uses the same helper so the two emissions never drift apart.
const hasAnimations = bodyHtml.includes('data-animation'); const hasAnimations = bodyHtml.includes('data-animation');
const animationBlock = hasAnimations ? animation : ''; const animationBlock = hasAnimations ? animation : '';
const animationScript = hasAnimations ? `\n${ANIMATION_SCRIPT}` : ''; const animationNoscript = hasAnimations ? `\n ${ANIMATION_NOSCRIPT}` : '';
const revealScript = buildAnimationScript(bodyHtml);
const animationScript = revealScript ? `\n${revealScript}` : '';
return `<!DOCTYPE html> return `<!DOCTYPE html>
<html lang="en"> <html lang="en">
@@ -372,7 +410,7 @@ function wrapInDocument(bodyHtml: string, options: ExportOptions): string {
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
${seoMeta}${fonts} ${seoMeta}${fonts}
<style>${reset}${responsive}${visibility}${animationBlock}${tokenCss}</style>${headCode} <style>${reset}${responsive}${visibility}${animationBlock}${tokenCss}</style>${animationNoscript}${headCode}
</head> </head>
<body> <body>
${bodyHtml}${animationScript} ${bodyHtml}${animationScript}