- Icon button with tooltip 'Search (Ctrl/Cmd+K)' calls openCommandPalette() - Preview passes fontScanHtml: composedBody and trims metaTitle so the Preview head matches the published head Refs #49 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
360 lines
15 KiB
TypeScript
360 lines
15 KiB
TypeScript
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.
|
|
*/
|
|
|
|
// #54: what the pre-publish checks see. Default (no pages) means no checks, so
|
|
// every pre-existing test publishes directly.
|
|
const checkFixture: { pages: any[]; liveState: string; activePageId: string; footerState: string | null } = { pages: [], liveState: '{}', activePageId: 'home', footerState: null };
|
|
vi.mock('../../state/PageContext', () => ({
|
|
usePages: () => ({
|
|
pages: checkFixture.pages,
|
|
headerPage: { id: '__header__', name: 'Header', slug: '__header__', craftState: null },
|
|
footerPage: { id: '__footer__', name: 'Footer', slug: '__footer__', craftState: checkFixture.footerState },
|
|
activePageId: checkFixture.activePageId,
|
|
switchPage: vi.fn(),
|
|
}),
|
|
}));
|
|
|
|
vi.mock('@craftjs/core', () => ({
|
|
useEditor: (collector?: (state: unknown, query: unknown) => Record<string, unknown>) => {
|
|
const query = {
|
|
serialize: () => checkFixture.liveState,
|
|
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 }));
|
|
const openPaletteMock = vi.fn();
|
|
vi.mock('../command-palette/CommandPalette', () => ({ openCommandPalette: () => openPaletteMock() }));
|
|
|
|
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 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();
|
|
checkFixture.pages = [];
|
|
checkFixture.liveState = '{}';
|
|
checkFixture.activePageId = 'home';
|
|
checkFixture.footerState = null;
|
|
openPaletteMock.mockReset();
|
|
});
|
|
|
|
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('[data-testid="save-status-pill"]')!.getAttribute('data-status')).toBe('published');
|
|
expect(container.querySelector('[data-testid="error-notice"]')).toBeNull();
|
|
expect(container.textContent).toContain('Submissions will not be delivered until an administrator enables it.');
|
|
});
|
|
|
|
test('warnings and the Published pill both outlast the old 3-second flash', 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();
|
|
});
|
|
|
|
const pillStatus = () => container.querySelector('[data-testid="save-status-pill"]')!.getAttribute('data-status');
|
|
expect(pillStatus()).toBe('published');
|
|
expect(container.textContent).toContain('Sticks around after the flash.');
|
|
|
|
act(() => {
|
|
vi.advanceTimersByTime(3000);
|
|
});
|
|
|
|
// Published persists until the next edit; no timer resets it.
|
|
expect(pillStatus()).toBe('published');
|
|
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();
|
|
});
|
|
});
|
|
|
|
describe('TopBar device switcher reads/writes DeviceContext (W0-breakpoints)', () => {
|
|
test('clicking Tablet updates the shared device for every consumer', async () => {
|
|
const { DeviceProvider, useDevice } = await import('../../state/DeviceContext');
|
|
const Probe: React.FC = () => <span data-testid="probe">{useDevice().device}</span>;
|
|
container = document.createElement('div');
|
|
document.body.appendChild(container);
|
|
act(() => {
|
|
root = createRoot(container);
|
|
root.render(
|
|
<EditorConfigProvider config={whpConfig}>
|
|
<DeviceProvider>
|
|
<TopBar showGuides={false} onToggleGuides={() => {}} />
|
|
<Probe />
|
|
</DeviceProvider>
|
|
</EditorConfigProvider>,
|
|
);
|
|
});
|
|
const tablet = container.querySelector<HTMLButtonElement>('.device-btn[aria-label="Tablet"]')!;
|
|
expect(tablet.getAttribute('aria-pressed')).toBe('false');
|
|
act(() => {
|
|
tablet.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
});
|
|
expect(container.querySelector('[data-testid="probe"]')!.textContent).toBe('tablet');
|
|
expect(tablet.getAttribute('aria-pressed')).toBe('true');
|
|
});
|
|
});
|
|
|
|
|
|
/** #54: Publish runs the checklist first; the modal gates publish() until confirmed. */
|
|
describe('TopBar pre-publish checklist', () => {
|
|
const stateWith = (nodes: Record<string, any>) => JSON.stringify({
|
|
ROOT: { type: { resolvedName: 'Container' }, props: {}, nodes: Object.keys(nodes), linkedNodes: {}, parent: null },
|
|
...Object.fromEntries(Object.entries(nodes).map(([id, n]) => [id, { nodes: [], linkedNodes: {}, parent: 'ROOT', ...n }])),
|
|
});
|
|
const H1 = { type: { resolvedName: 'Heading' }, props: { level: 'h1', text: 'Hi', style: {} } };
|
|
const BAD_IMG = { type: { resolvedName: 'ImageBlock' }, props: { src: 'assets/a.png', alt: '' } };
|
|
const page = (craftState: string) => ({ id: 'p1', name: 'Home', slug: 'index', seo: { metaDescription: 'd' }, craftState });
|
|
const modal = () => container.querySelector('[data-testid="publish-checklist"]');
|
|
const q = (id: string) => container.querySelector<HTMLButtonElement>(`[data-testid="${id}"]`)!;
|
|
const click = async (el: Element) => {
|
|
await act(async () => {
|
|
el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
await Promise.resolve();
|
|
await Promise.resolve();
|
|
});
|
|
};
|
|
|
|
test('with warnings: modal opens and publish() is NOT called until Publish anyway', async () => {
|
|
publishMock.mockResolvedValue({ success: true });
|
|
checkFixture.pages = [page(stateWith({ h: H1, img: BAD_IMG }))];
|
|
checkFixture.activePageId = 'other';
|
|
render();
|
|
await clickPublish();
|
|
expect(modal()).not.toBeNull();
|
|
expect(container.querySelectorAll('[data-testid="publish-check"]')).toHaveLength(1);
|
|
expect(publishMock).not.toHaveBeenCalled();
|
|
|
|
await click(q('publish-checklist-confirm'));
|
|
expect(publishMock).toHaveBeenCalledTimes(1);
|
|
expect(modal()).toBeNull();
|
|
});
|
|
|
|
test('Cancel closes the modal and never publishes', async () => {
|
|
checkFixture.pages = [page(stateWith({ h: H1, img: BAD_IMG }))];
|
|
checkFixture.activePageId = 'other';
|
|
render();
|
|
await clickPublish();
|
|
await click(q('publish-checklist-cancel'));
|
|
expect(modal()).toBeNull();
|
|
expect(publishMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('with nothing to flag: publishes directly, no modal', async () => {
|
|
publishMock.mockResolvedValue({ success: true });
|
|
checkFixture.pages = [page(stateWith({ h: H1 }))];
|
|
checkFixture.activePageId = 'other';
|
|
render();
|
|
await clickPublish();
|
|
expect(modal()).toBeNull();
|
|
expect(publishMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
test('checks the LIVE canvas for the active page, not its stale stored state', async () => {
|
|
publishMock.mockResolvedValue({ success: true });
|
|
checkFixture.pages = [page(stateWith({ h: H1 }))]; // stored: clean
|
|
checkFixture.activePageId = 'p1';
|
|
checkFixture.liveState = stateWith({ h: H1, img: BAD_IMG }); // canvas: unsaved bad image
|
|
render();
|
|
await clickPublish();
|
|
expect(modal()).not.toBeNull();
|
|
expect(publishMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('a failed save after confirming still surfaces as a publish failure (gate does not swallow it)', async () => {
|
|
publishMock.mockResolvedValue({ success: false, failedStep: 'save', message: 'Publish cancelled: the save before publishing did not complete.' });
|
|
checkFixture.pages = [page(stateWith({ h: H1, img: BAD_IMG }))];
|
|
checkFixture.activePageId = 'other';
|
|
render();
|
|
await clickPublish();
|
|
await click(q('publish-checklist-confirm'));
|
|
expect(publishMock).toHaveBeenCalledTimes(1);
|
|
expect(container.textContent).toContain('did not complete');
|
|
});
|
|
|
|
test('response.generated adds an info line to the post-publish banner', async () => {
|
|
publishMock.mockResolvedValue({ success: true, generated: ['sitemap.xml', 'robots.txt'] });
|
|
render();
|
|
await clickPublish();
|
|
expect(container.querySelector('[data-testid="publish-warnings"]')!.textContent).toContain('Generated sitemap.xml and robots.txt.');
|
|
});
|
|
});
|
|
|
|
describe('TopBar search button (#49 integration)', () => {
|
|
test('opens the command palette and carries the shortcut tooltip', () => {
|
|
render();
|
|
const btn = container.querySelector<HTMLButtonElement>('button[aria-label="Search"]');
|
|
expect(btn).not.toBeNull();
|
|
expect(btn!.getAttribute('data-tooltip')).toBe('Search (Ctrl/Cmd+K)');
|
|
act(() => { btn!.dispatchEvent(new MouseEvent('click', { bubbles: true })); });
|
|
expect(openPaletteMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|
|
|
|
describe('TopBar Preview head parity (item 14)', () => {
|
|
const rootState = (style: Record<string, string> = {}) => JSON.stringify({
|
|
ROOT: { type: { resolvedName: 'Container' }, isCanvas: true, props: { tag: 'div', style }, displayName: 'Container', custom: {}, hidden: false, nodes: [], linkedNodes: {} },
|
|
});
|
|
|
|
test('scans the composed header+body+footer for preset fonts and trims metaTitle', async () => {
|
|
checkFixture.liveState = rootState();
|
|
checkFixture.footerState = rootState({ fontFamily: 'Merriweather, serif' });
|
|
checkFixture.pages = [{ id: 'home', name: 'Home', slug: 'index', craftState: null, seo: { metaTitle: ' ' } }];
|
|
let blob: Blob | null = null;
|
|
const createUrl = vi.spyOn(URL, 'createObjectURL').mockImplementation((b) => { blob = b as Blob; return 'blob:x'; });
|
|
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
|
|
try {
|
|
render();
|
|
const btn = container.querySelector<HTMLButtonElement>('button[aria-label="Preview"]')!;
|
|
await act(async () => { btn.dispatchEvent(new MouseEvent('click', { bubbles: true })); });
|
|
await vi.waitFor(() => expect(blob).not.toBeNull());
|
|
const html = await blob!.text();
|
|
expect(html).toContain('family=Inter:wght@300;400;500;600;700&family=Merriweather:wght@300;400;700&display=swap');
|
|
expect(html).toContain('<title>Home</title>');
|
|
} finally {
|
|
createUrl.mockRestore();
|
|
openSpy.mockRestore();
|
|
}
|
|
});
|
|
});
|