feat(site-builder): per-breakpoint style model, device context and responsive export

- utils/breakpoints.ts: single source for 767/768/991/992; head
  VISIBILITY/RESPONSIVE CSS built from it (flex-stacking rule moved from
  768 to the 767 mobile boundary).
- utils/responsive-style.ts: styleTablet/styleMobile partial overrides,
  cascade resolution, pure setters, scoped @media CSS per node.
- state/DeviceContext.tsx: real DeviceProvider (owns the one-time mobile
  forcing from EditorShell); TopBar, overflow menu, ReportIssueModal and
  Canvas read useDevice() instead of props.
- editor/RenderNode.tsx: resolves the effective style for the current
  device in one place and marks overridden nodes with data-wsb-overridden.
  Craft passes an opaque <DefaultRender/> to onRender, so the component
  element is rebuilt with the resolved style (cloneElement cannot work).
- utils/html-export.ts: hidden nodes skipped; overrides emitted as one
  body-level <style data-wsb-responsive> block + data-wsb-r scope attr;
  injectAttrs skips leading <style> elements.
- test-utils/editorHarness.tsx: optional onRender/wrap options.

Refs #45
Refs #37

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Opus 5.5 committed 2026-10-07 11:28:44 -07:00
1 parent 2180f9a776
commit 5f99df23a7
24 files changed
+1006 -92

No files matched your search

+3 -3
View File
@@ -2,14 +2,13 @@ import React, { useMemo, useRef, useEffect } from 'react';
import { Frame, Element, useEditor } from '@craftjs/core';
import { Container } from '../components/layout/Container';
import { usePages } from '../state/PageContext';
import { DeviceMode } from '../types';
import { useDevice } from '../state/DeviceContext';
import { DEVICE_WIDTHS } from '../constants/presets';
import { exportBodyHtml } from '../utils/html-export';
import { useIsMobile } from '../hooks/useIsMobile';
import { useMobileChrome } from '../state/MobileChromeContext';
interface CanvasProps {
device: DeviceMode;
/** Item 10: when false, applies `.guides-off` to hide the dashed drop-target guides. */
showGuides: boolean;
}
@@ -130,7 +129,8 @@ export const EmptyCanvasHint: React.FC = () => {
);
};
export const Canvas: React.FC<CanvasProps> = ({ device, showGuides }) => {
export const Canvas: React.FC<CanvasProps> = ({ showGuides }) => {
const { device } = useDevice();
const width = DEVICE_WIDTHS[device];
const { isEditingHeader, isEditingFooter, headerPage, footerPage } = usePages();
+16 -22
View File
@@ -1,4 +1,4 @@
import React, { useState, useCallback, useEffect, useRef } from 'react';
import React, { useState, useCallback } from 'react';
import { useEditor } from '@craftjs/core';
import { TopBar } from '../panels/topbar/TopBar';
import { LeftPanel } from '../panels/left/LeftPanel';
@@ -14,7 +14,7 @@ import { MobileChromeProvider } from '../state/MobileChromeContext';
import { LayerFocusProvider } from '../panels/left/LayerFocusContext';
import { LoadGate } from './LoadGate';
import { DirtyTracker } from './DirtyTracker';
import { DeviceMode } from '../types';
import { DeviceProvider } from '../state/DeviceContext';
const SHOW_GUIDES_STORAGE_KEY = 'craft-show-guides';
@@ -27,28 +27,24 @@ function loadShowGuides(): boolean {
}
}
export const EditorShell: React.FC = () => {
/**
* DeviceProvider sits OUTSIDE the shell body so every hook the body calls
* (keyboard shortcuts, commands) sees the shared device, not the default.
*/
export const EditorShell: React.FC = () => (
<DeviceProvider>
<EditorShellBody />
</DeviceProvider>
);
const EditorShellBody: 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.
// `.canvas-device-frame`. (The device mode itself is shared through
// DeviceContext -- see the EditorShell wrapper above.)
const [showGuides, setShowGuidesState] = useState<boolean>(loadShowGuides);
const setShowGuides = useCallback((next: boolean) => {
setShowGuidesState(next);
@@ -91,15 +87,13 @@ export const EditorShell: React.FC = () => {
<LoadGate />
<DirtyTracker />
<TopBar
device={device}
onDeviceChange={setDevice}
showGuides={showGuides}
onToggleGuides={() => setShowGuides(!showGuides)}
/>
<div className="editor-container">
{!isMobile && <LeftPanel />}
<div onContextMenu={handleContextMenu} style={{ flex: 1, display: 'flex', minWidth: 0 }}>
<Canvas device={device} showGuides={showGuides} />
<Canvas showGuides={showGuides} />
</div>
{!isMobile && <RightPanel />}
</div>
+1 -1
View File
@@ -72,7 +72,7 @@ function mount() {
<SiteDesignProvider>
<PageProvider>
<LoadGate />
<TopBar device="desktop" onDeviceChange={() => {}} showGuides onToggleGuides={() => {}} />
<TopBar showGuides onToggleGuides={() => {}} />
<SiteDesignPanel />
<GuardProbe />
</PageProvider>
@@ -71,7 +71,7 @@ function mount() {
<SiteDesignProvider>
<PageProvider>
<LoadGate />
<TopBar device="desktop" onDeviceChange={() => {}} showGuides onToggleGuides={() => {}} />
<TopBar showGuides onToggleGuides={() => {}} />
<SiteDesignPanel />
<GuardProbe />
</PageProvider>
@@ -0,0 +1,118 @@
import { describe, test, expect, afterEach } from 'vitest';
import React from 'react';
import { renderEditorHarness, EditorHarness } from '../test-utils/editorHarness';
import { DeviceProvider, useDevice } from '../state/DeviceContext';
import { RenderNode } from './RenderNode';
import type { DeviceMode } from '../types';
/**
* Real-editor tests (no @craftjs/core mock -- RenderNode.test.tsx mocks it
* for the badge tests, and vi.mock is file-wide): the actual RenderNode is
* installed as `<Editor onRender>` under a real DeviceProvider, so the
* per-device style resolution runs against Craft's real render pipeline.
*/
const node = (type: string, props: Record<string, unknown>, nodes: string[] = [], extra: Record<string, unknown> = {}) => ({
type: { resolvedName: type },
isCanvas: type === 'Container',
props,
displayName: type,
custom: {},
hidden: false,
nodes,
linkedNodes: {},
...extra,
});
const state = (headingProps: Record<string, unknown>) =>
JSON.stringify({
ROOT: node('Container', { tag: 'div', style: {} }, ['sec1']),
sec1: node('Container', { tag: 'section', style: { padding: '20px' } }, ['head1'], { parent: 'ROOT' }),
head1: node('Heading', { text: 'Hello', level: 'h2', style: { fontSize: '40px' }, ...headingProps }, [], {
parent: 'sec1',
}),
});
let h: EditorHarness | null = null;
let setDevice: (d: DeviceMode) => void = () => {};
const DeviceGrab: React.FC = () => {
setDevice = useDevice().setDevice;
return null;
};
function mount(initialState: string, device: DeviceMode) {
h = renderEditorHarness({
initialState,
onRender: RenderNode,
wrap: (tree) => (
<DeviceProvider initialDevice={device}>
<DeviceGrab />
{tree}
</DeviceProvider>
),
});
return h;
}
const h2 = () => h!.container.querySelector('h2') as HTMLElement;
afterEach(() => {
h?.unmount();
h = null;
});
describe('RenderNode per-device style resolution (real editor)', () => {
test('mobile: a styleMobile override is applied to the rendered element', () => {
mount(state({ styleMobile: { textAlign: 'center' } }), 'mobile');
expect(h2().getAttribute('style')).toContain('text-align: center');
expect(h2().style.fontSize).toBe('40px');
});
test('desktop: the same node renders its desktop style only', () => {
mount(state({ styleMobile: { textAlign: 'center' } }), 'desktop');
expect(h2().getAttribute('style') || '').not.toContain('text-align');
expect(h2().hasAttribute('data-wsb-overridden')).toBe(false);
});
test('tablet: tablet override applies; mobile inherits it and layers its own', () => {
mount(state({ styleTablet: { fontSize: '32px' }, styleMobile: { textAlign: 'center' } }), 'tablet');
expect(h2().style.fontSize).toBe('32px');
expect(h2().style.textAlign).toBe('');
h!.act(() => setDevice('mobile'));
expect(h2().style.fontSize).toBe('32px');
expect(h2().style.textAlign).toBe('center');
h!.act(() => setDevice('desktop'));
expect(h2().style.fontSize).toBe('40px');
expect(h2().style.textAlign).toBe('');
});
test('data-wsb-overridden marks nodes overridden on the current device only', () => {
mount(state({ styleMobile: { textAlign: 'center' } }), 'mobile');
expect(h2().hasAttribute('data-wsb-overridden')).toBe(true);
h!.act(() => setDevice('tablet'));
expect(h2().hasAttribute('data-wsb-overridden')).toBe(false);
});
test('canvas children of an overridden container still render', () => {
const s = JSON.parse(state({}));
s.sec1.props.styleMobile = { padding: '4px' };
mount(JSON.stringify(s), 'mobile');
const section = h!.container.querySelector('section') as HTMLElement;
expect(section.style.padding).toBe('4px');
expect(section.querySelector('h2')).not.toBeNull();
expect(h2().textContent).toBe('Hello');
});
test('a prop edit through real actions.setProp is reflected on the mobile canvas', () => {
mount(state({}), 'mobile');
expect(h2().style.textAlign).toBe('');
h!.act(() => {
h!.actions.setProp('head1', (p: any) => {
p.styleMobile = { textAlign: 'right' };
});
});
expect(h2().style.textAlign).toBe('right');
// desktop style untouched in the serialized state
expect(JSON.parse(h!.getSerialized()).head1.props.style).toEqual({ fontSize: '40px' });
});
});
+76 -11
View File
@@ -1,6 +1,8 @@
import React, { useCallback, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { useEditor, useNode } from '@craftjs/core';
import { NodeElement, useEditor, useNode } from '@craftjs/core';
import { useDevice } from '../state/DeviceContext';
import { hasAnyOverride, resolveStyleForDevice, overrideFor, type ResponsiveProps } from '../utils/responsive-style';
interface RenderNodeProps {
render: React.ReactElement;
@@ -34,17 +36,48 @@ interface RenderNodeProps {
* -- `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`.
* - `data-wsb-overridden`: set while the current device mode (tablet/
* mobile, from DeviceContext) has per-breakpoint overrides for this node
* -- i.e. the canvas is showing something other than the desktop style.
*
* Per-breakpoint styles (#45/#37): when the device is not desktop and the
* node carries `styleTablet`/`styleMobile`, this is the ONE place the
* effective style is resolved (`resolveStyleForDevice`), so no component
* needs to know about devices. Craft hands `onRender` an opaque
* `<DefaultRender/>` element that reads the node's props itself, so the
* override cannot be applied with `cloneElement(render, {style})` -- instead
* the component element is rebuilt here exactly as Craft's DefaultRender
* does (`createElement(type, props, <NodeElement/> children)`) with the
* resolved `style`. Nodes without overrides, and every node on desktop,
* keep Craft's own `render` untouched.
*/
export const RenderNode: React.FC<RenderNodeProps> = ({ render }) => {
const { actions } = useEditor();
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 { device } = useDevice();
const { id, isSelected, dom, name, parent, isCanvas, isHovered, overridden } = useNode((node) => {
// Keep the collector cheap: the node's type/props/children are only
// collected for the (rare) nodes that actually carry overrides.
const props = node.data.props as ResponsiveProps | undefined;
const overridden = hasAnyOverride(props)
? { type: node.data.type, props: node.data.props, childIds: node.data.nodes }
: null;
return {
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,
overridden,
};
});
// Overrides that apply on the current device (mobile inherits tablet's).
const activeOverride =
device !== 'desktop' &&
!!overridden &&
(Object.keys(overrideFor(overridden.props, device)).length > 0 ||
(device === 'mobile' && Object.keys(overrideFor(overridden.props, 'tablet')).length > 0));
const badgeRef = useRef<HTMLDivElement>(null);
const active = isSelected && id !== 'ROOT' && !!dom;
@@ -86,11 +119,43 @@ export const RenderNode: React.FC<RenderNodeProps> = ({ render }) => {
}
}, [dom, isHovered]);
if (!active) return <>{render}</>;
useEffect(() => {
if (!dom) return;
if (activeOverride) {
dom.setAttribute('data-wsb-overridden', '');
} else {
dom.removeAttribute('data-wsb-overridden');
}
}, [dom, activeOverride]);
let output: React.ReactElement = render;
// String-typed (plain DOM) nodes go through Craft's own SimpleElement
// connector wrapper, which is not exported -- leave those untouched. Every
// resolver component is a React component, so this only skips raw tags.
if (device !== 'desktop' && overridden && typeof overridden.type !== 'string') {
const { type, props, childIds } = overridden;
const children =
childIds && childIds.length > 0 ? (
<>
{childIds.map((childId: string) => (
<NodeElement id={childId} key={childId} />
))}
</>
) : (
props.children
);
output = React.createElement(
type as React.ElementType,
{ ...props, style: resolveStyleForDevice(props as ResponsiveProps, device) },
children,
);
}
if (!active) return <>{output}</>;
return (
<>
{render}
{output}
{createPortal(
<div ref={badgeRef} className="component-indicator" style={{ position: 'fixed' }}>
<span>{name}</span>
+1 -1
View File
@@ -112,7 +112,7 @@ async function mount() {
<LoadGate />
<DirtyTracker />
<Probe />
<TopBar device="desktop" onDeviceChange={() => {}} showGuides onToggleGuides={() => {}} />
<TopBar showGuides onToggleGuides={() => {}} />
</PageProvider>
</SiteDesignProvider>
</SaveGuardProvider>
+1 -1
View File
@@ -96,7 +96,7 @@ async function mount() {
<LoadGate />
<DirtyTracker />
<Probe />
<TopBar device="desktop" onDeviceChange={() => {}} showGuides onToggleGuides={() => {}} />
<TopBar showGuides onToggleGuides={() => {}} />
</PageProvider>
</SiteDesignProvider>
</SaveGuardProvider>