Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb9fea6656 | ||
|
|
b1afdcb585 | ||
|
|
f00e4db3dc | ||
|
|
b9552faa30 | ||
|
|
77f35c4e9e | ||
|
|
2c8425ffb0 | ||
|
|
2a071bc7ab | ||
|
|
2a8a26687b | ||
|
|
979331b12d | ||
|
|
329a782052 | ||
|
|
da558fd52d | ||
|
|
8aeadefa88 |
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<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, viewport-fit=cover" />
|
||||||
<title>Site Builder</title>
|
<title>Site Builder</title>
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { usePages } from '../state/PageContext';
|
|||||||
import { DeviceMode } from '../types';
|
import { DeviceMode } from '../types';
|
||||||
import { DEVICE_WIDTHS } from '../constants/presets';
|
import { DEVICE_WIDTHS } from '../constants/presets';
|
||||||
import { exportBodyHtml } from '../utils/html-export';
|
import { exportBodyHtml } from '../utils/html-export';
|
||||||
|
import { useIsMobile } from '../hooks/useIsMobile';
|
||||||
|
import { useMobileChrome } from '../state/MobileChromeContext';
|
||||||
|
|
||||||
interface CanvasProps {
|
interface CanvasProps {
|
||||||
device: DeviceMode;
|
device: DeviceMode;
|
||||||
@@ -112,13 +114,18 @@ export const EmptyCanvasHint: React.FC = () => {
|
|||||||
isDragging: state.events.dragged.size > 0,
|
isDragging: state.events.dragged.size > 0,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
|
||||||
if (!isEmpty || isDragging) return null;
|
if (!isEmpty || isDragging) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="empty-canvas-hint">
|
<div className="empty-canvas-hint">
|
||||||
<i className="fa fa-cubes" aria-hidden />
|
<i className="fa fa-cubes" aria-hidden />
|
||||||
<span>Drag blocks from the left panel, or pick a Template to start.</span>
|
<span>
|
||||||
|
{isMobile
|
||||||
|
? <>Tap <strong>Blocks</strong> below to add content, or pick a Template to start.</>
|
||||||
|
: 'Drag blocks from the left panel, or pick a Template to start.'}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -129,6 +136,42 @@ export const Canvas: React.FC<CanvasProps> = ({ device, showGuides }) => {
|
|||||||
|
|
||||||
const isEditingRegularPage = !isEditingHeader && !isEditingFooter;
|
const isEditingRegularPage = !isEditingHeader && !isEditingFooter;
|
||||||
|
|
||||||
|
// Fast-follow item 4: while `MobileSelectionToolbar` is up (fixed, ~53px
|
||||||
|
// tall, just above the tab bar), it covers whatever content was at the
|
||||||
|
// very bottom of the canvas's own scroll area -- on a short page, the
|
||||||
|
// last section could sit permanently under the toolbar with no way to
|
||||||
|
// scroll past it. Mirrors that toolbar's own visibility condition
|
||||||
|
// (`selectedId && activeSheet === null`) exactly, computed independently
|
||||||
|
// here since Canvas has no other reason to depend on the toolbar
|
||||||
|
// component itself.
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
const { activeSheet } = useMobileChrome();
|
||||||
|
const { selectedId } = useEditor((state) => {
|
||||||
|
const selected = state.events.selected;
|
||||||
|
const id = selected && selected.size > 0 ? (Array.from(selected)[0] as string) : null;
|
||||||
|
return { selectedId: id && id !== 'ROOT' ? id : null };
|
||||||
|
});
|
||||||
|
const mobileToolbarVisible = isMobile && !!selectedId && activeSheet === null;
|
||||||
|
|
||||||
|
// Fast-follow item 3: `MobileSelectionToolbar`'s "Style" tap scrolls the
|
||||||
|
// selected node up towards the top of the canvas so it stays visible
|
||||||
|
// above the Styles sheet (~65dvh tall) -- but that scroll is still bound
|
||||||
|
// by the canvas's own natural scroll range. For a selected node near the
|
||||||
|
// END of the content (very plausibly the last section on the page --
|
||||||
|
// exactly the kind of node someone just added/duplicated and wants to
|
||||||
|
// style), there may not be enough scrollable distance below it to bring
|
||||||
|
// its top all the way up to the visible band above the sheet; the browser
|
||||||
|
// simply clamps at its existing max scrollTop, leaving the node's top
|
||||||
|
// stuck behind the sheet with nothing anyone can do about it (verified
|
||||||
|
// live: the last section of a page landed under the sheet even after the
|
||||||
|
// scroll-into-view ran). Pad the canvas with a full extra viewport's
|
||||||
|
// worth of scroll room while the sheet is open with a selection, exactly
|
||||||
|
// as `has-mobile-selection-toolbar` (item 4) already pads it for the
|
||||||
|
// fixed toolbar -- generous enough that ANY node, including the very
|
||||||
|
// last one, can always be scrolled with its top reaching the very top of
|
||||||
|
// the canvas (comfortably within the "top ~30%" target).
|
||||||
|
const mobileStylesSheetPad = isMobile && !!selectedId && activeSheet === 'styles';
|
||||||
|
|
||||||
const frameStyle = isEditingHeader
|
const frameStyle = isEditingHeader
|
||||||
? { minHeight: '60px', backgroundColor: '#ffffff', padding: '12px 24px', display: 'flex', alignItems: 'center' }
|
? { minHeight: '60px', backgroundColor: '#ffffff', padding: '12px 24px', display: 'flex', alignItems: 'center' }
|
||||||
: isEditingFooter
|
: isEditingFooter
|
||||||
@@ -138,7 +181,11 @@ export const Canvas: React.FC<CanvasProps> = ({ device, showGuides }) => {
|
|||||||
const frameTag = isEditingHeader ? 'header' : isEditingFooter ? 'footer' : 'div';
|
const frameTag = isEditingHeader ? 'header' : isEditingFooter ? 'footer' : 'div';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="editor-canvas">
|
<div
|
||||||
|
className={`editor-canvas${mobileToolbarVisible ? ' has-mobile-selection-toolbar' : ''}${
|
||||||
|
mobileStylesSheetPad ? ' has-mobile-styles-sheet' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
className={`canvas-device-frame${showGuides ? '' : ' guides-off'}`}
|
className={`canvas-device-frame${showGuides ? '' : ' guides-off'}`}
|
||||||
style={{
|
style={{
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
import React, { useState, useCallback } from 'react';
|
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { TopBar } from '../panels/topbar/TopBar';
|
import { TopBar } from '../panels/topbar/TopBar';
|
||||||
import { LeftPanel } from '../panels/left/LeftPanel';
|
import { LeftPanel } from '../panels/left/LeftPanel';
|
||||||
import { RightPanel } from '../panels/right/RightPanel';
|
import { RightPanel } from '../panels/right/RightPanel';
|
||||||
|
import { MobilePanelBar } from '../panels/mobile/MobilePanelBar';
|
||||||
|
import { MobileSelectionToolbar } from '../panels/mobile/MobileSelectionToolbar';
|
||||||
import { Canvas } from './Canvas';
|
import { Canvas } from './Canvas';
|
||||||
import { ContextMenu } from '../panels/context-menu/ContextMenu';
|
import { ContextMenu } from '../panels/context-menu/ContextMenu';
|
||||||
import { useContextMenu } from '../hooks/useContextMenu';
|
import { useContextMenu } from '../hooks/useContextMenu';
|
||||||
import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts';
|
import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts';
|
||||||
|
import { useIsMobile } from '../hooks/useIsMobile';
|
||||||
|
import { MobileChromeProvider } from '../state/MobileChromeContext';
|
||||||
import { DeviceMode } from '../types';
|
import { DeviceMode } from '../types';
|
||||||
|
|
||||||
const SHOW_GUIDES_STORAGE_KEY = 'craft-show-guides';
|
const SHOW_GUIDES_STORAGE_KEY = 'craft-show-guides';
|
||||||
@@ -21,7 +25,21 @@ function loadShowGuides(): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const EditorShell: React.FC = () => {
|
export const EditorShell: React.FC = () => {
|
||||||
|
const isMobile = useIsMobile();
|
||||||
const [device, setDevice] = useState<DeviceMode>('desktop');
|
const [device, setDevice] = useState<DeviceMode>('desktop');
|
||||||
|
// Phase A: default the canvas to the "mobile" preview width the first
|
||||||
|
// time we detect a mobile viewport, so the frame fits without the user
|
||||||
|
// having to reach for the device switcher (now tucked in TopBar's
|
||||||
|
// overflow menu on mobile). Only fires once, and only if the device is
|
||||||
|
// still at its initial default -- it must not fight a device the user
|
||||||
|
// has already picked (e.g. from the overflow menu) on a later re-render.
|
||||||
|
const mobileDeviceAppliedRef = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (isMobile && !mobileDeviceAppliedRef.current) {
|
||||||
|
mobileDeviceAppliedRef.current = true;
|
||||||
|
setDevice((current) => (current === 'desktop' ? 'mobile' : current));
|
||||||
|
}
|
||||||
|
}, [isMobile]);
|
||||||
// Item 10: canvas dashed "guide" outlines toggle -- default ON, persisted
|
// Item 10: canvas dashed "guide" outlines toggle -- default ON, persisted
|
||||||
// so the choice survives a reload. Lifted here (rather than owned by
|
// so the choice survives a reload. Lifted here (rather than owned by
|
||||||
// TopBar or Canvas alone) because the toggle button lives in TopBar but
|
// TopBar or Canvas alone) because the toggle button lives in TopBar but
|
||||||
@@ -59,6 +77,12 @@ export const EditorShell: React.FC = () => {
|
|||||||
}, [query, showMenu]);
|
}, [query, showMenu]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
// Mobile-A2: shared sheet/modal-open state (see MobileChromeContext) --
|
||||||
|
// provided around the whole shell so TopBar's Templates/Head Code modal
|
||||||
|
// state and MobilePanelBar's sheet state live in one place. Desktop
|
||||||
|
// doesn't render MobilePanelBar and TopBar's desktop branch behaves
|
||||||
|
// identically to before (same booleans, just sourced from context).
|
||||||
|
<MobileChromeProvider>
|
||||||
<div className="editor-app">
|
<div className="editor-app">
|
||||||
<TopBar
|
<TopBar
|
||||||
device={device}
|
device={device}
|
||||||
@@ -67,12 +91,14 @@ export const EditorShell: React.FC = () => {
|
|||||||
onToggleGuides={() => setShowGuides(!showGuides)}
|
onToggleGuides={() => setShowGuides(!showGuides)}
|
||||||
/>
|
/>
|
||||||
<div className="editor-container">
|
<div className="editor-container">
|
||||||
<LeftPanel />
|
{!isMobile && <LeftPanel />}
|
||||||
<div onContextMenu={handleContextMenu} style={{ flex: 1, display: 'flex', minWidth: 0 }}>
|
<div onContextMenu={handleContextMenu} style={{ flex: 1, display: 'flex', minWidth: 0 }}>
|
||||||
<Canvas device={device} showGuides={showGuides} />
|
<Canvas device={device} showGuides={showGuides} />
|
||||||
</div>
|
</div>
|
||||||
<RightPanel />
|
{!isMobile && <RightPanel />}
|
||||||
</div>
|
</div>
|
||||||
|
{isMobile && <MobilePanelBar />}
|
||||||
|
{isMobile && <MobileSelectionToolbar />}
|
||||||
<ContextMenu
|
<ContextMenu
|
||||||
visible={menuState.visible}
|
visible={menuState.visible}
|
||||||
x={menuState.x}
|
x={menuState.x}
|
||||||
@@ -81,5 +107,6 @@ export const EditorShell: React.FC = () => {
|
|||||||
onClose={hideMenu}
|
onClose={hideMenu}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</MobileChromeProvider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
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';
|
||||||
|
import { useIsMobile } from './useIsMobile';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile-A2 (review item 5): useIsMobile is the single source of truth every
|
||||||
|
* mobile-only branch (bottom tab bar, collapsed topbar, bottom sheets) reads
|
||||||
|
* from, so it needs direct coverage of: (a) it reflects matchMedia's
|
||||||
|
* `matches`, (b) the `change` listener is registered AND cleaned up on
|
||||||
|
* unmount (a leaked listener would keep re-rendering an unmounted tree /
|
||||||
|
* leak the component instance), and (c) the legacy Safari<14
|
||||||
|
* addListener/removeListener fallback is used when addEventListener isn't
|
||||||
|
* available.
|
||||||
|
*
|
||||||
|
* DOM-harness pattern mirrors PageContext.pure-updaters.test.tsx /
|
||||||
|
* useKeyboardShortcuts.test.tsx: bare createRoot + act, no @testing-library
|
||||||
|
* (not a project dependency).
|
||||||
|
*/
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
let originalMatchMedia: typeof window.matchMedia;
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A minimal fake MediaQueryList. `mode` picks which listener API it
|
||||||
|
* exposes, so tests can force the legacy fallback path. */
|
||||||
|
function makeMql(matches: boolean, mode: 'modern' | 'legacy' = 'modern') {
|
||||||
|
const listeners: Array<() => void> = [];
|
||||||
|
const mql: any = {
|
||||||
|
matches,
|
||||||
|
media: '(max-width: 768px)',
|
||||||
|
};
|
||||||
|
if (mode === 'modern') {
|
||||||
|
mql.addEventListener = vi.fn((_type: string, fn: () => void) => listeners.push(fn));
|
||||||
|
mql.removeEventListener = vi.fn((_type: string, fn: () => void) => {
|
||||||
|
const i = listeners.indexOf(fn);
|
||||||
|
if (i !== -1) listeners.splice(i, 1);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
mql.addListener = vi.fn((fn: () => void) => listeners.push(fn));
|
||||||
|
mql.removeListener = vi.fn((fn: () => void) => {
|
||||||
|
const i = listeners.indexOf(fn);
|
||||||
|
if (i !== -1) listeners.splice(i, 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { mql, fire: () => listeners.forEach((fn) => fn()), listenerCount: () => listeners.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
let probedValue: boolean | null = null;
|
||||||
|
const Probe: React.FC = () => {
|
||||||
|
probedValue = useIsMobile();
|
||||||
|
return <span data-value={String(probedValue)} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
originalMatchMedia = window.matchMedia;
|
||||||
|
probedValue = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
window.matchMedia = originalMatchMedia;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useIsMobile', () => {
|
||||||
|
test('returns true when the mobile media query matches', () => {
|
||||||
|
const { mql } = makeMql(true);
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(probedValue).toBe(true);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false when the mobile media query does not match', () => {
|
||||||
|
const { mql } = makeMql(false);
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(probedValue).toBe(false);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('registers the change listener via addEventListener and updates on change', () => {
|
||||||
|
const { mql, fire, listenerCount } = makeMql(false);
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(probedValue).toBe(false);
|
||||||
|
expect(mql.addEventListener).toHaveBeenCalledWith('change', expect.any(Function));
|
||||||
|
expect(listenerCount()).toBe(1);
|
||||||
|
|
||||||
|
// Flip the query result and fire the registered 'change' listener --
|
||||||
|
// the hook must re-read mql.matches, not just toggle blindly.
|
||||||
|
mql.matches = true;
|
||||||
|
act(() => {
|
||||||
|
fire();
|
||||||
|
});
|
||||||
|
expect(probedValue).toBe(true);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cleans up the addEventListener listener on unmount', () => {
|
||||||
|
const { mql, listenerCount } = makeMql(true);
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(listenerCount()).toBe(1);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
expect(mql.removeEventListener).toHaveBeenCalledWith('change', expect.any(Function));
|
||||||
|
expect(listenerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('falls back to legacy addListener/removeListener when addEventListener is unavailable', () => {
|
||||||
|
const { mql, fire, listenerCount } = makeMql(false, 'legacy');
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(probedValue).toBe(false);
|
||||||
|
expect(mql.addListener).toHaveBeenCalledWith(expect.any(Function));
|
||||||
|
expect(listenerCount()).toBe(1);
|
||||||
|
|
||||||
|
mql.matches = true;
|
||||||
|
act(() => {
|
||||||
|
fire();
|
||||||
|
});
|
||||||
|
expect(probedValue).toBe(true);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
expect(mql.removeListener).toHaveBeenCalledWith(expect.any(Function));
|
||||||
|
expect(listenerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
/** Mobile breakpoint for the editor chrome (Phase A). Keep in sync with the
|
||||||
|
* `@media (max-width: 768px)` block in `src/styles/editor.css` -- both the
|
||||||
|
* CSS and this hook must agree on where mobile chrome kicks in. */
|
||||||
|
export const MOBILE_BREAKPOINT_PX = 768;
|
||||||
|
const MOBILE_QUERY = `(max-width: ${MOBILE_BREAKPOINT_PX}px)`;
|
||||||
|
|
||||||
|
function computeIsMobile(): boolean {
|
||||||
|
if (typeof window === 'undefined') return false;
|
||||||
|
if (typeof window.matchMedia === 'function') {
|
||||||
|
try {
|
||||||
|
return window.matchMedia(MOBILE_QUERY).matches;
|
||||||
|
} catch {
|
||||||
|
// Fall through to the width check below (e.g. some older/embedded
|
||||||
|
// WebViews expose a matchMedia that throws instead of omitting it).
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return window.innerWidth <= MOBILE_BREAKPOINT_PX;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reports whether the viewport is at or below the mobile editor breakpoint.
|
||||||
|
* Drives every mobile-only branch introduced in Phase A (bottom tab bar,
|
||||||
|
* collapsed topbar, bottom sheets) -- desktop rendering must stay identical
|
||||||
|
* above the breakpoint, so this is the single source of truth both React
|
||||||
|
* and (via the matching CSS media query) plain CSS use to agree on "mobile".
|
||||||
|
*
|
||||||
|
* Falls back to a `resize` listener + `window.innerWidth` when
|
||||||
|
* `matchMedia` isn't available (e.g. some test/JSDOM environments), so the
|
||||||
|
* hook degrades gracefully rather than throwing.
|
||||||
|
*/
|
||||||
|
export function useIsMobile(): boolean {
|
||||||
|
const [isMobile, setIsMobile] = useState<boolean>(computeIsMobile);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
if (typeof window.matchMedia === 'function') {
|
||||||
|
let mql: MediaQueryList | null = null;
|
||||||
|
try {
|
||||||
|
mql = window.matchMedia(MOBILE_QUERY);
|
||||||
|
} catch {
|
||||||
|
mql = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mql) {
|
||||||
|
const handleChange = () => setIsMobile(mql!.matches);
|
||||||
|
handleChange();
|
||||||
|
|
||||||
|
if (typeof mql.addEventListener === 'function') {
|
||||||
|
mql.addEventListener('change', handleChange);
|
||||||
|
return () => mql!.removeEventListener('change', handleChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Safari < 14 only supports the deprecated addListener/removeListener pair.
|
||||||
|
const legacyMql = mql as MediaQueryList & {
|
||||||
|
addListener?: (listener: () => void) => void;
|
||||||
|
removeListener?: (listener: () => void) => void;
|
||||||
|
};
|
||||||
|
legacyMql.addListener?.(handleChange);
|
||||||
|
return () => legacyMql.removeListener?.(handleChange);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleResize = () => setIsMobile(window.innerWidth <= MOBILE_BREAKPOINT_PX);
|
||||||
|
window.addEventListener('resize', handleResize);
|
||||||
|
return () => window.removeEventListener('resize', handleResize);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return isMobile;
|
||||||
|
}
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
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';
|
||||||
|
import type { NodeTree, Node } from '@craftjs/core';
|
||||||
|
import { useNodeActions, type NodeActions } from './useNodeActions';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase B, item 1: `useNodeActions` was extracted out of `ContextMenu.tsx` so
|
||||||
|
* the desktop right-click menu and the mobile selection toolbar
|
||||||
|
* (`MobileSelectionToolbar`) share one implementation. This suite exercises
|
||||||
|
* the hook directly (mocking `@craftjs/core`'s `useEditor`, mirroring the
|
||||||
|
* pattern in `useKeyboardShortcuts.test.tsx`), covering:
|
||||||
|
* - moveUp/moveDown call `actions.move` with the right target index, and
|
||||||
|
* are no-ops at the respective boundary
|
||||||
|
* - canMoveUp/canMoveDown reflect the node's position among its siblings
|
||||||
|
* - duplicate regenerates ids, inserts the copy IMMEDIATELY AFTER the
|
||||||
|
* source node (`actions.addNodeTree(tree, parentId, sourceIndex + 1)`),
|
||||||
|
* and selects the new copy (`actions.selectNode(tree.rootNodeId)`) --
|
||||||
|
* Phase B fast-follow: the previous append-at-end behavior left the copy
|
||||||
|
* off-screen with the ORIGINAL still selected, so users couldn't see
|
||||||
|
* what "Duplicate" had just done.
|
||||||
|
* - selectParent calls `actions.selectNode` with the parent id
|
||||||
|
* - canSelectParent reflects whether the node's parent is itself real
|
||||||
|
* (not ROOT/missing) -- false at a top-level section, true one level in
|
||||||
|
* - deleteNode routes through `findDeletableTarget` (also covering the
|
||||||
|
* "no deletable target" no-op)
|
||||||
|
* - ROOT/null nodeId disables every action safely (no-ops, all
|
||||||
|
* canMoveUp/canMoveDown/canDelete/canSelectParent false)
|
||||||
|
*/
|
||||||
|
|
||||||
|
const moveMock = vi.fn();
|
||||||
|
const addNodeTreeMock = vi.fn();
|
||||||
|
const selectNodeMock = vi.fn();
|
||||||
|
const deleteMock = vi.fn();
|
||||||
|
|
||||||
|
interface FakeNodeData {
|
||||||
|
parent: string | null;
|
||||||
|
nodes: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
let fakeNodes: Record<string, { data: FakeNodeData }> = {};
|
||||||
|
|
||||||
|
const COPIED_TREE: NodeTree = {
|
||||||
|
rootNodeId: 'child-1',
|
||||||
|
nodes: {
|
||||||
|
'child-1': {
|
||||||
|
id: 'child-1',
|
||||||
|
data: { props: {}, type: { resolvedName: 'Container' }, name: 'Container', displayName: 'Container', isCanvas: false, parent: 'parent-1', linkedNodes: {}, nodes: [], hidden: false },
|
||||||
|
info: {},
|
||||||
|
events: { selected: false, dragged: false, hovered: false },
|
||||||
|
dom: null,
|
||||||
|
related: {},
|
||||||
|
rules: {},
|
||||||
|
_hydrationTimestamp: 0,
|
||||||
|
} as unknown as Node,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function makeQuery() {
|
||||||
|
return {
|
||||||
|
node: (id: string) => ({
|
||||||
|
get: () => fakeNodes[id] ?? null,
|
||||||
|
toNodeTree: () => {
|
||||||
|
if (id !== 'child-1') throw new Error(`unexpected toNodeTree() for "${id}"`);
|
||||||
|
return COPIED_TREE;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useEditor: (collector?: (state: any, query: any) => any) => {
|
||||||
|
const state = {
|
||||||
|
nodes: Object.fromEntries(Object.entries(fakeNodes).map(([id, n]) => [id, n])),
|
||||||
|
};
|
||||||
|
const query = makeQuery();
|
||||||
|
const collected = collector ? collector(state, query) : {};
|
||||||
|
return {
|
||||||
|
...collected,
|
||||||
|
actions: {
|
||||||
|
move: moveMock,
|
||||||
|
addNodeTree: addNodeTreeMock,
|
||||||
|
selectNode: selectNodeMock,
|
||||||
|
delete: deleteMock,
|
||||||
|
},
|
||||||
|
query,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../utils/craft-tree', async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import('../utils/craft-tree')>();
|
||||||
|
return { ...actual, regenerateTreeIds: vi.fn(actual.regenerateTreeIds) };
|
||||||
|
});
|
||||||
|
|
||||||
|
import { regenerateTreeIds } from '../utils/craft-tree';
|
||||||
|
const regenerateTreeIdsMock = vi.mocked(regenerateTreeIds);
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
let captured: NodeActions | null = null;
|
||||||
|
|
||||||
|
const Probe: React.FC<{ nodeId: string | null }> = ({ nodeId }) => {
|
||||||
|
captured = useNodeActions(nodeId);
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function render(nodeId: string | null) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(<Probe nodeId={nodeId} />);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function rerender(nodeId: string | null) {
|
||||||
|
act(() => {
|
||||||
|
root.render(<Probe nodeId={nodeId} />);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function unmount() {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
moveMock.mockClear();
|
||||||
|
addNodeTreeMock.mockClear();
|
||||||
|
selectNodeMock.mockClear();
|
||||||
|
deleteMock.mockClear();
|
||||||
|
regenerateTreeIdsMock.mockClear();
|
||||||
|
captured = null;
|
||||||
|
fakeNodes = {
|
||||||
|
ROOT: { data: { parent: null, nodes: ['parent-1'] } },
|
||||||
|
'parent-1': { data: { parent: 'ROOT', nodes: ['child-0', 'child-1', 'child-2'] } },
|
||||||
|
'child-0': { data: { parent: 'parent-1', nodes: [] } },
|
||||||
|
'child-1': { data: { parent: 'parent-1', nodes: [] } },
|
||||||
|
'child-2': { data: { parent: 'parent-1', nodes: [] } },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (root) unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useNodeActions', () => {
|
||||||
|
test('a middle child can move both up and down', () => {
|
||||||
|
render('child-1');
|
||||||
|
expect(captured!.canMoveUp).toBe(true);
|
||||||
|
expect(captured!.canMoveDown).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the first child cannot move up, but can move down', () => {
|
||||||
|
render('child-0');
|
||||||
|
expect(captured!.canMoveUp).toBe(false);
|
||||||
|
expect(captured!.canMoveDown).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the last child can move up, but not down', () => {
|
||||||
|
render('child-2');
|
||||||
|
expect(captured!.canMoveUp).toBe(true);
|
||||||
|
expect(captured!.canMoveDown).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('moveUp calls actions.move with idx - 1, moveDown with idx + 2 (Craft.js index semantics)', () => {
|
||||||
|
render('child-1');
|
||||||
|
act(() => captured!.moveUp());
|
||||||
|
expect(moveMock).toHaveBeenCalledWith('child-1', 'parent-1', 0);
|
||||||
|
|
||||||
|
moveMock.mockClear();
|
||||||
|
act(() => captured!.moveDown());
|
||||||
|
expect(moveMock).toHaveBeenCalledWith('child-1', 'parent-1', 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('moveUp/moveDown at a boundary are no-ops', () => {
|
||||||
|
render('child-0');
|
||||||
|
act(() => captured!.moveUp());
|
||||||
|
expect(moveMock).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
rerender('child-2');
|
||||||
|
act(() => captured!.moveDown());
|
||||||
|
expect(moveMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('duplicate inserts the copy immediately after the source (parentId, sourceIndex + 1) and selects it', () => {
|
||||||
|
render('child-1');
|
||||||
|
let returned: string | null | undefined;
|
||||||
|
act(() => {
|
||||||
|
returned = captured!.duplicate();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(regenerateTreeIdsMock).toHaveBeenCalledTimes(1);
|
||||||
|
expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
|
||||||
|
const [tree, parentId, index] = addNodeTreeMock.mock.calls[0];
|
||||||
|
// child-1 is at index 1 among ['child-0', 'child-1', 'child-2'] -> insert at 2.
|
||||||
|
expect(parentId).toBe('parent-1');
|
||||||
|
expect(index).toBe(2);
|
||||||
|
expect(tree.rootNodeId).not.toBe(COPIED_TREE.rootNodeId);
|
||||||
|
|
||||||
|
expect(selectNodeMock).toHaveBeenCalledTimes(1);
|
||||||
|
expect(selectNodeMock).toHaveBeenCalledWith(tree.rootNodeId);
|
||||||
|
expect(returned).toBe(tree.rootNodeId);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('selectParent calls actions.selectNode with the parent id', () => {
|
||||||
|
render('child-1');
|
||||||
|
act(() => captured!.selectParent());
|
||||||
|
expect(selectNodeMock).toHaveBeenCalledWith('parent-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('canSelectParent is false at a top-level node (parent is ROOT), true one level deeper', () => {
|
||||||
|
render('parent-1'); // parent-1's own parent is 'ROOT'
|
||||||
|
expect(captured!.canSelectParent).toBe(false);
|
||||||
|
|
||||||
|
rerender('child-1'); // child-1's parent is 'parent-1', a real node
|
||||||
|
expect(captured!.canSelectParent).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deleteNode calls actions.delete with the node id when deletable', () => {
|
||||||
|
render('child-1');
|
||||||
|
expect(captured!.canDelete).toBe(true);
|
||||||
|
act(() => captured!.deleteNode());
|
||||||
|
expect(deleteMock).toHaveBeenCalledWith('child-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ROOT nodeId disables every action and is a safe no-op', () => {
|
||||||
|
render('ROOT');
|
||||||
|
expect(captured!.canMoveUp).toBe(false);
|
||||||
|
expect(captured!.canMoveDown).toBe(false);
|
||||||
|
expect(captured!.canDelete).toBe(false);
|
||||||
|
expect(captured!.canSelectParent).toBe(false);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
captured!.moveUp();
|
||||||
|
captured!.moveDown();
|
||||||
|
captured!.duplicate();
|
||||||
|
captured!.selectParent();
|
||||||
|
captured!.deleteNode();
|
||||||
|
});
|
||||||
|
expect(moveMock).not.toHaveBeenCalled();
|
||||||
|
expect(addNodeTreeMock).not.toHaveBeenCalled();
|
||||||
|
expect(selectNodeMock).not.toHaveBeenCalled();
|
||||||
|
expect(deleteMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('null nodeId disables every action and is a safe no-op', () => {
|
||||||
|
render(null);
|
||||||
|
expect(captured!.canMoveUp).toBe(false);
|
||||||
|
expect(captured!.canMoveDown).toBe(false);
|
||||||
|
expect(captured!.canDelete).toBe(false);
|
||||||
|
expect(captured!.canSelectParent).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
import { useEditor } from '@craftjs/core';
|
||||||
|
import { regenerateTreeIds } from '../utils/craft-tree';
|
||||||
|
import { findDeletableTarget } from '../utils/craft-helpers';
|
||||||
|
|
||||||
|
export interface NodeActions {
|
||||||
|
moveUp: () => void;
|
||||||
|
moveDown: () => void;
|
||||||
|
/** Duplicates `nodeId`, inserting the copy immediately after the source in
|
||||||
|
* the parent's children and selecting it. Returns the new node's id (so
|
||||||
|
* callers -- e.g. `MobileSelectionToolbar` -- can scroll it into view),
|
||||||
|
* or null if the duplicate could not be performed (no-op for ROOT/null,
|
||||||
|
* or a caught error). */
|
||||||
|
duplicate: () => string | null;
|
||||||
|
deleteNode: () => void;
|
||||||
|
selectParent: () => void;
|
||||||
|
/** True if `nodeId` has an earlier sibling under the same parent (so
|
||||||
|
* `moveUp` would actually move it). False for ROOT/null/no-parent. */
|
||||||
|
canMoveUp: boolean;
|
||||||
|
/** True if `nodeId` has a later sibling under the same parent (so
|
||||||
|
* `moveDown` would actually move it). False for ROOT/null/no-parent. */
|
||||||
|
canMoveDown: boolean;
|
||||||
|
/** True if `findDeletableTarget` resolves to a real, deletable node (either
|
||||||
|
* `nodeId` itself, or an ancestor when `nodeId` is an empty linked-node
|
||||||
|
* slot whose siblings are all also empty -- see `craft-helpers.ts`). */
|
||||||
|
canDelete: boolean;
|
||||||
|
/** True if `nodeId` has a real parent to select -- i.e. the parent is
|
||||||
|
* neither ROOT nor missing. `selectParent` on a top-level section (whose
|
||||||
|
* parent IS 'ROOT') would only select the page-wide ROOT node, which has
|
||||||
|
* no on-canvas outline and no toolbar of its own -- a dead end for a
|
||||||
|
* mobile user with no way back. False for ROOT/null/no-parent too. */
|
||||||
|
canSelectParent: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared node-action logic (move up/down, duplicate, delete, select parent)
|
||||||
|
* extracted from `ContextMenu.tsx` (Phase B) so both the desktop right-click
|
||||||
|
* menu AND the mobile on-canvas selection toolbar (`MobileSelectionToolbar`)
|
||||||
|
* drive the exact same behavior from one place instead of two independent
|
||||||
|
* copies drifting apart.
|
||||||
|
*
|
||||||
|
* IMPORTANT gotcha this hook works around: `@craftjs/core`'s `useEditor`
|
||||||
|
* collector (`@craftjs/utils`' `useCollector`) only synchronously computes
|
||||||
|
* the collector function ONCE, on this hook's very first mount. After that,
|
||||||
|
* it updates purely in reaction to the underlying store's OWN change
|
||||||
|
* notifications, invoking whatever collector closure is current AT THAT
|
||||||
|
* NOTIFICATION -- so a collector that closes over `nodeId` (an argument that
|
||||||
|
* changes across renders of the SAME mounted hook instance, e.g. every time
|
||||||
|
* `MobileSelectionToolbar` re-renders with a newly-selected node) goes stale
|
||||||
|
* for exactly one render: the cached value from the last store notification
|
||||||
|
* (computed against the PREVIOUS nodeId) is what gets returned, until some
|
||||||
|
* unrelated store event happens to trigger a fresh computation. An earlier
|
||||||
|
* version of this hook computed `canMoveUp`/`canMoveDown`/`canDelete` inside
|
||||||
|
* such a collector and was caught showing the PREVIOUS selection's move
|
||||||
|
* boundaries in the mobile toolbar for one render after tapping a new node
|
||||||
|
* (verified with real Playwright touch taps against a real Craft.js
|
||||||
|
* document -- a plain mocked `useEditor` in a unit test doesn't reproduce
|
||||||
|
* this, since a hand-rolled mock has no reason to replicate the real
|
||||||
|
* library's caching).
|
||||||
|
*
|
||||||
|
* The fix: get `actions`/`query` from a collector-FREE `useEditor()` call
|
||||||
|
* (an always-live reference, same pattern `ContextMenu.tsx` used before this
|
||||||
|
* extraction) and compute `canMoveUp`/`canMoveDown`/`canDelete` as plain
|
||||||
|
* synchronous code during render using that live `query` -- never cached.
|
||||||
|
*
|
||||||
|
* That still leaves one gap: `nodeId` staying the SAME across renders while
|
||||||
|
* its position changes (e.g. tapping "Move Up" repeatedly on the same
|
||||||
|
* still-selected node) needs SOMETHING to trigger a re-render so the boundary
|
||||||
|
* flags below get recomputed. An earlier version of this hook forced that
|
||||||
|
* via a second `useEditor((state) => ({ _: state.nodes }))` subscription --
|
||||||
|
* but subscribing to the WHOLE node map reacts to every `dom` ref
|
||||||
|
* assignment too (Craft's `connectors.connect(ref)` calls `actions.setDOM`
|
||||||
|
* synchronously from a React ref callback during COMMIT, i.e. while some
|
||||||
|
* OTHER component is still mounting), which trips React's "Cannot update a
|
||||||
|
* component while rendering a different component" warning the moment a
|
||||||
|
* freshly-added container with children mounts. Callers that need
|
||||||
|
* `canMoveUp`/`canMoveDown` to refresh after a move they themselves
|
||||||
|
* triggered (`MobileSelectionToolbar`) should instead bump their OWN local
|
||||||
|
* state right after calling `moveUp`/`moveDown` -- a plain, local,
|
||||||
|
* event-handler-triggered re-render, not a store-wide subscription.
|
||||||
|
*/
|
||||||
|
export function useNodeActions(nodeId: string | null | undefined): NodeActions {
|
||||||
|
const { actions, query } = useEditor();
|
||||||
|
|
||||||
|
const isRootOrNull = !nodeId || nodeId === 'ROOT';
|
||||||
|
|
||||||
|
let canMoveUp = false;
|
||||||
|
let canMoveDown = false;
|
||||||
|
let canSelectParent = false;
|
||||||
|
if (!isRootOrNull) {
|
||||||
|
try {
|
||||||
|
const node = query.node(nodeId).get();
|
||||||
|
const parentId: string | null | undefined = node?.data?.parent;
|
||||||
|
if (parentId) {
|
||||||
|
canSelectParent = parentId !== 'ROOT';
|
||||||
|
const siblings: string[] = query.node(parentId).get()?.data?.nodes || [];
|
||||||
|
const idx = siblings.indexOf(nodeId);
|
||||||
|
canMoveUp = idx > 0;
|
||||||
|
canMoveDown = idx !== -1 && idx < siblings.length - 1;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Node no longer exists (e.g. deleted out from under a stale
|
||||||
|
// reference) -- leave both false.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const canDelete = !isRootOrNull && !!findDeletableTarget(query, nodeId);
|
||||||
|
|
||||||
|
const getParentId = (): string | null => {
|
||||||
|
if (!nodeId) return null;
|
||||||
|
try {
|
||||||
|
const node = query.node(nodeId).get();
|
||||||
|
return node?.data?.parent || null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const duplicate = (): string | null => {
|
||||||
|
if (!nodeId || nodeId === 'ROOT') return null;
|
||||||
|
try {
|
||||||
|
const parentId = getParentId();
|
||||||
|
if (!parentId) return null;
|
||||||
|
|
||||||
|
const tree = regenerateTreeIds(query.node(nodeId).toNodeTree());
|
||||||
|
|
||||||
|
// Insert the copy IMMEDIATELY AFTER the source node, not appended at
|
||||||
|
// the end of the parent -- on a top-level section, "append at end"
|
||||||
|
// landed the copy at the bottom of the page, off-screen, with the
|
||||||
|
// ORIGINAL still selected, so a duplicate looked like nothing had
|
||||||
|
// happened at all. Resolve the source's index among its siblings so
|
||||||
|
// the copy lands right next to what it was copied from; if that can't
|
||||||
|
// be resolved for any reason, fall back to the old append behavior
|
||||||
|
// rather than guessing at an index (or throwing).
|
||||||
|
let insertIndex: number | undefined;
|
||||||
|
try {
|
||||||
|
const siblings: string[] = query.node(parentId).get()?.data?.nodes || [];
|
||||||
|
const sourceIndex = siblings.indexOf(nodeId);
|
||||||
|
if (sourceIndex !== -1) insertIndex = sourceIndex + 1;
|
||||||
|
} catch {
|
||||||
|
// Leave insertIndex undefined -- addNodeTree appends when omitted.
|
||||||
|
}
|
||||||
|
|
||||||
|
if (insertIndex !== undefined) {
|
||||||
|
actions.addNodeTree(tree, parentId, insertIndex);
|
||||||
|
} else {
|
||||||
|
actions.addNodeTree(tree, parentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Select the new copy (not the original) so the toolbar/context menu
|
||||||
|
// and any on-canvas outline immediately reflect what was just created.
|
||||||
|
actions.selectNode(tree.rootNodeId);
|
||||||
|
|
||||||
|
return tree.rootNodeId;
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Duplicate failed:', e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveUp = () => {
|
||||||
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
|
try {
|
||||||
|
const parentId = getParentId();
|
||||||
|
if (!parentId) return;
|
||||||
|
const parent = query.node(parentId).get();
|
||||||
|
const children = parent.data.nodes || [];
|
||||||
|
const idx = children.indexOf(nodeId);
|
||||||
|
if (idx > 0) {
|
||||||
|
actions.move(nodeId, parentId, idx - 1);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Move up failed:', e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveDown = () => {
|
||||||
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
|
try {
|
||||||
|
const parentId = getParentId();
|
||||||
|
if (!parentId) return;
|
||||||
|
const parent = query.node(parentId).get();
|
||||||
|
const children = parent.data.nodes || [];
|
||||||
|
const idx = children.indexOf(nodeId);
|
||||||
|
if (idx < children.length - 1) {
|
||||||
|
actions.move(nodeId, parentId, idx + 2);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Move down failed:', e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectParent = () => {
|
||||||
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
|
const parentId = getParentId();
|
||||||
|
if (parentId) {
|
||||||
|
actions.selectNode(parentId);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteNode = () => {
|
||||||
|
const target = findDeletableTarget(query, nodeId);
|
||||||
|
if (!target) return;
|
||||||
|
try {
|
||||||
|
actions.delete(target);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Delete failed:', e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
moveUp,
|
||||||
|
moveDown,
|
||||||
|
duplicate,
|
||||||
|
deleteNode,
|
||||||
|
selectParent,
|
||||||
|
canMoveUp,
|
||||||
|
canMoveDown,
|
||||||
|
canDelete,
|
||||||
|
canSelectParent,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
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';
|
||||||
|
import { useVisualViewportInsets } from './useVisualViewport';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fast-follow coverage for `useVisualViewportInsets` (BottomSheet's
|
||||||
|
* keyboard-avoidance source of truth). Mirrors the bare createRoot + act
|
||||||
|
* harness `useIsMobile.test.tsx` uses (no @testing-library/react in this
|
||||||
|
* repo). Covers:
|
||||||
|
* - the no-`visualViewport` fallback (older WebViews) returns
|
||||||
|
* `{ height: window.innerHeight, keyboardInset: 0 }` AND registers no
|
||||||
|
* listener (there's nothing to listen to).
|
||||||
|
* - the keyboard-open math: `keyboardInset = innerHeight - (vv.height +
|
||||||
|
* vv.offsetTop)`, recomputed when the mocked vv fires `resize`.
|
||||||
|
* - both `resize` and `scroll` listeners are added on mount and the SAME
|
||||||
|
* handler is removed for both on unmount (a leaked listener would keep
|
||||||
|
* reacting after the owning component -- e.g. BottomSheet -- is gone).
|
||||||
|
*/
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
let originalInnerHeight: number;
|
||||||
|
let originalVisualViewport: VisualViewport | null;
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A minimal fake `visualViewport`: just enough surface for the hook
|
||||||
|
* (`height`, `offsetTop`, `addEventListener`/`removeEventListener`). */
|
||||||
|
function makeVisualViewport(height: number, offsetTop: number) {
|
||||||
|
const listeners: Record<string, Array<() => void>> = { resize: [], scroll: [] };
|
||||||
|
const vv: any = {
|
||||||
|
height,
|
||||||
|
offsetTop,
|
||||||
|
addEventListener: vi.fn((type: string, fn: () => void) => {
|
||||||
|
listeners[type].push(fn);
|
||||||
|
}),
|
||||||
|
removeEventListener: vi.fn((type: string, fn: () => void) => {
|
||||||
|
const i = listeners[type].indexOf(fn);
|
||||||
|
if (i !== -1) listeners[type].splice(i, 1);
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
vv,
|
||||||
|
fire: (type: 'resize' | 'scroll') => listeners[type].forEach((fn) => fn()),
|
||||||
|
listenerCount: (type: 'resize' | 'scroll') => listeners[type].length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let probed: { height: number; keyboardInset: number } | null = null;
|
||||||
|
const Probe: React.FC = () => {
|
||||||
|
probed = useVisualViewportInsets();
|
||||||
|
return <span data-height={probed.height} data-inset={probed.keyboardInset} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
originalInnerHeight = window.innerHeight;
|
||||||
|
originalVisualViewport = window.visualViewport;
|
||||||
|
probed = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
Object.defineProperty(window, 'innerHeight', {
|
||||||
|
value: originalInnerHeight,
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
Object.defineProperty(window, 'visualViewport', {
|
||||||
|
value: originalVisualViewport,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useVisualViewportInsets', () => {
|
||||||
|
test('falls back to innerHeight/0 and registers no listener when visualViewport is undefined', () => {
|
||||||
|
Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true, writable: true });
|
||||||
|
Object.defineProperty(window, 'visualViewport', { value: undefined, configurable: true });
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
|
||||||
|
expect(probed).toEqual({ height: 800, keyboardInset: 0 });
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('computes keyboardInset from visualViewport and recomputes on resize', () => {
|
||||||
|
Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true, writable: true });
|
||||||
|
const { vv, fire } = makeVisualViewport(800, 0);
|
||||||
|
Object.defineProperty(window, 'visualViewport', { value: vv, configurable: true });
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
|
||||||
|
// No keyboard open: vv fills the layout viewport exactly.
|
||||||
|
expect(probed).toEqual({ height: 800, keyboardInset: 0 });
|
||||||
|
|
||||||
|
// Simulate the on-screen keyboard opening: the visual viewport shrinks.
|
||||||
|
vv.height = 500;
|
||||||
|
vv.offsetTop = 0;
|
||||||
|
act(() => {
|
||||||
|
fire('resize');
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(probed).toEqual({ height: 500, keyboardInset: 300 });
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('registers resize and scroll listeners on mount and removes both (same handler) on unmount', () => {
|
||||||
|
Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true, writable: true });
|
||||||
|
const { vv, listenerCount } = makeVisualViewport(800, 0);
|
||||||
|
Object.defineProperty(window, 'visualViewport', { value: vv, configurable: true });
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
|
||||||
|
expect(vv.addEventListener).toHaveBeenCalledWith('resize', expect.any(Function));
|
||||||
|
expect(vv.addEventListener).toHaveBeenCalledWith('scroll', expect.any(Function));
|
||||||
|
expect(listenerCount('resize')).toBe(1);
|
||||||
|
expect(listenerCount('scroll')).toBe(1);
|
||||||
|
|
||||||
|
const resizeHandler = vv.addEventListener.mock.calls.find((c: any[]) => c[0] === 'resize')[1];
|
||||||
|
const scrollHandler = vv.addEventListener.mock.calls.find((c: any[]) => c[0] === 'scroll')[1];
|
||||||
|
expect(resizeHandler).toBe(scrollHandler);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
expect(vv.removeEventListener).toHaveBeenCalledWith('resize', resizeHandler);
|
||||||
|
expect(vv.removeEventListener).toHaveBeenCalledWith('scroll', scrollHandler);
|
||||||
|
expect(listenerCount('resize')).toBe(0);
|
||||||
|
expect(listenerCount('scroll')).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
export interface VisualViewportInsets {
|
||||||
|
/** The visual viewport's current height (shrinks when the on-screen
|
||||||
|
* keyboard opens). Falls back to `window.innerHeight` when
|
||||||
|
* `visualViewport` isn't supported. */
|
||||||
|
height: number;
|
||||||
|
/** Extra inset a `position: fixed`, bottom-anchored element should add to
|
||||||
|
* its own `bottom` offset to stay clear of the on-screen keyboard --
|
||||||
|
* `window.innerHeight` minus the visual viewport's bottom edge (its
|
||||||
|
* height + offsetTop). Zero whenever no keyboard is open, or
|
||||||
|
* `visualViewport` isn't supported (a safe no-op fallback). */
|
||||||
|
keyboardInset: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ZERO_INSETS: VisualViewportInsets = { height: 0, keyboardInset: 0 };
|
||||||
|
|
||||||
|
function computeInsets(): VisualViewportInsets {
|
||||||
|
if (typeof window === 'undefined') return ZERO_INSETS;
|
||||||
|
const vv = window.visualViewport;
|
||||||
|
if (!vv) return { height: window.innerHeight, keyboardInset: 0 };
|
||||||
|
const keyboardInset = Math.max(0, window.innerHeight - (vv.height + vv.offsetTop));
|
||||||
|
return { height: vv.height, keyboardInset };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tracks `window.visualViewport`'s height/offset (item 5, Phase B) so
|
||||||
|
* `BottomSheet` can stay clear of the on-screen keyboard. `position: fixed`
|
||||||
|
* elements are positioned against the LAYOUT viewport, which does NOT shrink
|
||||||
|
* when a mobile keyboard opens -- only the visual viewport does -- so a
|
||||||
|
* bottom-anchored sheet's inputs can otherwise end up hidden underneath the
|
||||||
|
* keyboard with no visual indication anything is wrong.
|
||||||
|
*
|
||||||
|
* Guards for browsers without `visualViewport` (older WebViews): falls back
|
||||||
|
* to `{ height: window.innerHeight, keyboardInset: 0 }`, i.e. a no-op, so
|
||||||
|
* the sheet just keeps its existing (keyboard-unaware) sizing there.
|
||||||
|
*/
|
||||||
|
export function useVisualViewportInsets(): VisualViewportInsets {
|
||||||
|
const [insets, setInsets] = useState<VisualViewportInsets>(computeInsets);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof window === 'undefined' || !window.visualViewport) return;
|
||||||
|
const vv = window.visualViewport;
|
||||||
|
const handleChange = () => setInsets(computeInsets());
|
||||||
|
handleChange();
|
||||||
|
vv.addEventListener('resize', handleChange);
|
||||||
|
vv.addEventListener('scroll', handleChange);
|
||||||
|
return () => {
|
||||||
|
vv.removeEventListener('resize', handleChange);
|
||||||
|
vv.removeEventListener('scroll', handleChange);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return insets;
|
||||||
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import React, { useEffect, useCallback, useRef } from 'react';
|
import React, { useEffect, useCallback, useRef } from 'react';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { findDeletableTarget } from '../../utils/craft-helpers';
|
|
||||||
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 { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard';
|
||||||
|
import { useNodeActions } from '../../hooks/useNodeActions';
|
||||||
|
|
||||||
interface ContextMenuProps {
|
interface ContextMenuProps {
|
||||||
visible: boolean;
|
visible: boolean;
|
||||||
@@ -65,19 +65,16 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
}
|
}
|
||||||
}, [nodeId, query]);
|
}, [nodeId, query]);
|
||||||
|
|
||||||
const duplicate = useCallback(() => {
|
// Shared move/duplicate/delete/select-parent logic (item 1, Phase B) --
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
// extracted into `useNodeActions` so the mobile selection toolbar drives
|
||||||
try {
|
// the exact same behavior. Wrapped here purely to also `onClose()` the
|
||||||
const parentId = getParentId();
|
// menu after each action, same as before the extraction.
|
||||||
if (!parentId) return;
|
const nodeActions = useNodeActions(nodeId);
|
||||||
|
|
||||||
const tree = regenerateTreeIds(query.node(nodeId).toNodeTree());
|
const duplicate = useCallback(() => {
|
||||||
actions.addNodeTree(tree, parentId);
|
nodeActions.duplicate();
|
||||||
} catch (e) {
|
|
||||||
console.error('Duplicate failed:', e);
|
|
||||||
}
|
|
||||||
onClose();
|
onClose();
|
||||||
}, [nodeId, actions, query, getParentId, onClose]);
|
}, [nodeActions, onClose]);
|
||||||
|
|
||||||
const copyNode = useCallback(() => {
|
const copyNode = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
@@ -118,47 +115,19 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
}, [nodeId, actions, query, onClose]);
|
}, [nodeId, actions, query, onClose]);
|
||||||
|
|
||||||
const moveUp = useCallback(() => {
|
const moveUp = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
nodeActions.moveUp();
|
||||||
try {
|
|
||||||
const parentId = getParentId();
|
|
||||||
if (!parentId) return;
|
|
||||||
const parent = query.node(parentId).get();
|
|
||||||
const children = parent.data.nodes || [];
|
|
||||||
const idx = children.indexOf(nodeId);
|
|
||||||
if (idx > 0) {
|
|
||||||
actions.move(nodeId, parentId, idx - 1);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Move up failed:', e);
|
|
||||||
}
|
|
||||||
onClose();
|
onClose();
|
||||||
}, [nodeId, actions, query, getParentId, onClose]);
|
}, [nodeActions, onClose]);
|
||||||
|
|
||||||
const moveDown = useCallback(() => {
|
const moveDown = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
nodeActions.moveDown();
|
||||||
try {
|
|
||||||
const parentId = getParentId();
|
|
||||||
if (!parentId) return;
|
|
||||||
const parent = query.node(parentId).get();
|
|
||||||
const children = parent.data.nodes || [];
|
|
||||||
const idx = children.indexOf(nodeId);
|
|
||||||
if (idx < children.length - 1) {
|
|
||||||
actions.move(nodeId, parentId, idx + 2);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Move down failed:', e);
|
|
||||||
}
|
|
||||||
onClose();
|
onClose();
|
||||||
}, [nodeId, actions, query, getParentId, onClose]);
|
}, [nodeActions, onClose]);
|
||||||
|
|
||||||
const selectParent = useCallback(() => {
|
const selectParent = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
nodeActions.selectParent();
|
||||||
const parentId = getParentId();
|
|
||||||
if (parentId) {
|
|
||||||
actions.selectNode(parentId);
|
|
||||||
}
|
|
||||||
onClose();
|
onClose();
|
||||||
}, [nodeId, actions, getParentId, onClose]);
|
}, [nodeActions, onClose]);
|
||||||
|
|
||||||
const askSitesmith = useCallback(() => {
|
const askSitesmith = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
@@ -172,18 +141,9 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
}, [nodeId, query, openSitesmith, onClose]);
|
}, [nodeId, query, openSitesmith, onClose]);
|
||||||
|
|
||||||
const deleteNode = useCallback(() => {
|
const deleteNode = useCallback(() => {
|
||||||
const target = findDeletableTarget(query, nodeId);
|
nodeActions.deleteNode();
|
||||||
if (!target) {
|
|
||||||
onClose();
|
onClose();
|
||||||
return;
|
}, [nodeActions, onClose]);
|
||||||
}
|
|
||||||
try {
|
|
||||||
actions.delete(target);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Delete failed:', e);
|
|
||||||
}
|
|
||||||
onClose();
|
|
||||||
}, [nodeId, actions, query, onClose]);
|
|
||||||
|
|
||||||
if (!visible) return null;
|
if (!visible) return null;
|
||||||
|
|
||||||
@@ -235,7 +195,12 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
label: 'Select Parent',
|
label: 'Select Parent',
|
||||||
icon: 'level-up',
|
icon: 'level-up',
|
||||||
action: selectParent,
|
action: selectParent,
|
||||||
disabled: isRoot,
|
// Not just `isRoot`: the real dead-end is when nodeId's PARENT is
|
||||||
|
// ROOT (selecting a top-level section -> Select Parent would only
|
||||||
|
// select the page-wide, un-editable ROOT -- no outline, no toolbar).
|
||||||
|
// `canSelectParent` (useNodeActions) already encodes that and matches
|
||||||
|
// the mobile selection toolbar's identical guard.
|
||||||
|
disabled: !nodeActions.canSelectParent,
|
||||||
dividerAfter: true,
|
dividerAfter: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,12 +2,14 @@ import React, { useEffect, useRef, useState, useCallback } from 'react';
|
|||||||
import { useAssets } from '../../hooks/useAssets';
|
import { useAssets } from '../../hooks/useAssets';
|
||||||
import { clickableProps } from '../../utils/a11y';
|
import { clickableProps } from '../../utils/a11y';
|
||||||
import { copyToClipboard } from '../../utils/clipboard';
|
import { copyToClipboard } from '../../utils/clipboard';
|
||||||
|
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||||
|
|
||||||
/** How long the "Delete?" confirm state stays armed before auto-resetting. */
|
/** How long the "Delete?" confirm state stays armed before auto-resetting. */
|
||||||
const DELETE_CONFIRM_TIMEOUT_MS = 4000;
|
const DELETE_CONFIRM_TIMEOUT_MS = 4000;
|
||||||
|
|
||||||
export const AssetsPanel: React.FC = () => {
|
export const AssetsPanel: React.FC = () => {
|
||||||
const { assets, loading, error, loadAssets, uploadAsset, deleteAsset } = useAssets();
|
const { assets, loading, error, loadAssets, uploadAsset, deleteAsset } = useAssets();
|
||||||
|
const isMobile = useIsMobile();
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
const [isDragOver, setIsDragOver] = useState(false);
|
const [isDragOver, setIsDragOver] = useState(false);
|
||||||
const [copiedUrl, setCopiedUrl] = useState<string | null>(null);
|
const [copiedUrl, setCopiedUrl] = useState<string | null>(null);
|
||||||
@@ -139,7 +141,9 @@ export const AssetsPanel: React.FC = () => {
|
|||||||
{assets.length === 0 && (
|
{assets.length === 0 && (
|
||||||
<i className="fa fa-cloud-upload" aria-hidden style={{ fontSize: 28, opacity: 0.5 }} />
|
<i className="fa fa-cloud-upload" aria-hidden style={{ fontSize: 28, opacity: 0.5 }} />
|
||||||
)}
|
)}
|
||||||
{assets.length === 0 ? 'Drag images here or click to upload' : 'Drop files here to upload'}
|
{assets.length === 0
|
||||||
|
? (isMobile ? 'Tap to upload images' : 'Drag images here or click to upload')
|
||||||
|
: 'Drop files here to upload'}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Error message */}
|
{/* Error message */}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useCallback, useState } from 'react';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
|
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||||
|
import { useMobileChrome } from '../../state/MobileChromeContext';
|
||||||
import { Container } from '../../components/layout/Container';
|
import { Container } from '../../components/layout/Container';
|
||||||
import { Section } from '../../components/layout/Section';
|
import { Section } from '../../components/layout/Section';
|
||||||
import { ColumnLayout } from '../../components/layout/ColumnLayout';
|
import { ColumnLayout } from '../../components/layout/ColumnLayout';
|
||||||
@@ -146,6 +148,8 @@ const categories: CategoryDef[] = [
|
|||||||
|
|
||||||
export const BlocksPanel: React.FC = () => {
|
export const BlocksPanel: React.FC = () => {
|
||||||
const { connectors, actions, query } = useEditor();
|
const { connectors, actions, query } = useEditor();
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
const { closeSheet } = useMobileChrome();
|
||||||
const [collapsed, setCollapsed] = useState<Record<string, boolean>>(() => {
|
const [collapsed, setCollapsed] = useState<Record<string, boolean>>(() => {
|
||||||
const initial: Record<string, boolean> = {};
|
const initial: Record<string, boolean> = {};
|
||||||
categories.forEach((cat, index) => {
|
categories.forEach((cat, index) => {
|
||||||
@@ -158,6 +162,101 @@ export const BlocksPanel: React.FC = () => {
|
|||||||
setCollapsed((prev) => ({ ...prev, [categoryId]: !prev[categoryId] }));
|
setCollapsed((prev) => ({ ...prev, [categoryId]: !prev[categoryId] }));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Default insertion target when there's no usable selection to anchor
|
||||||
|
* to: the first real Craft.js canvas in the document (falls back to
|
||||||
|
* ROOT). Extracted from the pre-existing onDoubleClick handler so
|
||||||
|
* tap-to-add (mobile, item 3) and double-click (desktop, unchanged) share
|
||||||
|
* the exact same fallback. */
|
||||||
|
const findDefaultCanvasId = useCallback((): string => {
|
||||||
|
try {
|
||||||
|
const serialized = JSON.parse(query.serialize());
|
||||||
|
const nodeIds = Object.keys(serialized);
|
||||||
|
for (const id of nodeIds) {
|
||||||
|
if (serialized[id].isCanvas && id !== 'ROOT') return id;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Fall through to ROOT below.
|
||||||
|
}
|
||||||
|
return 'ROOT';
|
||||||
|
}, [query]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a fresh node tree for `block` and inserts it into the canvas,
|
||||||
|
* returning the new node's id (or null on failure). Shared by desktop's
|
||||||
|
* double-click (unchanged behavior/position: always appended to
|
||||||
|
* `findDefaultCanvasId()`) and mobile's tap-to-add (item 3), which instead
|
||||||
|
* prefers inserting as a sibling right after the current selection --
|
||||||
|
* `insertAfterSelection: true` only from the mobile tap handler below.
|
||||||
|
*/
|
||||||
|
const addBlockNode = useCallback((block: BlockDef, insertAfterSelection: boolean): string | null => {
|
||||||
|
try {
|
||||||
|
const tree = query.parseReactElement(React.cloneElement(block.component)).toNodeTree();
|
||||||
|
|
||||||
|
let inserted = false;
|
||||||
|
if (insertAfterSelection) {
|
||||||
|
try {
|
||||||
|
const selectedIds = query.getEvent('selected').all();
|
||||||
|
const selectedId = selectedIds.length > 0 ? selectedIds[0] : null;
|
||||||
|
if (selectedId && selectedId !== 'ROOT') {
|
||||||
|
const selectedNode = query.node(selectedId).get();
|
||||||
|
const parentId = selectedNode?.data?.parent;
|
||||||
|
if (parentId) {
|
||||||
|
const parent = query.node(parentId).get();
|
||||||
|
const siblings: string[] = parent?.data?.nodes || [];
|
||||||
|
const idx = siblings.indexOf(selectedId);
|
||||||
|
if (idx !== -1) {
|
||||||
|
actions.addNodeTree(tree, parentId, idx + 1);
|
||||||
|
inserted = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Selection isn't a valid sibling target (e.g. lives in a
|
||||||
|
// linkedNodes slot) -- fall through to the default canvas below.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!inserted) {
|
||||||
|
actions.addNodeTree(tree, findDefaultCanvasId());
|
||||||
|
}
|
||||||
|
|
||||||
|
return tree.rootNodeId;
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to add block:', e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}, [query, actions, findDefaultCanvasId]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile tap-to-add (item 3): a single tap on a block tile inserts it,
|
||||||
|
* closes the Blocks sheet, then selects the new node and scrolls it into
|
||||||
|
* view so the user immediately sees it (and gets the selection toolbar).
|
||||||
|
* The select/scroll step is deferred two animation frames past the
|
||||||
|
* `addNodeTree` call -- Craft.js's own state update (and thus the new
|
||||||
|
* node's real DOM element) lands asynchronously after this handler
|
||||||
|
* returns, so `query.node(id).get().dom` isn't populated yet if read
|
||||||
|
* synchronously here.
|
||||||
|
*/
|
||||||
|
const handleTapToAdd = useCallback((block: BlockDef) => {
|
||||||
|
const newId = addBlockNode(block, true);
|
||||||
|
closeSheet();
|
||||||
|
if (!newId) return;
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
try {
|
||||||
|
actions.selectNode(newId);
|
||||||
|
} catch {
|
||||||
|
// Node may have failed to mount -- nothing to select.
|
||||||
|
}
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
try {
|
||||||
|
query.node(newId).get()?.dom?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
} catch {
|
||||||
|
// Best-effort scroll -- not fatal if the node/DOM isn't found.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, [addBlockNode, closeSheet, actions, query]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{categories.map((category) => {
|
{categories.map((category) => {
|
||||||
@@ -178,24 +277,9 @@ export const BlocksPanel: React.FC = () => {
|
|||||||
key={block.id}
|
key={block.id}
|
||||||
className="block-item"
|
className="block-item"
|
||||||
ref={(ref) => { if (ref) connectors.create(ref, block.component); }}
|
ref={(ref) => { if (ref) connectors.create(ref, block.component); }}
|
||||||
onDoubleClick={() => {
|
onDoubleClick={() => addBlockNode(block, false)}
|
||||||
try {
|
onClick={isMobile ? () => handleTapToAdd(block) : undefined}
|
||||||
const serialized = JSON.parse(query.serialize());
|
title={isMobile ? `Tap to add ${block.label}` : `Drag or double-click to add ${block.label}`}
|
||||||
const nodeIds = Object.keys(serialized);
|
|
||||||
let canvasId = 'ROOT';
|
|
||||||
for (const nodeId of nodeIds) {
|
|
||||||
if (serialized[nodeId].isCanvas && nodeId !== 'ROOT') {
|
|
||||||
canvasId = nodeId;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const tree = query.parseReactElement(React.cloneElement(block.component)).toNodeTree();
|
|
||||||
actions.addNodeTree(tree, canvasId);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to add block:', e);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
title={`Drag or double-click to add ${block.label}`}
|
|
||||||
>
|
>
|
||||||
<i className={`fa ${block.icon} block-item-icon`} />
|
<i className={`fa ${block.icon} block-item-icon`} />
|
||||||
<span className="block-item-label">{block.label}</span>
|
<span className="block-item-label">{block.label}</span>
|
||||||
|
|||||||
@@ -146,6 +146,7 @@ const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
|||||||
{...clickableProps(handleActivate)}
|
{...clickableProps(handleActivate)}
|
||||||
onMouseEnter={handleMouseEnter}
|
onMouseEnter={handleMouseEnter}
|
||||||
onMouseLeave={handleMouseLeave}
|
onMouseLeave={handleMouseLeave}
|
||||||
|
className="layer-node-row"
|
||||||
style={{
|
style={{
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { useVisualViewportInsets } from '../../hooks/useVisualViewport';
|
||||||
|
|
||||||
|
export interface BottomSheetProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
title: string;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vertical drag distance (px) past which releasing the handle/header
|
||||||
|
* commits to closing the sheet, rather than snapping back open. */
|
||||||
|
const SWIPE_DISMISS_THRESHOLD_PX = 80;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile-only bottom sheet (Phase A). Slides up from the bottom of the
|
||||||
|
* viewport to host one of the existing side-panel components
|
||||||
|
* (BlocksPanel/PagesPanel/LayersPanel/AssetsPanel/GuidedStyles) unchanged,
|
||||||
|
* as the mobile replacement for the desktop fixed left/right panel columns.
|
||||||
|
* See `MobilePanelBar`, which owns which sheet (if any) is open.
|
||||||
|
*
|
||||||
|
* Deliberately NOT a generic replacement for `src/ui/Modal.tsx` (centered
|
||||||
|
* dialog chrome) -- this is anchored to the bottom, sized to ~65dvh, and
|
||||||
|
* has its own drag-handle affordance + internally scrollable body, all of
|
||||||
|
* which Modal doesn't need for its centered use cases.
|
||||||
|
*
|
||||||
|
* Phase B adds two more deferred behaviors on top of Phase A's static sheet:
|
||||||
|
* - **Swipe-to-dismiss**: a touchstart/move/end drag tracked on the handle
|
||||||
|
* row + header (not the scrollable body, so it never fights a panel's own
|
||||||
|
* vertical scroll) that follows the finger while dragging down and either
|
||||||
|
* commits to `onClose()` past `SWIPE_DISMISS_THRESHOLD_PX` or snaps back
|
||||||
|
* with a short transition otherwise.
|
||||||
|
* - **On-screen-keyboard clearance**: `useVisualViewportInsets` reports how
|
||||||
|
* much the visual viewport has shrunk from the bottom (i.e. the
|
||||||
|
* keyboard's height); that's surfaced as a `--keyboard-inset` CSS custom
|
||||||
|
* property (see editor.css) which both lifts the whole backdrop/sheet
|
||||||
|
* clear of the keyboard AND caps the sheet's own max-height so it never
|
||||||
|
* extends into the space the keyboard occupies. A `focusin` listener also
|
||||||
|
* scrolls the newly-focused input into view once the keyboard has had a
|
||||||
|
* moment to animate in, as a second line of defense for a field that's
|
||||||
|
* still off-screen after the resize alone (e.g. deep in a long panel).
|
||||||
|
*/
|
||||||
|
export const BottomSheet: React.FC<BottomSheetProps> = ({ open, onClose, title, children }) => {
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape') onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', handleKeyDown);
|
||||||
|
|
||||||
|
const prevOverflow = document.body.style.overflow;
|
||||||
|
document.body.style.overflow = 'hidden';
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('keydown', handleKeyDown);
|
||||||
|
document.body.style.overflow = prevOverflow;
|
||||||
|
};
|
||||||
|
}, [open, onClose]);
|
||||||
|
|
||||||
|
const { keyboardInset } = useVisualViewportInsets();
|
||||||
|
|
||||||
|
const bodyRef = useRef<HTMLDivElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const bodyEl = bodyRef.current;
|
||||||
|
if (!bodyEl) return;
|
||||||
|
const handleFocusIn = (e: FocusEvent) => {
|
||||||
|
const target = e.target as HTMLElement | null;
|
||||||
|
if (!target) return;
|
||||||
|
const tag = target.tagName;
|
||||||
|
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable) {
|
||||||
|
// Give the on-screen keyboard a moment to finish animating in
|
||||||
|
// before scrolling -- doing it immediately measures the pre-keyboard
|
||||||
|
// layout and can undershoot.
|
||||||
|
window.setTimeout(() => {
|
||||||
|
target.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
bodyEl.addEventListener('focusin', handleFocusIn);
|
||||||
|
return () => bodyEl.removeEventListener('focusin', handleFocusIn);
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
// Swipe-to-dismiss: tracked only on the handle row + header (never the
|
||||||
|
// scrollable `.mobile-sheet-body`, which needs its own vertical touch
|
||||||
|
// scrolling to keep working unimpeded).
|
||||||
|
//
|
||||||
|
// The authoritative drag distance lives in a REF (`dragOffsetRef`),
|
||||||
|
// updated synchronously and imperatively on every touchmove -- NOT solely
|
||||||
|
// in the `dragOffset` state used for rendering the drag transform. Two
|
||||||
|
// touchmoves can fire back-to-back inside the same synchronous event
|
||||||
|
// dispatch (e.g. a fast real swipe, or synthetic touch events fired
|
||||||
|
// without a yield between them), and React batches their `setDragOffset`
|
||||||
|
// calls into a single pending update that hasn't committed yet by the
|
||||||
|
// time `touchend` runs in that same tick -- reading the `dragOffset`
|
||||||
|
// STATE value directly in `handleTouchEnd` would then see a stale
|
||||||
|
// (pre-drag) value and wrongly decide the swipe didn't clear the
|
||||||
|
// threshold. The ref sidesteps that entirely (plain synchronous mutation,
|
||||||
|
// no batching). Relatedly, `onClose()` mutates an ANCESTOR component's
|
||||||
|
// state (MobileChromeContext's `closeSheet`) -- it must be called as a
|
||||||
|
// plain statement in the event handler, never from inside a `setState`
|
||||||
|
// functional updater (that runs during this component's own render phase
|
||||||
|
// and trips React's "Cannot update a component while rendering a
|
||||||
|
// different component" warning).
|
||||||
|
const dragStartYRef = useRef<number | null>(null);
|
||||||
|
const dragOffsetRef = useRef(0);
|
||||||
|
const [dragOffset, setDragOffset] = useState(0);
|
||||||
|
|
||||||
|
const handleTouchStart = useCallback((e: React.TouchEvent) => {
|
||||||
|
if (e.touches.length !== 1) return;
|
||||||
|
dragStartYRef.current = e.touches[0].clientY;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleTouchMove = useCallback((e: React.TouchEvent) => {
|
||||||
|
if (dragStartYRef.current === null) return;
|
||||||
|
const delta = e.touches[0].clientY - dragStartYRef.current;
|
||||||
|
// Only follow downward drags -- dragging up shouldn't do anything (the
|
||||||
|
// sheet is already fully open; there's no "expand further" state).
|
||||||
|
const next = Math.max(0, delta);
|
||||||
|
dragOffsetRef.current = next;
|
||||||
|
setDragOffset(next);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleTouchEnd = useCallback(() => {
|
||||||
|
dragStartYRef.current = null;
|
||||||
|
const finalOffset = dragOffsetRef.current;
|
||||||
|
dragOffsetRef.current = 0;
|
||||||
|
setDragOffset(0);
|
||||||
|
if (finalOffset > SWIPE_DISMISS_THRESHOLD_PX) onClose();
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="mobile-sheet-backdrop"
|
||||||
|
onClick={(e) => {
|
||||||
|
if (e.target === e.currentTarget) onClose();
|
||||||
|
}}
|
||||||
|
style={{ ['--keyboard-inset' as any]: `${keyboardInset}px` }}
|
||||||
|
>
|
||||||
|
{/* Deliberately NOT aria-modal: the tab bar stays reachable/operable
|
||||||
|
while a sheet is open (tapping another tab swaps sheets directly),
|
||||||
|
so the rest of the screen must not be marked inert to assistive
|
||||||
|
tech the way a true modal dialog would be. */}
|
||||||
|
<div
|
||||||
|
className="mobile-sheet"
|
||||||
|
role="dialog"
|
||||||
|
aria-label={title}
|
||||||
|
style={{
|
||||||
|
transform: dragOffset ? `translateY(${dragOffset}px)` : undefined,
|
||||||
|
transition: dragOffset ? 'none' : 'transform 0.2s ease',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="mobile-sheet-handle-row"
|
||||||
|
onTouchStart={handleTouchStart}
|
||||||
|
onTouchMove={handleTouchMove}
|
||||||
|
onTouchEnd={handleTouchEnd}
|
||||||
|
onTouchCancel={handleTouchEnd}
|
||||||
|
>
|
||||||
|
<span className="mobile-sheet-handle" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="mobile-sheet-header"
|
||||||
|
onTouchStart={handleTouchStart}
|
||||||
|
onTouchMove={handleTouchMove}
|
||||||
|
onTouchEnd={handleTouchEnd}
|
||||||
|
onTouchCancel={handleTouchEnd}
|
||||||
|
>
|
||||||
|
<span className="mobile-sheet-title">{title}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-sheet-close"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-label={`Close ${title}`}
|
||||||
|
>
|
||||||
|
<i className="fa fa-times" aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="mobile-sheet-body" ref={bodyRef}>{children}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
import { describe, test, expect, vi } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { MobilePanelBar } from './MobilePanelBar';
|
||||||
|
import { MobileChromeProvider } from '../../state/MobileChromeContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile-A2 (review item 5): the real BlocksPanel/PagesPanel/LayersPanel/
|
||||||
|
* AssetsPanel/GuidedStyles all pull in Craft.js's `useEditor` and other
|
||||||
|
* heavy dependencies not relevant here, so they're stubbed out -- this
|
||||||
|
* suite is only exercising MobilePanelBar's OWN wiring: tapping a tab opens
|
||||||
|
* that tab's sheet with only its panel rendered, tapping the active tab
|
||||||
|
* again closes it, and (mirroring MobileChromeContext.test.tsx) only one
|
||||||
|
* sheet's content is ever mounted at once.
|
||||||
|
*/
|
||||||
|
vi.mock('../left/BlocksPanel', () => ({ BlocksPanel: () => <div data-testid="panel-blocks" /> }));
|
||||||
|
vi.mock('../left/PagesPanel', () => ({ PagesPanel: () => <div data-testid="panel-pages" /> }));
|
||||||
|
vi.mock('../left/LayersPanel', () => ({ LayersPanel: () => <div data-testid="panel-layers" /> }));
|
||||||
|
vi.mock('../left/AssetsPanel', () => ({ AssetsPanel: () => <div data-testid="panel-assets" /> }));
|
||||||
|
vi.mock('../right/GuidedStyles', () => ({ GuidedStyles: () => <div data-testid="panel-styles" /> }));
|
||||||
|
|
||||||
|
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 tabButton(label: string): HTMLButtonElement {
|
||||||
|
const buttons = Array.from(container.querySelectorAll('.mobile-tab-btn')) as HTMLButtonElement[];
|
||||||
|
const btn = buttons.find((b) => b.textContent?.includes(label));
|
||||||
|
if (!btn) throw new Error(`No tab button found for "${label}"`);
|
||||||
|
return btn;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPanelIds(): string[] {
|
||||||
|
return Array.from(container.querySelectorAll('[data-testid^="panel-"]')).map(
|
||||||
|
(el) => (el as HTMLElement).dataset.testid!,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MobilePanelBar', () => {
|
||||||
|
test('no sheet is open initially', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
expect(container.querySelector('.mobile-sheet-backdrop')).toBeNull();
|
||||||
|
expect(openPanelIds()).toEqual([]);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tapping a tab opens exactly that tab\'s panel', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Blocks').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-blocks']);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('switching tabs replaces the open sheet -- only one panel mounted at a time', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Blocks').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-blocks']);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Styles').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-styles']);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Assets').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-assets']);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tapping the active tab again closes the sheet', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Pages').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-pages']);
|
||||||
|
expect(container.querySelector('.mobile-sheet-backdrop')).not.toBeNull();
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Pages').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual([]);
|
||||||
|
expect(container.querySelector('.mobile-sheet-backdrop')).toBeNull();
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('active tab button carries aria-pressed=true only for the open sheet', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Layers').click();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(tabButton('Layers').getAttribute('aria-pressed')).toBe('true');
|
||||||
|
expect(tabButton('Blocks').getAttribute('aria-pressed')).toBe('false');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { BottomSheet } from './BottomSheet';
|
||||||
|
import { BlocksPanel } from '../left/BlocksPanel';
|
||||||
|
import { PagesPanel } from '../left/PagesPanel';
|
||||||
|
import { LayersPanel } from '../left/LayersPanel';
|
||||||
|
import { AssetsPanel } from '../left/AssetsPanel';
|
||||||
|
import { GuidedStyles } from '../right/GuidedStyles';
|
||||||
|
import { useMobileChrome, MobileSheetTab } from '../../state/MobileChromeContext';
|
||||||
|
|
||||||
|
const TABS: { id: MobileSheetTab; label: string; icon: string }[] = [
|
||||||
|
{ id: 'blocks', label: 'Blocks', icon: 'fa-cube' },
|
||||||
|
{ id: 'pages', label: 'Pages', icon: 'fa-file-o' },
|
||||||
|
{ id: 'layers', label: 'Layers', icon: 'fa-sitemap' },
|
||||||
|
{ id: 'assets', label: 'Assets', icon: 'fa-image' },
|
||||||
|
{ id: 'styles', label: 'Styles', icon: 'fa-paint-brush' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile replacement for the desktop LeftPanel/RightPanel column layout
|
||||||
|
* (Phase A). A fixed bottom tab bar (Blocks/Pages/Layers/Assets/Styles)
|
||||||
|
* toggles a single `BottomSheet` at a time, hosting the SAME panel
|
||||||
|
* component the desktop side panels use -- unchanged, so behavior/state
|
||||||
|
* stays identical, only the chrome around it differs. Tapping the active
|
||||||
|
* tab again, tapping the backdrop, the sheet's close button, or Escape all
|
||||||
|
* close the open sheet.
|
||||||
|
*
|
||||||
|
* "Styles" hosts `GuidedStyles`, which already falls back to the
|
||||||
|
* site-design panel when nothing is selected and switches to the
|
||||||
|
* per-type style panel once something is -- this is the natural place to
|
||||||
|
* edit a tapped element's styling (Phase B deepens the tap-to-select flow;
|
||||||
|
* this component only wires up the sheet, per the Phase A brief).
|
||||||
|
*
|
||||||
|
* Sheet-open state itself lives in `MobileChromeContext` (Mobile-A2), not
|
||||||
|
* a private `useState`, so Phase B can open/close a sheet from elsewhere
|
||||||
|
* (e.g. a canvas selection toolbar). The toggle-to-close-on-repeat-tap
|
||||||
|
* behavior is local to this click handler -- `openSheet` always opens.
|
||||||
|
*/
|
||||||
|
export const MobilePanelBar: React.FC = () => {
|
||||||
|
const { activeSheet, openSheet, closeSheet } = useMobileChrome();
|
||||||
|
|
||||||
|
const handleTabClick = (tab: MobileSheetTab) => {
|
||||||
|
if (activeSheet === tab) closeSheet();
|
||||||
|
else openSheet(tab);
|
||||||
|
};
|
||||||
|
|
||||||
|
const activeLabel = TABS.find((t) => t.id === activeSheet)?.label ?? '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<BottomSheet open={activeSheet !== null} onClose={closeSheet} title={activeLabel}>
|
||||||
|
{activeSheet === 'blocks' && <BlocksPanel />}
|
||||||
|
{activeSheet === 'pages' && <PagesPanel />}
|
||||||
|
{activeSheet === 'layers' && <LayersPanel />}
|
||||||
|
{activeSheet === 'assets' && <AssetsPanel />}
|
||||||
|
{activeSheet === 'styles' && <GuidedStyles />}
|
||||||
|
</BottomSheet>
|
||||||
|
|
||||||
|
<nav className="mobile-tab-bar" aria-label="Editor panels">
|
||||||
|
{TABS.map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
type="button"
|
||||||
|
className={`mobile-tab-btn${activeSheet === tab.id ? ' active' : ''}`}
|
||||||
|
onClick={() => handleTabClick(tab.id)}
|
||||||
|
aria-pressed={activeSheet === tab.id}
|
||||||
|
>
|
||||||
|
<i className={`fa ${tab.icon}`} aria-hidden="true" />
|
||||||
|
<span>{tab.label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { useEditor } from '@craftjs/core';
|
||||||
|
import { useNodeActions } from '../../hooks/useNodeActions';
|
||||||
|
import { useMobileChrome } from '../../state/MobileChromeContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase B mobile selection toolbar -- the on-canvas action bar that makes a
|
||||||
|
* tap-selected node actually EDITABLE by touch (reorder/duplicate/delete/
|
||||||
|
* select-parent/edit-styles), mirroring the desktop right-click ContextMenu.
|
||||||
|
* Both share the exact same behavior via `useNodeActions` (item 1).
|
||||||
|
*
|
||||||
|
* Mounted ONCE (in `EditorShell`'s mobile branch), reading the current
|
||||||
|
* selection from `useEditor` directly -- NOT per-node -- and positioned
|
||||||
|
* bottom-fixed just above the tab bar (simplest, robust; a node-anchored
|
||||||
|
* floating toolbar would have to constantly reposition as the canvas
|
||||||
|
* scrolls, and risks being clipped at the viewport edge for a node near the
|
||||||
|
* top or bottom of a tall page). This is a deliberate design call: see the
|
||||||
|
* report for the alternative (floating over the node) that was passed over.
|
||||||
|
*
|
||||||
|
* Hidden whenever a bottom sheet is open (`activeSheet !== null`) -- the
|
||||||
|
* sheet supersedes it, and the two must never visually stack.
|
||||||
|
*
|
||||||
|
* Delete is a two-tap in-app confirm (tap once -> the button becomes
|
||||||
|
* "Confirm?" for a few seconds; tap again within that window commits the
|
||||||
|
* delete; selecting something else cancels it) rather than a native
|
||||||
|
* `confirm()`, matching the project's no-native-dialogs rule.
|
||||||
|
*/
|
||||||
|
const DELETE_CONFIRM_TIMEOUT_MS = 3000;
|
||||||
|
|
||||||
|
export const MobileSelectionToolbar: React.FC = () => {
|
||||||
|
const { activeSheet, openSheet } = useMobileChrome();
|
||||||
|
const { selectedId } = useEditor((state) => {
|
||||||
|
const selected = state.events.selected;
|
||||||
|
const id = selected && selected.size > 0 ? (Array.from(selected)[0] as string) : null;
|
||||||
|
return { selectedId: id && id !== 'ROOT' ? id : null };
|
||||||
|
});
|
||||||
|
// Collector-free -- an always-live reference (same pattern as
|
||||||
|
// GuidedStyles.tsx/BlocksPanel.tsx), used only for imperative DOM lookups
|
||||||
|
// below (scroll-into-view), never for anything that needs to react to
|
||||||
|
// store changes on its own.
|
||||||
|
const { query } = useEditor();
|
||||||
|
|
||||||
|
const nodeActions = useNodeActions(selectedId);
|
||||||
|
const [confirmingDelete, setConfirmingDelete] = useState(false);
|
||||||
|
const confirmTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
// `useNodeActions` computes canMoveUp/canMoveDown/canDelete synchronously
|
||||||
|
// from a live (never-cached) Craft.js query -- see that hook's doc comment
|
||||||
|
// for why it deliberately does NOT hold its own store subscription to force
|
||||||
|
// a refresh. Moving/duplicating/deleting via THIS toolbar changes the
|
||||||
|
// selected node's position/siblings WITHOUT changing `selectedId` itself
|
||||||
|
// (the node stays selected), so nothing else would otherwise trigger a
|
||||||
|
// re-render of this component to pick up the new boundary flags after,
|
||||||
|
// say, tapping "Move Up" until the node reaches the top. Bumping a plain
|
||||||
|
// local tick from these buttons' own click handlers -- an ordinary,
|
||||||
|
// locally-owned re-render -- covers exactly that, without the broader
|
||||||
|
// store-wide subscription that was found to trip React's "setState while
|
||||||
|
// rendering a different component" warning whenever some unrelated
|
||||||
|
// container mounts (see useNodeActions.ts).
|
||||||
|
const [, forceRefresh] = useState(0);
|
||||||
|
const bumpTick = useCallback(() => forceRefresh((n) => n + 1), []);
|
||||||
|
|
||||||
|
const clearConfirmTimeout = useCallback(() => {
|
||||||
|
if (confirmTimeoutRef.current) {
|
||||||
|
clearTimeout(confirmTimeoutRef.current);
|
||||||
|
confirmTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Reset the two-tap delete confirmation whenever the selection changes
|
||||||
|
// (including being cleared) so a stale "Confirm?" state never lingers onto
|
||||||
|
// a different node.
|
||||||
|
const prevSelectedRef = useRef(selectedId);
|
||||||
|
useEffect(() => {
|
||||||
|
if (prevSelectedRef.current !== selectedId) {
|
||||||
|
prevSelectedRef.current = selectedId;
|
||||||
|
clearConfirmTimeout();
|
||||||
|
setConfirmingDelete(false);
|
||||||
|
}
|
||||||
|
}, [selectedId, clearConfirmTimeout]);
|
||||||
|
|
||||||
|
useEffect(() => clearConfirmTimeout, [clearConfirmTimeout]);
|
||||||
|
|
||||||
|
// Fast-follow item 3: the Styles bottom sheet covers the bottom ~65dvh of
|
||||||
|
// the canvas, so a selected node sitting anywhere in that band goes
|
||||||
|
// invisible the instant the sheet opens -- live style edits then have no
|
||||||
|
// visible effect until the user closes the sheet to check. Whenever the
|
||||||
|
// sheet becomes 'styles' (however it got opened -- currently only this
|
||||||
|
// toolbar's own "Style" button, but this is keyed on the sheet/selection
|
||||||
|
// state rather than the button tap so it stays correct if another entry
|
||||||
|
// point is added later) scroll the selected node to the top of the
|
||||||
|
// canvas's scroll area, into the sliver of screen the sheet leaves clear.
|
||||||
|
useEffect(() => {
|
||||||
|
if (activeSheet !== 'styles' || !selectedId) return;
|
||||||
|
try {
|
||||||
|
query.node(selectedId).get()?.dom?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||||
|
} catch {
|
||||||
|
// Best-effort -- not fatal if the node/DOM isn't found.
|
||||||
|
}
|
||||||
|
}, [activeSheet, selectedId, query]);
|
||||||
|
|
||||||
|
const handleDeleteTap = useCallback(() => {
|
||||||
|
if (confirmingDelete) {
|
||||||
|
clearConfirmTimeout();
|
||||||
|
setConfirmingDelete(false);
|
||||||
|
nodeActions.deleteNode();
|
||||||
|
bumpTick();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setConfirmingDelete(true);
|
||||||
|
clearConfirmTimeout();
|
||||||
|
confirmTimeoutRef.current = setTimeout(() => setConfirmingDelete(false), DELETE_CONFIRM_TIMEOUT_MS);
|
||||||
|
}, [confirmingDelete, clearConfirmTimeout, nodeActions, bumpTick]);
|
||||||
|
|
||||||
|
const handleEditStyles = useCallback(() => {
|
||||||
|
openSheet('styles');
|
||||||
|
}, [openSheet]);
|
||||||
|
|
||||||
|
const handleMoveUp = useCallback(() => {
|
||||||
|
nodeActions.moveUp();
|
||||||
|
bumpTick();
|
||||||
|
}, [nodeActions, bumpTick]);
|
||||||
|
|
||||||
|
const handleMoveDown = useCallback(() => {
|
||||||
|
nodeActions.moveDown();
|
||||||
|
bumpTick();
|
||||||
|
}, [nodeActions, bumpTick]);
|
||||||
|
|
||||||
|
const handleDuplicate = useCallback(() => {
|
||||||
|
const newId = nodeActions.duplicate();
|
||||||
|
bumpTick();
|
||||||
|
if (!newId) return;
|
||||||
|
// Mirror BlocksPanel's tap-to-add pattern: the new node's real DOM
|
||||||
|
// element isn't attached yet the instant `duplicate()` returns (Craft.js
|
||||||
|
// mounts it asynchronously after this handler's synchronous state
|
||||||
|
// update), so defer two animation frames before reading `.dom` off the
|
||||||
|
// query, same as `handleTapToAdd` does.
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
try {
|
||||||
|
query.node(newId).get()?.dom?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
} catch {
|
||||||
|
// Best-effort scroll -- not fatal if the node/DOM isn't found.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, [nodeActions, bumpTick, query]);
|
||||||
|
|
||||||
|
if (!selectedId || activeSheet !== null) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mobile-selection-toolbar" role="toolbar" aria-label="Selected element actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={handleMoveUp}
|
||||||
|
disabled={!nodeActions.canMoveUp}
|
||||||
|
aria-label="Move up"
|
||||||
|
>
|
||||||
|
<i className="fa fa-arrow-up" aria-hidden="true" />
|
||||||
|
<span>Up</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={handleMoveDown}
|
||||||
|
disabled={!nodeActions.canMoveDown}
|
||||||
|
aria-label="Move down"
|
||||||
|
>
|
||||||
|
<i className="fa fa-arrow-down" aria-hidden="true" />
|
||||||
|
<span>Down</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={handleDuplicate}
|
||||||
|
aria-label="Duplicate"
|
||||||
|
>
|
||||||
|
<i className="fa fa-clone" aria-hidden="true" />
|
||||||
|
<span>Copy</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={nodeActions.selectParent}
|
||||||
|
disabled={!nodeActions.canSelectParent}
|
||||||
|
aria-label="Select parent"
|
||||||
|
>
|
||||||
|
<i className="fa fa-level-up" aria-hidden="true" />
|
||||||
|
<span>Parent</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={handleEditStyles}
|
||||||
|
aria-label="Edit styles"
|
||||||
|
>
|
||||||
|
<i className="fa fa-paint-brush" aria-hidden="true" />
|
||||||
|
<span>Style</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`mobile-selection-toolbar-btn danger${confirmingDelete ? ' confirming' : ''}`}
|
||||||
|
onClick={handleDeleteTap}
|
||||||
|
disabled={!nodeActions.canDelete}
|
||||||
|
aria-label={confirmingDelete ? 'Tap again to confirm delete' : 'Delete'}
|
||||||
|
>
|
||||||
|
<i className="fa fa-trash" aria-hidden="true" />
|
||||||
|
<span>{confirmingDelete ? 'Confirm?' : 'Delete'}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -10,6 +10,7 @@ export const ChatInput: React.FC<Props> = ({ disabled, placeholder, onSend }) =>
|
|||||||
<div style={{ display: 'flex', gap: 8, padding: '8px 0' }}>
|
<div style={{ display: 'flex', gap: 8, padding: '8px 0' }}>
|
||||||
<textarea value={v} onChange={(e) => setV(e.target.value)} onKeyDown={onKey} rows={2} disabled={disabled}
|
<textarea value={v} onChange={(e) => setV(e.target.value)} onKeyDown={onKey} rows={2} disabled={disabled}
|
||||||
placeholder={placeholder || 'Describe what you want...'}
|
placeholder={placeholder || 'Describe what you want...'}
|
||||||
|
className="sitesmith-textarea"
|
||||||
style={{
|
style={{
|
||||||
flex: 1, background: disabled ? '#1f1f24' : '#0f0f17', color: '#e5e7eb',
|
flex: 1, background: disabled ? '#1f1f24' : '#0f0f17', color: '#e5e7eb',
|
||||||
border: '1px solid #3f3f46', borderRadius: 6, padding: 10, fontSize: 14, resize: 'none',
|
border: '1px solid #3f3f46', borderRadius: 6, padding: 10, fontSize: 14, resize: 'none',
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
|
|||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
closeOnEscape={false}
|
closeOnEscape={false}
|
||||||
closeOnBackdropClick={false}
|
closeOnBackdropClick={false}
|
||||||
backdropStyle={{ backgroundColor: 'rgba(0,0,0,0.8)', zIndex: 9000 }}
|
backdropStyle={{ backgroundColor: 'rgba(0,0,0,0.8)' }}
|
||||||
backdropProps={{ role: 'dialog', 'aria-modal': true }}
|
backdropProps={{ role: 'dialog', 'aria-modal': true }}
|
||||||
>
|
>
|
||||||
<div style={panel}>
|
<div style={panel}>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
import { Modal } from '../../ui/Modal';
|
import { Modal } from '../../ui/Modal';
|
||||||
|
|
||||||
@@ -10,7 +11,15 @@ interface HeadCodeModalProps {
|
|||||||
export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) => {
|
export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) => {
|
||||||
const { design, updateDesign } = useSiteDesign();
|
const { design, updateDesign } = useSiteDesign();
|
||||||
|
|
||||||
return (
|
// Mobile-A2/Phase B: portaled to `document.body` -- same fix TemplateModal
|
||||||
|
// already got (see its comment). TopBar.tsx mounts this modal as a child
|
||||||
|
// of `.topbar`, which (as a flex item with its own z-index) forms its own
|
||||||
|
// stacking context; that trapped the modal's fixed-position backdrop
|
||||||
|
// underneath the mobile tab bar (z-index: var(--z-tabbar)) no matter how
|
||||||
|
// high the modal's own z-index was set. Portaling escapes that stacking
|
||||||
|
// context entirely so `--z-modal` (editor.css) is evaluated at the
|
||||||
|
// document root, same as TemplateModal/SitesmithModal.
|
||||||
|
return createPortal(
|
||||||
<Modal open={open} onClose={onClose}>
|
<Modal open={open} onClose={onClose}>
|
||||||
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
|
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -82,7 +91,8 @@ export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) =
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>,
|
||||||
|
document.body,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
|
import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { usePages } from '../../state/PageContext';
|
import { usePages } from '../../state/PageContext';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
@@ -8,9 +9,10 @@ import {
|
|||||||
TemplateComponent,
|
TemplateComponent,
|
||||||
TemplateCategory,
|
TemplateCategory,
|
||||||
} from '../../templates';
|
} from '../../templates';
|
||||||
import { componentResolver } from '../../components/resolver';
|
|
||||||
import { clickableProps } from '../../utils/a11y';
|
import { clickableProps } from '../../utils/a11y';
|
||||||
import { Modal } from '../../ui/Modal';
|
import { Modal } from '../../ui/Modal';
|
||||||
|
import { buildNodeTree } from '../../utils/craft-tree';
|
||||||
|
import { templateComponentToTreeNode } from '../../templates/apply-template';
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Types
|
// Types
|
||||||
@@ -77,28 +79,31 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
return allTemplates.filter((t) => t.category === activeTab);
|
return allTemplates.filter((t) => t.category === activeTab);
|
||||||
}, [activeTab]);
|
}, [activeTab]);
|
||||||
|
|
||||||
// Resolve a TemplateComponent type name to its React component
|
|
||||||
const resolverMap = componentResolver as Record<string, React.ComponentType<any>>;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add all components from a template definition onto the current (empty) canvas ROOT.
|
* Add all components from a template definition onto the current (empty) canvas ROOT.
|
||||||
* Uses Craft.js parseReactElement + addNodeTree which correctly builds valid node structures.
|
* Converts each `TemplateComponent` (the plain `{type, props, children?}`
|
||||||
|
* shape templates author) to a `SerializedTreeNode` and runs it through
|
||||||
|
* `buildNodeTree` (sanitize -> flatten -> materialize), the same tree pipeline
|
||||||
|
* already used for AI-generated content. This recurses into nested
|
||||||
|
* `children` (e.g. a header/footer `Container` wrapping `Logo`/`Menu`, or a
|
||||||
|
* page `Section` wrapping a `Heading`) AND correctly routes them through a
|
||||||
|
* component's SHELL_INNER linked canvas / linked columns where needed --
|
||||||
|
* see `templates/apply-template.ts` for the two bugs this fixes (dropped
|
||||||
|
* children, and a naive `parseReactElement` tree crashing `Section`/
|
||||||
|
* `BackgroundSection`/`FormContainer`/`ColumnLayout`).
|
||||||
*/
|
*/
|
||||||
const addTemplateComponents = useCallback(
|
const addTemplateComponents = useCallback(
|
||||||
(components: TemplateComponent[]) => {
|
(components: TemplateComponent[]) => {
|
||||||
for (const comp of components) {
|
for (const comp of components) {
|
||||||
const Component = resolverMap[comp.type];
|
try {
|
||||||
if (!Component) {
|
const tree = buildNodeTree(query, templateComponentToTreeNode(comp));
|
||||||
console.warn(`Template references unknown component type: ${comp.type}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const element = React.createElement(Component, comp.props);
|
|
||||||
const tree = query.parseReactElement(element).toNodeTree();
|
|
||||||
actions.addNodeTree(tree, 'ROOT');
|
actions.addNodeTree(tree, 'ROOT');
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to build template component tree for type "${comp.type}":`, e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[query, actions, resolverMap],
|
[query, actions],
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -234,7 +239,14 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
}
|
}
|
||||||
}, [confirmTemplate, applyDesign, pages, addPage, switchPage, deletePage, updateDesign, addTemplateComponents, clearCanvas, applyHeaderFooter, wait, onClose]);
|
}, [confirmTemplate, applyDesign, pages, addPage, switchPage, deletePage, updateDesign, addTemplateComponents, clearCanvas, applyHeaderFooter, wait, onClose]);
|
||||||
|
|
||||||
return (
|
// Mobile-A2: portaled to `document.body` -- TopBar.tsx mounts this modal
|
||||||
|
// as a child of `.topbar`, which (as a flex item with its own z-index)
|
||||||
|
// forms its own stacking context. That trapped the modal's fixed-position
|
||||||
|
// backdrop underneath the mobile tab bar (z-index: var(--z-tabbar)) no
|
||||||
|
// matter how high the modal's own z-index was set. Portaling escapes that
|
||||||
|
// stacking context entirely so `--z-modal` (see editor.css) is evaluated
|
||||||
|
// at the document root, same as SitesmithModal.
|
||||||
|
return createPortal(
|
||||||
<Modal open={open} onClose={handleModalClose}>
|
<Modal open={open} onClose={handleModalClose}>
|
||||||
<div style={modalStyle}>
|
<div style={modalStyle}>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -249,8 +261,10 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
|
className="template-modal-close-btn"
|
||||||
style={closeButtonStyle}
|
style={closeButtonStyle}
|
||||||
title="Close"
|
title="Close"
|
||||||
|
aria-label="Close"
|
||||||
onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)'; (e.currentTarget as HTMLElement).style.color = 'var(--color-text)'; }}
|
onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)'; (e.currentTarget as HTMLElement).style.color = 'var(--color-text)'; }}
|
||||||
onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.background = 'transparent'; (e.currentTarget as HTMLElement).style.color = '#71717a'; }}
|
onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.background = 'transparent'; (e.currentTarget as HTMLElement).style.color = '#71717a'; }}
|
||||||
>
|
>
|
||||||
@@ -258,11 +272,15 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filter Tabs */}
|
{/* Filter Tabs -- horizontally scrollable (tabBarStyle sets
|
||||||
<div style={tabBarStyle}>
|
overflowX: 'auto') so the row never wraps/overflows the modal at
|
||||||
|
narrow widths; template-modal-tab-btn below keeps each tab from
|
||||||
|
shrinking below a comfortable touch target on mobile. */}
|
||||||
|
<div className="template-modal-tabbar" style={tabBarStyle}>
|
||||||
{TABS.map((tab) => (
|
{TABS.map((tab) => (
|
||||||
<button
|
<button
|
||||||
key={tab.value}
|
key={tab.value}
|
||||||
|
className="template-modal-tab-btn"
|
||||||
onClick={() => setActiveTab(tab.value)}
|
onClick={() => setActiveTab(tab.value)}
|
||||||
style={{
|
style={{
|
||||||
...tabStyle,
|
...tabStyle,
|
||||||
@@ -371,7 +389,8 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>,
|
||||||
|
document.body,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,12 @@ import { useEditorConfig } from '../../state/EditorConfigContext';
|
|||||||
import { useWhpApi } from '../../hooks/useWhpApi';
|
import { useWhpApi } from '../../hooks/useWhpApi';
|
||||||
import { usePages } from '../../state/PageContext';
|
import { usePages } from '../../state/PageContext';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
|
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||||
|
import { useMobileChrome } from '../../state/MobileChromeContext';
|
||||||
import { DeviceMode } from '../../types';
|
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 { SitesmithButton } from '../sitesmith/SitesmithButton';
|
import { SitesmithButton } from '../sitesmith/SitesmithButton';
|
||||||
import { useSitesmithModal } from '../../state/SitesmithContext';
|
import { useSitesmithModal } from '../../state/SitesmithContext';
|
||||||
|
|
||||||
@@ -31,8 +34,11 @@ 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 [isDraft, setIsDraft] = useState(false);
|
const [isDraft, setIsDraft] = useState(false);
|
||||||
const [templateModalOpen, setTemplateModalOpen] = useState(false);
|
// Mobile-A2: lifted from private useState into MobileChromeContext so
|
||||||
const [headCodeModalOpen, setHeadCodeModalOpen] = useState(false);
|
// opening a mobile sheet can close these modals (item 3) -- behavior is
|
||||||
|
// otherwise identical for both the desktop and mobile branches below.
|
||||||
|
const { templateModalOpen, setTemplateModalOpen, headCodeModalOpen, setHeadCodeModalOpen, overflowOpen, setOverflowOpen } = useMobileChrome();
|
||||||
|
const isMobile = useIsMobile();
|
||||||
const { open: openSitesmith } = useSitesmithModal();
|
const { open: openSitesmith } = useSitesmithModal();
|
||||||
const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
const publishTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const publishTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
@@ -122,6 +128,156 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Extracted so both the desktop inline Preview button and the mobile
|
||||||
|
// overflow-menu "Preview" item can trigger the exact same flow.
|
||||||
|
const handlePreview = useCallback(() => {
|
||||||
|
try {
|
||||||
|
const serialized = query.serialize();
|
||||||
|
import('../../utils/html-export').then(({ exportToHtml, exportBodyHtml }) => {
|
||||||
|
// Get header HTML
|
||||||
|
let headerHtml = '';
|
||||||
|
try {
|
||||||
|
if (headerPage.craftState) {
|
||||||
|
headerHtml = exportBodyHtml(headerPage.craftState).html;
|
||||||
|
}
|
||||||
|
} catch (e) { console.warn('Header export failed:', e); }
|
||||||
|
|
||||||
|
// Get page body HTML
|
||||||
|
const bodyResult = exportBodyHtml(serialized);
|
||||||
|
const bodyHtml = bodyResult.html;
|
||||||
|
|
||||||
|
// Get footer HTML
|
||||||
|
let footerHtml = '';
|
||||||
|
try {
|
||||||
|
if (footerPage.craftState) {
|
||||||
|
footerHtml = exportBodyHtml(footerPage.craftState).html;
|
||||||
|
}
|
||||||
|
} catch (e) { console.warn('Footer export failed:', e); }
|
||||||
|
|
||||||
|
// Compose full page: header + body + footer
|
||||||
|
const composedBody = headerHtml + bodyHtml + footerHtml;
|
||||||
|
const result = exportToHtml(serialized, {
|
||||||
|
title: whpConfig?.siteName || 'Preview',
|
||||||
|
includeFonts: true,
|
||||||
|
headCode: design.headCode,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Replace the body in the full document with our composed version.
|
||||||
|
// Use a function replacer -- a plain string replacer treats
|
||||||
|
// `$&`/`$1`/`$$` sequences in user content as replacement
|
||||||
|
// patterns, silently corrupting the output.
|
||||||
|
let html = result.html;
|
||||||
|
const bodyMatch = html.match(/<body[^>]*>([\s\S]*)<\/body>/i);
|
||||||
|
if (bodyMatch) {
|
||||||
|
html = html.replace(bodyMatch[1], () => composedBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make proxy URLs absolute so they work from the blob: context
|
||||||
|
const origin = window.location.origin;
|
||||||
|
html = html.replace(/src="\/api\//g, `src="${origin}/api/`);
|
||||||
|
html = html.replace(/url\('\/api\//g, `url('${origin}/api/`);
|
||||||
|
const blob = new Blob([html], { type: 'text/html' });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
window.open(url, '_blank');
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Preview failed:', e);
|
||||||
|
}
|
||||||
|
}, [query, headerPage, footerPage, whpConfig, design]);
|
||||||
|
|
||||||
|
// Phase A: at ≤768px the topbar collapses to only the essentials --
|
||||||
|
// back arrow, Undo/Redo, Save (+Publish) -- with Templates, Sitesmith,
|
||||||
|
// Preview, Head Code, the guides toggle, and the device switcher moved
|
||||||
|
// into the "⋯" overflow menu. This keeps desktop's JSX/behavior below
|
||||||
|
// completely untouched.
|
||||||
|
if (isMobile) {
|
||||||
|
return (
|
||||||
|
<nav className="topbar topbar-mobile">
|
||||||
|
<div className="topbar-left">
|
||||||
|
{isWHP && (
|
||||||
|
<a
|
||||||
|
href={whpConfig!.backUrl}
|
||||||
|
className="topbar-btn icon-only back-btn"
|
||||||
|
aria-label="Back to Panel"
|
||||||
|
data-tooltip="Back"
|
||||||
|
>
|
||||||
|
<i className="fa fa-arrow-left" />
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="topbar-right">
|
||||||
|
<button
|
||||||
|
className="topbar-btn icon-only"
|
||||||
|
onClick={() => actions.history.undo()}
|
||||||
|
disabled={!canUndo}
|
||||||
|
aria-label="Undo"
|
||||||
|
data-tooltip="Undo"
|
||||||
|
>
|
||||||
|
<i className="fa fa-undo" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="topbar-btn icon-only"
|
||||||
|
onClick={() => actions.history.redo()}
|
||||||
|
disabled={!canRedo}
|
||||||
|
aria-label="Redo"
|
||||||
|
data-tooltip="Redo"
|
||||||
|
>
|
||||||
|
<i className="fa fa-repeat" />
|
||||||
|
</button>
|
||||||
|
<span className="topbar-divider" />
|
||||||
|
<button
|
||||||
|
className="topbar-btn icon-only primary"
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={saveStatus === 'saving'}
|
||||||
|
aria-label="Save Draft"
|
||||||
|
data-tooltip="Save"
|
||||||
|
>
|
||||||
|
<i className={`fa ${saveStatus === 'saving' ? 'fa-spinner fa-spin' : 'fa-save'}`} />
|
||||||
|
</button>
|
||||||
|
{isWHP && (
|
||||||
|
<button
|
||||||
|
className="topbar-btn icon-only publish"
|
||||||
|
onClick={handlePublish}
|
||||||
|
disabled={publishStatus === 'publishing' || saveStatus === 'saving'}
|
||||||
|
aria-label="Publish to live site"
|
||||||
|
data-tooltip="Publish"
|
||||||
|
>
|
||||||
|
<i className={`fa ${publishStatus === 'publishing' ? 'fa-spinner fa-spin' : 'fa-globe'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`topbar-btn icon-only overflow-toggle${overflowOpen ? ' active' : ''}`}
|
||||||
|
onClick={() => setOverflowOpen(!overflowOpen)}
|
||||||
|
aria-label="More options"
|
||||||
|
aria-expanded={overflowOpen}
|
||||||
|
aria-haspopup="menu"
|
||||||
|
data-tooltip="More"
|
||||||
|
>
|
||||||
|
<i className="fa fa-ellipsis-h" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<TopBarOverflowMenu
|
||||||
|
open={overflowOpen}
|
||||||
|
onClose={() => setOverflowOpen(false)}
|
||||||
|
device={device}
|
||||||
|
onDeviceChange={onDeviceChange}
|
||||||
|
showGuides={showGuides}
|
||||||
|
onToggleGuides={onToggleGuides}
|
||||||
|
onOpenTemplates={() => setTemplateModalOpen(true)}
|
||||||
|
onOpenHeadCode={() => setHeadCodeModalOpen(true)}
|
||||||
|
onPreview={handlePreview}
|
||||||
|
sitesmithNode={<SitesmithButton onClick={() => openSitesmith()} />}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<TemplateModal open={templateModalOpen} onClose={() => setTemplateModalOpen(false)} />
|
||||||
|
<HeadCodeModal open={headCodeModalOpen} onClose={() => setHeadCodeModalOpen(false)} />
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<nav className="topbar">
|
<nav className="topbar">
|
||||||
<div className="topbar-left">
|
<div className="topbar-left">
|
||||||
@@ -182,60 +338,7 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
|||||||
>
|
>
|
||||||
<i className="fa fa-code" />
|
<i className="fa fa-code" />
|
||||||
</button>
|
</button>
|
||||||
<button className="topbar-btn icon-only" aria-label="Preview" data-tooltip="Preview" onClick={() => {
|
<button className="topbar-btn icon-only" aria-label="Preview" data-tooltip="Preview" onClick={handlePreview}>
|
||||||
try {
|
|
||||||
const serialized = query.serialize();
|
|
||||||
import('../../utils/html-export').then(({ exportToHtml, exportBodyHtml }) => {
|
|
||||||
// Get header HTML
|
|
||||||
let headerHtml = '';
|
|
||||||
try {
|
|
||||||
if (headerPage.craftState) {
|
|
||||||
headerHtml = exportBodyHtml(headerPage.craftState).html;
|
|
||||||
}
|
|
||||||
} catch (e) { console.warn('Header export failed:', e); }
|
|
||||||
|
|
||||||
// Get page body HTML
|
|
||||||
const bodyResult = exportBodyHtml(serialized);
|
|
||||||
const bodyHtml = bodyResult.html;
|
|
||||||
|
|
||||||
// Get footer HTML
|
|
||||||
let footerHtml = '';
|
|
||||||
try {
|
|
||||||
if (footerPage.craftState) {
|
|
||||||
footerHtml = exportBodyHtml(footerPage.craftState).html;
|
|
||||||
}
|
|
||||||
} catch (e) { console.warn('Footer export failed:', e); }
|
|
||||||
|
|
||||||
// Compose full page: header + body + footer
|
|
||||||
const composedBody = headerHtml + bodyHtml + footerHtml;
|
|
||||||
const result = exportToHtml(serialized, {
|
|
||||||
title: whpConfig?.siteName || 'Preview',
|
|
||||||
includeFonts: true,
|
|
||||||
headCode: design.headCode,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Replace the body in the full document with our composed version.
|
|
||||||
// Use a function replacer -- a plain string replacer treats
|
|
||||||
// `$&`/`$1`/`$$` sequences in user content as replacement
|
|
||||||
// patterns, silently corrupting the output.
|
|
||||||
let html = result.html;
|
|
||||||
const bodyMatch = html.match(/<body[^>]*>([\s\S]*)<\/body>/i);
|
|
||||||
if (bodyMatch) {
|
|
||||||
html = html.replace(bodyMatch[1], () => composedBody);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make proxy URLs absolute so they work from the blob: context
|
|
||||||
const origin = window.location.origin;
|
|
||||||
html = html.replace(/src="\/api\//g, `src="${origin}/api/`);
|
|
||||||
html = html.replace(/url\('\/api\//g, `url('${origin}/api/`);
|
|
||||||
const blob = new Blob([html], { type: 'text/html' });
|
|
||||||
const url = URL.createObjectURL(blob);
|
|
||||||
window.open(url, '_blank');
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Preview failed:', e);
|
|
||||||
}
|
|
||||||
}}>
|
|
||||||
<i className="fa fa-eye" />
|
<i className="fa fa-eye" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import React, { useEffect, useRef } from 'react';
|
||||||
|
import { DeviceMode } from '../../types';
|
||||||
|
|
||||||
|
export interface TopBarOverflowMenuProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
device: DeviceMode;
|
||||||
|
onDeviceChange: (device: DeviceMode) => void;
|
||||||
|
showGuides: boolean;
|
||||||
|
onToggleGuides: () => void;
|
||||||
|
onOpenTemplates: () => void;
|
||||||
|
onOpenHeadCode: () => void;
|
||||||
|
onPreview: () => void;
|
||||||
|
/** Rendered `<SitesmithButton onClick={...} />` -- passed in rather than
|
||||||
|
* re-implemented here so the mobile menu reuses the exact same
|
||||||
|
* lock/cap-aware button the desktop topbar shows. */
|
||||||
|
sitesmithNode: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile topbar "⋯" overflow menu (Phase A). At ≤768px, TopBar collapses to
|
||||||
|
* just the back arrow, Undo/Redo, Save/Publish, and this menu -- everything
|
||||||
|
* else that's inline on desktop (Templates, Sitesmith, Preview, Head Code,
|
||||||
|
* the guides toggle, and the device-width switcher) moves in here so the
|
||||||
|
* collapsed bar never overlaps or pushes controls off-screen.
|
||||||
|
*/
|
||||||
|
export const TopBarOverflowMenu: React.FC<TopBarOverflowMenuProps> = ({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
device,
|
||||||
|
onDeviceChange,
|
||||||
|
showGuides,
|
||||||
|
onToggleGuides,
|
||||||
|
onOpenTemplates,
|
||||||
|
onOpenHeadCode,
|
||||||
|
onPreview,
|
||||||
|
sitesmithNode,
|
||||||
|
}) => {
|
||||||
|
const menuRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const handleClick = (e: MouseEvent) => {
|
||||||
|
if (menuRef.current && !menuRef.current.contains(e.target as Node)) onClose();
|
||||||
|
};
|
||||||
|
const handleEsc = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape') onClose();
|
||||||
|
};
|
||||||
|
document.addEventListener('mousedown', handleClick);
|
||||||
|
document.addEventListener('keydown', handleEsc);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousedown', handleClick);
|
||||||
|
document.removeEventListener('keydown', handleEsc);
|
||||||
|
};
|
||||||
|
}, [open, onClose]);
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
const runAndClose = (fn: () => void) => () => {
|
||||||
|
fn();
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={menuRef} className="topbar-overflow-menu" role="menu">
|
||||||
|
<div className="topbar-overflow-section">
|
||||||
|
<span className="topbar-overflow-label">Preview width</span>
|
||||||
|
<div className="device-switcher">
|
||||||
|
{(['desktop', 'tablet', 'mobile'] as DeviceMode[]).map((d) => (
|
||||||
|
<button
|
||||||
|
key={d}
|
||||||
|
type="button"
|
||||||
|
className={`device-btn ${device === d ? 'active' : ''}`}
|
||||||
|
onClick={() => onDeviceChange(d)}
|
||||||
|
title={d.charAt(0).toUpperCase() + d.slice(1)}
|
||||||
|
aria-label={d.charAt(0).toUpperCase() + d.slice(1)}
|
||||||
|
aria-pressed={device === d}
|
||||||
|
>
|
||||||
|
<i className={`fa ${d === 'desktop' ? 'fa-desktop' : d === 'tablet' ? 'fa-tablet' : 'fa-mobile'}`} />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onOpenTemplates)}>
|
||||||
|
<i className="fa fa-th-large" aria-hidden="true" /> Templates
|
||||||
|
</button>
|
||||||
|
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onPreview)}>
|
||||||
|
<i className="fa fa-eye" aria-hidden="true" /> Preview
|
||||||
|
</button>
|
||||||
|
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onOpenHeadCode)}>
|
||||||
|
<i className="fa fa-code" aria-hidden="true" /> Head Code
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`topbar-overflow-item${showGuides ? ' active' : ''}`}
|
||||||
|
role="menuitem"
|
||||||
|
onClick={runAndClose(onToggleGuides)}
|
||||||
|
aria-pressed={showGuides}
|
||||||
|
>
|
||||||
|
<i className={`fa ${showGuides ? 'fa-th' : 'fa-th-large'}`} aria-hidden="true" />
|
||||||
|
{' '}{showGuides ? 'Hide Guides' : 'Show Guides'}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="topbar-overflow-sitesmith" onClick={onClose}>
|
||||||
|
{sitesmithNode}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { Editor, useEditor } from '@craftjs/core';
|
||||||
|
import { componentResolver } from '../../components/resolver';
|
||||||
|
import { allTemplates } from '../../templates';
|
||||||
|
import { buildNodeTree } from '../../utils/craft-tree';
|
||||||
|
import { templateComponentToTreeNode } from '../../templates/apply-template';
|
||||||
|
import { exportBodyHtml } from '../../utils/html-export';
|
||||||
|
import { DEFAULT_HEADER_STATE } from '../../state/PageContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression test for: loading a template makes the header/footer ZONE
|
||||||
|
* PREVIEW (`ZonePreview` in `editor/Canvas.tsx`, which calls
|
||||||
|
* `exportBodyHtml(craftState)`) render as an empty strip -- no nav links, no
|
||||||
|
* logo, no footer text -- and (a second bug found while fixing the first)
|
||||||
|
* makes a template page's `Section`-wrapped content crash the live editor
|
||||||
|
* entirely.
|
||||||
|
*
|
||||||
|
* This drives the EXACT same path `TemplateModal.tsx`'s `applyZone` /
|
||||||
|
* `addTemplateComponents` uses to load a template's header/footer/page
|
||||||
|
* content onto the live Craft.js canvas (`buildNodeTree` +
|
||||||
|
* `actions.addNodeTree(tree, 'ROOT')`), then serializes it
|
||||||
|
* (`query.serialize()`, exactly what `PageContext`'s `switchPage` /
|
||||||
|
* `saveCurrentState` do right after `TemplateModal` finishes applying a
|
||||||
|
* zone/page) and feeds the result through `exportBodyHtml` -- the same
|
||||||
|
* function `ZonePreview` calls, and the same function `handlePublish` uses
|
||||||
|
* to compose the published header/footer HTML. So this also covers whether
|
||||||
|
* published output is affected (it was).
|
||||||
|
*/
|
||||||
|
let api: any;
|
||||||
|
function Harness() {
|
||||||
|
const { actions, query } = useEditor();
|
||||||
|
api = { actions, query };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mount() {
|
||||||
|
const container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
let root!: Root;
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(
|
||||||
|
<Editor resolver={componentResolver}>
|
||||||
|
<Harness />
|
||||||
|
</Editor>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
container,
|
||||||
|
unmount: () => {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mirrors TemplateModal.tsx's addTemplateComponents(). */
|
||||||
|
function addTemplateComponents(components: any[]) {
|
||||||
|
for (const comp of components) {
|
||||||
|
const tree = buildNodeTree(api.query, templateComponentToTreeNode(comp));
|
||||||
|
api.actions.addNodeTree(tree, 'ROOT');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY_HEADER_ROOT =
|
||||||
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{},"tag":"header"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
||||||
|
|
||||||
|
const EMPTY_CANVAS_ROOT =
|
||||||
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{},"tag":"div"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
||||||
|
|
||||||
|
describe('template header/footer zone export (loading a template)', () => {
|
||||||
|
test('sanity check: the DEFAULT header (fresh project, no template) exports its content', () => {
|
||||||
|
const { html } = exportBodyHtml(DEFAULT_HEADER_STATE);
|
||||||
|
expect(html).toContain('MySite');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a template header (SaaS Landing) exports its real nav/logo content -- not an empty strip', () => {
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing');
|
||||||
|
expect(tpl).toBeDefined();
|
||||||
|
expect(tpl!.header.components.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const { unmount } = mount();
|
||||||
|
act(() => {
|
||||||
|
api.actions.deserialize(EMPTY_HEADER_ROOT);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
addTemplateComponents(tpl!.header.components);
|
||||||
|
});
|
||||||
|
|
||||||
|
const serialized = api.query.serialize();
|
||||||
|
const { html } = exportBodyHtml(serialized);
|
||||||
|
|
||||||
|
// The template's logo text and a real nav link -- if these are missing,
|
||||||
|
// the header rendered as an empty strip (the reported bug).
|
||||||
|
expect(html).toContain('FlowStack');
|
||||||
|
expect(html).toContain('Features');
|
||||||
|
expect(html).toContain('Start Free');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a template footer (SaaS Landing) exports its real copyright/tagline content -- not an empty strip', () => {
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing');
|
||||||
|
expect(tpl).toBeDefined();
|
||||||
|
expect(tpl!.footer.components.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const { unmount } = mount();
|
||||||
|
act(() => {
|
||||||
|
api.actions.deserialize(
|
||||||
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{},"tag":"footer"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
addTemplateComponents(tpl!.footer.components);
|
||||||
|
});
|
||||||
|
|
||||||
|
const serialized = api.query.serialize();
|
||||||
|
const { html } = exportBodyHtml(serialized);
|
||||||
|
|
||||||
|
expect(html).toContain('FlowStack, Inc.');
|
||||||
|
expect(html).toContain('Ship products faster');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a template page Section with nested children (SaaS Landing Home) builds + exports without crashing', () => {
|
||||||
|
// Regression for the SECOND bug surfaced while fixing the first: naively
|
||||||
|
// rebuilding nested children via React.createElement + parseReactElement
|
||||||
|
// crashes any component with an internal SHELL_INNER linked canvas
|
||||||
|
// (Section/BackgroundSection/FormContainer) or linked columns
|
||||||
|
// (ColumnLayout). The SaaS Landing home page's second component is a
|
||||||
|
// `Section` wrapping a `Heading` ("Trusted by 10,000+ development
|
||||||
|
// teams...") -- exactly this shape.
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing');
|
||||||
|
const homePage = tpl!.pages[0];
|
||||||
|
const sectionComp = homePage.content.components.find((c) => c.type === 'Section');
|
||||||
|
expect(sectionComp).toBeDefined();
|
||||||
|
expect(sectionComp!.children?.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const { unmount } = mount();
|
||||||
|
act(() => {
|
||||||
|
api.actions.deserialize(EMPTY_CANVAS_ROOT);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
act(() => {
|
||||||
|
addTemplateComponents([sectionComp!]);
|
||||||
|
});
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
const serialized = api.query.serialize();
|
||||||
|
const { html } = exportBodyHtml(serialized);
|
||||||
|
expect(html).toContain('Trusted by 10,000+ development teams');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { MobileChromeProvider, useMobileChrome, MobileSheetTab } from './MobileChromeContext';
|
||||||
|
import { SitesmithProvider, useSitesmithModal } from './SitesmithContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile-A2 (review item 5): covers the two invariants item 3 depends on --
|
||||||
|
* (1) only one sheet is ever open ("tab-bar-always-wins", Phase A's existing
|
||||||
|
* behavior, now backed by the shared context instead of a private
|
||||||
|
* useState), and (2) opening a sheet closes any open full-screen modal
|
||||||
|
* (Templates / Head Code / Sitesmith), so a sheet is never shown stacked
|
||||||
|
* underneath one.
|
||||||
|
*
|
||||||
|
* DOM-harness pattern mirrors PageContext.pure-updaters.test.tsx: bare
|
||||||
|
* createRoot + act, a Consumer component that stashes the hook result on an
|
||||||
|
* outer variable so assertions can run outside of render.
|
||||||
|
*/
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
let chrome: ReturnType<typeof useMobileChrome> | null = null;
|
||||||
|
let sitesmith: ReturnType<typeof useSitesmithModal> | null = null;
|
||||||
|
|
||||||
|
const Consumer: React.FC = () => {
|
||||||
|
chrome = useMobileChrome();
|
||||||
|
sitesmith = useSitesmithModal();
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function renderProviders() {
|
||||||
|
render(
|
||||||
|
<SitesmithProvider>
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<Consumer />
|
||||||
|
</MobileChromeProvider>
|
||||||
|
</SitesmithProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MobileChromeContext', () => {
|
||||||
|
test('only one sheet is ever open at a time', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('blocks'));
|
||||||
|
expect(chrome!.activeSheet).toBe('blocks');
|
||||||
|
|
||||||
|
// Opening a different sheet replaces the previous one -- never both.
|
||||||
|
act(() => chrome!.openSheet('styles'));
|
||||||
|
expect(chrome!.activeSheet).toBe('styles');
|
||||||
|
|
||||||
|
act(() => chrome!.closeSheet());
|
||||||
|
expect(chrome!.activeSheet).toBeNull();
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('openSheet is idempotent-safe: opening the same tab twice stays open (caller owns toggle-to-close)', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('pages'));
|
||||||
|
expect(chrome!.activeSheet).toBe('pages');
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('pages'));
|
||||||
|
expect(chrome!.activeSheet).toBe('pages');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('openSheet closes an open Templates modal', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.setTemplateModalOpen(true));
|
||||||
|
expect(chrome!.templateModalOpen).toBe(true);
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('blocks'));
|
||||||
|
expect(chrome!.templateModalOpen).toBe(false);
|
||||||
|
expect(chrome!.activeSheet).toBe('blocks');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('openSheet closes an open Head Code modal', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.setHeadCodeModalOpen(true));
|
||||||
|
expect(chrome!.headCodeModalOpen).toBe(true);
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('assets'));
|
||||||
|
expect(chrome!.headCodeModalOpen).toBe(false);
|
||||||
|
expect(chrome!.activeSheet).toBe('assets');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('openSheet closes an open Sitesmith modal', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => sitesmith!.open());
|
||||||
|
expect(sitesmith!.isOpen).toBe(true);
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('layers'));
|
||||||
|
|
||||||
|
// sitesmith is a stale snapshot from before the re-render the `act`
|
||||||
|
// above triggered; re-read via the live ref after settling.
|
||||||
|
expect(sitesmith!.isOpen).toBe(false);
|
||||||
|
expect(chrome!.activeSheet).toBe('layers');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('closeSheet does not disturb modal state', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('styles'));
|
||||||
|
act(() => chrome!.closeSheet());
|
||||||
|
|
||||||
|
expect(chrome!.activeSheet).toBeNull();
|
||||||
|
expect(chrome!.templateModalOpen).toBe(false);
|
||||||
|
expect(chrome!.headCodeModalOpen).toBe(false);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sheet tabs are exactly the five mobile panels', () => {
|
||||||
|
const tabs: MobileSheetTab[] = ['blocks', 'pages', 'layers', 'assets', 'styles'];
|
||||||
|
renderProviders();
|
||||||
|
tabs.forEach((tab) => {
|
||||||
|
act(() => chrome!.openSheet(tab));
|
||||||
|
expect(chrome!.activeSheet).toBe(tab);
|
||||||
|
});
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
|
||||||
|
import { useSitesmithModal } from './SitesmithContext';
|
||||||
|
|
||||||
|
/** Mobile bottom-sheet tabs (Phase A: Blocks/Pages/Layers/Assets/Styles).
|
||||||
|
* Exported so Phase B can open a specific sheet from outside
|
||||||
|
* `MobilePanelBar` -- e.g. the selection toolbar's "Edit styles" action
|
||||||
|
* opening 'styles', or tap-to-add closing 'blocks' after inserting a
|
||||||
|
* block on the canvas. */
|
||||||
|
export type MobileSheetTab = 'blocks' | 'pages' | 'layers' | 'assets' | 'styles';
|
||||||
|
|
||||||
|
interface MobileChromeContextValue {
|
||||||
|
/** Which bottom sheet (if any) is open. Only one at a time -- this is a
|
||||||
|
* single value by construction, not a set, so "one sheet open" is an
|
||||||
|
* invariant of the type, not something callers have to maintain. */
|
||||||
|
activeSheet: MobileSheetTab | null;
|
||||||
|
/** Opens `tab`'s sheet (replacing whatever sheet, if any, was open).
|
||||||
|
* Per item 3 (no accidental overlay stacking), this also closes any
|
||||||
|
* open full-screen modal -- Templates, Head Code, Sitesmith -- so a
|
||||||
|
* sheet is never shown stacked underneath one. Toggle-to-close is the
|
||||||
|
* CALLER's job (see MobilePanelBar's tab click handler): this function
|
||||||
|
* always opens, so Phase B can call it unconditionally. */
|
||||||
|
openSheet: (tab: MobileSheetTab) => void;
|
||||||
|
/** Closes the open sheet, if any. No-op otherwise. */
|
||||||
|
closeSheet: () => void;
|
||||||
|
|
||||||
|
/** Mobile topbar "..." overflow menu open state -- lifted here too
|
||||||
|
* ("+ the overflow-menu open state if convenient" per the brief) so
|
||||||
|
* Phase B can close it alongside sheets/modals from one place. */
|
||||||
|
overflowOpen: boolean;
|
||||||
|
setOverflowOpen: (open: boolean) => void;
|
||||||
|
|
||||||
|
/** Templates / Head Code modal open state, lifted out of TopBar so
|
||||||
|
* `openSheet` can close them directly (see above). Behavior is
|
||||||
|
* otherwise identical to the private useState these replaced. */
|
||||||
|
templateModalOpen: boolean;
|
||||||
|
setTemplateModalOpen: (open: boolean) => void;
|
||||||
|
|
||||||
|
headCodeModalOpen: boolean;
|
||||||
|
setHeadCodeModalOpen: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const noop = () => {};
|
||||||
|
|
||||||
|
/** Default value mirrors the other state contexts in this codebase
|
||||||
|
* (EditorConfigContext, PageContext, SiteDesignContext): a harmless no-op
|
||||||
|
* stub rather than throwing, so a consumer rendered outside the provider
|
||||||
|
* (e.g. in a narrower test) degrades quietly instead of crashing. */
|
||||||
|
const MobileChromeContext = createContext<MobileChromeContextValue>({
|
||||||
|
activeSheet: null,
|
||||||
|
openSheet: noop,
|
||||||
|
closeSheet: noop,
|
||||||
|
overflowOpen: false,
|
||||||
|
setOverflowOpen: noop,
|
||||||
|
templateModalOpen: false,
|
||||||
|
setTemplateModalOpen: noop,
|
||||||
|
headCodeModalOpen: false,
|
||||||
|
setHeadCodeModalOpen: noop,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const useMobileChrome = () => useContext(MobileChromeContext);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared mobile editor-chrome state (Phase A hardening / Phase B prep).
|
||||||
|
* Previously `activeTab`/sheet-open state lived as a private `useState`
|
||||||
|
* inside `MobilePanelBar`, which meant only a tap on the tab bar itself
|
||||||
|
* could open or close a sheet. Phase B needs to drive this from elsewhere
|
||||||
|
* (a canvas selection toolbar, tap-to-add, etc.), so it's lifted into this
|
||||||
|
* context, provided once in `EditorShell.tsx` around the whole mobile+
|
||||||
|
* desktop tree (harmless on desktop -- nothing there consumes it except
|
||||||
|
* `TopBar`'s Templates/Head Code modal state, which behaves identically to
|
||||||
|
* the private `useState` it replaced).
|
||||||
|
*/
|
||||||
|
export const MobileChromeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||||
|
const [activeSheet, setActiveSheet] = useState<MobileSheetTab | null>(null);
|
||||||
|
const [overflowOpen, setOverflowOpen] = useState(false);
|
||||||
|
const [templateModalOpen, setTemplateModalOpen] = useState(false);
|
||||||
|
const [headCodeModalOpen, setHeadCodeModalOpen] = useState(false);
|
||||||
|
const { close: closeSitesmith } = useSitesmithModal();
|
||||||
|
|
||||||
|
const openSheet = useCallback((tab: MobileSheetTab) => {
|
||||||
|
setActiveSheet(tab);
|
||||||
|
// Item 3: a sheet and a full-screen modal must never stack -- opening
|
||||||
|
// a sheet always wins over whatever modal was open.
|
||||||
|
setTemplateModalOpen(false);
|
||||||
|
setHeadCodeModalOpen(false);
|
||||||
|
closeSitesmith();
|
||||||
|
}, [closeSitesmith]);
|
||||||
|
|
||||||
|
const closeSheet = useCallback(() => setActiveSheet(null), []);
|
||||||
|
|
||||||
|
const value = useMemo<MobileChromeContextValue>(() => ({
|
||||||
|
activeSheet,
|
||||||
|
openSheet,
|
||||||
|
closeSheet,
|
||||||
|
overflowOpen,
|
||||||
|
setOverflowOpen,
|
||||||
|
templateModalOpen,
|
||||||
|
setTemplateModalOpen,
|
||||||
|
headCodeModalOpen,
|
||||||
|
setHeadCodeModalOpen,
|
||||||
|
}), [activeSheet, openSheet, closeSheet, overflowOpen, templateModalOpen, headCodeModalOpen]);
|
||||||
|
|
||||||
|
return <MobileChromeContext.Provider value={value}>{children}</MobileChromeContext.Provider>;
|
||||||
|
};
|
||||||
+500
-3
@@ -31,6 +31,32 @@
|
|||||||
--radius-lg: 8px;
|
--radius-lg: 8px;
|
||||||
--transition-fast: 0.15s ease;
|
--transition-fast: 0.15s ease;
|
||||||
--transition-normal: 0.25s ease;
|
--transition-normal: 0.25s ease;
|
||||||
|
/* Phase A (mobile): fixed bottom tab bar height, used to size
|
||||||
|
.editor-container and the safe-area padding math below. */
|
||||||
|
--mobile-tabbar-height: 58px;
|
||||||
|
/* Phase B fast-follow item 4: rendered height of `.mobile-selection-toolbar`
|
||||||
|
(44px min-height content + 4px top/bottom padding + 1px border) -- used
|
||||||
|
to pad the canvas scroll area clear of it while it's visible, see
|
||||||
|
`.editor-canvas.has-mobile-selection-toolbar` below. */
|
||||||
|
--mobile-selection-toolbar-height: 53px;
|
||||||
|
|
||||||
|
/* Mobile-A2: explicit overlay layer scale (was ad-hoc numbers scattered
|
||||||
|
across the mobile block + Modal.tsx, causing accidental stacking --
|
||||||
|
e.g. the Templates modal getting trapped under the tab bar inside
|
||||||
|
.topbar's own stacking context). Higher = closer to the user.
|
||||||
|
--z-selection-toolbar is reserved for Phase B's selection toolbar. */
|
||||||
|
--z-sheet-backdrop: 400;
|
||||||
|
--z-tabbar: 500;
|
||||||
|
--z-selection-toolbar: 600;
|
||||||
|
--z-modal: 5000;
|
||||||
|
--z-overflow: 10000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------------
|
||||||
|
Modals (shared by Modal.tsx -- TemplateModal, HeadCodeModal, SitesmithModal)
|
||||||
|
-------------------------------------------------------------------------- */
|
||||||
|
.modal-backdrop {
|
||||||
|
z-index: var(--z-modal);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------------------
|
/* --------------------------------------------------------------------------
|
||||||
@@ -1377,13 +1403,484 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
|
/* ------------------------------------------------------------------------
|
||||||
|
Phase A -- Mobile Editor Chrome
|
||||||
|
Gated entirely behind this breakpoint; desktop styles above are
|
||||||
|
untouched. See useIsMobile() (same 768px breakpoint) for the React-side
|
||||||
|
equivalent that swaps LeftPanel/RightPanel for MobilePanelBar, and
|
||||||
|
collapses TopBar.
|
||||||
|
------------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/* Side panels are not rendered on mobile (EditorShell swaps them for the
|
||||||
|
bottom tab bar) -- kept as a defensive fallback in case either is ever
|
||||||
|
mounted at this width. */
|
||||||
.panel-left,
|
.panel-left,
|
||||||
.panel-right {
|
.panel-right {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.topbar-btn span,
|
/* --------------------------------------------------------------------
|
||||||
.topbar-domain {
|
Viewport sizing -- dynamic viewport height accounts for mobile
|
||||||
display: none;
|
browsers' collapsing URL bar; the unconditional 100vh set earlier in
|
||||||
|
this file is the fallback for browsers without dvh support.
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.editor-app {
|
||||||
|
height: 100vh;
|
||||||
|
height: 100dvh;
|
||||||
|
padding-top: env(safe-area-inset-top, 0px);
|
||||||
|
padding-left: env(safe-area-inset-left, 0px);
|
||||||
|
padding-right: env(safe-area-inset-right, 0px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-container {
|
||||||
|
height: calc(100vh - var(--topbar-height) - var(--mobile-tabbar-height) - env(safe-area-inset-bottom, 0px));
|
||||||
|
height: calc(100dvh - var(--topbar-height) - var(--mobile-tabbar-height) - env(safe-area-inset-bottom, 0px));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Full-width canvas, safe-area-aware bottom padding so content never
|
||||||
|
sits flush against the fixed bottom tab bar. */
|
||||||
|
.editor-canvas {
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------
|
||||||
|
Topbar collapse (TopBar.tsx renders a distinct `.topbar-mobile` markup
|
||||||
|
branch -- this is purely the styling for it)
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.topbar-mobile {
|
||||||
|
padding: 0 8px;
|
||||||
|
padding-left: calc(8px + env(safe-area-inset-left, 0px));
|
||||||
|
padding-right: calc(8px + env(safe-area-inset-right, 0px));
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-mobile .topbar-left {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-mobile .topbar-right {
|
||||||
|
flex: 1;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-mobile .topbar-btn.icon-only {
|
||||||
|
width: 44px;
|
||||||
|
height: 44px;
|
||||||
|
padding: 0;
|
||||||
|
justify-content: center;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-mobile .topbar-divider {
|
||||||
|
margin: 0 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-btn.overflow-toggle.active {
|
||||||
|
color: var(--color-accent);
|
||||||
|
background: var(--color-accent-subtle);
|
||||||
|
border-color: var(--color-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------
|
||||||
|
Full-screen modals (Modal.tsx -- TemplateModal/HeadCodeModal/
|
||||||
|
SitesmithModal share `.modal-backdrop`). Same tab-bar cutout as
|
||||||
|
`.mobile-sheet-backdrop` below, and for the same reason: without it,
|
||||||
|
the backdrop's default `inset: 0` sits ABOVE the tab bar (--z-modal >
|
||||||
|
--z-tabbar) and swallows every tap there, so "open Templates -> tap a
|
||||||
|
bottom tab" would silently just close Templates (a tap on the
|
||||||
|
backdrop) instead of ALSO opening the tapped sheet. `!important`
|
||||||
|
because Modal.tsx sets `bottom` via an inline style, which otherwise
|
||||||
|
beats this class rule. The modal's own content still sits above the
|
||||||
|
tab bar (it's a commit/cancel moment) -- only the dismiss-affordance
|
||||||
|
backdrop stops short, exactly like the sheet backdrop.
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.modal-backdrop {
|
||||||
|
bottom: calc(var(--mobile-tabbar-height) + env(safe-area-inset-bottom, 0px)) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------
|
||||||
|
"⋯" overflow menu (TopBarOverflowMenu.tsx)
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.topbar-overflow-menu {
|
||||||
|
position: fixed;
|
||||||
|
top: calc(var(--topbar-height) + env(safe-area-inset-top, 0px) + 6px);
|
||||||
|
right: calc(8px + env(safe-area-inset-right, 0px));
|
||||||
|
z-index: var(--z-overflow);
|
||||||
|
min-width: 220px;
|
||||||
|
max-width: calc(100vw - 16px);
|
||||||
|
max-height: calc(100dvh - var(--topbar-height) - 24px);
|
||||||
|
overflow-y: auto;
|
||||||
|
background: var(--color-bg-elevated);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.5);
|
||||||
|
padding: 8px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-overflow-section {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 6px 8px 10px;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-overflow-label {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-overflow-section .device-switcher {
|
||||||
|
height: 44px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-overflow-section .device-btn {
|
||||||
|
width: 44px;
|
||||||
|
height: 42px;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-overflow-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--color-text);
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-overflow-item:hover,
|
||||||
|
.topbar-overflow-item:active {
|
||||||
|
background: var(--color-bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-overflow-item.active {
|
||||||
|
color: var(--color-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-overflow-sitesmith {
|
||||||
|
padding: 6px 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-overflow-sitesmith .sitesmith-btn {
|
||||||
|
width: 100%;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 44px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------
|
||||||
|
Bottom tab bar (MobilePanelBar.tsx)
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.mobile-tab-bar {
|
||||||
|
position: fixed;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
/* Above .mobile-sheet-backdrop (400) -- the tab bar must stay clickable
|
||||||
|
even while a sheet is open so tapping a different tab swaps sheets
|
||||||
|
directly, instead of requiring a close-then-reopen round trip. The
|
||||||
|
backdrop itself stops short of the tab bar (see its `bottom` offset
|
||||||
|
below) so this is mostly belt-and-suspenders for the boundary. */
|
||||||
|
z-index: var(--z-tabbar);
|
||||||
|
display: flex;
|
||||||
|
height: calc(var(--mobile-tabbar-height) + env(safe-area-inset-bottom, 0px));
|
||||||
|
background: var(--color-bg-surface);
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
padding-bottom: env(safe-area-inset-bottom, 0px);
|
||||||
|
padding-left: env(safe-area-inset-left, 0px);
|
||||||
|
padding-right: env(safe-area-inset-right, 0px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-tab-btn {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 3px;
|
||||||
|
min-height: 44px;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-tab-btn i {
|
||||||
|
font-size: 17px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-tab-btn.active {
|
||||||
|
color: var(--color-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------
|
||||||
|
Mobile selection toolbar (MobileSelectionToolbar.tsx, Phase B item 2)
|
||||||
|
Bottom-fixed just above the tab bar -- simplest, robust positioning
|
||||||
|
that never has to track a scrolling/resizing node's DOM rect. Sits at
|
||||||
|
--z-selection-toolbar (600), above the tab bar (500) and sheet backdrop
|
||||||
|
(400) so it's never occluded by either, but well below --z-modal
|
||||||
|
(5000). Hidden entirely (component returns null) whenever a sheet is
|
||||||
|
open, so it never has to fight the sheet for the same screen space.
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.mobile-selection-toolbar {
|
||||||
|
position: fixed;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: calc(var(--mobile-tabbar-height) + env(safe-area-inset-bottom, 0px));
|
||||||
|
z-index: var(--z-selection-toolbar);
|
||||||
|
display: flex;
|
||||||
|
background: var(--color-bg-elevated);
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.35);
|
||||||
|
padding: 4px calc(2px + env(safe-area-inset-right, 0px)) 4px calc(2px + env(safe-area-inset-left, 0px));
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-selection-toolbar-btn {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 2px;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 4px 2px;
|
||||||
|
font-size: 9px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1;
|
||||||
|
color: var(--color-text);
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
cursor: pointer;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-selection-toolbar-btn i {
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-selection-toolbar-btn:disabled {
|
||||||
|
color: var(--color-text-dim);
|
||||||
|
opacity: 0.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-selection-toolbar-btn.danger {
|
||||||
|
color: var(--color-danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-selection-toolbar-btn.danger.confirming {
|
||||||
|
background: rgba(239, 68, 68, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fast-follow item 4: while the toolbar above is visible, give the canvas
|
||||||
|
scroll area enough extra bottom padding to clear it (on top of the
|
||||||
|
regular 12px `.editor-canvas` padding, not replacing it), so the last
|
||||||
|
section of a short page is still reachable by scrolling instead of
|
||||||
|
sitting permanently underneath the fixed toolbar. */
|
||||||
|
.editor-canvas.has-mobile-selection-toolbar {
|
||||||
|
padding-bottom: calc(12px + var(--mobile-selection-toolbar-height));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fast-follow item 3: while the Styles sheet is open with a node selected,
|
||||||
|
`MobileSelectionToolbar`'s scroll-into-view effect needs somewhere to
|
||||||
|
scroll THE NODE TO even when it's the last thing on the page -- without
|
||||||
|
extra room below it, the canvas is already at its max scrollTop and the
|
||||||
|
node's top can't be brought up past wherever it naturally landed
|
||||||
|
(verified live: the last section stayed stuck under the sheet). A full
|
||||||
|
extra viewport's worth of bottom padding guarantees any node's top can
|
||||||
|
always reach the very top of the canvas. Temporary/cosmetic cost (a
|
||||||
|
stretch of blank canvas below the real content while this is active) is
|
||||||
|
an acceptable trade for the node never being permanently unreachable.
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.editor-canvas.has-mobile-styles-sheet {
|
||||||
|
padding-bottom: 100vh;
|
||||||
|
padding-bottom: 100dvh;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------
|
||||||
|
Bottom sheet (BottomSheet.tsx)
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.mobile-sheet-backdrop {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
/* Stop above the bottom tab bar (rather than a full-viewport `inset: 0`)
|
||||||
|
so the tab bar is never covered/blocked by the backdrop -- tapping a
|
||||||
|
different tab while a sheet is open swaps sheets directly instead of
|
||||||
|
being swallowed by the overlay sitting on top of it.
|
||||||
|
`--keyboard-inset` (item 5, Phase B) is set inline by BottomSheet.tsx
|
||||||
|
from `useVisualViewportInsets` -- 0px when no on-screen keyboard is
|
||||||
|
open (the default below is the no-JS/unsupported-browser fallback),
|
||||||
|
otherwise the keyboard's height, so the whole sheet lifts clear of it
|
||||||
|
instead of the keyboard covering its lower portion. */
|
||||||
|
bottom: calc(var(--mobile-tabbar-height) + env(safe-area-inset-bottom, 0px) + var(--keyboard-inset, 0px));
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
z-index: var(--z-sheet-backdrop);
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet {
|
||||||
|
width: 100%;
|
||||||
|
/* Capped a second time by the keyboard inset so the sheet's own
|
||||||
|
max-height shrinks along with the lifted backdrop -- without this the
|
||||||
|
sheet could still try to be 65dvh tall from its new (higher) bottom
|
||||||
|
edge and overflow off the top of the screen. */
|
||||||
|
max-height: calc(65vh - var(--keyboard-inset, 0px));
|
||||||
|
max-height: calc(65dvh - var(--keyboard-inset, 0px));
|
||||||
|
background: var(--color-bg-surface);
|
||||||
|
border-top-left-radius: 16px;
|
||||||
|
border-top-right-radius: 16px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-bottom: none;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet-handle-row {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 8px 0 4px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
/* Swipe-to-dismiss (item 4, Phase B) tracks its own touchmove here --
|
||||||
|
`none` stops the browser's native scroll/rubber-band gesture from
|
||||||
|
competing with it. */
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet-handle {
|
||||||
|
width: 36px;
|
||||||
|
height: 4px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: var(--color-border-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 4px 12px 10px 16px;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
flex-shrink: 0;
|
||||||
|
/* Swipe-to-dismiss (item 4, Phase B) -- see .mobile-sheet-handle-row. */
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet-title {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet-close {
|
||||||
|
width: 44px;
|
||||||
|
height: 44px;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 16px;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
cursor: pointer;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet-body {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
padding: 12px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------
|
||||||
|
Touch ergonomics inside sheets -- 16px inputs kill iOS's auto-zoom on
|
||||||
|
focus; touch-action speeds up tap response on chrome that doesn't need
|
||||||
|
native scroll-gesture handling.
|
||||||
|
|
||||||
|
`!important` is required here: GuidedStyles/StylePanel inputs (see
|
||||||
|
`inputStyle` in `panels/right/styles/shared.tsx`) carry an INLINE
|
||||||
|
`font-size: 12px`, which otherwise beats this class rule on the
|
||||||
|
Styles sheet -- the most-used mobile surface -- and iOS zooms in on
|
||||||
|
focus. `.sitesmith-textarea` (ChatInput.tsx, inline font-size: 14)
|
||||||
|
has the same problem even though the Sitesmith modal isn't a sheet.
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.mobile-sheet-body button,
|
||||||
|
.mobile-sheet-body .block-item {
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet-body input,
|
||||||
|
.mobile-sheet-body select,
|
||||||
|
.mobile-sheet-body textarea,
|
||||||
|
.guided-input,
|
||||||
|
.control-input,
|
||||||
|
.control-select,
|
||||||
|
.topbar input,
|
||||||
|
.topbar textarea,
|
||||||
|
.topbar select,
|
||||||
|
.sitesmith-textarea {
|
||||||
|
font-size: 16px !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet-body .settings-tabs button {
|
||||||
|
min-height: 44px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sheet-body .color-preset {
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Layers panel rows (item 4) -- the reliable fallback selection path when
|
||||||
|
a node is hard to hit precisely on the canvas by touch. Bumped to the
|
||||||
|
44px touch-target minimum; tapping a row already selects (LayerNode's
|
||||||
|
`handleActivate`), unchanged. */
|
||||||
|
.mobile-sheet-body .layer-node-row {
|
||||||
|
min-height: 44px;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------
|
||||||
|
Templates modal: category tabs stay horizontally scrollable and never
|
||||||
|
shrink below a comfortable touch target; close button enlarged to the
|
||||||
|
44px minimum (overriding its 32px inline style).
|
||||||
|
-------------------------------------------------------------------- */
|
||||||
|
.template-modal-tabbar {
|
||||||
|
gap: 8px;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-modal-tab-btn {
|
||||||
|
flex-shrink: 0;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 8px 16px !important;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-modal-close-btn {
|
||||||
|
width: 44px !important;
|
||||||
|
height: 44px !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { templateComponentToTreeNode } from './apply-template';
|
||||||
|
|
||||||
|
describe('templateComponentToTreeNode', () => {
|
||||||
|
test('converts a childless TemplateComponent to a SerializedTreeNode with an empty `nodes` array', () => {
|
||||||
|
const node = templateComponentToTreeNode({ type: 'Heading', props: { text: 'Hi' } });
|
||||||
|
expect(node).toEqual({
|
||||||
|
type: { resolvedName: 'Heading' },
|
||||||
|
props: { text: 'Hi' },
|
||||||
|
nodes: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('regression: recursively converts nested `children` into `nodes` (previously dropped entirely)', () => {
|
||||||
|
const node = templateComponentToTreeNode({
|
||||||
|
type: 'Container',
|
||||||
|
props: { tag: 'header' },
|
||||||
|
children: [
|
||||||
|
{ type: 'Logo', props: { text: 'FlowStack' } },
|
||||||
|
{ type: 'Menu', props: { links: [] } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(node.nodes).toHaveLength(2);
|
||||||
|
expect(node.nodes![0]).toEqual({ type: { resolvedName: 'Logo' }, props: { text: 'FlowStack' }, nodes: [] });
|
||||||
|
expect(node.nodes![1]).toEqual({ type: { resolvedName: 'Menu' }, props: { links: [] }, nodes: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('recurses more than one level deep', () => {
|
||||||
|
const node = templateComponentToTreeNode({
|
||||||
|
type: 'Section',
|
||||||
|
props: {},
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
type: 'ColumnLayout',
|
||||||
|
props: { columns: 1 },
|
||||||
|
children: [{ type: 'TextBlock', props: { text: 'deep' } }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const col = node.nodes![0];
|
||||||
|
expect(col.type.resolvedName).toBe('ColumnLayout');
|
||||||
|
expect(col.nodes![0]).toEqual({ type: { resolvedName: 'TextBlock' }, props: { text: 'deep' }, nodes: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not mutate the input TemplateComponent', () => {
|
||||||
|
const comp = { type: 'Heading', props: { text: 'Hi' } };
|
||||||
|
const frozen = JSON.parse(JSON.stringify(comp));
|
||||||
|
templateComponentToTreeNode(comp);
|
||||||
|
expect(comp).toEqual(frozen);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import type { SerializedTreeNode } from '../types/sitesmith';
|
||||||
|
import { TemplateComponent } from './definitions';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a template's `TemplateComponent` tree (the plain
|
||||||
|
* `{ type, props, children? }` shape authored in `templates/definitions.ts`)
|
||||||
|
* into a `SerializedTreeNode` (the shape `craft-tree.ts`'s `buildNodeTree` /
|
||||||
|
* `sanitizeAiTree` / `flattenTreeForCraft` pipeline already knows how to
|
||||||
|
* materialize into a real Craft.js `NodeTree`).
|
||||||
|
*
|
||||||
|
* Bug this fixes: `TemplateModal`'s `addTemplateComponents` used to call
|
||||||
|
* `React.createElement(Component, comp.props)` with no children argument,
|
||||||
|
* which silently dropped every nested `children` array authored in
|
||||||
|
* definitions.ts -- e.g. `makeHeader()`'s `Container > Logo + Menu`,
|
||||||
|
* `makeFooterContent()`'s `Container > TextBlock...`, or a page `Section`
|
||||||
|
* wrapping a `Heading`/`TextBlock`/`ButtonLink`. The resulting Craft.js node
|
||||||
|
* ended up with `nodes: []`, so the header/footer zone preview
|
||||||
|
* (`ZonePreview` in `editor/Canvas.tsx`, via `exportBodyHtml`) -- and the
|
||||||
|
* same-path published HTML (`handlePublish` composes header/footer HTML
|
||||||
|
* from the same serialized state) -- rendered as an empty strip instead of
|
||||||
|
* the real nav/footer/section content.
|
||||||
|
*
|
||||||
|
* A follow-up attempt fixed that by building a real nested React element
|
||||||
|
* tree (`React.createElement(Component, props, ...children)`) and handing
|
||||||
|
* it to `query.parseReactElement(...).toNodeTree()`. That approach breaks
|
||||||
|
* for any component with an internal SHELL_INNER-style linked canvas
|
||||||
|
* (`Section`, `BackgroundSection`, `FormContainer` -- see `SHELL_INNER` in
|
||||||
|
* `craft-tree.ts`) or linked columns (`ColumnLayout`): `parseReactElement`
|
||||||
|
* statically walks the JSX tree and has no way to know that e.g. `Section`
|
||||||
|
* routes its `children` into a nested `<Element id="section-inner" canvas>`
|
||||||
|
* at render time, not directly under itself. Feeding it raw nested children
|
||||||
|
* produces a tree where Craft.js has to auto-materialize that linked node on
|
||||||
|
* first render -- which stores the wrong `type` and crashes with "component
|
||||||
|
* type (undefined) does not exist in the resolver" the moment the section
|
||||||
|
* renders (reproduced live: loading the SaaS Landing template crashed the
|
||||||
|
* whole editor on its "Trusted by 10,000+ development teams" `Section`).
|
||||||
|
*
|
||||||
|
* Converting to `SerializedTreeNode` and reusing `buildNodeTree` sidesteps
|
||||||
|
* both bugs at once: it's the same tree-building pipeline already used (and
|
||||||
|
* tested) for AI-generated content in `apply-ai-response.ts`, which already
|
||||||
|
* knows how to route content through SHELL_INNER / linked columns correctly.
|
||||||
|
*/
|
||||||
|
export function templateComponentToTreeNode(comp: TemplateComponent): SerializedTreeNode {
|
||||||
|
return {
|
||||||
|
type: { resolvedName: comp.type },
|
||||||
|
props: { ...comp.props },
|
||||||
|
nodes: (comp.children || []).map(templateComponentToTreeNode),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { Editor, Frame, Element, useEditor } from '@craftjs/core';
|
||||||
|
import { componentResolver } from '../components/resolver';
|
||||||
|
import { Container } from '../components/layout/Container';
|
||||||
|
import { EditorConfigProvider } from '../state/EditorConfigContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real-`@craftjs/core` integration test harness.
|
||||||
|
*
|
||||||
|
* Mounts an ACTUAL `<Editor resolver={componentResolver}>` + `<Frame>` via
|
||||||
|
* `react-dom/client`'s `createRoot` (no `@testing-library/react`, matching
|
||||||
|
* the existing `*.test.tsx` convention in this repo -- see
|
||||||
|
* `useKeyboardShortcuts.test.tsx` / `RenderNode.test.tsx`). Nothing in
|
||||||
|
* `@craftjs/core` is mocked here: `query`/`actions` come straight out of a
|
||||||
|
* live `useEditor()` call, so `regenerateTreeIds`, `buildNodeTree`,
|
||||||
|
* `parseFreshNode`, `addNodeTree`, `deserialize`, and `serialize` all run
|
||||||
|
* their REAL implementations against a REAL Craft.js `EditorStore`.
|
||||||
|
*
|
||||||
|
* Why this catches bugs the mocked unit tests didn't: a hand-rolled fake
|
||||||
|
* `useEditor`/`query`/`node().toNodeTree()` can only echo back whatever
|
||||||
|
* plain-data shape the test author imagined -- it has no way to reproduce
|
||||||
|
* Craft's actual internal node shape (`data.type` as a live component
|
||||||
|
* function reference, real `parseFreshNode` resolver validation, real
|
||||||
|
* `<Frame>` rendering). Every one of the three historical bugs this suite
|
||||||
|
* targets (`regenerateTreeIds` + `structuredClone`, `TemplateModal` dropping
|
||||||
|
* `children`, `buildNodeTree` emitting `data.type={resolvedName}`) slipped
|
||||||
|
* past its mocked unit test for exactly that reason.
|
||||||
|
*
|
||||||
|
* jsdom shims: as of writing, mounting `<Editor><Frame>...` in this repo's
|
||||||
|
* jsdom (v29, see vitest.config.ts) did NOT require stubbing
|
||||||
|
* `ResizeObserver`/`matchMedia`/`getBoundingClientRect` -- none of the
|
||||||
|
* components exercised by these integration tests read layout geometry
|
||||||
|
* during render. `ensureJsdomShims()` below still installs a `ResizeObserver`
|
||||||
|
* stub defensively (idempotent, only if absent) since it's the one API
|
||||||
|
* Craft/DOM-heavy component code most commonly reaches for and a future
|
||||||
|
* template/component could easily start needing it; add further shims here
|
||||||
|
* (not per-test) if a future component trips over a missing browser API.
|
||||||
|
*/
|
||||||
|
|
||||||
|
let shimsInstalled = false;
|
||||||
|
|
||||||
|
/** Install browser APIs jsdom doesn't implement, if not already present. Safe
|
||||||
|
* to call multiple times (idempotent) and safe in a real browser (guarded by
|
||||||
|
* `typeof` checks, so it never clobbers a real implementation). */
|
||||||
|
export function ensureJsdomShims(): void {
|
||||||
|
if (shimsInstalled) return;
|
||||||
|
shimsInstalled = true;
|
||||||
|
|
||||||
|
if (typeof (globalThis as any).ResizeObserver === 'undefined') {
|
||||||
|
class ResizeObserverStub {
|
||||||
|
observe() {}
|
||||||
|
unobserve() {}
|
||||||
|
disconnect() {}
|
||||||
|
}
|
||||||
|
(globalThis as any).ResizeObserver = ResizeObserverStub;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== 'undefined' && typeof window.matchMedia !== 'function') {
|
||||||
|
window.matchMedia = ((query: string) => ({
|
||||||
|
matches: false,
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addListener: () => {},
|
||||||
|
removeListener: () => {},
|
||||||
|
addEventListener: () => {},
|
||||||
|
removeEventListener: () => {},
|
||||||
|
dispatchEvent: () => false,
|
||||||
|
})) as unknown as typeof window.matchMedia;
|
||||||
|
}
|
||||||
|
|
||||||
|
// jsdom (as of v29, used by this repo's vitest.config.ts) does NOT
|
||||||
|
// implement `HTMLElement.prototype.innerText` at all -- `'innerText' in
|
||||||
|
// document.createElement('div')` is `false`, so assigning to it (as
|
||||||
|
// `Heading.tsx`/`TextBlock.tsx` do imperatively in a `useEffect`, to avoid
|
||||||
|
// fighting `contentEditable`'s caret position on every prop update) just
|
||||||
|
// sets a throwaway own-property that never touches `textContent`/
|
||||||
|
// `innerHTML` -- real rendered text from these two components would
|
||||||
|
// silently read back as empty in any DOM assertion. Shimmed as a plain
|
||||||
|
// `textContent` alias (real `innerText` also collapses whitespace/applies
|
||||||
|
// layout-based visibility, neither of which matters for these tests).
|
||||||
|
if (typeof HTMLElement !== 'undefined') {
|
||||||
|
if (!Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText')) {
|
||||||
|
Object.defineProperty(HTMLElement.prototype, 'innerText', {
|
||||||
|
configurable: true,
|
||||||
|
get(this: HTMLElement) {
|
||||||
|
return this.textContent;
|
||||||
|
},
|
||||||
|
set(this: HTMLElement, value: string) {
|
||||||
|
this.textContent = value;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CapturedApi {
|
||||||
|
query: any;
|
||||||
|
actions: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Invisible child that grabs a live `query`/`actions` pair out of a real
|
||||||
|
* `useEditor()` call and writes them into a mutable ref the harness owns --
|
||||||
|
* the same "Capture" pattern the brief describes and
|
||||||
|
* `template-zone-export.test.tsx` already uses ad hoc; this hoists it into a
|
||||||
|
* reusable helper. `query`/`actions` from Craft.js are live references (they
|
||||||
|
* read the current store at call time, not a react-state snapshot), so
|
||||||
|
* capturing them once on first render is sufficient -- no need to re-grab
|
||||||
|
* them after every store mutation. */
|
||||||
|
const Capture: React.FC<{ apiRef: React.MutableRefObject<CapturedApi | null> }> = ({ apiRef }) => {
|
||||||
|
const { query, actions } = useEditor();
|
||||||
|
apiRef.current = { query, actions };
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface EditorHarnessOptions {
|
||||||
|
/** A `query.serialize()`-shaped JSON string to `actions.deserialize()`
|
||||||
|
* immediately after mount, replacing the default empty ROOT. */
|
||||||
|
initialState?: string;
|
||||||
|
/** Craft.js `Frame` seed root tag -- 'div' for a regular page, 'header'/
|
||||||
|
* 'footer' for zone editing (mirrors `Canvas.tsx`'s `frameTag`). Ignored
|
||||||
|
* once `initialState` is given (deserialize replaces ROOT anyway); only
|
||||||
|
* affects the very first (pre-deserialize) paint. */
|
||||||
|
frameTag?: 'div' | 'header' | 'footer';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EditorHarness {
|
||||||
|
/** Live `query` from the real `useEditor()` -- reads current store state. */
|
||||||
|
readonly query: any;
|
||||||
|
/** Live `actions` from the real `useEditor()`. */
|
||||||
|
readonly actions: any;
|
||||||
|
/** `query.serialize()` -- the exact string `PageContext`/`useWhpApi` persist
|
||||||
|
* and `exportBodyHtml` consumes. */
|
||||||
|
getSerialized: () => string;
|
||||||
|
/** The DOM node the whole tree (including the real rendered `<Frame>`
|
||||||
|
* content) is mounted under -- assert on `.textContent`/`.innerHTML` here
|
||||||
|
* to verify actual rendering, not just serialized state. */
|
||||||
|
container: HTMLDivElement;
|
||||||
|
/** Re-exported `act` from `react-dom/test-utils` for convenience, matching
|
||||||
|
* the existing `*.test.tsx` files in this repo. */
|
||||||
|
act: typeof act;
|
||||||
|
/** Mount (or replace) an additional child inside the live `<Editor>` tree,
|
||||||
|
* alongside `<Frame>` -- e.g. a probe component that calls a real hook
|
||||||
|
* (`useNodeActions`, `useKeyboardShortcuts`) so the test can drive it
|
||||||
|
* against the REAL editor instance this harness set up. Wrapped in `act`. */
|
||||||
|
mountChild: (node: React.ReactNode) => void;
|
||||||
|
/** Unmounts the React tree and removes `container` from `document.body`. */
|
||||||
|
unmount: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mounts a real `<Editor resolver={componentResolver}>` + `<Frame>` (via
|
||||||
|
* `EditorConfigProvider config={null}` -- standalone mode, no WHP backend)
|
||||||
|
* and returns live `query`/`actions` plus helpers for driving further
|
||||||
|
* real-editor interactions from a test.
|
||||||
|
*/
|
||||||
|
export function renderEditorHarness(opts: EditorHarnessOptions = {}): EditorHarness {
|
||||||
|
ensureJsdomShims();
|
||||||
|
|
||||||
|
const container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
|
||||||
|
const apiRef: React.MutableRefObject<CapturedApi | null> = { current: null };
|
||||||
|
let extraChild: React.ReactNode = null;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
const frameTag = opts.frameTag ?? 'div';
|
||||||
|
|
||||||
|
function paint() {
|
||||||
|
root.render(
|
||||||
|
<EditorConfigProvider config={null}>
|
||||||
|
<Editor resolver={componentResolver} enabled={true}>
|
||||||
|
<Frame>
|
||||||
|
<Element is={Container} canvas tag={frameTag} style={{}} />
|
||||||
|
</Frame>
|
||||||
|
<Capture apiRef={apiRef} />
|
||||||
|
{extraChild}
|
||||||
|
</Editor>
|
||||||
|
</EditorConfigProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
paint();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (opts.initialState) {
|
||||||
|
act(() => {
|
||||||
|
apiRef.current!.actions.deserialize(opts.initialState!);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
get query() {
|
||||||
|
return apiRef.current!.query;
|
||||||
|
},
|
||||||
|
get actions() {
|
||||||
|
return apiRef.current!.actions;
|
||||||
|
},
|
||||||
|
getSerialized: () => apiRef.current!.query.serialize(),
|
||||||
|
container,
|
||||||
|
act,
|
||||||
|
mountChild: (node: React.ReactNode) => {
|
||||||
|
extraChild = node;
|
||||||
|
act(() => {
|
||||||
|
paint();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
unmount: () => {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
import { describe, test, expect, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { renderEditorHarness, EditorHarness } from '../editorHarness';
|
||||||
|
import { useApplyAiResponse } from '../../utils/apply-ai-response';
|
||||||
|
import { exportBodyHtml } from '../../utils/html-export';
|
||||||
|
import type { SitesmithResponse } from '../../types/sitesmith';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real-`@craftjs/core` integration coverage for applying a Sitesmith (AI)
|
||||||
|
* response.
|
||||||
|
*
|
||||||
|
* Historical bug: `buildNodeTree` used to hand `query.parseFreshNode`/the
|
||||||
|
* manually-constructed synthetic node a `data.type` of the SERIALIZED
|
||||||
|
* `{ resolvedName }` wrapper object (or, in an earlier attempt, a bare
|
||||||
|
* resolvedName string) instead of the actual component function reference
|
||||||
|
* from `componentResolver`. A live Craft.js node's renderer does
|
||||||
|
* `React.createElement(data.type, props)` directly, so anything other than
|
||||||
|
* a real component reference either fails Craft's own resolver validation
|
||||||
|
* inside `parseFreshNode`/`addNodeTree` ("component type ... does not exist
|
||||||
|
* in the resolver") or -- worse -- passes that validation but renders
|
||||||
|
* nothing/garbage. Either way, a section-replace or insert AI op became a
|
||||||
|
* silent no-op in the live app. The pre-existing mocked unit test
|
||||||
|
* (`apply-ai-response.test.ts`) fakes `query.parseFreshNode` as
|
||||||
|
* `(input) => ({ toNode: () => input })` -- a pure echo with NO validation
|
||||||
|
* at all -- so it could never have caught `buildNodeTree` emitting the
|
||||||
|
* wrong `data.type` shape.
|
||||||
|
*
|
||||||
|
* This suite drives the REAL `useApplyAiResponse()` hook (the exact
|
||||||
|
* consumer-facing API `SitesmithModal`/`useSitesmith` call after a
|
||||||
|
* successful AI response) against a real `EditorStore`/`<Frame>` from
|
||||||
|
* `editorHarness.tsx` -- so a regression in `buildNodeTree`'s `data.type`
|
||||||
|
* would throw here (real `parseFreshNode` resolver validation) or fail the
|
||||||
|
* "content actually landed" assertions (real render/export), exactly as it
|
||||||
|
* did live.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const INITIAL_STATE = JSON.stringify({
|
||||||
|
ROOT: {
|
||||||
|
type: { resolvedName: 'Container' },
|
||||||
|
isCanvas: true,
|
||||||
|
props: { style: {}, tag: 'div' },
|
||||||
|
displayName: 'Container',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
nodes: ['anchor-1'],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
'anchor-1': {
|
||||||
|
type: { resolvedName: 'Heading' },
|
||||||
|
isCanvas: false,
|
||||||
|
props: { text: 'Anchor Heading', level: 'h2' },
|
||||||
|
displayName: 'Heading',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
parent: 'ROOT',
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let harness: EditorHarness | null = null;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (harness) {
|
||||||
|
harness.unmount();
|
||||||
|
harness = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Mounts `useApplyAiResponse()` (the real hook) inside the harness's live
|
||||||
|
* Editor and returns the captured `apply` function. */
|
||||||
|
function mountApplyFn(h: EditorHarness): { current: ReturnType<typeof useApplyAiResponse> | null } {
|
||||||
|
const ref: { current: ReturnType<typeof useApplyAiResponse> | null } = { current: null };
|
||||||
|
const Probe: React.FC = () => {
|
||||||
|
ref.current = useApplyAiResponse();
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
h.mountChild(<Probe />);
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AI apply-response (real @craftjs/core editor)', () => {
|
||||||
|
test('section-scope replace with no target: appends a real, rendered node -- not a silent no-op', async () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
const applyRef = mountApplyFn(harness);
|
||||||
|
expect(applyRef.current).not.toBeNull();
|
||||||
|
|
||||||
|
const resp: SitesmithResponse = {
|
||||||
|
type: 'replace',
|
||||||
|
scope: 'section',
|
||||||
|
pages: [
|
||||||
|
{
|
||||||
|
name: 'section',
|
||||||
|
tree: { type: { resolvedName: 'Heading' }, props: { text: 'AI Inserted Heading Panel' }, nodes: [] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
message: 'inserted a section',
|
||||||
|
};
|
||||||
|
|
||||||
|
let result: { ok: boolean; message?: string } | undefined;
|
||||||
|
await harness.act(async () => {
|
||||||
|
result = await applyRef.current!(resp);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result!.ok).toBe(true);
|
||||||
|
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toHaveLength(2);
|
||||||
|
expect(rootChildren).toContain('anchor-1');
|
||||||
|
const newId = rootChildren.find((id) => id !== 'anchor-1')!;
|
||||||
|
expect(newId).toBeDefined();
|
||||||
|
|
||||||
|
// Real node.data.type must be the actual component reference so React
|
||||||
|
// can render it -- not a `{resolvedName}` wrapper or a bare string.
|
||||||
|
const newNodeType = harness.query.node(newId).get().data.type;
|
||||||
|
expect(typeof newNodeType).toBe('function');
|
||||||
|
|
||||||
|
expect(harness.container.textContent).toContain('AI Inserted Heading Panel');
|
||||||
|
|
||||||
|
const { html } = exportBodyHtml(harness.getSerialized());
|
||||||
|
expect(html).toContain('AI Inserted Heading Panel');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('section-scope replace WITH a target node: replaces that node in place (same slot, fresh id)', async () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
const applyRef = mountApplyFn(harness);
|
||||||
|
|
||||||
|
const resp: SitesmithResponse = {
|
||||||
|
type: 'replace',
|
||||||
|
scope: 'section',
|
||||||
|
pages: [
|
||||||
|
{
|
||||||
|
name: 'section',
|
||||||
|
tree: { type: { resolvedName: 'Heading' }, props: { text: 'AI Replaced The Anchor' }, nodes: [] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
message: 'replaced the section',
|
||||||
|
};
|
||||||
|
|
||||||
|
await harness.act(async () => {
|
||||||
|
await applyRef.current!(resp, 'anchor-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toHaveLength(1); // still just one node in that slot
|
||||||
|
expect(rootChildren).not.toContain('anchor-1'); // the old node is gone
|
||||||
|
|
||||||
|
expect(harness.container.textContent).toContain('AI Replaced The Anchor');
|
||||||
|
expect(harness.container.textContent).not.toContain('Anchor Heading');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('patch op insert_after: inserts a real node as the very next sibling', async () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
const applyRef = mountApplyFn(harness);
|
||||||
|
|
||||||
|
const resp: SitesmithResponse = {
|
||||||
|
type: 'patch',
|
||||||
|
ops: [
|
||||||
|
{
|
||||||
|
op: 'insert_after',
|
||||||
|
node_id: 'anchor-1',
|
||||||
|
tree: { type: { resolvedName: 'Heading' }, props: { text: 'AI Patched In After Anchor' }, nodes: [] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
message: 'patched',
|
||||||
|
};
|
||||||
|
|
||||||
|
let result: { ok: boolean; message?: string } | undefined;
|
||||||
|
await harness.act(async () => {
|
||||||
|
result = await applyRef.current!(resp);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result!.ok).toBe(true);
|
||||||
|
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toHaveLength(2);
|
||||||
|
expect(rootChildren[0]).toBe('anchor-1');
|
||||||
|
const insertedId = rootChildren[1];
|
||||||
|
|
||||||
|
expect(typeof harness.query.node(insertedId).get().data.type).toBe('function');
|
||||||
|
expect(harness.container.textContent).toContain('AI Patched In After Anchor');
|
||||||
|
// The original anchor is untouched.
|
||||||
|
expect(harness.container.textContent).toContain('Anchor Heading');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import { describe, test, expect, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { renderEditorHarness, EditorHarness } from '../editorHarness';
|
||||||
|
import { useNodeActions, NodeActions } from '../../hooks/useNodeActions';
|
||||||
|
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts';
|
||||||
|
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real-`@craftjs/core` integration coverage for duplicate/paste.
|
||||||
|
*
|
||||||
|
* Historical bug: `regenerateTreeIds` used `structuredClone(oldNode.data)` to
|
||||||
|
* clone a copied subtree. For a REAL (live) Craft.js node, `data.type` is the
|
||||||
|
* actual component function reference (not a plain `{resolvedName}` string
|
||||||
|
* wrapper) -- `structuredClone` cannot clone a function and throws
|
||||||
|
* `DataCloneError`, which silently broke duplicate/paste for EVERY
|
||||||
|
* component in the real app. The pre-existing mocked unit tests
|
||||||
|
* (`useNodeActions.test.tsx`, `useKeyboardShortcuts.test.tsx`) faked
|
||||||
|
* `query.node(id).toNodeTree()` to return a plain-data object with
|
||||||
|
* `type: { resolvedName: 'Container' }` -- never a function -- so
|
||||||
|
* `structuredClone` never saw anything it couldn't clone there, and the bug
|
||||||
|
* shipped anyway.
|
||||||
|
*
|
||||||
|
* This suite drives the REAL `useNodeActions`/`useKeyboardShortcuts` hooks
|
||||||
|
* (no `vi.mock('@craftjs/core')` anywhere) against a real
|
||||||
|
* `EditorStore`/`query`/`actions` from `editorHarness.tsx`, on a real
|
||||||
|
* `SocialLinks` node (its `.craft` config makes Craft.js store the actual
|
||||||
|
* `SocialLinks` function as `data.type`) -- so a regression back to
|
||||||
|
* `structuredClone(oldNode.data)` throws here exactly as it did live. See
|
||||||
|
* `task-integ-harness-report.md` for the recorded red-proof run.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const INITIAL_STATE = JSON.stringify({
|
||||||
|
ROOT: {
|
||||||
|
type: { resolvedName: 'Container' },
|
||||||
|
isCanvas: true,
|
||||||
|
props: { style: {}, tag: 'div' },
|
||||||
|
displayName: 'Container',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
nodes: ['social-1', 'heading-1'],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
'social-1': {
|
||||||
|
type: { resolvedName: 'SocialLinks' },
|
||||||
|
isCanvas: false,
|
||||||
|
props: {
|
||||||
|
links: [{ platform: 'facebook', url: 'https://facebook.com/original' }],
|
||||||
|
iconColor: '#ffffff',
|
||||||
|
},
|
||||||
|
displayName: 'Social Links',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
parent: 'ROOT',
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
'heading-1': {
|
||||||
|
type: { resolvedName: 'Heading' },
|
||||||
|
isCanvas: false,
|
||||||
|
props: { text: 'Sibling Heading', level: 'h2' },
|
||||||
|
displayName: 'Heading',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
parent: 'ROOT',
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let harness: EditorHarness | null = null;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
setClipboardNodeId(null);
|
||||||
|
if (harness) {
|
||||||
|
harness.unmount();
|
||||||
|
harness = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('duplicate/paste (real @craftjs/core editor)', () => {
|
||||||
|
test('useNodeActions().duplicate() on a real SocialLinks node: no throw, +1 node, inserted right after the source, with an independent props copy', () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
|
||||||
|
const before = Object.keys(harness.query.getNodes());
|
||||||
|
expect(before).toHaveLength(3); // ROOT, social-1, heading-1
|
||||||
|
|
||||||
|
const probeRef: { current: NodeActions | null } = { current: null };
|
||||||
|
const Probe: React.FC = () => {
|
||||||
|
probeRef.current = useNodeActions('social-1');
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
harness.mountChild(<Probe />);
|
||||||
|
expect(probeRef.current).not.toBeNull();
|
||||||
|
|
||||||
|
let newId: string | null = null;
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => {
|
||||||
|
newId = probeRef.current!.duplicate();
|
||||||
|
});
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
expect(newId).not.toBeNull();
|
||||||
|
expect(newId).not.toBe('social-1');
|
||||||
|
|
||||||
|
// +1 node overall.
|
||||||
|
const after = Object.keys(harness.query.getNodes());
|
||||||
|
expect(after).toHaveLength(4);
|
||||||
|
|
||||||
|
// Inserted immediately AFTER the source, not appended at the end.
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toEqual(['social-1', newId, 'heading-1']);
|
||||||
|
|
||||||
|
// The new node was selected.
|
||||||
|
expect(Array.from(harness.query.getEvent('selected').all())).toEqual([newId]);
|
||||||
|
|
||||||
|
// The copy's props object (and any nested arrays/objects within it) must
|
||||||
|
// be a SEPARATE object from the original -- not shared by reference.
|
||||||
|
const originalProps = harness.query.node('social-1').get().data.props;
|
||||||
|
const copyProps = harness.query.node(newId!).get().data.props;
|
||||||
|
expect(copyProps).not.toBe(originalProps);
|
||||||
|
expect(copyProps.links).not.toBe(originalProps.links);
|
||||||
|
expect(copyProps).toEqual(originalProps); // same VALUES though
|
||||||
|
|
||||||
|
// Mutating the copy via setProp must not affect the original.
|
||||||
|
harness.act(() => {
|
||||||
|
harness!.actions.setProp(newId!, (p: any) => {
|
||||||
|
p.links[0].url = 'https://facebook.com/MUTATED-COPY';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
expect(harness.query.node(newId!).get().data.props.links[0].url).toBe(
|
||||||
|
'https://facebook.com/MUTATED-COPY',
|
||||||
|
);
|
||||||
|
expect(harness.query.node('social-1').get().data.props.links[0].url).toBe(
|
||||||
|
'https://facebook.com/original',
|
||||||
|
);
|
||||||
|
|
||||||
|
// Real DOM assertion, not just serialized state: the Frame actually
|
||||||
|
// re-rendered with a second SocialLinks <a> link on the canvas.
|
||||||
|
expect(harness.container.querySelectorAll('a[href="https://facebook.com/original"]')).toHaveLength(1);
|
||||||
|
expect(harness.container.querySelectorAll('a[href="https://facebook.com/MUTATED-COPY"]')).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Ctrl+C / Ctrl+V (useKeyboardShortcuts) on the real editor: pastes a fresh-id sibling copy, original untouched', () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
|
||||||
|
const Consumer: React.FC = () => {
|
||||||
|
useKeyboardShortcuts();
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
harness.mountChild(<Consumer />);
|
||||||
|
|
||||||
|
// 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(getClipboardNodeId()).toBe('social-1');
|
||||||
|
|
||||||
|
// Select heading-1 (a sibling), then paste -- should land as a sibling
|
||||||
|
// of heading-1's parent (ROOT), with brand-new ids.
|
||||||
|
harness.act(() => {
|
||||||
|
harness!.actions.selectNode('heading-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
const before = Object.keys(harness.query.getNodes());
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => {
|
||||||
|
document.dispatchEvent(
|
||||||
|
new KeyboardEvent('keydown', { key: 'v', ctrlKey: true, bubbles: true, cancelable: true }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
const after = Object.keys(harness.query.getNodes());
|
||||||
|
expect(after).toHaveLength(before.length + 1);
|
||||||
|
|
||||||
|
const pastedId = after.find((id) => !before.includes(id))!;
|
||||||
|
expect(pastedId).toBeDefined();
|
||||||
|
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toContain(pastedId);
|
||||||
|
|
||||||
|
// Independent props copy again -- same class of bug, same guard.
|
||||||
|
const pastedProps = harness.query.node(pastedId).get().data.props;
|
||||||
|
const originalProps = harness.query.node('social-1').get().data.props;
|
||||||
|
expect(pastedProps.links).not.toBe(originalProps.links);
|
||||||
|
expect(pastedProps).toEqual(originalProps);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import { describe, test, expect, afterEach } from 'vitest';
|
||||||
|
import { renderEditorHarness, EditorHarness } from '../editorHarness';
|
||||||
|
import { allTemplates } from '../../templates';
|
||||||
|
import { buildNodeTree } from '../../utils/craft-tree';
|
||||||
|
import { templateComponentToTreeNode } from '../../templates/apply-template';
|
||||||
|
import { exportBodyHtml } from '../../utils/html-export';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real-`@craftjs/core` integration coverage for loading a template.
|
||||||
|
*
|
||||||
|
* Historical bug: `TemplateModal.addTemplateComponents` used to build each
|
||||||
|
* template component via `React.createElement(Component, comp.props)` with
|
||||||
|
* NO children argument, silently dropping every nested `children` array
|
||||||
|
* authored in `templates/definitions.ts` (e.g. `makeHeader()`'s
|
||||||
|
* `Container > Logo + Menu`, `makeFooterContent()`'s `Container > TextBlock`,
|
||||||
|
* or any page `Section` wrapping a `Heading`/`ColumnLayout`). The resulting
|
||||||
|
* Craft.js node had `nodes: []`, so both the editor's own header/footer zone
|
||||||
|
* preview AND the published HTML (same `exportBodyHtml` path) rendered as an
|
||||||
|
* empty strip instead of the real nav/footer/section content. The mocked
|
||||||
|
* unit test for `templateComponentToTreeNode` (`apply-template.test.ts`)
|
||||||
|
* tests the pure conversion function in isolation and would pass either way
|
||||||
|
* -- it never drove the result through a real Craft.js tree/render, so it
|
||||||
|
* couldn't have caught `TemplateModal` itself dropping children at the
|
||||||
|
* call site.
|
||||||
|
*
|
||||||
|
* This suite drives the EXACT same path `TemplateModal.tsx`'s
|
||||||
|
* `addTemplateComponents` uses against a REAL Craft.js editor mounted with a
|
||||||
|
* REAL `<Frame>` (via `editorHarness.tsx`) -- so it also exercises real
|
||||||
|
* component rendering (Section/Container SHELL_INNER canvases, ColumnLayout
|
||||||
|
* linked columns), not just tree-shape assertions.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing')!;
|
||||||
|
|
||||||
|
/** Mirrors TemplateModal.tsx's addTemplateComponents(). */
|
||||||
|
function addTemplateComponents(harness: EditorHarness, components: any[]) {
|
||||||
|
for (const comp of components) {
|
||||||
|
const tree = buildNodeTree(harness.query, templateComponentToTreeNode(comp));
|
||||||
|
harness.actions.addNodeTree(tree, 'ROOT');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY_HEADER_ROOT = JSON.stringify({
|
||||||
|
ROOT: {
|
||||||
|
type: { resolvedName: 'Container' },
|
||||||
|
isCanvas: true,
|
||||||
|
props: { style: {}, tag: 'header' },
|
||||||
|
displayName: 'Container',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const EMPTY_FOOTER_ROOT = JSON.stringify({
|
||||||
|
ROOT: {
|
||||||
|
type: { resolvedName: 'Container' },
|
||||||
|
isCanvas: true,
|
||||||
|
props: { style: {}, tag: 'footer' },
|
||||||
|
displayName: 'Container',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let harness: EditorHarness | null = null;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (harness) {
|
||||||
|
harness.unmount();
|
||||||
|
harness = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('template load (real @craftjs/core editor + real <Frame> render)', () => {
|
||||||
|
test('sanity: the SaaS Landing template actually has nested header/footer/page content to lose', () => {
|
||||||
|
expect(tpl).toBeDefined();
|
||||||
|
expect(tpl.header.components.length).toBeGreaterThan(0);
|
||||||
|
expect(tpl.footer.components.length).toBeGreaterThan(0);
|
||||||
|
expect(tpl.pages[0].content.components.length).toBeGreaterThan(0);
|
||||||
|
const hasNestedChildren = tpl.header.components.some((c: any) => (c.children?.length ?? 0) > 0);
|
||||||
|
expect(hasNestedChildren).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loading the header keeps its nested nav links + logo -- both in the real DOM and in export', () => {
|
||||||
|
harness = renderEditorHarness({ initialState: EMPTY_HEADER_ROOT, frameTag: 'header' });
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => addTemplateComponents(harness!, tpl.header.components));
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
// Real rendered DOM -- not just serialized state.
|
||||||
|
expect(harness.container.textContent).toContain('FlowStack');
|
||||||
|
expect(harness.container.textContent).toContain('Features');
|
||||||
|
expect(harness.container.textContent).toContain('Start Free');
|
||||||
|
|
||||||
|
const { html } = exportBodyHtml(harness.getSerialized());
|
||||||
|
expect(html).toContain('FlowStack');
|
||||||
|
expect(html).toContain('Features');
|
||||||
|
expect(html).toContain('Start Free');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loading the footer keeps its nested copyright/tagline content -- both in the real DOM and in export', () => {
|
||||||
|
harness = renderEditorHarness({ initialState: EMPTY_FOOTER_ROOT, frameTag: 'footer' });
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => addTemplateComponents(harness!, tpl.footer.components));
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
expect(harness.container.textContent).toContain('FlowStack, Inc.');
|
||||||
|
expect(harness.container.textContent).toContain('Ship products faster');
|
||||||
|
|
||||||
|
const { html } = exportBodyHtml(harness.getSerialized());
|
||||||
|
expect(html).toContain('FlowStack, Inc.');
|
||||||
|
expect(html).toContain('Ship products faster');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loading the home page keeps a Section-wrapped Heading\'s nested content -- both in the real DOM and in export', () => {
|
||||||
|
const homePage = tpl.pages[0];
|
||||||
|
const sectionComp = homePage.content.components.find((c: any) => c.type === 'Section');
|
||||||
|
expect(sectionComp).toBeDefined();
|
||||||
|
expect(sectionComp!.children?.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
harness = renderEditorHarness(); // default empty 'div' root, like a regular page
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => addTemplateComponents(harness!, [sectionComp]));
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
expect(harness.container.textContent).toContain('Trusted by 10,000+ development teams');
|
||||||
|
|
||||||
|
const { html } = exportBodyHtml(harness.getSerialized());
|
||||||
|
expect(html).toContain('Trusted by 10,000+ development teams');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loading the FULL home page (all components) keeps every top-level node\'s content -- no silent drops', () => {
|
||||||
|
const homePage = tpl.pages[0];
|
||||||
|
harness = renderEditorHarness();
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => addTemplateComponents(harness!, homePage.content.components));
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
// ROOT should have exactly as many direct children as the template
|
||||||
|
// defines top-level page components -- if children got dropped, nested
|
||||||
|
// content wouldn't show up in ROOT's descendant count via serialize, but
|
||||||
|
// an easier, more direct regression signal is: every top-level
|
||||||
|
// component's OWN text ends up rendered somewhere on the canvas.
|
||||||
|
const serialized = JSON.parse(harness.getSerialized());
|
||||||
|
const totalNodeCount = Object.keys(serialized).length;
|
||||||
|
// A flat (children-dropped) tree would have exactly
|
||||||
|
// homePage.content.components.length + 1 (ROOT) nodes. The real template
|
||||||
|
// has nested children, so a correct load must produce MORE nodes than
|
||||||
|
// that -- this is the shape-level assertion the pre-existing mocked test
|
||||||
|
// could never make (it never touched a real tree).
|
||||||
|
expect(totalNodeCount).toBeGreaterThan(homePage.content.components.length + 1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -31,7 +31,10 @@ const defaultBackdropStyle: React.CSSProperties = {
|
|||||||
display: 'flex',
|
display: 'flex',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
justifyContent: 'center',
|
justifyContent: 'center',
|
||||||
zIndex: 10000,
|
/* z-index comes from the `.modal-backdrop` class (--z-modal in the
|
||||||
|
shared layer scale, editor.css) rather than an inline value, so every
|
||||||
|
Modal consumer -- including ones that pass a custom `backdropStyle`
|
||||||
|
without a zIndex, like SitesmithModal -- lands on the same layer. */
|
||||||
};
|
};
|
||||||
|
|
||||||
/* ---------- Shared modal chrome ----------
|
/* ---------- Shared modal chrome ----------
|
||||||
@@ -77,6 +80,7 @@ export const Modal: React.FC<ModalProps> = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
className="modal-backdrop"
|
||||||
{...backdropProps}
|
{...backdropProps}
|
||||||
style={backdropStyle ? { ...defaultBackdropStyle, ...backdropStyle } : defaultBackdropStyle}
|
style={backdropStyle ? { ...defaultBackdropStyle, ...backdropStyle } : defaultBackdropStyle}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import type { NodeTree } from '@craftjs/core';
|
|
||||||
import { usePages } from '../state/PageContext';
|
import { usePages } from '../state/PageContext';
|
||||||
import { SitesmithResponse, SerializedTreeNode, SitesmithPatchOp } from '../types/sitesmith';
|
import { SitesmithResponse, SerializedTreeNode, SitesmithPatchOp } from '../types/sitesmith';
|
||||||
import { sanitizeAiTree, flattenTreeForCraft } from './craft-tree';
|
import { sanitizeAiTree, buildNodeTree } from './craft-tree';
|
||||||
|
|
||||||
// Re-exported for existing callers/tests that import sanitizeAiTree from
|
// Re-exported for existing callers/tests that import sanitizeAiTree/
|
||||||
// this module — the implementation now lives in craft-tree.ts alongside the
|
// buildNodeTree from this module — the implementation lives in craft-tree.ts
|
||||||
// shared flattener, since treeToState (PageContext.tsx) needs the same
|
// alongside the shared flattener: `templates/apply-template.ts` needs the
|
||||||
// validation this module pioneered.
|
// exact same tree-materialization logic to load template header/footer/page
|
||||||
export { sanitizeAiTree };
|
// content (see the doc comment on `buildNodeTree` in craft-tree.ts).
|
||||||
|
export { sanitizeAiTree, buildNodeTree };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* update_props may never touch these keys, regardless of what the AI sends.
|
* update_props may never touch these keys, regardless of what the AI sends.
|
||||||
@@ -18,52 +18,6 @@ export { sanitizeAiTree };
|
|||||||
*/
|
*/
|
||||||
const PROTECTED_UPDATE_PROPS_KEYS = new Set<string>(['node_id']);
|
const PROTECTED_UPDATE_PROPS_KEYS = new Set<string>(['node_id']);
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a Craft.js `NodeTree` from a `SerializedTreeNode` using `query.parseFreshNode`.
|
|
||||||
* This is the correct way to construct a tree for `actions.addNodeTree()` when
|
|
||||||
* inserting/replacing sections or individual nodes.
|
|
||||||
*/
|
|
||||||
function buildNodeTree(query: any, tree: SerializedTreeNode): NodeTree {
|
|
||||||
// Validate + sanitize at the AI boundary before touching Craft.js at all:
|
|
||||||
// unknown resolvedNames are dropped (never reach parseFreshNode/addNodeTree,
|
|
||||||
// which would throw), and ids are repaired ('ROOT'/empty/colliding →
|
|
||||||
// regenerated) against the live document's existing node ids so a new
|
|
||||||
// AI-supplied id can never clobber or duplicate one already on the canvas.
|
|
||||||
const existingIds = new Set<string>(
|
|
||||||
typeof query?.getNodes === 'function' ? Object.keys(query.getNodes()) : [],
|
|
||||||
);
|
|
||||||
const sanitized = sanitizeAiTree(tree, existingIds);
|
|
||||||
if (!sanitized) {
|
|
||||||
throw new Error('sitesmith: AI tree root has an unknown/invalid component type; nothing to build');
|
|
||||||
}
|
|
||||||
|
|
||||||
// sanitizeAiTree() has already guaranteed every node has a valid, unique,
|
|
||||||
// non-'ROOT' node_id and a registered resolvedName — the shared flattener
|
|
||||||
// just needs to do the structural walk (linkedNodes/SHELL_INNER/style
|
|
||||||
// normalization) common to every tree-flattening caller in this codebase.
|
|
||||||
const flat = flattenTreeForCraft(sanitized);
|
|
||||||
|
|
||||||
const craftNodes: Record<string, any> = {};
|
|
||||||
for (const [id, flatNode] of Object.entries(flat.nodes)) {
|
|
||||||
if (flat.syntheticIds.has(id)) {
|
|
||||||
// The SHELL_INNER wrapper Container is synthesized by the flattener,
|
|
||||||
// not present in the AI's tree — build it directly rather than
|
|
||||||
// through query.parseFreshNode(), which would merge in Container's
|
|
||||||
// default `craft.props` (e.g. default padding) and change its look.
|
|
||||||
craftNodes[id] = {
|
|
||||||
id,
|
|
||||||
data: { ...flatNode },
|
|
||||||
events: { selected: false, hovered: false, dragged: false },
|
|
||||||
rules: { canDrag: () => true, canMoveIn: () => true, canMoveOut: () => true, canDrop: () => true },
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
craftNodes[id] = (query.parseFreshNode({ id, data: { ...flatNode } }) as any).toNode();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { rootNodeId: flat.rootNodeId, nodes: craftNodes };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Find the Craft.js node id that corresponds to an AI node_id value.
|
* Find the Craft.js node id that corresponds to an AI node_id value.
|
||||||
* Checks `data.props.node_id` first, then falls back to raw id equality.
|
* Checks `data.props.node_id` first, then falls back to raw id equality.
|
||||||
|
|||||||
@@ -147,6 +147,37 @@ describe('regenerateTreeIds', () => {
|
|||||||
|
|
||||||
expect(input.nodes['root-1'].data.props).toEqual({ alignment: 'left' });
|
expect(input.nodes['root-1'].data.props).toEqual({ alignment: 'left' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Regression test (found via real-browser Playwright touch verification,
|
||||||
|
// Phase B): a LIVE Craft.js node's `data.type` is the actual component
|
||||||
|
// function reference (not the `{resolvedName}` string wrapper used only
|
||||||
|
// in SERIALIZED state) -- `query.node(id).toNodeTree()` returns nodes
|
||||||
|
// shaped exactly like this. The previous implementation ran
|
||||||
|
// `structuredClone(oldNode.data)` on the WHOLE data object, which throws
|
||||||
|
// `DataCloneError` the instant `data.type` is a function, silently
|
||||||
|
// breaking Duplicate (ContextMenu.tsx / useNodeActions.ts) and Ctrl+V
|
||||||
|
// Paste (useKeyboardShortcuts.ts) for every real node in the app --
|
||||||
|
// masked by every other test in this suite using a plain string `type`
|
||||||
|
// ('div'), and by unit tests elsewhere that mock `@craftjs/core` entirely
|
||||||
|
// (so `toNodeTree()` never actually returns a function there).
|
||||||
|
test('does not throw when data.type is a live component function reference', () => {
|
||||||
|
const ButtonLikeComponent = (props: { text?: string }) => props.text;
|
||||||
|
const input = makeTree();
|
||||||
|
input.nodes['root-1'].data.type = ButtonLikeComponent as unknown as Node['data']['type'];
|
||||||
|
input.nodes['root-1'].data.props = { text: 'Click Me' };
|
||||||
|
|
||||||
|
expect(() => regenerateTreeIds(input)).not.toThrow();
|
||||||
|
|
||||||
|
const output = regenerateTreeIds(input);
|
||||||
|
const outputRoot = output.nodes[output.rootNodeId];
|
||||||
|
// The component reference itself is preserved (shared, not cloned --
|
||||||
|
// it's a stable reference, not mutable data).
|
||||||
|
expect(outputRoot.data.type).toBe(ButtonLikeComponent);
|
||||||
|
// Props are still genuinely deep-cloned (the actual bug fix's point).
|
||||||
|
expect(outputRoot.data.props).toEqual({ text: 'Click Me' });
|
||||||
|
(outputRoot.data.props as { text: string }).text = 'changed';
|
||||||
|
expect(input.nodes['root-1'].data.props).toEqual({ text: 'Click Me' });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('flattenTreeForCraft', () => {
|
describe('flattenTreeForCraft', () => {
|
||||||
|
|||||||
@@ -225,6 +225,105 @@ export function flattenTreeForCraft(tree: SerializedTreeNode): FlattenTreeResult
|
|||||||
return { rootNodeId, nodes, syntheticIds };
|
return { rootNodeId, nodes, syntheticIds };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a Craft.js `NodeTree` from a `SerializedTreeNode` using
|
||||||
|
* `query.parseFreshNode`. This is the correct way to construct a tree for
|
||||||
|
* `actions.addNodeTree()` when inserting/replacing sections, individual
|
||||||
|
* nodes, or (via `templates/apply-template.ts`) a template's header/footer/
|
||||||
|
* page content -- anything whose input isn't already a live Craft.js state.
|
||||||
|
*
|
||||||
|
* Originally lived in `apply-ai-response.ts` (the AI-response path pioneered
|
||||||
|
* it); moved here alongside `sanitizeAiTree`/`flattenTreeForCraft` once
|
||||||
|
* `templates/apply-template.ts` needed the exact same tree-materialization
|
||||||
|
* logic — building a node tree by hand via `React.createElement` +
|
||||||
|
* `query.parseReactElement` does NOT correctly route content through a
|
||||||
|
* `Section`/`BackgroundSection`/`FormContainer`'s internal SHELL_INNER
|
||||||
|
* linked canvas or `ColumnLayout`'s linked columns (see the `SHELL_INNER`
|
||||||
|
* comment above): Craft.js would auto-materialize that linked node at
|
||||||
|
* render time with a botched `type` field and crash `toNodeTree` with
|
||||||
|
* "component type (undefined) does not exist in the resolver". Going through
|
||||||
|
* `sanitizeAiTree` + `flattenTreeForCraft` (as this function does) avoids
|
||||||
|
* that entirely.
|
||||||
|
*/
|
||||||
|
export function buildNodeTree(query: any, tree: SerializedTreeNode): NodeTree {
|
||||||
|
// Validate + sanitize at the boundary before touching Craft.js at all:
|
||||||
|
// unknown resolvedNames are dropped (never reach parseFreshNode/addNodeTree,
|
||||||
|
// which would throw), and ids are repaired ('ROOT'/empty/colliding →
|
||||||
|
// regenerated) against the live document's existing node ids so a new
|
||||||
|
// caller-supplied id can never clobber or duplicate one already on the canvas.
|
||||||
|
const existingIds = new Set<string>(
|
||||||
|
typeof query?.getNodes === 'function' ? Object.keys(query.getNodes()) : [],
|
||||||
|
);
|
||||||
|
const sanitized = sanitizeAiTree(tree, existingIds);
|
||||||
|
if (!sanitized) {
|
||||||
|
throw new Error('craft-tree: tree root has an unknown/invalid component type; nothing to build');
|
||||||
|
}
|
||||||
|
|
||||||
|
// sanitizeAiTree() has already guaranteed every node has a valid, unique,
|
||||||
|
// non-'ROOT' node_id and a registered resolvedName — flattenTreeForCraft
|
||||||
|
// just needs to do the structural walk (linkedNodes/SHELL_INNER/style
|
||||||
|
// normalization) common to every tree-flattening caller in this codebase.
|
||||||
|
const flat = flattenTreeForCraft(sanitized);
|
||||||
|
|
||||||
|
const craftNodes: Record<string, any> = {};
|
||||||
|
for (const [id, flatNode] of Object.entries(flat.nodes)) {
|
||||||
|
// Live Craft.js nodes need `data.type` to be the ACTUAL component
|
||||||
|
// reference (the function/class from `componentResolver`) -- not the
|
||||||
|
// `{ resolvedName }` wrapper object `flattenTreeForCraft` produces (that
|
||||||
|
// wrapper is the *serialized* form used by `actions.deserialize()`/
|
||||||
|
// `query.serialize()`, a different Craft.js entry point), and not a
|
||||||
|
// plain resolvedName string either.
|
||||||
|
//
|
||||||
|
// A plain string passes `parseFreshNode`'s own validation (it special-
|
||||||
|
// cases strings) AND `actions.addNodeTree`'s, so that alone looks fine --
|
||||||
|
// but it's wrong for RENDERING: Craft.js's node renderer does
|
||||||
|
// `React.createElement(data.type, props)` directly, so a string type
|
||||||
|
// makes React treat e.g. "Section" as a literal (invalid, lowercase-
|
||||||
|
// expected) HTML tag name instead of resolving it to the real `Section`
|
||||||
|
// component. Symptom: "is using incorrect casing" console warnings and
|
||||||
|
// the component's own render logic (and thus its content) never runs --
|
||||||
|
// reproduced live by loading a template: the header/footer rendered fine
|
||||||
|
// but the page canvas went blank. The `{ resolvedName }` wrapper object
|
||||||
|
// fails even earlier, at `parseFreshNode`/`addNodeTree`'s own validation
|
||||||
|
// ("component type (undefined) does not exist in the resolver"), because
|
||||||
|
// their resolution only accepts a string or a component reference.
|
||||||
|
//
|
||||||
|
// None of this was caught by the pre-existing mocked test for this
|
||||||
|
// function (in apply-ai-response.test.ts) because its fake
|
||||||
|
// `parseFreshNode` just echoes the input back unchanged rather than
|
||||||
|
// exercising Craft.js's real validation/rendering.
|
||||||
|
const resolvedComponent = (componentResolver as Record<string, unknown>)[flatNode.type.resolvedName];
|
||||||
|
|
||||||
|
if (flat.syntheticIds.has(id)) {
|
||||||
|
// The SHELL_INNER wrapper Container is synthesized by the flattener,
|
||||||
|
// not present in the input tree — build it directly rather than
|
||||||
|
// through query.parseFreshNode(), which would merge in Container's
|
||||||
|
// default `craft.props` (e.g. default padding) and change its look.
|
||||||
|
//
|
||||||
|
// `actions.addNodeTree`'s own validation for a non-string `data.type`
|
||||||
|
// checks `resolver[data.name]` (NOT a reverse lookup from `data.type`
|
||||||
|
// like `parseFreshNode` does) -- so `data.name` must be set to the
|
||||||
|
// resolvedName string here too, or this synthetic node fails that
|
||||||
|
// check with "component type (Container) does not exist in the
|
||||||
|
// resolver" the moment `addNodeTree` runs, even though `resolvedComponent`
|
||||||
|
// itself is perfectly valid.
|
||||||
|
craftNodes[id] = {
|
||||||
|
id,
|
||||||
|
data: { ...flatNode, type: resolvedComponent, name: flatNode.type.resolvedName },
|
||||||
|
events: { selected: false, hovered: false, dragged: false },
|
||||||
|
rules: { canDrag: () => true, canMoveIn: () => true, canMoveOut: () => true, canDrop: () => true },
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
craftNodes[id] = (query.parseFreshNode({
|
||||||
|
id,
|
||||||
|
data: { ...flatNode, type: resolvedComponent },
|
||||||
|
}) as any).toNode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { rootNodeId: flat.rootNodeId, nodes: craftNodes };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a deep-cloned NodeTree where every node id in the tree
|
* Returns a deep-cloned NodeTree where every node id in the tree
|
||||||
* (rootNodeId, the `nodes` map keys, each `node.id`, each internal
|
* (rootNodeId, the `nodes` map keys, each `node.id`, each internal
|
||||||
@@ -267,12 +366,27 @@ export function regenerateTreeIds(tree: NodeTree): NodeTree {
|
|||||||
newLinkedNodes[slot] = remapId(linkedId);
|
newLinkedNodes[slot] = remapId(linkedId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deep-clone data so mutable sub-objects (props, custom, etc.) are never
|
// Deep-clone only the mutable sub-objects (props, custom) so they're
|
||||||
// shared by reference between the original node and its regenerated
|
// never shared by reference between the original node and its
|
||||||
// copy. Craft.js's setProp mutates data.props in place, so a shallow
|
// regenerated copy -- Craft.js's setProp mutates data.props in place, so
|
||||||
// copy here would let edits to the duplicate silently corrupt the
|
// a shallow copy here would let edits to the duplicate silently corrupt
|
||||||
// original.
|
// the original.
|
||||||
const clonedData = structuredClone(oldNode.data);
|
//
|
||||||
|
// Deliberately NOT `structuredClone(oldNode.data)` as a whole: for a
|
||||||
|
// LIVE Craft.js node (as opposed to a plain serialized one), `data.type`
|
||||||
|
// is the actual component function/class reference (see the long
|
||||||
|
// comment on `buildNodeTree` above) -- `structuredClone` cannot clone a
|
||||||
|
// function and throws `DataCloneError`, which silently broke EVERY
|
||||||
|
// duplicate/paste in the real app (masked in unit tests that mock
|
||||||
|
// `@craftjs/core` with plain-data fake nodes, so `toNodeTree()` never
|
||||||
|
// actually returns a function there). `type` is a stable reference that
|
||||||
|
// both the original and the duplicate should point at unchanged, so it
|
||||||
|
// never needed cloning in the first place.
|
||||||
|
const clonedData = {
|
||||||
|
...oldNode.data,
|
||||||
|
props: structuredClone(oldNode.data.props),
|
||||||
|
custom: structuredClone(oldNode.data.custom),
|
||||||
|
};
|
||||||
|
|
||||||
const newNode: Node = {
|
const newNode: Node = {
|
||||||
...oldNode,
|
...oldNode,
|
||||||
|
|||||||
Reference in New Issue
Block a user