Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a8a26687b | ||
|
|
979331b12d | ||
|
|
329a782052 | ||
|
|
da558fd52d | ||
|
|
8aeadefa88 | ||
|
|
2066059c35 | ||
|
|
473fe8d421 | ||
|
|
5d6ae7946b | ||
|
|
1c85ab93eb | ||
|
|
67228f24b4 | ||
|
|
613a44c4d4 | ||
|
|
5685670895 |
+1
-1
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<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>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
|
||||
@@ -5,9 +5,12 @@ import { usePages } from '../state/PageContext';
|
||||
import { DeviceMode } from '../types';
|
||||
import { DEVICE_WIDTHS } from '../constants/presets';
|
||||
import { exportBodyHtml } from '../utils/html-export';
|
||||
import { useIsMobile } from '../hooks/useIsMobile';
|
||||
|
||||
interface CanvasProps {
|
||||
device: DeviceMode;
|
||||
/** Item 10: when false, applies `.guides-off` to hide the dashed drop-target guides. */
|
||||
showGuides: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -81,13 +84,14 @@ const ZonePreview: React.FC<{ craftState: string | null; zone: 'header' | 'foote
|
||||
<div
|
||||
ref={containerRef}
|
||||
data-zone-preview={zone}
|
||||
className="zone-preview-sep"
|
||||
style={{
|
||||
width: '100%',
|
||||
position: 'relative',
|
||||
pointerEvents: 'none',
|
||||
userSelect: 'none',
|
||||
borderBottom: zone === 'header' ? '1px dashed rgba(245,158,11,0.3)' : 'none',
|
||||
borderTop: zone === 'footer' ? '1px dashed rgba(245,158,11,0.3)' : 'none',
|
||||
borderBottom: zone === 'header' ? '1px dashed rgba(148,163,184,0.25)' : 'none',
|
||||
borderTop: zone === 'footer' ? '1px dashed rgba(148,163,184,0.25)' : 'none',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
@@ -109,18 +113,23 @@ export const EmptyCanvasHint: React.FC = () => {
|
||||
isDragging: state.events.dragged.size > 0,
|
||||
};
|
||||
});
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
if (!isEmpty || isDragging) return null;
|
||||
|
||||
return (
|
||||
<div className="empty-canvas-hint">
|
||||
<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>
|
||||
);
|
||||
};
|
||||
|
||||
export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
||||
export const Canvas: React.FC<CanvasProps> = ({ device, showGuides }) => {
|
||||
const width = DEVICE_WIDTHS[device];
|
||||
const { isEditingHeader, isEditingFooter, headerPage, footerPage } = usePages();
|
||||
|
||||
@@ -137,7 +146,7 @@ export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
||||
return (
|
||||
<div className="editor-canvas">
|
||||
<div
|
||||
className="canvas-device-frame"
|
||||
className={`canvas-device-frame${showGuides ? '' : ' guides-off'}`}
|
||||
style={{
|
||||
width,
|
||||
maxWidth: '100%',
|
||||
|
||||
@@ -1,16 +1,59 @@
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import { TopBar } from '../panels/topbar/TopBar';
|
||||
import { LeftPanel } from '../panels/left/LeftPanel';
|
||||
import { RightPanel } from '../panels/right/RightPanel';
|
||||
import { MobilePanelBar } from '../panels/mobile/MobilePanelBar';
|
||||
import { Canvas } from './Canvas';
|
||||
import { ContextMenu } from '../panels/context-menu/ContextMenu';
|
||||
import { useContextMenu } from '../hooks/useContextMenu';
|
||||
import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts';
|
||||
import { useIsMobile } from '../hooks/useIsMobile';
|
||||
import { MobileChromeProvider } from '../state/MobileChromeContext';
|
||||
import { DeviceMode } from '../types';
|
||||
|
||||
const SHOW_GUIDES_STORAGE_KEY = 'craft-show-guides';
|
||||
|
||||
function loadShowGuides(): boolean {
|
||||
try {
|
||||
const stored = window.localStorage.getItem(SHOW_GUIDES_STORAGE_KEY);
|
||||
return stored === null ? true : stored === '1';
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export const EditorShell: React.FC = () => {
|
||||
const isMobile = useIsMobile();
|
||||
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
|
||||
// so the choice survives a reload. Lifted here (rather than owned by
|
||||
// TopBar or Canvas alone) because the toggle button lives in TopBar but
|
||||
// the `.guides-off` class it drives is applied to Canvas's
|
||||
// `.canvas-device-frame`, mirroring how `device` is already lifted for
|
||||
// the same reason.
|
||||
const [showGuides, setShowGuidesState] = useState<boolean>(loadShowGuides);
|
||||
const setShowGuides = useCallback((next: boolean) => {
|
||||
setShowGuidesState(next);
|
||||
try {
|
||||
window.localStorage.setItem(SHOW_GUIDES_STORAGE_KEY, next ? '1' : '0');
|
||||
} catch {
|
||||
// Storage unavailable (private browsing, etc.) -- in-memory state still works.
|
||||
}
|
||||
}, []);
|
||||
const { menuState, show: showMenu, hide: hideMenu } = useContextMenu();
|
||||
const { query } = useEditor();
|
||||
|
||||
@@ -33,15 +76,27 @@ export const EditorShell: React.FC = () => {
|
||||
}, [query, showMenu]);
|
||||
|
||||
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">
|
||||
<TopBar device={device} onDeviceChange={setDevice} />
|
||||
<TopBar
|
||||
device={device}
|
||||
onDeviceChange={setDevice}
|
||||
showGuides={showGuides}
|
||||
onToggleGuides={() => setShowGuides(!showGuides)}
|
||||
/>
|
||||
<div className="editor-container">
|
||||
<LeftPanel />
|
||||
{!isMobile && <LeftPanel />}
|
||||
<div onContextMenu={handleContextMenu} style={{ flex: 1, display: 'flex', minWidth: 0 }}>
|
||||
<Canvas device={device} />
|
||||
<Canvas device={device} showGuides={showGuides} />
|
||||
</div>
|
||||
<RightPanel />
|
||||
{!isMobile && <RightPanel />}
|
||||
</div>
|
||||
{isMobile && <MobilePanelBar />}
|
||||
<ContextMenu
|
||||
visible={menuState.visible}
|
||||
x={menuState.x}
|
||||
@@ -50,5 +105,6 @@ export const EditorShell: React.FC = () => {
|
||||
onClose={hideMenu}
|
||||
/>
|
||||
</div>
|
||||
</MobileChromeProvider>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -10,9 +10,11 @@ import { act } from 'react-dom/test-utils';
|
||||
let mockNode: {
|
||||
id: string;
|
||||
selected: boolean;
|
||||
hovered: boolean;
|
||||
dom: HTMLElement | null;
|
||||
displayName: string;
|
||||
parent: string | null;
|
||||
isCanvas: boolean;
|
||||
};
|
||||
const selectNodeSpy = vi.fn();
|
||||
|
||||
@@ -20,9 +22,14 @@ vi.mock('@craftjs/core', () => ({
|
||||
useEditor: () => ({ actions: { selectNode: selectNodeSpy } }),
|
||||
useNode: (collect?: (node: any) => any) => {
|
||||
const node = {
|
||||
events: { selected: mockNode.selected },
|
||||
events: { selected: mockNode.selected, hovered: mockNode.hovered },
|
||||
dom: mockNode.dom,
|
||||
data: { custom: {}, displayName: mockNode.displayName, parent: mockNode.parent },
|
||||
data: {
|
||||
custom: {},
|
||||
displayName: mockNode.displayName,
|
||||
parent: mockNode.parent,
|
||||
isCanvas: mockNode.isCanvas,
|
||||
},
|
||||
};
|
||||
return { id: mockNode.id, ...(collect ? collect(node) : {}) };
|
||||
},
|
||||
@@ -46,7 +53,15 @@ function render(ui: React.ReactElement) {
|
||||
beforeEach(() => {
|
||||
nodeDom = document.createElement('div');
|
||||
document.body.appendChild(nodeDom);
|
||||
mockNode = { id: 'node-1', selected: false, dom: nodeDom, displayName: 'Heading', parent: 'ROOT' };
|
||||
mockNode = {
|
||||
id: 'node-1',
|
||||
selected: false,
|
||||
hovered: false,
|
||||
dom: nodeDom,
|
||||
displayName: 'Heading',
|
||||
parent: 'ROOT',
|
||||
isCanvas: false,
|
||||
};
|
||||
selectNodeSpy.mockClear();
|
||||
});
|
||||
|
||||
@@ -105,4 +120,50 @@ describe('RenderNode (Editor onRender override)', () => {
|
||||
nodeDom.remove();
|
||||
document.querySelector('.component-indicator')?.remove();
|
||||
});
|
||||
|
||||
test('tags a droppable (isCanvas) node dom with data-craft-node', () => {
|
||||
mockNode.isCanvas = true;
|
||||
render(<RenderNode render={rendered} />);
|
||||
expect(nodeDom.hasAttribute('data-craft-node')).toBe(true);
|
||||
container.remove();
|
||||
nodeDom.remove();
|
||||
});
|
||||
|
||||
test('does not tag a non-canvas (leaf) node dom with data-craft-node', () => {
|
||||
mockNode.isCanvas = false;
|
||||
render(<RenderNode render={rendered} />);
|
||||
expect(nodeDom.hasAttribute('data-craft-node')).toBe(false);
|
||||
container.remove();
|
||||
nodeDom.remove();
|
||||
});
|
||||
|
||||
test('never tags ROOT with data-craft-node even though ROOT is a canvas', () => {
|
||||
mockNode.id = 'ROOT';
|
||||
mockNode.isCanvas = true;
|
||||
render(<RenderNode render={rendered} />);
|
||||
expect(nodeDom.hasAttribute('data-craft-node')).toBe(false);
|
||||
container.remove();
|
||||
nodeDom.remove();
|
||||
});
|
||||
|
||||
test('tags the dom with data-craft-hovered when the Craft hovered event is set (Layers panel hover sync)', () => {
|
||||
mockNode.hovered = true;
|
||||
render(<RenderNode render={rendered} />);
|
||||
expect(nodeDom.hasAttribute('data-craft-hovered')).toBe(true);
|
||||
container.remove();
|
||||
nodeDom.remove();
|
||||
});
|
||||
|
||||
test('removes data-craft-hovered once the hovered event clears', () => {
|
||||
mockNode.hovered = true;
|
||||
render(<RenderNode render={rendered} />);
|
||||
expect(nodeDom.hasAttribute('data-craft-hovered')).toBe(true);
|
||||
mockNode.hovered = false;
|
||||
act(() => {
|
||||
root.render(<RenderNode render={rendered} />);
|
||||
});
|
||||
expect(nodeDom.hasAttribute('data-craft-hovered')).toBe(false);
|
||||
container.remove();
|
||||
nodeDom.remove();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,14 +14,36 @@ interface RenderNodeProps {
|
||||
* straight through as a Fragment, so this never touches layout, never
|
||||
* appears in `toHtml` export (that walks the Craft node tree, not this
|
||||
* portal), and doesn't wrap every node in extra DOM.
|
||||
*
|
||||
* It also imperatively tags each node's real DOM element with two
|
||||
* editor-only data attributes (never part of `toHtml` export, which walks
|
||||
* the Craft node tree, not the live DOM):
|
||||
* - `data-craft-node`: set on actual Craft.js droppable containers
|
||||
* (`node.data.isCanvas`, excluding ROOT). `editor.css`'s dashed "guide"
|
||||
* outlines target this attribute instead of blanket tag selectors
|
||||
* (div/section/header/...), so a component's own internal wrapper markup
|
||||
* no longer picks up a guide outline it isn't a real drop target for.
|
||||
* - `data-craft-hovered`: mirrors `node.events.hovered` (Craft's hover
|
||||
* event set). Craft's own `connectors.connect()` (called by every
|
||||
* component) wires a native mouseover/mouseleave listener to this event
|
||||
* internally, so a plain mouse hover over any connected node sets it --
|
||||
* this attribute is a real-mouse-hover canvas highlight. (The Layers
|
||||
* panel's row-hover -> canvas-highlight sync, item 12, uses a sibling
|
||||
* `data-layer-hovered` attribute written directly by LayersPanel.tsx
|
||||
* instead of this event, since the action that would drive it here
|
||||
* -- `actions.setNodeEvent` -- is stripped from the public `useEditor()`
|
||||
* API at runtime.) editor.css matches both attributes for the same
|
||||
* outline and suppresses both under `.guides-off`.
|
||||
*/
|
||||
export const RenderNode: React.FC<RenderNodeProps> = ({ render }) => {
|
||||
const { actions } = useEditor();
|
||||
const { id, isSelected, dom, name, parent } = useNode((node) => ({
|
||||
const { id, isSelected, dom, name, parent, isCanvas, isHovered } = useNode((node) => ({
|
||||
isSelected: node.events.selected,
|
||||
isHovered: node.events.hovered,
|
||||
dom: node.dom,
|
||||
name: (node.data.props?.aiName as string) || node.data.displayName,
|
||||
parent: node.data.parent,
|
||||
isCanvas: node.data.isCanvas,
|
||||
}));
|
||||
|
||||
const badgeRef = useRef<HTMLDivElement>(null);
|
||||
@@ -46,6 +68,24 @@ export const RenderNode: React.FC<RenderNodeProps> = ({ render }) => {
|
||||
};
|
||||
}, [active, updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!dom) return;
|
||||
if (isCanvas && id !== 'ROOT') {
|
||||
dom.setAttribute('data-craft-node', '');
|
||||
} else {
|
||||
dom.removeAttribute('data-craft-node');
|
||||
}
|
||||
}, [dom, isCanvas, id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!dom) return;
|
||||
if (isHovered) {
|
||||
dom.setAttribute('data-craft-hovered', '');
|
||||
} else {
|
||||
dom.removeAttribute('data-craft-hovered');
|
||||
}
|
||||
}, [dom, isHovered]);
|
||||
|
||||
if (!active) return <>{render}</>;
|
||||
|
||||
return (
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -199,18 +199,21 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
||||
},
|
||||
{
|
||||
label: 'Duplicate',
|
||||
icon: 'clone',
|
||||
shortcut: 'Ctrl+D',
|
||||
action: duplicate,
|
||||
disabled: isRoot,
|
||||
},
|
||||
{
|
||||
label: 'Copy',
|
||||
icon: 'files-o',
|
||||
shortcut: 'Ctrl+C',
|
||||
action: copyNode,
|
||||
disabled: isRoot,
|
||||
},
|
||||
{
|
||||
label: 'Paste',
|
||||
icon: 'clipboard',
|
||||
shortcut: 'Ctrl+V',
|
||||
action: pasteNode,
|
||||
disabled: !getClipboardNodeId(),
|
||||
@@ -218,22 +221,26 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
||||
},
|
||||
{
|
||||
label: 'Move Up',
|
||||
icon: 'arrow-up',
|
||||
action: moveUp,
|
||||
disabled: isRoot,
|
||||
},
|
||||
{
|
||||
label: 'Move Down',
|
||||
icon: 'arrow-down',
|
||||
action: moveDown,
|
||||
disabled: isRoot,
|
||||
},
|
||||
{
|
||||
label: 'Select Parent',
|
||||
icon: 'level-up',
|
||||
action: selectParent,
|
||||
disabled: isRoot,
|
||||
dividerAfter: true,
|
||||
},
|
||||
{
|
||||
label: 'Delete',
|
||||
icon: 'trash',
|
||||
shortcut: 'Del',
|
||||
action: deleteNode,
|
||||
danger: true,
|
||||
|
||||
@@ -2,12 +2,14 @@ import React, { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useAssets } from '../../hooks/useAssets';
|
||||
import { clickableProps } from '../../utils/a11y';
|
||||
import { copyToClipboard } from '../../utils/clipboard';
|
||||
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||
|
||||
/** How long the "Delete?" confirm state stays armed before auto-resetting. */
|
||||
const DELETE_CONFIRM_TIMEOUT_MS = 4000;
|
||||
|
||||
export const AssetsPanel: React.FC = () => {
|
||||
const { assets, loading, error, loadAssets, uploadAsset, deleteAsset } = useAssets();
|
||||
const isMobile = useIsMobile();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [copiedUrl, setCopiedUrl] = useState<string | null>(null);
|
||||
@@ -139,7 +141,9 @@ export const AssetsPanel: React.FC = () => {
|
||||
{assets.length === 0 && (
|
||||
<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>
|
||||
|
||||
{/* Error message */}
|
||||
|
||||
@@ -1,14 +1,74 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import React, { useCallback, useEffect, useRef } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import { clickableProps } from '../../utils/a11y';
|
||||
|
||||
/**
|
||||
* Per-type icon lookup keyed by the component's `craft.displayName` (the
|
||||
* same human label `LayerNode` already resolves and shows as the row text).
|
||||
* Mirrors the icon choices in `BlocksPanel.tsx` where a block exists for the
|
||||
* type; the remaining entries (Navbar, Container, Section, Columns,
|
||||
* Background Section, Map, Video, Image, form fields, and the richer
|
||||
* section blocks not draggable from the Basic/Sections categories) get a
|
||||
* sensible FA4 icon of their own. Unknown/future types fall back to
|
||||
* `DEFAULT_ICON`.
|
||||
*/
|
||||
const TYPE_ICONS: Record<string, string> = {
|
||||
// Layout
|
||||
Container: 'fa-square-o',
|
||||
Section: 'fa-window-maximize',
|
||||
Columns: 'fa-th-large',
|
||||
'Background Section': 'fa-picture-o',
|
||||
// Basic
|
||||
Heading: 'fa-header',
|
||||
Text: 'fa-paragraph',
|
||||
Button: 'fa-square',
|
||||
Logo: 'fa-bookmark',
|
||||
Menu: 'fa-bars',
|
||||
Navbar: 'fa-bars',
|
||||
Footer: 'fa-window-minimize',
|
||||
Divider: 'fa-minus',
|
||||
Spacer: 'fa-arrows-v',
|
||||
Icon: 'fa-star',
|
||||
'Star Rating': 'fa-star-half-o',
|
||||
'Social Links': 'fa-share-alt',
|
||||
'Search Bar': 'fa-search',
|
||||
HTML: 'fa-code',
|
||||
// Media
|
||||
Image: 'fa-image',
|
||||
Video: 'fa-play-circle',
|
||||
Map: 'fa-map-marker',
|
||||
// Sections
|
||||
Hero: 'fa-star-o',
|
||||
'Features Grid': 'fa-th-large',
|
||||
'CTA Section': 'fa-bullhorn',
|
||||
'Call to Action': 'fa-bullhorn',
|
||||
Countdown: 'fa-clock-o',
|
||||
Testimonials: 'fa-quote-left',
|
||||
'Content Slider': 'fa-sliders',
|
||||
'Number Counter': 'fa-sort-numeric-asc',
|
||||
Accordion: 'fa-list',
|
||||
Tabs: 'fa-folder-o',
|
||||
'Pricing Table': 'fa-usd',
|
||||
Gallery: 'fa-th',
|
||||
// Forms
|
||||
Form: 'fa-wpforms',
|
||||
Input: 'fa-i-cursor',
|
||||
Textarea: 'fa-align-left',
|
||||
'Submit Button': 'fa-paper-plane',
|
||||
'Contact Form': 'fa-envelope',
|
||||
'Subscribe Form': 'fa-paper-plane',
|
||||
};
|
||||
|
||||
const DEFAULT_ICON = 'fa-cube';
|
||||
const ROOT_ICON = 'fa-desktop';
|
||||
|
||||
interface LayerNodeProps {
|
||||
nodeId: string;
|
||||
depth: number;
|
||||
}
|
||||
|
||||
const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
||||
const { node, selectedId, actions } = useEditor((state) => {
|
||||
const { node, selectedId, actions, query } = useEditor((state) => {
|
||||
const n = state.nodes[nodeId];
|
||||
const selectedIds = state.events.selected;
|
||||
const selId = selectedIds ? Array.from(selectedIds)[0] : null;
|
||||
@@ -18,28 +78,76 @@ const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
||||
};
|
||||
});
|
||||
|
||||
const isSelected = selectedId === nodeId;
|
||||
|
||||
const handleActivate = useCallback(() => {
|
||||
actions.selectNode(nodeId);
|
||||
}, [actions, nodeId]);
|
||||
|
||||
// Layers-panel <-> canvas hover sync (Item 12): tags the target node's own
|
||||
// DOM element (found via `query`) with `data-layer-hovered` directly.
|
||||
// `RenderNode.tsx` mirrors Craft's *own* `hovered` node event onto
|
||||
// `data-craft-hovered` for the (separate, mouse-driven) canvas hover
|
||||
// outline -- editor.css's rule matches both attributes. This panel can't
|
||||
// reuse that path: `setNodeEvent` is a private action that `useEditor()`
|
||||
// strips from its `actions` return at runtime (see
|
||||
// @craftjs/core/dist/esm's `xe()` action stripper, not just its TypeScript
|
||||
// type), so calling it here throws. Writing our own attribute directly is
|
||||
// a supported, version-stable way to get the same highlight.
|
||||
const hoveredDomRef = useRef<HTMLElement | null>(null);
|
||||
|
||||
const handleMouseEnter = useCallback(
|
||||
(e: React.MouseEvent<HTMLElement> | React.FocusEvent<HTMLElement>) => {
|
||||
const dom = query.node(nodeId).get()?.dom;
|
||||
if (dom) {
|
||||
dom.setAttribute('data-layer-hovered', '');
|
||||
hoveredDomRef.current = dom;
|
||||
}
|
||||
if (!isSelected) {
|
||||
(e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)';
|
||||
}
|
||||
},
|
||||
[query, nodeId, isSelected],
|
||||
);
|
||||
|
||||
const handleMouseLeave = useCallback(
|
||||
(e: React.MouseEvent<HTMLElement> | React.FocusEvent<HTMLElement>) => {
|
||||
hoveredDomRef.current?.removeAttribute('data-layer-hovered');
|
||||
hoveredDomRef.current = null;
|
||||
if (!isSelected) {
|
||||
(e.currentTarget as HTMLElement).style.background = 'transparent';
|
||||
}
|
||||
},
|
||||
[isSelected],
|
||||
);
|
||||
|
||||
// Safety net: if this row unmounts (e.g. the user switches away from the
|
||||
// Layers tab, or the tree re-shuffles) while still hovered, clear the
|
||||
// attribute so it doesn't get stuck highlighted on the canvas forever.
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
hoveredDomRef.current?.removeAttribute('data-layer-hovered');
|
||||
hoveredDomRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!node) return null;
|
||||
|
||||
const isSelected = selectedId === nodeId;
|
||||
const nodeType = node.data.type;
|
||||
const resolvedName = typeof nodeType === 'object' && nodeType !== null && 'resolvedName' in nodeType
|
||||
? (nodeType as any).resolvedName
|
||||
: typeof nodeType === 'string' ? nodeType : undefined;
|
||||
const displayName = (node.data.props?.aiName as string) || node.data.displayName || (node.data.type as any)?.resolvedName || 'Node';
|
||||
const childNodeIds: string[] = node.data.nodes || [];
|
||||
const linkedNodeIds: string[] = Object.values(node.data.linkedNodes || {}) as string[];
|
||||
const allChildren = [...childNodeIds, ...linkedNodeIds];
|
||||
const isRoot = nodeId === 'ROOT';
|
||||
const icon = isRoot ? ROOT_ICON : TYPE_ICONS[displayName] || DEFAULT_ICON;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
{...clickableProps(handleActivate)}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
style={{
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
padding: '5px 8px',
|
||||
@@ -56,30 +164,53 @@ const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
||||
textOverflow: 'ellipsis',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (!isSelected) {
|
||||
(e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)';
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
if (!isSelected) {
|
||||
(e.currentTarget as HTMLElement).style.background = 'transparent';
|
||||
}
|
||||
}}
|
||||
onFocus={handleMouseEnter}
|
||||
onBlur={handleMouseLeave}
|
||||
>
|
||||
{/* Indentation indicator */}
|
||||
{allChildren.length > 0 && (
|
||||
<span style={{ marginRight: 4, fontSize: 8, color: 'var(--color-text-dim)' }}>
|
||||
{/* Indent guides: one vertical line per ancestor depth level,
|
||||
aligned under each ancestor's disclosure/icon column so nested
|
||||
rows read as a tree instead of a flat, ever-further-indented list. */}
|
||||
{Array.from({ length: depth }).map((_, level) => (
|
||||
<span
|
||||
key={level}
|
||||
aria-hidden="true"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: `${8 + level * 16 + 4}px`,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
width: 1,
|
||||
background: 'var(--color-border)',
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Indentation/disclosure indicator */}
|
||||
{allChildren.length > 0 ? (
|
||||
<span style={{ marginRight: 4, fontSize: 8, color: 'var(--color-text-dim)', flexShrink: 0 }}>
|
||||
▼
|
||||
</span>
|
||||
)}
|
||||
{allChildren.length === 0 && (
|
||||
<span style={{ marginRight: 4, fontSize: 8, color: 'transparent' }}>
|
||||
) : (
|
||||
<span style={{ marginRight: 4, fontSize: 8, color: 'transparent', flexShrink: 0 }}>
|
||||
▼
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Component type icon and name */}
|
||||
{/* Component type icon */}
|
||||
<i
|
||||
className={`fa ${icon}`}
|
||||
aria-hidden="true"
|
||||
style={{
|
||||
marginRight: 6,
|
||||
fontSize: 11,
|
||||
width: 12,
|
||||
textAlign: 'center',
|
||||
flexShrink: 0,
|
||||
color: isSelected ? 'var(--color-accent)' : 'var(--color-text-dim)',
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Name */}
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{isRoot ? 'Canvas (Root)' : displayName}
|
||||
</span>
|
||||
|
||||
@@ -58,18 +58,23 @@ export const PagesPanel: React.FC = () => {
|
||||
.replace(/-+/g, '-');
|
||||
};
|
||||
|
||||
/* ---------- Zone button style ---------- */
|
||||
const zoneButtonStyle = (isActive: boolean): React.CSSProperties => ({
|
||||
/* ---------- Zone row style ----------
|
||||
* Same neutral surface language as the page-list rows below (Item 11) --
|
||||
* header/footer are just two more items in the tree, not a louder,
|
||||
* differently-colored category. The active/editing state reuses the same
|
||||
* accent-outline treatment the page list already uses for the active page,
|
||||
* so there's one consistent "this is what's currently open" affordance. */
|
||||
const zoneRowStyle = (isActive: boolean): React.CSSProperties => ({
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
padding: '7px 10px',
|
||||
fontSize: 12,
|
||||
fontWeight: 600,
|
||||
color: isActive ? '#f59e0b' : '#fbbf24',
|
||||
background: isActive ? 'rgba(245, 158, 11, 0.15)' : 'rgba(245, 158, 11, 0.06)',
|
||||
border: `1px solid ${isActive ? 'rgba(245, 158, 11, 0.5)' : 'rgba(245, 158, 11, 0.2)'}`,
|
||||
fontWeight: isActive ? 600 : 500,
|
||||
color: isActive ? 'var(--color-accent)' : 'var(--color-text-muted)',
|
||||
background: isActive ? 'var(--color-accent-subtle)' : 'var(--color-bg-elevated)',
|
||||
border: `1px solid ${isActive ? 'var(--color-accent)' : 'var(--color-border)'}`,
|
||||
borderRadius: 'var(--radius-md)',
|
||||
cursor: 'pointer',
|
||||
transition: 'all var(--transition-fast)',
|
||||
@@ -78,57 +83,35 @@ export const PagesPanel: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{/* Header/Footer zone buttons */}
|
||||
{/* Header/Footer zone rows */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 8 }}>
|
||||
<button
|
||||
onClick={editHeader}
|
||||
style={zoneButtonStyle(isEditingHeader)}
|
||||
className="zone-row"
|
||||
style={zoneRowStyle(isEditingHeader)}
|
||||
title="Appears on all pages"
|
||||
>
|
||||
<i className="fa fa-window-maximize" style={{ fontSize: 13 }} />
|
||||
<div style={{ flex: 1 }}>
|
||||
<div>Edit Header</div>
|
||||
<div style={{ fontSize: 10, opacity: 0.7, fontWeight: 400, marginTop: 1 }}>
|
||||
Appears on all pages
|
||||
</div>
|
||||
</div>
|
||||
{isEditingHeader && (
|
||||
<span style={{
|
||||
fontSize: 9,
|
||||
fontWeight: 700,
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px',
|
||||
background: 'rgba(245, 158, 11, 0.25)',
|
||||
padding: '2px 6px',
|
||||
borderRadius: 'var(--radius-sm)',
|
||||
}}>
|
||||
Editing
|
||||
</span>
|
||||
<i className="fa fa-window-maximize" style={{ fontSize: 12, width: 14, textAlign: 'center', flexShrink: 0 }} />
|
||||
<span style={{ flex: 1 }}>Header</span>
|
||||
{isEditingHeader ? (
|
||||
<i className="fa fa-check-circle" style={{ fontSize: 11 }} aria-hidden />
|
||||
) : (
|
||||
<i className="fa fa-pencil zone-row-pencil" style={{ fontSize: 11 }} aria-hidden />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={editFooter}
|
||||
style={zoneButtonStyle(isEditingFooter)}
|
||||
className="zone-row"
|
||||
style={zoneRowStyle(isEditingFooter)}
|
||||
title="Appears on all pages"
|
||||
>
|
||||
<i className="fa fa-window-minimize" style={{ fontSize: 13 }} />
|
||||
<div style={{ flex: 1 }}>
|
||||
<div>Edit Footer</div>
|
||||
<div style={{ fontSize: 10, opacity: 0.7, fontWeight: 400, marginTop: 1 }}>
|
||||
Appears on all pages
|
||||
</div>
|
||||
</div>
|
||||
{isEditingFooter && (
|
||||
<span style={{
|
||||
fontSize: 9,
|
||||
fontWeight: 700,
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px',
|
||||
background: 'rgba(245, 158, 11, 0.25)',
|
||||
padding: '2px 6px',
|
||||
borderRadius: 'var(--radius-sm)',
|
||||
}}>
|
||||
Editing
|
||||
</span>
|
||||
<i className="fa fa-window-minimize" style={{ fontSize: 12, width: 14, textAlign: 'center', flexShrink: 0 }} />
|
||||
<span style={{ flex: 1 }}>Footer</span>
|
||||
{isEditingFooter ? (
|
||||
<i className="fa fa-check-circle" style={{ fontSize: 11 }} aria-hidden />
|
||||
) : (
|
||||
<i className="fa fa-pencil zone-row-pencil" style={{ fontSize: 11 }} aria-hidden />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
@@ -328,18 +311,21 @@ export const PagesPanel: React.FC = () => {
|
||||
title="This is the landing page — published as the root URL (index.html)"
|
||||
style={{
|
||||
fontSize: 9,
|
||||
fontWeight: 700,
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px',
|
||||
color: '#fbbf24',
|
||||
background: 'rgba(245, 158, 11, 0.15)',
|
||||
border: '1px solid rgba(245, 158, 11, 0.35)',
|
||||
fontWeight: 600,
|
||||
letterSpacing: '0.3px',
|
||||
color: 'var(--color-text-muted)',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--color-border-light)',
|
||||
padding: '1px 5px',
|
||||
borderRadius: 'var(--radius-sm)',
|
||||
flexShrink: 0,
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: 4,
|
||||
}}
|
||||
>
|
||||
<i className="fa fa-home" style={{ marginRight: 3 }} />Landing
|
||||
<i className="fa fa-home" aria-hidden="true" style={{ fontSize: 8, color: 'inherit' }} />
|
||||
Landing
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -359,7 +345,8 @@ export const PagesPanel: React.FC = () => {
|
||||
>
|
||||
<button
|
||||
onClick={() => startEditing(page)}
|
||||
title="Rename"
|
||||
data-tooltip="Rename"
|
||||
aria-label={`Rename ${page.name}`}
|
||||
style={{
|
||||
width: 24,
|
||||
height: 24,
|
||||
@@ -374,12 +361,13 @@ export const PagesPanel: React.FC = () => {
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
✎
|
||||
<i className="fa fa-pencil" aria-hidden="true" />
|
||||
</button>
|
||||
{pages.length > 1 && !isLanding && (
|
||||
<button
|
||||
onClick={() => setDeleteConfirmId(page.id)}
|
||||
title="Delete"
|
||||
data-tooltip="Delete"
|
||||
aria-label={`Delete ${page.name}`}
|
||||
style={{
|
||||
width: 24,
|
||||
height: 24,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import React, { useEffect } from 'react';
|
||||
|
||||
export interface BottomSheetProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="mobile-sheet-backdrop"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
{/* 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}>
|
||||
<div className="mobile-sheet-handle-row">
|
||||
<span className="mobile-sheet-handle" aria-hidden="true" />
|
||||
</div>
|
||||
<div className="mobile-sheet-header">
|
||||
<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">{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>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -10,6 +10,7 @@ export const ChatInput: React.FC<Props> = ({ disabled, placeholder, onSend }) =>
|
||||
<div style={{ display: 'flex', gap: 8, padding: '8px 0' }}>
|
||||
<textarea value={v} onChange={(e) => setV(e.target.value)} onKeyDown={onKey} rows={2} disabled={disabled}
|
||||
placeholder={placeholder || 'Describe what you want...'}
|
||||
className="sitesmith-textarea"
|
||||
style={{
|
||||
flex: 1, background: disabled ? '#1f1f24' : '#0f0f17', color: '#e5e7eb',
|
||||
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}
|
||||
closeOnEscape={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 }}
|
||||
>
|
||||
<div style={panel}>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import { usePages } from '../../state/PageContext';
|
||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
@@ -8,9 +9,10 @@ import {
|
||||
TemplateComponent,
|
||||
TemplateCategory,
|
||||
} from '../../templates';
|
||||
import { componentResolver } from '../../components/resolver';
|
||||
import { clickableProps } from '../../utils/a11y';
|
||||
import { Modal } from '../../ui/Modal';
|
||||
import { buildNodeTree } from '../../utils/craft-tree';
|
||||
import { templateComponentToTreeNode } from '../../templates/apply-template';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
@@ -77,28 +79,31 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
||||
return allTemplates.filter((t) => t.category === 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.
|
||||
* 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(
|
||||
(components: TemplateComponent[]) => {
|
||||
for (const comp of components) {
|
||||
const Component = resolverMap[comp.type];
|
||||
if (!Component) {
|
||||
console.warn(`Template references unknown component type: ${comp.type}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const element = React.createElement(Component, comp.props);
|
||||
const tree = query.parseReactElement(element).toNodeTree();
|
||||
try {
|
||||
const tree = buildNodeTree(query, templateComponentToTreeNode(comp));
|
||||
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]);
|
||||
|
||||
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}>
|
||||
<div style={modalStyle}>
|
||||
{/* Header */}
|
||||
@@ -247,21 +259,39 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
||||
Choose a template to get started quickly
|
||||
</p>
|
||||
</div>
|
||||
<button onClick={onClose} style={closeButtonStyle} title="Close">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="template-modal-close-btn"
|
||||
style={closeButtonStyle}
|
||||
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)'; }}
|
||||
onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.background = 'transparent'; (e.currentTarget as HTMLElement).style.color = '#71717a'; }}
|
||||
>
|
||||
<i className="fa fa-times" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filter Tabs */}
|
||||
<div style={tabBarStyle}>
|
||||
{/* Filter Tabs -- horizontally scrollable (tabBarStyle sets
|
||||
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) => (
|
||||
<button
|
||||
key={tab.value}
|
||||
className="template-modal-tab-btn"
|
||||
onClick={() => setActiveTab(tab.value)}
|
||||
style={{
|
||||
...tabStyle,
|
||||
...(activeTab === tab.value ? tabActiveStyle : {}),
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (activeTab !== tab.value) (e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
if (activeTab !== tab.value) (e.currentTarget as HTMLElement).style.background = 'transparent';
|
||||
}}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
@@ -359,7 +389,8 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
</Modal>,
|
||||
document.body,
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -4,18 +4,24 @@ import { useEditorConfig } from '../../state/EditorConfigContext';
|
||||
import { useWhpApi } from '../../hooks/useWhpApi';
|
||||
import { usePages } from '../../state/PageContext';
|
||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||
import { useMobileChrome } from '../../state/MobileChromeContext';
|
||||
import { DeviceMode } from '../../types';
|
||||
import { TemplateModal } from './TemplateModal';
|
||||
import { HeadCodeModal } from './HeadCodeModal';
|
||||
import { TopBarOverflowMenu } from './TopBarOverflowMenu';
|
||||
import { SitesmithButton } from '../sitesmith/SitesmithButton';
|
||||
import { useSitesmithModal } from '../../state/SitesmithContext';
|
||||
|
||||
interface TopBarProps {
|
||||
device: DeviceMode;
|
||||
onDeviceChange: (device: DeviceMode) => void;
|
||||
/** Item 10: canvas dashed guide outlines, default ON. */
|
||||
showGuides: boolean;
|
||||
onToggleGuides: () => void;
|
||||
}
|
||||
|
||||
export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
||||
export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuides, onToggleGuides }) => {
|
||||
const { whpConfig, isWHP } = useEditorConfig();
|
||||
const { actions, query, canUndo, canRedo } = useEditor((_state, query) => ({
|
||||
canUndo: query.history.canUndo(),
|
||||
@@ -28,8 +34,11 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
||||
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
|
||||
const [publishStatus, setPublishStatus] = useState<'idle' | 'publishing' | 'published' | 'error'>('idle');
|
||||
const [isDraft, setIsDraft] = useState(false);
|
||||
const [templateModalOpen, setTemplateModalOpen] = useState(false);
|
||||
const [headCodeModalOpen, setHeadCodeModalOpen] = useState(false);
|
||||
// Mobile-A2: lifted from private useState into MobileChromeContext so
|
||||
// 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 saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const publishTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
@@ -119,52 +128,9 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<nav className="topbar">
|
||||
<div className="topbar-left">
|
||||
{isWHP && (
|
||||
<a href={whpConfig!.backUrl} className="topbar-btn back-btn" aria-label="Back to Panel">
|
||||
<i className="fa fa-arrow-left" /> Back to Panel
|
||||
</a>
|
||||
)}
|
||||
<span className="topbar-title">Site Builder</span>
|
||||
{isWHP && (
|
||||
<span className="topbar-domain">{whpConfig!.siteDomain}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="topbar-center">
|
||||
<div className="device-switcher">
|
||||
{(['desktop', 'tablet', 'mobile'] as DeviceMode[]).map((d) => (
|
||||
<button
|
||||
key={d}
|
||||
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>
|
||||
|
||||
<div className="topbar-right">
|
||||
<button className="topbar-btn" onClick={() => actions.history.undo()} disabled={!canUndo} title="Undo" aria-label="Undo">
|
||||
<i className="fa fa-undo" />
|
||||
</button>
|
||||
<button className="topbar-btn" onClick={() => actions.history.redo()} disabled={!canRedo} title="Redo" aria-label="Redo">
|
||||
<i className="fa fa-repeat" />
|
||||
</button>
|
||||
<span className="topbar-divider" />
|
||||
<button className="topbar-btn" title="Templates" aria-label="Templates" onClick={() => setTemplateModalOpen(true)}>
|
||||
<i className="fa fa-th-large" /> Templates
|
||||
</button>
|
||||
<button className="topbar-btn" title="Custom Head Code" aria-label="Custom Head Code" onClick={() => setHeadCodeModalOpen(true)}>
|
||||
<i className="fa fa-code" /> Code
|
||||
</button>
|
||||
<button className="topbar-btn" title="Preview" aria-label="Preview" onClick={() => {
|
||||
// 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 }) => {
|
||||
@@ -217,8 +183,163 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
||||
} catch (e) {
|
||||
console.error('Preview failed:', e);
|
||||
}
|
||||
}}>
|
||||
<i className="fa fa-eye" /> Preview
|
||||
}, [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 (
|
||||
<nav className="topbar">
|
||||
<div className="topbar-left">
|
||||
{isWHP && (
|
||||
<a href={whpConfig!.backUrl} className="topbar-btn back-btn" aria-label="Back to Panel">
|
||||
<i className="fa fa-arrow-left" /> Back to Panel
|
||||
</a>
|
||||
)}
|
||||
<span className="topbar-title">Site Builder</span>
|
||||
{isWHP && (
|
||||
<span className="topbar-domain">{whpConfig!.siteDomain}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="topbar-center">
|
||||
<div className="device-switcher">
|
||||
{(['desktop', 'tablet', 'mobile'] as DeviceMode[]).map((d) => (
|
||||
<button
|
||||
key={d}
|
||||
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>
|
||||
<button
|
||||
type="button"
|
||||
className={`topbar-btn guides-toggle icon-only${showGuides ? ' active' : ''}`}
|
||||
onClick={onToggleGuides}
|
||||
aria-pressed={showGuides}
|
||||
aria-label={showGuides ? 'Hide canvas guides' : 'Show canvas guides'}
|
||||
data-tooltip={showGuides ? 'Hide guides' : 'Show guides'}
|
||||
>
|
||||
<i className={`fa ${showGuides ? 'fa-th' : 'fa-th-large'}`} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="topbar-right">
|
||||
<button className="topbar-btn" onClick={() => actions.history.undo()} disabled={!canUndo} title="Undo" aria-label="Undo">
|
||||
<i className="fa fa-undo" />
|
||||
</button>
|
||||
<button className="topbar-btn" onClick={() => actions.history.redo()} disabled={!canRedo} title="Redo" aria-label="Redo">
|
||||
<i className="fa fa-repeat" />
|
||||
</button>
|
||||
<span className="topbar-divider" />
|
||||
<button className="topbar-btn" title="Templates" aria-label="Templates" onClick={() => setTemplateModalOpen(true)}>
|
||||
<i className="fa fa-th-large" /> Templates
|
||||
</button>
|
||||
<button
|
||||
className="topbar-btn icon-only"
|
||||
aria-label="Custom Head Code"
|
||||
data-tooltip="Code"
|
||||
onClick={() => setHeadCodeModalOpen(true)}
|
||||
>
|
||||
<i className="fa fa-code" />
|
||||
</button>
|
||||
<button className="topbar-btn icon-only" aria-label="Preview" data-tooltip="Preview" onClick={handlePreview}>
|
||||
<i className="fa fa-eye" />
|
||||
</button>
|
||||
|
||||
{/* Draft/Published status badge */}
|
||||
|
||||
@@ -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>;
|
||||
};
|
||||
@@ -119,6 +119,13 @@ export function treeToCraftState(tree: SerializedTreeNode): string {
|
||||
// Container), so there was no menu to edit and the empty zone rendered as a
|
||||
// stray band above the page. Seeding a real Navbar gives every new site an
|
||||
// editable menu-with-links out of the box (and removes the empty-header gap).
|
||||
//
|
||||
// Item 15: the nav used to link Home/About/Services/Contact, but a brand
|
||||
// new site only has a "Home" page -- About/Services/Contact were dead links
|
||||
// on first click. Rather than seeding three empty placeholder pages nobody
|
||||
// asked for, the simpler default is a nav with just the one real page (Home)
|
||||
// plus a CTA button, which is inert (`href: '#'`) rather than pointing at a
|
||||
// page that doesn't exist. Users add pages/links as their site grows.
|
||||
// Node shape matches treeToCraftState() / Craft's actions.deserialize().
|
||||
export const DEFAULT_HEADER_STATE = JSON.stringify({
|
||||
ROOT: {
|
||||
@@ -144,9 +151,7 @@ export const DEFAULT_HEADER_STATE = JSON.stringify({
|
||||
logoFontSize: '20px',
|
||||
links: [
|
||||
{ text: 'Home', href: '/' },
|
||||
{ text: 'About', href: '#about' },
|
||||
{ text: 'Services', href: '#services' },
|
||||
{ text: 'Contact', href: '#contact', isCta: true },
|
||||
{ text: 'Get Started', href: '#', isCta: true },
|
||||
],
|
||||
backgroundColor: '#ffffff',
|
||||
textColor: '#3f3f46',
|
||||
|
||||
@@ -23,8 +23,14 @@ describe('DEFAULT_HEADER_STATE seed', () => {
|
||||
const { html } = exportBodyHtml(DEFAULT_HEADER_STATE);
|
||||
expect(html).toContain('<nav');
|
||||
expect(html).toContain('MySite');
|
||||
for (const link of ['Home', 'About', 'Services', 'Contact']) {
|
||||
// Item 15: the default nav only links pages/anchors that actually exist
|
||||
// on a brand new site (just "Home") plus an inert CTA -- no dead links
|
||||
// to About/Services/Contact pages that were never seeded.
|
||||
for (const link of ['Home', 'Get Started']) {
|
||||
expect(html).toContain(link);
|
||||
}
|
||||
expect(html).not.toContain('About');
|
||||
expect(html).not.toContain('Services');
|
||||
expect(html).not.toContain('Contact');
|
||||
});
|
||||
});
|
||||
|
||||
+478
-44
@@ -31,6 +31,27 @@
|
||||
--radius-lg: 8px;
|
||||
--transition-fast: 0.15s 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;
|
||||
|
||||
/* 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);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
@@ -136,7 +157,7 @@ body {
|
||||
color: var(--color-text);
|
||||
background: transparent;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 20px;
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: background var(--transition-fast), border-color var(--transition-fast),
|
||||
@@ -198,6 +219,19 @@ body {
|
||||
margin: 0 4px;
|
||||
}
|
||||
|
||||
/* Icon-only topbar buttons (Show Guides, Code, Preview) -- square-ish
|
||||
footprint instead of the label+icon pill, tooltip via [data-tooltip]. */
|
||||
.topbar-btn.icon-only {
|
||||
gap: 0;
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.topbar-btn.guides-toggle.active {
|
||||
color: var(--color-accent);
|
||||
background: var(--color-accent-subtle);
|
||||
border-color: var(--color-accent);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
Device Switcher
|
||||
-------------------------------------------------------------------------- */
|
||||
@@ -1002,63 +1036,80 @@ body {
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
Editor Visual Guides — dashed outlines for containers/columns/sections
|
||||
Editor Visual Guides — dashed outlines for real drop targets only
|
||||
-------------------------------------------------------------------------- */
|
||||
|
||||
/* All block-level elements in the canvas get a subtle dashed border */
|
||||
.canvas-device-frame div,
|
||||
.canvas-device-frame section,
|
||||
.canvas-device-frame header,
|
||||
.canvas-device-frame footer,
|
||||
.canvas-device-frame main,
|
||||
.canvas-device-frame article,
|
||||
.canvas-device-frame nav,
|
||||
.canvas-device-frame form {
|
||||
/* Only actual Craft.js droppable containers get a guide outline -- these are
|
||||
tagged with `data-craft-node` in RenderNode.tsx (the `<Editor onRender>`
|
||||
override) based on `node.data.isCanvas`, not a blanket tag selector. A
|
||||
component's own internal wrapper `<div>`s (e.g. Section's inner max-width
|
||||
container) are real DOM elements but not Craft nodes, so they never get
|
||||
this attribute and never get a guide outline -- this is what stops
|
||||
finished sections from showing 3-4 nested dashed boxes. */
|
||||
.canvas-device-frame [data-craft-node] {
|
||||
outline: 1px dashed rgba(148, 163, 184, 0.2);
|
||||
outline-offset: -1px;
|
||||
transition: outline-color 0.15s;
|
||||
}
|
||||
|
||||
/* Don't outline the outermost root wrapper or tiny utility divs */
|
||||
.canvas-device-frame > div {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* Rows (flex containers) get a slightly more visible border */
|
||||
.canvas-device-frame div[style*="display: flex"],
|
||||
.canvas-device-frame div[style*="display:flex"] {
|
||||
.canvas-device-frame [data-craft-node][style*="display: flex"],
|
||||
.canvas-device-frame [data-craft-node][style*="display:flex"] {
|
||||
outline: 1px dashed rgba(148, 163, 184, 0.35);
|
||||
}
|
||||
|
||||
/* Empty containers: more visible + minimum height so they're clickable */
|
||||
.canvas-device-frame div:empty,
|
||||
.canvas-device-frame section:empty,
|
||||
.canvas-device-frame main:empty,
|
||||
.canvas-device-frame header:empty,
|
||||
.canvas-device-frame footer:empty {
|
||||
.canvas-device-frame [data-craft-node]:empty {
|
||||
outline: 2px dashed rgba(148, 163, 184, 0.4);
|
||||
min-height: 60px;
|
||||
}
|
||||
|
||||
/* Hover highlights */
|
||||
.canvas-device-frame div:hover,
|
||||
.canvas-device-frame section:hover,
|
||||
.canvas-device-frame header:hover,
|
||||
.canvas-device-frame footer:hover,
|
||||
.canvas-device-frame main:hover,
|
||||
.canvas-device-frame nav:hover {
|
||||
.canvas-device-frame [data-craft-node]:hover {
|
||||
outline-color: rgba(59, 130, 246, 0.5);
|
||||
}
|
||||
|
||||
/* Header/footer zones get a distinct amber color */
|
||||
.canvas-device-frame [data-zone="header"],
|
||||
.canvas-device-frame [data-zone="footer"] {
|
||||
outline: 1px dashed rgba(245, 158, 11, 0.4);
|
||||
/* `data-craft-hovered` is set (presence, no value) in RenderNode.tsx,
|
||||
mirroring Craft's own `hovered` node event. Craft.js's `connectors.connect()`
|
||||
(called by every component) wires that event to a native
|
||||
mouseover/mouseleave listener on each node's dom internally, so this
|
||||
rule is a real mouse-hover highlight for any node (container or leaf).
|
||||
Scoped under `.canvas-device-frame` and suppressed by `.guides-off` so
|
||||
"Show guides: off" stays airtight. */
|
||||
.canvas-device-frame [data-craft-hovered] {
|
||||
outline: 2px dashed var(--color-accent) !important;
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
.canvas-device-frame [data-zone="header"]:hover,
|
||||
.canvas-device-frame [data-zone="footer"]:hover {
|
||||
outline-color: rgba(245, 158, 11, 0.7);
|
||||
/* `data-layer-hovered` is set directly by the Layers panel (LayersPanel.tsx)
|
||||
on its own row hover/focus -- a separate producer (writing straight to the
|
||||
target's dom rather than through Craft's `hovered` event, since the
|
||||
action that drives it is stripped from the public `useEditor()` API at
|
||||
runtime) that drives a highlight when hovering a layer row. This is a
|
||||
deliberate locator action (not a structural drop-target guide), so it
|
||||
uses a SOLID outline -- visually distinct from the dashed structural
|
||||
guides -- and is intentionally NOT suppressed by `.guides-off`: hiding
|
||||
guides shouldn't blind the Layers-panel hover→canvas locator. */
|
||||
.canvas-device-frame [data-layer-hovered] {
|
||||
outline: 2px solid var(--color-accent) !important;
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
/* "Show guides" topbar toggle (TopBar.tsx) -- flips this class on
|
||||
.canvas-device-frame to hide structural drop-target guides and the
|
||||
mouse-hover highlight at once. Default ON. `[data-layer-hovered]` is
|
||||
deliberately excluded -- see rule above. */
|
||||
.canvas-device-frame.guides-off [data-craft-node],
|
||||
.canvas-device-frame.guides-off [data-craft-hovered] {
|
||||
outline: none !important;
|
||||
}
|
||||
|
||||
/* Header/footer zone-preview separator (Canvas.tsx ZonePreview) -- a neutral
|
||||
dashed rule marking where the editable page meets the read-only
|
||||
header/footer preview. It's a structural guide, so it hides with the
|
||||
rest when "Show guides" is off. */
|
||||
.canvas-device-frame.guides-off .zone-preview-sep {
|
||||
border-color: transparent !important;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
@@ -1069,11 +1120,6 @@ body {
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
.craftjs-renderer [data-hovered="true"] {
|
||||
outline: 1px dashed var(--color-accent) !important;
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
/* Component indicator badge (floats over the selected node via a portal --
|
||||
position/top/left are set inline per-node, see RenderNode.tsx) */
|
||||
.component-indicator {
|
||||
@@ -1153,6 +1199,21 @@ body {
|
||||
scrollbar-color: var(--color-border) transparent;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
Pages Panel — Header/Footer zone rows (Item 11)
|
||||
Compact rows in the same neutral surface language as the page list, with
|
||||
a pencil hint that only appears on hover instead of a permanently-loud
|
||||
"Editing" pill.
|
||||
-------------------------------------------------------------------------- */
|
||||
.zone-row-pencil {
|
||||
opacity: 0;
|
||||
transition: opacity var(--transition-fast);
|
||||
}
|
||||
|
||||
.zone-row:hover .zone-row-pencil {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
Tooltip
|
||||
-------------------------------------------------------------------------- */
|
||||
@@ -1183,6 +1244,16 @@ body {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Topbar sits flush against the top of the viewport (`body { overflow:
|
||||
hidden }`), so the default "tooltip above the trigger" placement gets
|
||||
clipped off-screen for topbar buttons -- flip those to render below
|
||||
instead. Left-panel/canvas tooltips keep the default above placement,
|
||||
which has room to render there. */
|
||||
.topbar [data-tooltip]::after {
|
||||
bottom: auto;
|
||||
top: calc(100% + 6px);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
Notifications / Toasts
|
||||
-------------------------------------------------------------------------- */
|
||||
@@ -1327,13 +1398,376 @@ body {
|
||||
}
|
||||
|
||||
@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-right {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.topbar-btn span,
|
||||
.topbar-domain {
|
||||
display: none;
|
||||
/* --------------------------------------------------------------------
|
||||
Viewport sizing -- dynamic viewport height accounts for mobile
|
||||
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);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------
|
||||
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. */
|
||||
bottom: calc(var(--mobile-tabbar-height) + env(safe-area-inset-bottom, 0px));
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
z-index: var(--z-sheet-backdrop);
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.mobile-sheet {
|
||||
width: 100%;
|
||||
max-height: 65vh;
|
||||
max-height: 65dvh;
|
||||
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;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------
|
||||
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),
|
||||
};
|
||||
}
|
||||
@@ -31,7 +31,10 @@ const defaultBackdropStyle: React.CSSProperties = {
|
||||
display: 'flex',
|
||||
alignItems: '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 ----------
|
||||
@@ -77,6 +80,7 @@ export const Modal: React.FC<ModalProps> = ({
|
||||
|
||||
return (
|
||||
<div
|
||||
className="modal-backdrop"
|
||||
{...backdropProps}
|
||||
style={backdropStyle ? { ...defaultBackdropStyle, ...backdropStyle } : defaultBackdropStyle}
|
||||
onClick={(e) => {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import type { NodeTree } from '@craftjs/core';
|
||||
import { usePages } from '../state/PageContext';
|
||||
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
|
||||
// this module — the implementation now lives in craft-tree.ts alongside the
|
||||
// shared flattener, since treeToState (PageContext.tsx) needs the same
|
||||
// validation this module pioneered.
|
||||
export { sanitizeAiTree };
|
||||
// Re-exported for existing callers/tests that import sanitizeAiTree/
|
||||
// buildNodeTree from this module — the implementation lives in craft-tree.ts
|
||||
// alongside the shared flattener: `templates/apply-template.ts` needs the
|
||||
// exact same tree-materialization logic to load template header/footer/page
|
||||
// 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.
|
||||
@@ -18,52 +18,6 @@ export { sanitizeAiTree };
|
||||
*/
|
||||
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.
|
||||
* Checks `data.props.node_id` first, then falls back to raw id equality.
|
||||
|
||||
@@ -225,6 +225,105 @@ export function flattenTreeForCraft(tree: SerializedTreeNode): FlattenTreeResult
|
||||
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
|
||||
* (rootNodeId, the `nodes` map keys, each `node.id`, each internal
|
||||
|
||||
Reference in New Issue
Block a user