Compare commits

..
Author SHA1 Message Date
shadowdaoandClaude Opus 4.8 0291ddce9a feat(site-builder): per-page SEO meta + favicon + design-token CSS-var wiring + published-output a11y/perf
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 07:14:56 -07:00
jknapp f7da654c11 Merge PR #20: enh nav 2026-07-14 13:58:11 +00:00
shadowdaoandClaude Opus 4.8 54572f648a feat(builder): nav/menu link-to-page picker, page sync, download attr, box-model rollout
NavStylePanel (Navbar/Menu/Logo/Footer):
- LinkPicker: dropdown of the site's pages (read-only via usePages()) plus
  manual URL / #anchor / tel: / mailto: entry, wired into every link-href
  field (standalone Logo href, Navbar logoUrl, Navbar/Menu link items).
- "Sync links with Pages" button in the Links section: repopulates the
  links array from the current pages list (label = page name, href = '/'
  for the landing page else '/{slug}'), preserving any existing CTA link.
  Regression-fix vs the legacy GrapesJS builder, which had this.
- `download` checkbox per link (Navbar/Menu links, standalone Logo href)
  emits the `download` attribute on export for links to files.
- Links/Colors sections now gate on the component actually carrying a
  `links`/color prop, so Footer (no links array) no longer shows a dead
  "Add Link" editor.
- Box-model (Margin/Padding via SpacingControl, Border & Effects via
  BorderControl + box-shadow presets + opacity), AnimationControl, and
  VisibilityControl added for all four owned components, backed by new
  animation/animationDelay/hideOnDesktop/hideOnTablet/hideOnMobile props
  (with blank/default values in each component's .craft.props).

Tests: NavStylePanel.test.tsx (new, 17 tests: LinkPicker modes, sync
preserves CTA, download toggle, box-model/animation/visibility wiring) +
extended Navbar/Menu/Logo/Footer .toHtml.test.ts (download attribute,
craft.props defaults). Full suite: 683/683 passing. `npm run build` green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:47:59 -07:00
23 changed files with 1747 additions and 31 deletions
@@ -20,3 +20,14 @@ describe('Footer.toHtml text escaping (attacker-controlled `text` prop)', () =>
expect(html).toContain('© 2026 MySite. All rights reserved.');
});
});
describe('Footer (F4: box-model + animation + visibility props on craft.props)', () => {
test('craft.props includes animation/visibility defaults so the panel controls always render', () => {
const craftProps = (Footer as any).craft.props;
expect(craftProps).toHaveProperty('animation', 'none');
expect(craftProps).toHaveProperty('animationDelay', '0');
expect(craftProps).toHaveProperty('hideOnDesktop', false);
expect(craftProps).toHaveProperty('hideOnTablet', false);
expect(craftProps).toHaveProperty('hideOnMobile', false);
});
});
+10
View File
@@ -6,6 +6,11 @@ import { escapeHtml } from '../../utils/escape';
interface FooterProps {
text?: string;
style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
}
export const Footer: UserComponent<FooterProps> = ({
@@ -92,6 +97,11 @@ Footer.craft = {
fontSize: '14px',
padding: '24px 20px',
},
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
},
rules: {
canDrag: () => true,
@@ -43,6 +43,29 @@ describe('Logo.toHtml image src/alt sanitization (type="image")', () => {
});
});
describe('Logo.toHtml download attribute (F3: link-to-file toggle)', () => {
test('download:true emits the download attribute', () => {
const { html } = toHtml({ href: '/resume.pdf', download: true, text: 'Resume' }, '');
expect(html).toMatch(/<a href="\/resume\.pdf" download/);
});
test('no download prop -> no download attribute emitted', () => {
const { html } = toHtml({ href: '/', text: 'MySite' }, '');
expect(html).not.toContain('download');
});
});
describe('Logo (F4: box-model + animation + visibility props on craft.props)', () => {
test('craft.props includes animation/visibility defaults so the panel controls always render', () => {
const craftProps = (Logo as any).craft.props;
expect(craftProps).toHaveProperty('animation', 'none');
expect(craftProps).toHaveProperty('animationDelay', '0');
expect(craftProps).toHaveProperty('hideOnDesktop', false);
expect(craftProps).toHaveProperty('hideOnTablet', false);
expect(craftProps).toHaveProperty('hideOnMobile', false);
});
});
describe('Logo.toHtml text-logo styling sanitization', () => {
test('a quote-breakout color does not escape the span style attribute', () => {
const malicious = 'red" onmouseover="alert(1)';
+17 -1
View File
@@ -12,11 +12,18 @@ interface LogoProps {
imageSrc?: string;
imageWidth?: string;
href?: string;
/** Adds the `download` attribute to the exported anchor (F3: link to a file). */
download?: boolean;
fontFamily?: string;
fontSize?: string;
fontWeight?: string;
color?: string;
style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
}
/* ---------- Component ---------- */
@@ -27,6 +34,7 @@ export const Logo: UserComponent<LogoProps> = ({
imageSrc = '',
imageWidth = '120px',
href = '/',
download = false,
fontFamily = 'Inter, sans-serif',
fontSize = '20px',
fontWeight = '700',
@@ -44,6 +52,7 @@ export const Logo: UserComponent<LogoProps> = ({
<a
ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
href={href}
download={download || undefined}
onClick={(e) => e.preventDefault()}
style={{
textDecoration: 'none',
@@ -87,7 +96,13 @@ Logo.craft = {
fontSize: '20px',
fontWeight: '700',
color: undefined,
download: false,
style: {},
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
} as LogoProps,
rules: {
canDrag: () => true,
@@ -122,8 +137,9 @@ Logo.craft = {
flexShrink: '0',
...props.style,
});
const downloadAttr = props.download ? ' download' : '';
return {
html: `<a href="${escapeAttr(safeUrl(href))}"${aStyle ? ` style="${aStyle}"` : ''}>${innerHtml}</a>`,
html: `<a href="${escapeAttr(safeUrl(href))}"${downloadAttr}${aStyle ? ` style="${aStyle}"` : ''}>${innerHtml}</a>`,
};
};
@@ -31,6 +31,29 @@ describe('Menu.toHtml deterministic + unique scope ids (thread node id, no Math.
});
});
describe('Menu.toHtml download attribute (F3: link-to-file toggle)', () => {
test('a link with download:true emits the download attribute', () => {
const { html } = toHtml({ links: [{ text: 'Brochure', href: '/brochure.pdf', download: true }] }, '', 'node-dl1');
expect(html).toMatch(/<a href="\/brochure\.pdf"[^>]* download[^>]*>Brochure<\/a>/);
});
test('a link without download does not emit the attribute', () => {
const { html } = toHtml({ links: [{ text: 'Home', href: '/' }] }, '', 'node-dl2');
expect(html).not.toContain(' download');
});
});
describe('Menu (F4: box-model + animation + visibility props on craft.props)', () => {
test('craft.props includes animation/visibility defaults so the panel controls always render', () => {
const craftProps = (Menu as any).craft.props;
expect(craftProps).toHaveProperty('animation', 'none');
expect(craftProps).toHaveProperty('animationDelay', '0');
expect(craftProps).toHaveProperty('hideOnDesktop', false);
expect(craftProps).toHaveProperty('hideOnTablet', false);
expect(craftProps).toHaveProperty('hideOnMobile', false);
});
});
describe('Menu.toHtml XSS hardening (linkHoverColor into <style>)', () => {
test('a linkHoverColor value containing </style><script> is neutralized', () => {
const malicious = '#fff}</style><script>alert(1)</script><style>{';
+15 -1
View File
@@ -10,6 +10,8 @@ interface MenuLink {
href: string;
isExternal?: boolean;
isCta?: boolean;
/** Adds the `download` attribute to the exported anchor (F3: links to files). */
download?: boolean;
}
interface MenuProps {
@@ -23,6 +25,11 @@ interface MenuProps {
orientation?: 'horizontal' | 'vertical';
fontSize?: string;
style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
}
/* ---------- Defaults ---------- */
@@ -75,6 +82,7 @@ export const Menu: UserComponent<MenuProps> = ({
href={link.href}
target={link.isExternal ? '_blank' : undefined}
rel={link.isExternal ? 'noopener noreferrer' : undefined}
download={link.download || undefined}
onClick={(e) => e.preventDefault()}
onMouseEnter={() => setHoveredLink(i)}
onMouseLeave={() => setHoveredLink(null)}
@@ -114,6 +122,11 @@ Menu.craft = {
orientation: 'horizontal',
fontSize: '14px',
style: {},
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
} as MenuProps,
rules: {
canDrag: () => true,
@@ -162,6 +175,7 @@ Menu.craft = {
const linksHtml = links.map((link) => {
const target = link.isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
const downloadAttr = link.download ? ' download' : '';
const cls = link.isCta ? `${scope}-cta` : `${scope}-link`;
const linkStyle = cssPropsToString({
textDecoration: 'none',
@@ -173,7 +187,7 @@ Menu.craft = {
borderRadius: link.isCta ? '6px' : '0',
transition: 'color 0.15s, background-color 0.15s',
});
return `<a href="${escapeAttr(safeUrl(link.href || '#'))}" class="${cls}"${target}${linkStyle ? ` style="${linkStyle}"` : ''}>${escapeHtml(link.text)}</a>`;
return `<a href="${escapeAttr(safeUrl(link.href || '#'))}" class="${cls}"${target}${downloadAttr}${linkStyle ? ` style="${linkStyle}"` : ''}>${escapeHtml(link.text)}</a>`;
}).join('\n ');
const hoverCss = `<style>
@@ -83,6 +83,29 @@ describe('Navbar.toHtml node-scoped ids/hover styles (M-1: two navbars must not
});
});
describe('Navbar.toHtml download attribute (F3: link-to-file toggle)', () => {
test('a link with download:true emits the download attribute', () => {
const { html } = toHtml({ links: [{ text: 'Brochure', href: '/brochure.pdf', download: true }] }, '', 'node-dl1');
expect(html).toMatch(/<a href="\/brochure\.pdf"[^>]* download[^>]*>Brochure<\/a>/);
});
test('a link without download does not emit the attribute', () => {
const { html } = toHtml({ links: [{ text: 'Home', href: '/' }] }, '', 'node-dl2');
expect(html).not.toContain(' download');
});
});
describe('Navbar (F4: box-model + animation + visibility props on craft.props)', () => {
test('craft.props includes animation/visibility defaults so the panel controls always render', () => {
const craftProps = (Navbar as any).craft.props;
expect(craftProps).toHaveProperty('animation', 'none');
expect(craftProps).toHaveProperty('animationDelay', '0');
expect(craftProps).toHaveProperty('hideOnDesktop', false);
expect(craftProps).toHaveProperty('hideOnTablet', false);
expect(craftProps).toHaveProperty('hideOnMobile', false);
});
});
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
const malicious = '#fff}</style><script>alert(1)</script><style>{';
+15 -1
View File
@@ -11,6 +11,8 @@ interface NavLink {
href: string;
isExternal?: boolean;
isCta?: boolean;
/** Adds the `download` attribute to the exported anchor (F3: links to files). */
download?: boolean;
}
interface NavbarProps {
@@ -33,6 +35,11 @@ interface NavbarProps {
isSticky?: boolean;
showMobileMenu?: boolean;
style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
}
/* ---------- Defaults ---------- */
@@ -149,6 +156,7 @@ export const Navbar: UserComponent<NavbarProps> = ({
href={link.href}
target={link.isExternal ? '_blank' : undefined}
rel={link.isExternal ? 'noopener noreferrer' : undefined}
download={link.download || undefined}
onClick={(e) => e.preventDefault()}
onMouseEnter={() => setHoveredLink(i)}
onMouseLeave={() => setHoveredLink(null)}
@@ -200,6 +208,11 @@ Navbar.craft = {
style: {
borderBottom: '1px solid #e4e4e7',
},
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
} as NavbarProps,
rules: {
canDrag: () => true,
@@ -308,6 +321,7 @@ Navbar.craft = {
// Add CSS class to each link for hover
const linksHtmlWithClass = links.map((link) => {
const target = link.isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
const downloadAttr = link.download ? ' download' : '';
const cls = link.isCta ? 'navbar-cta' : 'navbar-link';
const linkStyle = cssPropsToString({
textDecoration: 'none',
@@ -319,7 +333,7 @@ Navbar.craft = {
borderRadius: link.isCta ? '6px' : '0',
transition: 'color 0.15s, background-color 0.15s',
});
return `<a href="${escapeAttr(safeUrl(link.href || "#"))}" class="${cls}"${target}${linkStyle ? ` style="${linkStyle}"` : ''}>${escapeHtml(link.text)}</a>`;
return `<a href="${escapeAttr(safeUrl(link.href || "#"))}" class="${cls}"${target}${downloadAttr}${linkStyle ? ` style="${linkStyle}"` : ''}>${escapeHtml(link.text)}</a>`;
}).join('\n ');
return {
+159
View File
@@ -0,0 +1,159 @@
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 { EditorConfigProvider } from '../state/EditorConfigContext';
import { PageProvider, usePages } from '../state/PageContext';
import { SiteDesignProvider } from '../state/SiteDesignContext';
import { useWhpApi } from './useWhpApi';
import { WhpConfig } from '../types';
/**
* PKG-H §5 round-trip coverage: `load()` must restore per-page `seo`
* (PageSeo) from `proj.pages_craft_state[].seo` back onto the reconstructed
* `PageData`, exactly like it already restores `craftState`. Mocks
* `@craftjs/core`'s `useEditor` (same pattern as
* `PageContext.pure-updaters.test.tsx`) since this test only needs
* `query.serialize`/`actions.deserialize` as inert stubs -- it drives
* `load()`, not the live canvas.
*/
const deserializeMock = vi.fn();
vi.mock('@craftjs/core', () => ({
useEditor: () => ({
query: { serialize: () => '{}' },
actions: { deserialize: deserializeMock },
}),
}));
const whpConfig: WhpConfig = {
user: 'testuser',
apiUrl: '/panel/api/site-builder',
csrfToken: 'tok',
siteId: 42,
siteDomain: 'example.com',
siteName: 'Test Site',
backUrl: '/panel/sites',
isRoot: false,
};
let container: HTMLDivElement;
let root: Root;
interface Captured {
load: ReturnType<typeof useWhpApi>['load'];
pages: ReturnType<typeof usePages>['pages'];
}
function render(): { get: () => Captured } {
container = document.createElement('div');
document.body.appendChild(container);
let captured: Captured | null = null;
const Consumer: React.FC = () => {
const { load } = useWhpApi();
const { pages } = usePages();
captured = { load, pages };
return null;
};
act(() => {
root = createRoot(container);
root.render(
<EditorConfigProvider config={whpConfig}>
<SiteDesignProvider>
<PageProvider>
<Consumer />
</PageProvider>
</SiteDesignProvider>
</EditorConfigProvider>,
);
});
return { get: () => captured! };
}
function unmount() {
act(() => {
root.unmount();
});
container.remove();
}
describe('useWhpApi load() restores PageData.seo (PKG-H §5)', () => {
beforeEach(() => {
deserializeMock.mockClear();
});
afterEach(() => {
vi.unstubAllGlobals();
});
test('a saved project with per-page seo restores seo onto the reconstructed PageData', async () => {
const seoPayload = {
metaTitle: 'Custom Title',
metaDescription: 'A custom description.',
ogTitle: 'Custom OG Title',
ogImage: '/uploads/og.jpg',
twitterCard: 'summary_large_image' as const,
noindex: true,
};
const fetchMock = vi.fn().mockResolvedValue({
json: async () => ({
success: true,
project: {
design: null,
header_craft_state: null,
footer_craft_state: null,
pages_craft_state: [
{ id: 'home', name: 'Home', slug: 'index', craftState: '{"ROOT":{}}', seo: seoPayload },
{ id: 'page_2', name: 'About', slug: 'about', craftState: '{"ROOT":{}}' },
],
},
}),
});
vi.stubGlobal('fetch', fetchMock);
const harness = render();
await act(async () => {
await harness.get().load();
});
const { pages } = harness.get();
expect(pages.find((p) => p.id === 'home')?.seo).toEqual(seoPayload);
// A page with no seo in the payload stays undefined -- back-compat, not
// coerced into an empty object.
expect(pages.find((p) => p.id === 'page_2')?.seo).toBeUndefined();
unmount();
});
test('a legacy project with no seo on any page loads without adding seo fields', async () => {
const fetchMock = vi.fn().mockResolvedValue({
json: async () => ({
success: true,
project: {
design: null,
header_craft_state: null,
footer_craft_state: null,
pages_craft_state: [
{ id: 'home', name: 'Home', slug: 'index', craftState: '{"ROOT":{}}' },
],
},
}),
});
vi.stubGlobal('fetch', fetchMock);
const harness = render();
await act(async () => {
await harness.get().load();
});
const { pages } = harness.get();
expect(pages.find((p) => p.id === 'home')?.seo).toBeUndefined();
unmount();
});
});
+59
View File
@@ -147,4 +147,63 @@ describe('buildSavePayload', () => {
expect(payload.design).toEqual(design);
expect(payload.design.headCode).toBe('<meta name="x">');
});
test('PKG-H §5: per-page seo is included in both pages_craft_state and pages entries', () => {
const pageWithSeo: PageData = {
id: 'home',
name: 'Home',
slug: 'index',
craftState: 'STORED_HOME',
seo: {
metaTitle: 'Custom Title',
metaDescription: 'Custom description',
ogTitle: 'Custom OG',
ogImage: '/uploads/og.jpg',
twitterCard: 'summary_large_image',
noindex: true,
},
};
const payload = buildSavePayload({
siteId: 1,
siteName: 'Test Site',
liveCraftState: 'LIVE_PAGE_HOME',
pages: [pageWithSeo, pageB],
headerPage,
footerPage,
activePageId: 'home',
isEditingHeader: false,
isEditingFooter: false,
headCode: DEFAULT_SITE_DESIGN.headCode,
design: DEFAULT_SITE_DESIGN,
});
expect(payload.pages_craft_state.find((p) => p.id === 'home')?.seo).toEqual(pageWithSeo.seo);
expect(payload.pages.find((p) => p.filename === 'index.html')?.seo).toEqual(pageWithSeo.seo);
// A page with no seo overrides omits the field entirely (undefined),
// not an empty object -- back-compat with pre-PKG-H saved shapes.
expect(payload.pages_craft_state.find((p) => p.id === 'page_2')?.seo).toBeUndefined();
expect(payload.pages.find((p) => p.filename === 'about.html')?.seo).toBeUndefined();
});
test('PKG-H §5: favicon flows through the design object already carried by the payload', () => {
const design = { ...DEFAULT_SITE_DESIGN, favicon: '/uploads/favicon.png' };
const payload = buildSavePayload({
siteId: 1,
siteName: 'Test Site',
liveCraftState: 'LIVE_PAGE_HOME',
pages: [pageA, pageB],
headerPage,
footerPage,
activePageId: 'home',
isEditingHeader: false,
isEditingFooter: false,
headCode: DEFAULT_SITE_DESIGN.headCode,
design,
});
expect(payload.design.favicon).toBe('/uploads/favicon.png');
});
});
+11 -2
View File
@@ -149,6 +149,12 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
filename,
title: page.name,
html: pageHtml,
// PKG-H §5: per-page SEO overrides, read by the backend's
// `handlePublish` (mirrors the existing `title` field above) to build
// the published <head> for this file. Omitted (undefined) when the
// page has no seo overrides -- JSON.stringify drops undefined keys,
// so legacy-shaped payloads round-trip unchanged.
seo: page.seo,
};
});
@@ -166,6 +172,9 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
// name.html) lines up with the file we just wrote (index.html).
slug: i === 0 ? 'index' : page.slug,
craftState: (isPageActive && page.id === effectiveActivePageId) ? liveCraftState : (page.craftState || null),
// PKG-H §5: round-trips PageData.seo through save -> load() so the
// editor's SEO fields survive a reload (mirrors craftState above).
seo: page.seo,
}));
return {
@@ -292,8 +301,8 @@ export function useWhpApi() {
// Restore pages and load the first page into the canvas
if (proj.pages_craft_state && Array.isArray(proj.pages_craft_state) && proj.pages_craft_state.length > 0) {
setPagesCraftState(proj.pages_craft_state.map((p: { id: string; name: string; slug: string; craftState: string | null }) => ({
id: p.id, name: p.name, slug: p.slug, craftState: p.craftState || null,
setPagesCraftState(proj.pages_craft_state.map((p: { id: string; name: string; slug: string; craftState: string | null; seo?: PageData['seo'] }) => ({
id: p.id, name: p.name, slug: p.slug, craftState: p.craftState || null, seo: p.seo,
})));
// Load the first page (home) into the canvas
+234
View File
@@ -0,0 +1,234 @@
import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Modal } from '../../ui/Modal';
import { AssetPicker } from '../../ui/AssetPicker';
import { PageData, PageSeo } from '../../types';
interface PageSettingsModalProps {
open: boolean;
onClose: () => void;
page: PageData | null;
updatePageSeo: (pageId: string, seo: Partial<PageSeo>) => void;
}
const EMPTY_SEO: PageSeo = {
metaTitle: '',
metaDescription: '',
ogTitle: '',
ogImage: '',
twitterCard: 'summary_large_image',
noindex: false,
};
/**
* Per-page SEO/meta settings (PKG-H contract §1/§4). Opened via the gear
* icon on a page row in PagesPanel. Fields map 1:1 onto `PageData.seo`
* (`types/index.ts`) and are consumed by `html-export.ts`'s `wrapInDocument`
* (Preview) and the backend's `generateCompiledHTML` (published output) --
* field names here MUST match the shared contract exactly.
*
* Follows the HeadCodeModal precedent: portaled to `document.body` (escapes
* the topbar/left-panel's own stacking context, same fix HeadCodeModal and
* TemplateModal already needed), built on the shared `Modal` shell, edits
* commit immediately via `updatePageSeo` (no separate Save step) rather than
* buffering to a "Save" button -- consistent with HeadCodeModal's live-edit
* pattern for `design.headCode`.
*/
export const PageSettingsModal: React.FC<PageSettingsModalProps> = ({ open, onClose, page, updatePageSeo }) => {
const [seo, setSeo] = useState<PageSeo>(EMPTY_SEO);
// Re-sync local form state from the target page's stored seo whenever the
// modal opens (or the target page changes while open) -- mirrors the
// pattern of resetting form-local state on prop identity change rather
// than deriving directly from props (dropdowns/checkboxes need editable
// local state).
useEffect(() => {
if (!open) return;
setSeo({ ...EMPTY_SEO, ...(page?.seo || {}) });
}, [open, page?.id, page?.seo]);
if (!page) return null;
const update = (patch: Partial<PageSeo>) => {
setSeo((prev) => ({ ...prev, ...patch }));
updatePageSeo(page.id, patch);
};
return createPortal(
<Modal open={open} onClose={onClose}>
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
{/* Header */}
<div style={modalHeaderStyle}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<i className="fa fa-cog" style={{ color: 'var(--color-accent)', fontSize: 16 }} />
<div>
<div style={{ fontSize: 15, fontWeight: 600, color: 'var(--color-text)' }}>
Page Settings — {page.name}
</div>
<div style={{ fontSize: 11, color: 'var(--color-text-muted)', marginTop: 2 }}>
SEO and social-sharing metadata for this page only.
</div>
</div>
</div>
<button onClick={onClose} style={closeButtonStyle} aria-label="Close">
<i className="fa fa-times" />
</button>
</div>
{/* Body */}
<div style={{ padding: 20, flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
<div>
<label style={fieldLabelStyle}>Meta Title</label>
<input
type="text"
className="control-input"
value={seo.metaTitle || ''}
onChange={(e) => update({ metaTitle: e.target.value })}
placeholder={page.name}
data-testid="page-seo-meta-title"
/>
<p style={hintStyle}>Overrides the browser tab title. Leave blank to use the page name.</p>
</div>
<div>
<label style={fieldLabelStyle}>Meta Description</label>
<textarea
className="control-input"
value={seo.metaDescription || ''}
onChange={(e) => update({ metaDescription: e.target.value })}
placeholder="A short summary shown in search results and link previews..."
rows={3}
style={{ resize: 'vertical' as const }}
data-testid="page-seo-meta-description"
/>
</div>
<div>
<label style={fieldLabelStyle}>Social Share Title (og:title)</label>
<input
type="text"
className="control-input"
value={seo.ogTitle || ''}
onChange={(e) => update({ ogTitle: e.target.value })}
placeholder={seo.metaTitle || page.name}
data-testid="page-seo-og-title"
/>
</div>
<div>
<label style={fieldLabelStyle}>Social Share Image (og:image)</label>
<AssetPicker
value={seo.ogImage || ''}
onChange={(url) => update({ ogImage: url })}
mediaType="image"
variant="full"
placeholder="Or paste image URL..."
/>
</div>
<div>
<label style={fieldLabelStyle}>Twitter Card Type</label>
<select
className="control-select"
value={seo.twitterCard || 'summary_large_image'}
onChange={(e) => update({ twitterCard: e.target.value as PageSeo['twitterCard'] })}
data-testid="page-seo-twitter-card"
>
<option value="summary">Summary</option>
<option value="summary_large_image">Summary with Large Image</option>
</select>
</div>
<label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--color-text)', cursor: 'pointer' }}>
<input
type="checkbox"
checked={!!seo.noindex}
onChange={(e) => update({ noindex: e.target.checked })}
data-testid="page-seo-noindex"
/>
Hide this page from search engines (noindex)
</label>
</div>
{/* Footer */}
<div style={{
padding: '12px 20px',
borderTop: '1px solid var(--color-border)',
display: 'flex',
justifyContent: 'flex-end',
gap: 8,
}}>
<button onClick={onClose} style={doneButtonStyle}>
Done
</button>
</div>
</div>
</Modal>,
document.body,
);
};
/* ---------- Styles ---------- */
const modalStyle: React.CSSProperties = {
width: '90vw',
maxWidth: 560,
maxHeight: '85vh',
backgroundColor: 'var(--color-bg-surface)',
borderRadius: 12,
border: '1px solid var(--color-border)',
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
};
const modalHeaderStyle: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '16px 20px',
borderBottom: '1px solid var(--color-border)',
flexShrink: 0,
};
const closeButtonStyle: React.CSSProperties = {
width: 32,
height: 32,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
background: 'none',
border: '1px solid var(--color-border)',
borderRadius: 6,
color: 'var(--color-text-muted)',
cursor: 'pointer',
fontSize: 14,
};
const doneButtonStyle: React.CSSProperties = {
padding: '8px 24px',
fontSize: 13,
fontWeight: 600,
background: 'var(--color-accent)',
color: '#fff',
border: 'none',
borderRadius: 6,
cursor: 'pointer',
};
const fieldLabelStyle: React.CSSProperties = {
display: 'block',
fontSize: 11,
fontWeight: 600,
color: 'var(--color-text-muted)',
marginBottom: 6,
textTransform: 'uppercase',
letterSpacing: '0.3px',
};
const hintStyle: React.CSSProperties = {
fontSize: 10,
color: 'var(--color-text-dim)',
margin: '4px 0 0',
};
+31
View File
@@ -1,6 +1,7 @@
import React, { useState } from 'react';
import { usePages } from '../../state/PageContext';
import { clickableProps } from '../../utils/a11y';
import { PageSettingsModal } from './PageSettingsModal';
export const PagesPanel: React.FC = () => {
const {
@@ -14,6 +15,7 @@ export const PagesPanel: React.FC = () => {
addPage,
deletePage,
renamePage,
updatePageSeo,
} = usePages();
const [isAdding, setIsAdding] = useState(false);
const [newName, setNewName] = useState('');
@@ -22,6 +24,8 @@ export const PagesPanel: React.FC = () => {
const [editName, setEditName] = useState('');
const [editSlug, setEditSlug] = useState('');
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
const [seoSettingsPageId, setSeoSettingsPageId] = useState<string | null>(null);
const seoSettingsPage = pages.find((p) => p.id === seoSettingsPageId) || null;
const handleAdd = () => {
if (!newName.trim()) return;
@@ -343,6 +347,26 @@ export const PagesPanel: React.FC = () => {
style={{ display: 'flex', gap: 4, flexShrink: 0 }}
onClick={(e) => e.stopPropagation()}
>
<button
onClick={() => setSeoSettingsPageId(page.id)}
data-tooltip="Page Settings (SEO)"
aria-label={`Page settings for ${page.name}`}
style={{
width: 24,
height: 24,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 11,
color: 'var(--color-text-muted)',
background: 'transparent',
border: 'none',
borderRadius: 'var(--radius-sm)',
cursor: 'pointer',
}}
>
<i className="fa fa-cog" aria-hidden="true" />
</button>
<button
onClick={() => startEditing(page)}
data-tooltip="Rename"
@@ -492,6 +516,13 @@ export const PagesPanel: React.FC = () => {
+ Add Page
</button>
)}
<PageSettingsModal
open={seoSettingsPageId !== null}
onClose={() => setSeoSettingsPageId(null)}
page={seoSettingsPage}
updatePageSeo={updatePageSeo}
/>
</div>
);
};
@@ -1,6 +1,7 @@
import React, { useState } from 'react';
import { useSiteDesign, DEFAULT_SITE_DESIGN } from '../../state/SiteDesignContext';
import { FONT_FAMILIES } from '../../constants/presets';
import { AssetPicker } from '../../ui/AssetPicker';
type DesignTab = 'basic' | 'advanced';
@@ -200,6 +201,19 @@ export const SiteDesignPanel: React.FC = () => {
{/* Basic tab */}
{tab === 'basic' && (
<>
<div className="guided-section">
<label className="guided-section-label">Favicon</label>
<AssetPicker
value={design.favicon}
onChange={(url) => updateDesign({ favicon: url })}
mediaType="image"
variant="full"
placeholder="Or paste favicon URL..."
/>
<p style={{ fontSize: 10, color: 'var(--color-text-dim)', margin: '4px 0 0' }}>
Shown in browser tabs and bookmarks. Applies site-wide.
</p>
</div>
<ColorField
label="Primary Color"
value={design.primaryColor}
@@ -0,0 +1,282 @@
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';
/* NavStylePanel (via useNodeProp/LinkPicker in this file) needs useEditor
from @craftjs/core and usePages from PageContext. Mock both following the
DOM-harness pattern used across this repo's other *StylePanel tests (no
@testing-library/react here) -- PageContext itself is Wave-2's territory,
this package only READS pages via usePages(), so mocking it is the
correct boundary for these tests. */
const setPropSpy = vi.fn((_id: string, updater: (p: any) => void) => {
updater(lastProps);
});
let lastProps: any;
vi.mock('@craftjs/core', () => ({
useEditor: () => ({ actions: { setProp: setPropSpy } }),
}));
let mockPages: { id: string; name: string; slug: string; craftState: string | null }[] = [];
vi.mock('../../../state/PageContext', () => ({
usePages: () => ({ pages: mockPages }),
}));
vi.mock('../../../ui/AssetPicker', () => ({
AssetPicker: () => null,
}));
import { NavStylePanel, LinkPicker, pageHref } from './NavStylePanel';
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 rerender(ui: React.ReactElement) {
act(() => { root.render(ui); });
}
function unmount() {
act(() => { root.unmount(); });
container.remove();
}
function setValue(el: HTMLInputElement | HTMLSelectElement, value: string) {
const proto = el instanceof HTMLSelectElement ? window.HTMLSelectElement.prototype : window.HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, 'value')!.set!;
act(() => {
setter.call(el, value);
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
});
}
function click(el: Element | null) {
act(() => { (el as HTMLElement).dispatchEvent(new MouseEvent('click', { bubbles: true })); });
}
beforeEach(() => {
setPropSpy.mockClear();
mockPages = [
{ id: 'home', name: 'Home', slug: 'index', craftState: null },
{ id: 'about', name: 'About', slug: 'about', craftState: null },
];
});
afterEach(() => {
if (container) unmount();
});
describe('pageHref (landing page is always "/")', () => {
test('index 0 (landing page) -> "/"', () => {
expect(pageHref(mockPages[0], 0)).toBe('/');
});
test('any other page -> "/{slug}"', () => {
expect(pageHref(mockPages[1], 1)).toBe('/about');
});
});
describe('LinkPicker (F1: link-to-page picker + manual URL/anchor/tel/mailto)', () => {
test('a value matching a page href starts in "Page" mode and lists every page', () => {
render(<LinkPicker value="/about" onChange={vi.fn()} />);
const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
expect(modeSelect.value).toBe('page');
const optionText = Array.from(container.querySelectorAll('option')).map((o) => o.textContent);
expect(optionText).toContain('Home');
expect(optionText).toContain('About');
});
test('picking a different page from the page dropdown emits that page\'s href', () => {
const onChange = vi.fn();
render(<LinkPicker value="/about" onChange={onChange} />);
const [, pageSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
setValue(pageSelect, '/');
expect(onChange).toHaveBeenCalledWith('/');
});
test('a "#section" value starts in Anchor mode', () => {
render(<LinkPicker value="#pricing" onChange={vi.fn()} />);
const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
expect(modeSelect.value).toBe('anchor');
const input = container.querySelector('input[type="text"]') as HTMLInputElement;
expect(input.value).toBe('#pricing');
});
test('switching mode to Anchor seeds a bare "#"', () => {
const onChange = vi.fn();
render(<LinkPicker value="/about" onChange={onChange} />);
const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
setValue(modeSelect, 'anchor');
expect(onChange).toHaveBeenCalledWith('#');
});
test('mailto: helper strips the scheme for editing and re-adds it on change', () => {
const onChange = vi.fn();
render(<LinkPicker value="mailto:foo@example.com" onChange={onChange} />);
const input = container.querySelector('input[type="text"]') as HTMLInputElement;
expect(input.value).toBe('foo@example.com');
setValue(input, 'bar@example.com');
expect(onChange).toHaveBeenCalledWith('mailto:bar@example.com');
});
test('tel: helper strips the scheme for editing and re-adds it on change', () => {
const onChange = vi.fn();
render(<LinkPicker value="tel:5551234567" onChange={onChange} />);
const input = container.querySelector('input[type="text"]') as HTMLInputElement;
expect(input.value).toBe('5551234567');
setValue(input, '5559876543');
expect(onChange).toHaveBeenCalledWith('tel:5559876543');
});
test('a plain https:// URL falls back to Custom URL mode', () => {
render(<LinkPicker value="https://example.com" onChange={vi.fn()} />);
const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
expect(modeSelect.value).toBe('url');
});
});
describe('NavStylePanel Links section: href set via LinkPicker (F1 wired into the panel)', () => {
test('choosing a page for a Navbar link writes that page\'s href onto the link', () => {
lastProps = {
links: [{ text: 'Home', href: '/old-home' }],
};
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const selects = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
// First select for the one link item is its LinkPicker mode select (the
// href starts as a Custom URL, so it opens on "url" mode); switch it to
// "page" then pick the About page from the resulting page dropdown.
const modeSelect = selects[0];
setValue(modeSelect, 'page');
expect(setPropSpy).toHaveBeenCalled();
expect(lastProps.links[0].href).toBe('/'); // defaults to the first page
// The mock setProp mutates `lastProps` in place rather than triggering a
// real Craft.js state update, so force a re-render (passing the same,
// now-mutated, object) to get the LinkPicker to reflect its new "page"
// mode and render the page <select>.
rerender(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const pageSelect = Array.from(container.querySelectorAll('select'))[1] as HTMLSelectElement;
setValue(pageSelect, '/about');
expect(lastProps.links[0].href).toBe('/about');
});
test('toggling the Download checkbox for a link sets download:true', () => {
lastProps = { links: [{ text: 'Brochure', href: '/brochure.pdf' }] };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const checkbox = container.querySelector('input[type="checkbox"]') as HTMLInputElement;
act(() => { checkbox.click(); });
expect(lastProps.links[0].download).toBe(true);
});
});
describe('NavStylePanel: "Sync links with Pages" (F2, regression vs legacy builder)', () => {
test('populates links from the mocked pages list and preserves the CTA link', () => {
lastProps = {
links: [
{ text: 'Old Home', href: '/old' },
{ text: 'Old About', href: '/old-about' },
{ text: 'Get Started', href: '#signup', isCta: true },
],
};
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const syncBtn = Array.from(container.querySelectorAll('button'))
.find((b) => b.textContent?.includes('Sync links with Pages'))!;
expect(syncBtn).toBeTruthy();
click(syncBtn);
expect(lastProps.links).toEqual([
{ text: 'Home', href: '/' },
{ text: 'About', href: '/about' },
{ text: 'Get Started', href: '#signup', isCta: true },
]);
});
test('with no CTA link, sync just replaces links 1:1 with the pages list', () => {
lastProps = { links: [{ text: 'Stale', href: '/stale' }] };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const syncBtn = Array.from(container.querySelectorAll('button'))
.find((b) => b.textContent?.includes('Sync links with Pages'))!;
click(syncBtn);
expect(lastProps.links).toEqual([
{ text: 'Home', href: '/' },
{ text: 'About', href: '/about' },
]);
});
test('the Links section (and its Sync button) is not shown for Footer (no `links` prop)', () => {
lastProps = { text: '© 2026' };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const syncBtn = Array.from(container.querySelectorAll('button'))
.find((b) => b.textContent?.includes('Sync links with Pages'));
expect(syncBtn).toBeUndefined();
});
});
/** The Spacing/Border & Effects/Animation/Visibility CollapsibleSections all
* default closed (defaultOpen={false}, matching the pre-existing "Spacing"
* section's convention) -- open one by clicking its header button before
* asserting on / interacting with its contents. */
function openSection(title: string) {
const header = Array.from(container.querySelectorAll('button'))
.find((b) => b.textContent?.includes(title))!;
click(header);
}
describe('NavStylePanel: box-model + animation + visibility controls always present', () => {
test('Spacing (Margin/Padding), Border & Effects, Animation, and Visibility sections render for a Navbar', () => {
lastProps = {
backgroundColor: '#ffffff',
style: {},
animation: 'none',
animationDelay: '0',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
};
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
openSection('Spacing');
openSection('Border & Effects');
openSection('Animation');
openSection('Visibility');
expect(container.querySelector('[data-testid="spacing-control"]')).toBeTruthy();
expect(container.querySelector('[data-testid="border-control"]')).toBeTruthy();
expect(container.querySelector('[data-testid="animation-control"]')).toBeTruthy();
expect(container.querySelector('[data-testid="visibility-control"]')).toBeTruthy();
});
test('checking "Hide on Mobile" writes hideOnMobile:true via setProp', () => {
lastProps = { hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
openSection('Visibility');
const checkbox = container.querySelector('[data-testid="visibility-hideOnMobile"]') as HTMLInputElement;
act(() => {
checkbox.click();
});
expect(lastProps.hideOnMobile).toBe(true);
});
test('picking an entrance animation writes animation via setProp', () => {
lastProps = { animation: 'none', animationDelay: '0' };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
openSection('Animation');
const fadeInBtn = Array.from(container.querySelectorAll('[data-testid="animation-control"] button'))
.find((b) => b.textContent === 'Fade In')!;
click(fadeInBtn);
expect(lastProps.animation).toBe('fade-in');
});
});
+230 -15
View File
@@ -2,6 +2,7 @@ import React, { useCallback } from 'react';
import { useEditor } from '@craftjs/core';
import {
SPACING_PRESETS,
SHADOW_PRESETS,
} from '../../../constants/presets';
import {
StylePanelProps,
@@ -16,13 +17,145 @@ import {
smallInputStyle,
sectionGap,
useNodeProp,
SpacingControl,
BorderControl,
BorderValue,
buildBorderShorthand,
AnimationControl,
VisibilityControl,
} from './shared';
import { AssetPicker } from '../../../ui/AssetPicker';
import { usePages } from '../../../state/PageContext';
import { PageData } from '../../../types';
/* ---------- NAV / MENU / LOGO ---------- */
/* ---------- Link-to-page helpers (F1/F2: link picker + Sync with Pages) ----------
Mirrors the export convention used elsewhere: the first page is always the
landing page and publishes to '/', every other page publishes to '/{slug}'.
See PageContext.tsx's uniqueSlug/slugify and the landing-page-lock comment
in renamePage() for why index 0 is special-cased this way. */
export function pageHref(page: PageData, index: number): string {
return index === 0 ? '/' : `/${page.slug}`;
}
type LinkMode = 'page' | 'url' | 'anchor' | 'tel' | 'mailto';
function detectLinkMode(value: string, pageHrefs: string[]): LinkMode {
const v = value || '';
if (pageHrefs.includes(v)) return 'page';
if (v.startsWith('#')) return 'anchor';
if (v.startsWith('tel:')) return 'tel';
if (v.startsWith('mailto:')) return 'mailto';
return 'url';
}
/* ---------- LinkPicker ----------
Reused for every link-href field in this panel (standalone Logo's href,
Navbar's logoUrl, and each Navbar/Menu link item's href): a dropdown of
the site's PAGES (read-only via usePages() -- PageContext itself is
Wave-2's territory) plus manual URL / #anchor / tel: / mailto: entry.
safeUrl (in toHtml) already allows tel:/mailto: schemes, so no export-side
change is needed for those. */
interface LinkPickerProps {
value: string;
onChange: (value: string) => void;
}
export const LinkPicker: React.FC<LinkPickerProps> = ({ value, onChange }) => {
const { pages } = usePages();
const pageOptions = pages.map((p, i) => ({ id: p.id, name: p.name, href: pageHref(p, i) }));
const mode = detectLinkMode(value || '', pageOptions.map((p) => p.href));
const switchMode = (next: LinkMode) => {
if (next === mode) return;
if (next === 'page') onChange(pageOptions[0]?.href || '/');
else if (next === 'anchor') onChange('#');
else if (next === 'tel') onChange('tel:');
else if (next === 'mailto') onChange('mailto:');
else onChange('');
};
return (
<div style={sectionGap} data-testid="link-picker">
<label style={labelStyle}>Link</label>
<select
value={mode}
onChange={(e) => switchMode(e.target.value as LinkMode)}
style={{ ...inputStyle, marginBottom: 4, cursor: 'pointer' }}
>
<option value="page">Page</option>
<option value="url">Custom URL</option>
<option value="anchor">Anchor (#section)</option>
<option value="tel">Phone (tel:)</option>
<option value="mailto">Email (mailto:)</option>
</select>
{mode === 'page' && (
pageOptions.length > 0 ? (
<select value={value} onChange={(e) => onChange(e.target.value)} style={inputStyle}>
{pageOptions.map((p) => (
<option key={p.id} value={p.href}>{p.name}</option>
))}
</select>
) : (
<div style={{ fontSize: 11, color: '#71717a' }}>No pages yet</div>
)
)}
{mode === 'anchor' && (
<input
type="text"
value={value || ''}
onChange={(e) => onChange(e.target.value.startsWith('#') ? e.target.value : `#${e.target.value}`)}
placeholder="#section-id"
style={inputStyle}
/>
)}
{mode === 'tel' && (
<input
type="text"
value={(value || '').replace(/^tel:/, '')}
onChange={(e) => onChange(`tel:${e.target.value}`)}
placeholder="+15551234567"
style={inputStyle}
/>
)}
{mode === 'mailto' && (
<input
type="text"
value={(value || '').replace(/^mailto:/, '')}
onChange={(e) => onChange(`mailto:${e.target.value}`)}
placeholder="name@example.com"
style={inputStyle}
/>
)}
{mode === 'url' && (
<input
type="text"
value={value || ''}
onChange={(e) => onChange(e.target.value)}
placeholder="https://example.com or /page"
style={inputStyle}
/>
)}
</div>
);
};
/* Parses a `border` shorthand ("2px solid #hex" / "none") back into the
{ width, style, color } shape BorderControl edits. */
function parseBorderShorthand(v: string | undefined): BorderValue {
if (!v || v === 'none') return { width: '', style: 'none', color: '#000000' };
const m = v.trim().match(/^(\S+)\s+(\S+)\s+(.+)$/);
if (!m) return { width: '', style: 'none', color: '#000000' };
return { width: m[1], style: m[2], color: m[3] };
}
function capitalize(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1);
}
/* ---------- NAV / MENU / LOGO / FOOTER ---------- */
export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const { setProp, setPropStyle } = useNodeProp(selectedId);
const { pages } = usePages();
const links: any[] = nodeProps.links || [];
@@ -48,6 +181,20 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
});
}, [actions, selectedId]);
/* F2: (re)populate the links array from the current pages list --
label = page name, href = '/' for the landing page else '/{slug}'.
Any existing CTA link (isCta: true) is preserved (appended after the
freshly-generated page links) rather than being wiped, matching the
legacy GrapesJS builder's "Sync with Pages" behavior. */
const syncWithPages = useCallback(() => {
actions.setProp(selectedId, (props: any) => {
const existing: any[] = props.links || [];
const ctaLinks = existing.filter((l) => l.isCta);
const pageLinks = pages.map((p, i) => ({ text: p.name, href: pageHref(p, i) }));
props.links = [...pageLinks, ...ctaLinks];
});
}, [actions, selectedId, pages]);
/* Detect standalone Logo vs Navbar/Menu */
const isStandaloneLogo = nodeProps.type !== undefined && (nodeProps.type === 'text' || nodeProps.type === 'image') && nodeProps.logoText === undefined;
@@ -66,6 +213,15 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
);
const GAP_PRESETS = ['8px', '16px', '24px', '32px', '40px'].map((g) => ({ label: g, value: g }));
/* Box-model / animation / visibility values, read off `style` (margin,
padding, border, boxShadow, opacity) or top-level props (animation,
hideOn*). This panel is only ever mounted for the 4 owned components
(Navbar/Menu/Logo/Footer), which all now carry these props (see each
component's .craft.props), so -- unlike the Links/Colors sections above,
which are shared across a genuinely disparate prop schema -- these
sections render unconditionally rather than gating on presence. */
const style = nodeProps.style || {};
return (
<>
{/* Standalone Logo component settings */}
@@ -124,10 +280,11 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
</div>
</>
)}
<div style={sectionGap}>
<label style={labelStyle}>Link URL</label>
<input type="text" value={nodeProps.href || '/'} onChange={(e) => setProp('href', e.target.value)} placeholder="/" style={inputStyle} />
</div>
<LinkPicker value={nodeProps.href || '/'} onChange={(v) => setProp('href', v)} />
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#e4e4e7', cursor: 'pointer', marginTop: -8, marginBottom: 12 }}>
<input type="checkbox" checked={!!nodeProps.download} onChange={(e) => setProp('download', e.target.checked)} />
Download (link points at a file)
</label>
</CollapsibleSection>
)}
@@ -145,17 +302,22 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
</div>
)}
{nodeProps.logoUrl !== undefined && (
<div style={sectionGap}>
<label style={labelStyle}>Logo Link URL</label>
<input type="text" value={nodeProps.logoUrl || ''} onChange={(e) => setProp('logoUrl', e.target.value)} placeholder="/" style={inputStyle} />
</div>
<LinkPicker value={nodeProps.logoUrl || '/'} onChange={(v) => setProp('logoUrl', v)} />
)}
</CollapsibleSection>
)}
{/* Links (not shown for standalone Logo) */}
{!isStandaloneLogo && (
{/* Links (not shown for standalone Logo, or for components -- like
Footer -- that don't carry a `links` array at all). */}
{!isStandaloneLogo && nodeProps.links !== undefined && (
<CollapsibleSection title="Links">
<button
onClick={syncWithPages}
title="Replace these links with one per page (preserves any CTA link)"
style={{ marginBottom: 8, width: '100%', padding: '6px', fontSize: 11, background: 'rgba(59,130,246,0.12)', color: '#93c5fd', border: '1px solid rgba(59,130,246,0.4)', borderRadius: 4, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}
>
<i className="fa fa-refresh" /> Sync links with Pages
</button>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{links.map((link, i) => (
<div key={i} style={{ background: '#1e1e22', borderRadius: 6, padding: 6, display: 'flex', flexDirection: 'column', gap: 3 }}>
@@ -165,7 +327,11 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
<i className="fa fa-times" />
</button>
</div>
<input type="text" value={link.href || ''} onChange={(e) => updateLink(i, 'href', e.target.value)} placeholder="URL" style={{ ...smallInputStyle, color: '#71717a' }} />
<LinkPicker value={link.href || ''} onChange={(v) => updateLink(i, 'href', v)} />
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 10, color: '#a1a1aa', cursor: 'pointer', marginTop: -6 }}>
<input type="checkbox" checked={!!link.download} onChange={(e) => updateLink(i, 'download', e.target.checked)} />
Download (points at a file)
</label>
</div>
))}
</div>
@@ -234,12 +400,61 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
</CollapsibleSection>
)}
{/* Style overrides */}
{/* Box model: margin + padding (per-side, via style.*). The old
single "Padding" preset row is folded into the Padding SpacingControl
below (still writes to style.padding when linked, matching the
previous behavior exactly). */}
<CollapsibleSection title="Spacing" defaultOpen={false}>
<SpacingControl
label="Margin"
value={{ top: style.marginTop, right: style.marginRight, bottom: style.marginBottom, left: style.marginLeft }}
onChange={(side, v) => setPropStyle(`margin${capitalize(side)}`, v)}
/>
<SpacingControl
label="Padding"
value={{ top: style.paddingTop, right: style.paddingRight, bottom: style.paddingBottom, left: style.paddingLeft }}
onChange={(side, v) => setPropStyle(`padding${capitalize(side)}`, v)}
presets={SPACING_PRESETS}
/>
</CollapsibleSection>
{/* Border & Effects: border, box-shadow, opacity */}
<CollapsibleSection title="Border & Effects" defaultOpen={false}>
<BorderControl
value={parseBorderShorthand(style.border)}
onChange={(v) => setPropStyle('border', buildBorderShorthand(v))}
/>
<div className="guided-section">
<SectionLabel>Padding</SectionLabel>
<PresetButtonGrid presets={SPACING_PRESETS} activeValue={(nodeProps.style || {}).padding as string} onSelect={(v) => setPropStyle('padding', v)} />
<SectionLabel>Box Shadow</SectionLabel>
<PresetButtonGrid presets={SHADOW_PRESETS} activeValue={style.boxShadow || 'none'} onSelect={(v) => setPropStyle('boxShadow', v)} />
</div>
<div style={sectionGap}>
<label style={labelStyle}>Opacity</label>
<input
type="range"
min={0}
max={100}
value={style.opacity !== undefined ? Math.round(parseFloat(style.opacity) * 100) : 100}
onChange={(e) => setPropStyle('opacity', String(Number(e.target.value) / 100))}
style={{ width: '100%' }}
/>
</div>
</CollapsibleSection>
{/* Entrance animation */}
<CollapsibleSection title="Animation" defaultOpen={false}>
<AnimationControl
value={{ animation: nodeProps.animation, animationDelay: nodeProps.animationDelay }}
onChange={(v) => actions.setProp(selectedId, (p: any) => { p.animation = v.animation; p.animationDelay = v.animationDelay; })}
/>
</CollapsibleSection>
{/* Responsive visibility */}
<CollapsibleSection title="Visibility" defaultOpen={false}>
<VisibilityControl
value={{ hideOnDesktop: nodeProps.hideOnDesktop, hideOnTablet: nodeProps.hideOnTablet, hideOnMobile: nodeProps.hideOnMobile }}
onChange={(v) => actions.setProp(selectedId, (p: any) => { p.hideOnDesktop = v.hideOnDesktop; p.hideOnTablet = v.hideOnTablet; p.hideOnMobile = v.hideOnMobile; })}
/>
</CollapsibleSection>
</>
);
+20 -3
View File
@@ -28,7 +28,7 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
canRedo: query.history.canRedo(),
}));
const { save, publish, load } = useWhpApi();
const { headerPage, footerPage } = usePages();
const { headerPage, footerPage, pages, activePageId } = usePages();
const { design } = useSiteDesign();
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
@@ -156,10 +156,27 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
// Compose full page: header + body + footer
const composedBody = headerHtml + bodyHtml + footerHtml;
// PKG-H: fold the active page's own SEO overrides + the site-wide
// design tokens/favicon into the Preview export so editor Preview
// === published output (contract §4/§7). `title` is the fully
// resolved TITLE (seo.metaTitle || page.name) per the contract --
// html-export's buildSeoMeta/og:title fallback both key off it.
const activePage = pages.find((p) => p.id === activePageId);
const seo = activePage?.seo;
const title = seo?.metaTitle || activePage?.name || whpConfig?.siteName || 'Preview';
const result = exportToHtml(serialized, {
title: whpConfig?.siteName || 'Preview',
title,
includeFonts: true,
headCode: design.headCode,
description: seo?.metaDescription,
ogTitle: seo?.ogTitle,
ogImage: seo?.ogImage,
twitterCard: seo?.twitterCard,
noindex: seo?.noindex,
favicon: design.favicon,
design,
});
// Replace the body in the full document with our composed version.
@@ -183,7 +200,7 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
} catch (e) {
console.error('Preview failed:', e);
}
}, [query, headerPage, footerPage, whpConfig, design]);
}, [query, headerPage, footerPage, whpConfig, design, pages, activePageId]);
// Phase A: at ≤768px the topbar collapses to only the essentials --
// back arrow, Undo/Redo, Save (+Publish) -- with Templates, Sitesmith,
+15 -3
View File
@@ -1,6 +1,6 @@
import React, { createContext, useContext, useState, useCallback, useRef, ReactNode } from 'react';
import { useEditor } from '@craftjs/core';
import { PageData } from '../types';
import { PageData, PageSeo } from '../types';
import { SerializedTreeNode } from '../types/sitesmith';
import { useSiteDesign, SiteDesign } from './SiteDesignContext';
import { sanitizeAiTree, flattenTreeForCraft, FlatCraftNode } from '../utils/craft-tree';
@@ -18,9 +18,11 @@ interface PageContextValue {
addPage: (name: string, slug: string) => void;
deletePage: (pageId: string) => void;
renamePage: (pageId: string, name: string, slug: string) => void;
/** Merges `seo` fields onto the target page's existing `seo` (creating it if absent). */
updatePageSeo: (pageId: string, seo: Partial<PageSeo>) => void;
setHeaderCraftState: (craftState: string) => void;
setFooterCraftState: (craftState: string) => void;
setPagesCraftState: (pagesData: { id: string; name: string; slug: string; craftState: string | null }[]) => void;
setPagesCraftState: (pagesData: { id: string; name: string; slug: string; craftState: string | null; seo?: PageSeo }[]) => void;
/**
* Bookkeeping-only: point `activePageId` at an already-loaded page without
* re-serializing/deserializing the canvas (the caller -- e.g. useWhpApi's
@@ -186,6 +188,7 @@ const PageContext = createContext<PageContextValue>({
addPage: () => {},
deletePage: () => {},
renamePage: () => {},
updatePageSeo: () => {},
setHeaderCraftState: () => {},
setFooterCraftState: () => {},
setPagesCraftState: () => {},
@@ -421,6 +424,13 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
);
}, []);
/** Merges `seo` fields onto the target page's existing `seo` (creating it if absent). */
const updatePageSeo = useCallback((pageId: string, seo: Partial<PageSeo>) => {
setPages((prev) =>
prev.map((p) => (p.id === pageId ? { ...p, seo: { ...p.seo, ...seo } } : p)),
);
}, []);
/** Allow external code (e.g., load from API) to set the header craft state */
const setHeaderCraftState = useCallback((craftState: string) => {
setHeaderPage((prev) => ({ ...prev, craftState }));
@@ -442,7 +452,7 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
}, []);
/** Allow external code (e.g., load from API) to restore pages with craft states */
const setPagesCraftState = useCallback((pagesData: { id: string; name: string; slug: string; craftState: string | null }[]) => {
const setPagesCraftState = useCallback((pagesData: { id: string; name: string; slug: string; craftState: string | null; seo?: PageSeo }[]) => {
setPages(pagesData.map((p, i) => ({
id: p.id,
name: p.name,
@@ -451,6 +461,7 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
// ALWAYS the landing page → slug 'index' → file index.html.
slug: i === 0 ? 'index' : p.slug,
craftState: p.craftState,
seo: p.seo,
})));
}, []);
@@ -545,6 +556,7 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
addPage,
deletePage,
renamePage,
updatePageSeo,
setHeaderCraftState,
setFooterCraftState,
setPagesCraftState,
@@ -0,0 +1,118 @@
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 { PageProvider, usePages } from './PageContext';
/**
* PKG-H: `updatePageSeo(pageId, seo)` merges `seo` fields onto the target
* page's existing `seo` (creating it if absent), leaving every other page
* and every other field on the target page untouched -- mirrors
* `renamePage`'s existing merge-by-id pattern.
*/
vi.mock('@craftjs/core', () => ({
useEditor: () => ({
query: { serialize: () => '{}' },
actions: { deserialize: vi.fn() },
}),
}));
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();
}
describe('PageContext.updatePageSeo', () => {
test('sets seo on a page that previously had none', async () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
expect(ctx!.pages[0].seo).toBeUndefined();
act(() => {
ctx!.updatePageSeo(ctx!.pages[0].id, { metaTitle: 'Hello World', noindex: true });
});
expect(ctx!.pages[0].seo).toEqual({ metaTitle: 'Hello World', noindex: true });
unmount();
});
test('merges new fields onto existing seo without clobbering untouched fields', async () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => {
ctx!.updatePageSeo(ctx!.pages[0].id, { metaTitle: 'First', metaDescription: 'Desc' });
});
act(() => {
ctx!.updatePageSeo(ctx!.pages[0].id, { metaTitle: 'Second' });
});
expect(ctx!.pages[0].seo).toEqual({ metaTitle: 'Second', metaDescription: 'Desc' });
unmount();
});
test('only touches the targeted page, leaving other pages untouched', async () => {
let ctx: ReturnType<typeof usePages> | null = null;
const Consumer: React.FC = () => {
ctx = usePages();
return null;
};
render(
<PageProvider>
<Consumer />
</PageProvider>,
);
act(() => {
ctx!.addPage('About', 'about');
});
const homeId = ctx!.pages[0].id;
const aboutId = ctx!.pages[1].id;
act(() => {
ctx!.updatePageSeo(aboutId, { metaTitle: 'About Us' });
});
expect(ctx!.pages.find((p) => p.id === aboutId)?.seo).toEqual({ metaTitle: 'About Us' });
expect(ctx!.pages.find((p) => p.id === homeId)?.seo).toBeUndefined();
unmount();
});
});
+4
View File
@@ -24,6 +24,9 @@ export interface SiteDesign {
// Site-wide custom code
headCode: string;
/** Site-wide favicon URL (one per site, not per-page). Empty string = none. */
favicon: string;
}
export interface SiteDesignContextValue {
@@ -52,6 +55,7 @@ export const DEFAULT_SITE_DESIGN: SiteDesign = {
buttonRadius: '8px',
navStyle: 'light',
headCode: '',
favicon: '',
};
const SiteDesignContext = createContext<SiteDesignContextValue>({
+23
View File
@@ -11,11 +11,34 @@ export interface WhpConfig {
isRoot: boolean;
}
/**
* Per-page SEO/meta overrides (PKG-H contract §1). All fields optional --
* an absent `seo` (or absent individual field) means "no override, fall
* back to the page name / no tag emitted", preserving back-compat for
* every project saved before this field existed.
*/
export interface PageSeo {
/** Overrides <title>; when empty, <title> falls back to page.name. */
metaTitle?: string;
/** <meta name="description"> + og:description. */
metaDescription?: string;
/** og:title; when empty falls back to metaTitle || page.name. */
ogTitle?: string;
/** Absolute or site-relative image URL (via AssetPicker mediaType=image). */
ogImage?: string;
/** Default 'summary_large_image' when ogImage set, else 'summary'. */
twitterCard?: 'summary' | 'summary_large_image';
/** Emits <meta name="robots" content="noindex, nofollow">. */
noindex?: boolean;
}
export interface PageData {
id: string;
name: string;
slug: string;
craftState: string | null;
/** NEW -- optional; absent === no SEO overrides (back-compat). */
seo?: PageSeo;
}
export interface AssetData {
+239 -1
View File
@@ -1,5 +1,6 @@
import { describe, test, expect } from 'vitest';
import { exportBodyHtml } from './html-export';
import { exportBodyHtml, exportToHtml, ExportOptions } from './html-export';
import { DEFAULT_SITE_DESIGN, SiteDesign } from '../state/SiteDesignContext';
/**
* C2: buildDataAttrs (internal to html-export.ts) previously interpolated
@@ -97,3 +98,240 @@ describe('renderNode div-fallback allowlists props.tag', () => {
expect(html).toContain('</section>');
});
});
/**
* PKG-H contract §2-4: per-page SEO/meta, favicon, and design-token CSS
* variables emitted into `wrapInDocument`'s <head> (exercised via
* `exportToHtml`, since `exportBodyHtml` intentionally stays body-only --
* contract §7). These assert the exact "only emit when set" / sanitization
* / ordering rules the backend implementer's `generateCompiledHTML` must
* mirror byte-for-byte for editor Preview === published output.
*/
describe('PKG-H: SEO/meta + favicon + design-token <head> emission', () => {
const EMPTY_ROOT_STATE = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { style: {}, tag: 'div' },
displayName: 'Container',
custom: {},
hidden: false,
nodes: [],
linkedNodes: {},
},
});
function exportWith(options: ExportOptions): string {
return exportToHtml(EMPTY_ROOT_STATE, options).html;
}
describe('back-compat: no seo, no favicon, no design passed', () => {
const html = exportWith({ title: 'Legacy Page' });
test('title falls back to the passed title, no robots/description/og/twitter/favicon tags appear', () => {
expect(html).toContain('<title>Legacy Page</title>');
expect(html).not.toContain('name="robots"');
expect(html).not.toContain('name="description"');
expect(html).not.toContain('property="og:description"');
expect(html).not.toContain('property="og:image"');
expect(html).not.toContain('rel="icon"');
// og:title still always emits (falls back to title) -- og:type is a
// fixed tag too -- neither depends on seo being set.
expect(html).toContain('<meta property="og:title" content="Legacy Page">');
expect(html).toContain('<meta property="og:type" content="website">');
// twitter:card only emits when ogImage or description is set -- neither
// is here, so it must be absent.
expect(html).not.toContain('name="twitter:card"');
});
test('still emits the :root token block + token-base CSS + a11y/perf CSS using design defaults (§7 intended change)', () => {
expect(html).toContain(':root{--wsb-primary:');
expect(html).toContain('--wsb-button-radius:');
expect(html).toContain('body{font-family:var(--wsb-body-font)');
expect(html).toContain('a:focus-visible');
expect(html).toContain('prefers-reduced-motion:reduce');
});
});
describe('meta/og/twitter/robots/favicon emit ONLY when their source is set', () => {
test('metaDescription set -> description + og:description + twitter:card (summary) all appear', () => {
const html = exportWith({ title: 'Page', description: 'A great page.' });
expect(html).toContain('<meta name="description" content="A great page.">');
expect(html).toContain('<meta property="og:description" content="A great page.">');
expect(html).toContain('<meta name="twitter:card" content="summary">');
});
test('ogImage set (no description) -> og:image + twitter:card defaults to summary_large_image', () => {
const html = exportWith({ title: 'Page', ogImage: '/uploads/hero.jpg' });
expect(html).toContain('<meta property="og:image" content="/uploads/hero.jpg">');
expect(html).toContain('<meta name="twitter:card" content="summary_large_image">');
expect(html).not.toContain('name="description"');
});
test('explicit twitterCard overrides the derived default', () => {
const html = exportWith({ title: 'Page', ogImage: '/uploads/hero.jpg', twitterCard: 'summary' });
expect(html).toContain('<meta name="twitter:card" content="summary">');
});
test('ogTitle set -> og:title uses it instead of the page title', () => {
const html = exportWith({ title: 'Page Title', ogTitle: 'Custom Share Title' });
expect(html).toContain('<meta property="og:title" content="Custom Share Title">');
expect(html).not.toContain('<meta property="og:title" content="Page Title">');
});
test('noindex true -> robots meta appears; false/absent -> it does not', () => {
expect(exportWith({ title: 'Page', noindex: true })).toContain('<meta name="robots" content="noindex, nofollow">');
expect(exportWith({ title: 'Page', noindex: false })).not.toContain('name="robots"');
expect(exportWith({ title: 'Page' })).not.toContain('name="robots"');
});
test('favicon set -> icon link appears with the exact URL', () => {
const html = exportWith({ title: 'Page', favicon: '/uploads/favicon.png' });
expect(html).toContain('<link rel="icon" href="/uploads/favicon.png">');
});
test('favicon absent -> no icon link', () => {
expect(exportWith({ title: 'Page' })).not.toContain('rel="icon"');
});
});
describe('sanitization neutralizes malicious values', () => {
test('a javascript: og:image / favicon URL is dropped entirely (no tag emitted)', () => {
const html = exportWith({
title: 'Page',
ogImage: 'javascript:alert(1)',
favicon: 'javascript:alert(1)',
description: 'x', // keep twitter:card path alive to prove ogImage really resolved empty
});
expect(html).not.toContain('javascript:alert');
expect(html).not.toContain('property="og:image"');
expect(html).not.toContain('rel="icon"');
// og:image resolved empty -> twitter:card falls back to 'summary' (description-only path), not 'summary_large_image'.
expect(html).toContain('<meta name="twitter:card" content="summary">');
});
test('a data:image/png og:image URL is allowed through unchanged (image sink)', () => {
const html = exportWith({ title: 'Page', ogImage: 'data:image/png;base64,AAAA' });
expect(html).toContain('<meta property="og:image" content="data:image/png;base64,AAAA">');
});
test('an attribute-breakout metaDescription is escaped, not left raw', () => {
const payload = '"><script>alert(1)</script>';
const html = exportWith({ title: 'Page', description: payload });
expect(html).not.toContain('<script>alert(1)</script>');
expect(html).toContain('&quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;');
});
test('a malicious design-token value cannot break out of the :root{} block', () => {
const design: SiteDesign = { ...DEFAULT_SITE_DESIGN, primaryColor: '</style><script>alert(1)</script>' };
const html = exportWith({ title: 'Page', design });
expect(html).not.toContain('<script>alert(1)</script>');
expect(html).not.toContain('</style><script>');
});
});
describe(':root token block', () => {
test('emits all 16 contract-named CSS variables with sanitized values, in order', () => {
const design: SiteDesign = {
...DEFAULT_SITE_DESIGN,
primaryColor: '#111111',
secondaryColor: '#222222',
accentColor: '#333333',
linkColor: '#444444',
successColor: '#555555',
warningColor: '#666666',
errorColor: '#777777',
backgroundColor: '#888888',
textColor: '#999999',
mutedTextColor: '#aaaaaa',
borderColor: '#bbbbbb',
borderRadius: '12px',
headingFont: 'Georgia, serif',
bodyFont: 'Verdana, sans-serif',
buttonFont: 'Tahoma, sans-serif',
buttonRadius: '4px',
};
const html = exportWith({ title: 'Page', design });
const rootMatch = html.match(/:root\{([^}]*)\}/);
expect(rootMatch).not.toBeNull();
const rootBlock = rootMatch![1];
const expectedOrder = [
['--wsb-primary', '#111111'],
['--wsb-secondary', '#222222'],
['--wsb-accent', '#333333'],
['--wsb-link', '#444444'],
['--wsb-success', '#555555'],
['--wsb-warning', '#666666'],
['--wsb-error', '#777777'],
['--wsb-bg', '#888888'],
['--wsb-text', '#999999'],
['--wsb-muted', '#aaaaaa'],
['--wsb-border', '#bbbbbb'],
['--wsb-radius', '12px'],
['--wsb-heading-font', 'Georgia, serif'],
['--wsb-body-font', 'Verdana, sans-serif'],
['--wsb-button-font', 'Tahoma, sans-serif'],
['--wsb-button-radius', '4px'],
];
let lastIndex = -1;
for (const [varName, value] of expectedOrder) {
const decl = `${varName}:${value}`;
expect(rootBlock).toContain(decl);
const idx = rootBlock.indexOf(decl);
expect(idx).toBeGreaterThan(lastIndex);
lastIndex = idx;
}
});
});
describe('a11y/perf CSS', () => {
test('focus-visible outline rule is present', () => {
const html = exportWith({ title: 'Page' });
expect(html).toContain('a:focus-visible,button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--wsb-accent);outline-offset:2px}');
});
test('prefers-reduced-motion rule is present', () => {
const html = exportWith({ title: 'Page' });
expect(html).toContain('@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important;scroll-behavior:auto!important}}');
});
});
describe('Google Fonts link', () => {
test('always includes display=swap, with no design passed (fallback full link)', () => {
const html = exportWith({ title: 'Page', includeFonts: true });
expect(html).toContain('display=swap');
expect(html).toContain('fonts.googleapis.com');
});
test('subsets to only the used families when all 3 design fonts are known presets', () => {
const design: SiteDesign = {
...DEFAULT_SITE_DESIGN,
headingFont: 'Playfair Display, serif',
bodyFont: 'Inter, sans-serif',
buttonFont: 'Inter, sans-serif',
};
const html = exportWith({ title: 'Page', includeFonts: true, design });
expect(html).toContain('display=swap');
expect(html).toContain('family=Playfair+Display');
expect(html).toContain('family=Inter');
// Not one of the 3 used fonts -- subset link must not pull it in.
expect(html).not.toContain('family=Merriweather');
});
test('falls back to the full multi-font link when a design font is not a known preset', () => {
const design: SiteDesign = {
...DEFAULT_SITE_DESIGN,
headingFont: 'Comic Sans MS, cursive',
};
const html = exportWith({ title: 'Page', includeFonts: true, design });
expect(html).toContain('display=swap');
// Full fallback link carries every preset family, including ones the
// design object doesn't reference -- a component using ANY preset
// never silently loses its font.
expect(html).toContain('family=Merriweather');
});
});
});
+171 -4
View File
@@ -1,13 +1,30 @@
import { componentResolver } from '../components/resolver';
import { cssPropsToString } from './style-helpers';
import { escapeHtml, escapeAttr } from './escape';
import { escapeHtml, escapeAttr, cssValue, safeImageUrl } from './escape';
import { sanitizeContainerTag } from '../components/layout/Container';
import { SiteDesign, DEFAULT_SITE_DESIGN } from '../state/SiteDesignContext';
export interface ExportOptions {
title?: string;
includeFonts?: boolean;
minifyCss?: boolean;
headCode?: string;
/** PageSeo.metaDescription -- also feeds og:description when set. */
description?: string;
/** PageSeo.ogTitle -- falls back to `title` (which itself already folds in metaTitle) when empty. */
ogTitle?: string;
/** PageSeo.ogImage -- absolute or site-relative image URL. */
ogImage?: string;
/** PageSeo.twitterCard -- default 'summary_large_image' when ogImage set, else 'summary'. */
twitterCard?: 'summary' | 'summary_large_image';
/** PageSeo.noindex -- emits <meta name="robots" content="noindex, nofollow">. */
noindex?: boolean;
/** SiteDesign.favicon -- site-wide, one per site. */
favicon?: string;
/** Full site design tokens -- drives the :root{} CSS-variable block (contract §2).
* Falls back to DEFAULT_SITE_DESIGN when omitted so every export (including legacy
* callers that don't pass it) still emits the token/base/a11y CSS -- see §7. */
design?: SiteDesign;
}
interface ResolverMap {
@@ -138,6 +155,149 @@ const GOOGLE_FONTS_LINK = `<link rel="preconnect" href="https://fonts.googleapis
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Roboto:wght@300;400;500;700&family=Open+Sans:wght@300;400;600;700&family=Poppins:wght@300;400;500;600;700&family=Montserrat:wght@300;400;500;600;700&family=Playfair+Display:wght@400;600;700&family=Merriweather:wght@300;400;700&family=Source+Code+Pro:wght@400;500;600&display=swap" rel="stylesheet">`;
// Google Fonts family= params for each of the 8 presets in constants/presets.ts
// FONT_FAMILIES, keyed by the CSS font-family name (the part before the first
// comma in e.g. 'Playfair Display, serif'). Used to build a best-effort
// SUBSET fonts link (perf: §3) when every design font resolves to a known
// preset; otherwise buildFontsLink() falls back to the full GOOGLE_FONTS_LINK
// above (which already covers all 8 and already has &display=swap) so a
// component using a preset outside the design's 3 font fields never loses
// its font.
const GOOGLE_FONT_PARAMS: Record<string, string> = {
'Inter': 'family=Inter:wght@300;400;500;600;700',
'Roboto': 'family=Roboto:wght@300;400;500;700',
'Open Sans': 'family=Open+Sans:wght@300;400;600;700',
'Poppins': 'family=Poppins:wght@300;400;500;600;700',
'Montserrat': 'family=Montserrat:wght@300;400;500;600;700',
'Playfair Display': 'family=Playfair+Display:wght@400;600;700',
'Merriweather': 'family=Merriweather:wght@300;400;700',
'Source Code Pro': 'family=Source+Code+Pro:wght@400;500;600',
};
/** Extracts the CSS font-family name from a value like 'Inter, sans-serif' -> 'Inter'. */
function extractFontName(value: string | undefined): string {
return (value || '').split(',')[0].trim();
}
/**
* Best-effort Google Fonts link (contract §3): tries to build a SUBSET link
* containing only the design's heading/body/button fonts (+ display=swap).
* Falls back to the full multi-font GOOGLE_FONTS_LINK -- which still has
* display=swap -- whenever any of those three fonts isn't one of the 8 known
* presets, so a font a component actually uses is never silently dropped.
*/
export function buildFontsLink(design?: SiteDesign): string {
if (!design) return GOOGLE_FONTS_LINK;
const families = [design.headingFont, design.bodyFont, design.buttonFont]
.map(extractFontName)
.filter((f, i, arr) => f !== '' && arr.indexOf(f) === i);
if (families.length === 0) return GOOGLE_FONTS_LINK;
const params = families.map((f) => GOOGLE_FONT_PARAMS[f]).filter((p): p is string => !!p);
if (params.length !== families.length) return GOOGLE_FONTS_LINK;
return `<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?${params.join('&')}&display=swap" rel="stylesheet">`;
}
// ---------- Design-token CSS-variable block (contract §2) ----------
// Ordered [cssVarName, SiteDesign key] pairs -- exact order/names from the
// PKG-H shared contract §2. Both the frontend (here) and the backend
// (site-builder.php) emit this same 16-line block for the same data so
// editor Preview === published output.
const TOKEN_VARS: Array<[string, keyof SiteDesign]> = [
['--wsb-primary', 'primaryColor'],
['--wsb-secondary', 'secondaryColor'],
['--wsb-accent', 'accentColor'],
['--wsb-link', 'linkColor'],
['--wsb-success', 'successColor'],
['--wsb-warning', 'warningColor'],
['--wsb-error', 'errorColor'],
['--wsb-bg', 'backgroundColor'],
['--wsb-text', 'textColor'],
['--wsb-muted', 'mutedTextColor'],
['--wsb-border', 'borderColor'],
['--wsb-radius', 'borderRadius'],
['--wsb-heading-font', 'headingFont'],
['--wsb-body-font', 'bodyFont'],
['--wsb-button-font', 'buttonFont'],
['--wsb-button-radius', 'buttonRadius'],
];
// Fixed token-base CSS (contract §2) -- makes the tokens actually take effect
// globally; component inline styles still override via specificity.
const TOKEN_BASE_CSS = `body{font-family:var(--wsb-body-font);color:var(--wsb-text);background:var(--wsb-bg)}h1,h2,h3,h4,h5,h6{font-family:var(--wsb-heading-font)}a{color:var(--wsb-link)}`;
// Fixed a11y/perf CSS (contract §3), emitted for every published/preview page.
const A11Y_PERF_CSS = `a:focus-visible,button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--wsb-accent);outline-offset:2px}@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important;scroll-behavior:auto!important}}`;
/**
* Builds the `:root{...}` design-token block + the fixed token-base CSS +
* the fixed a11y/perf CSS (contract §2/§3). Every token value is sanitized
* through `cssValue()` before interpolation -- it sits raw inside a
* `:root{ }` CSS-element context (not a string-quoted context), so a
* malicious value could otherwise break out of the block / the `<style>`
* element itself.
*/
export function buildTokenCss(design: SiteDesign): string {
const vars = TOKEN_VARS.map(([varName, key]) => `${varName}:${cssValue(design[key] as string)}`).join(';');
return `:root{${vars}}${TOKEN_BASE_CSS}${A11Y_PERF_CSS}`;
}
// ---------- <head> SEO/meta block (contract §4) ----------
/**
* Builds the ordered SEO/meta tag block from `<meta name="robots">` (only
* when noindex) through the favicon `<link>` -- everything between `<title>`
* and the Google Fonts link in the contract §4 order. `title` must already
* be the FULLY RESOLVED title (i.e. `seo.metaTitle || page.name`) -- the
* og:title fallback chain in the contract (`ogTitle || metaTitle || TITLE`)
* collapses to `ogTitle || title` once `title` itself already folds in the
* metaTitle fallback, so no separate metaTitle parameter is needed here.
* Each optional tag is emitted ONLY when its source value is non-empty --
* no empty `content=""` tags ever ship.
*/
export function buildSeoMeta(options: ExportOptions, title: string): string {
const lines: string[] = [];
if (options.noindex) {
lines.push('<meta name="robots" content="noindex, nofollow">');
}
lines.push(`<title>${escapeHtml(title)}</title>`);
const description = options.description || '';
if (description) {
lines.push(`<meta name="description" content="${escapeAttr(description)}">`);
}
const ogTitle = options.ogTitle || title;
lines.push(`<meta property="og:title" content="${escapeAttr(ogTitle)}">`);
if (description) {
lines.push(`<meta property="og:description" content="${escapeAttr(description)}">`);
}
const ogImage = options.ogImage ? safeImageUrl(options.ogImage) : '';
if (ogImage) {
lines.push(`<meta property="og:image" content="${escapeAttr(ogImage)}">`);
}
lines.push('<meta property="og:type" content="website">');
if (ogImage || description) {
const card = options.twitterCard || (ogImage ? 'summary_large_image' : 'summary');
lines.push(`<meta name="twitter:card" content="${escapeAttr(card)}">`);
}
const favicon = options.favicon ? safeImageUrl(options.favicon) : '';
if (favicon) {
lines.push(`<link rel="icon" href="${escapeAttr(favicon)}">`);
}
return lines.join('\n ');
}
const RESPONSIVE_CSS = `
@media (max-width: 768px) {
[style*="display: flex"][style*="flex-direction: row"],
@@ -191,8 +351,15 @@ function wrapInDocument(bodyHtml: string, options: ExportOptions): string {
const responsive = minify ? RESPONSIVE_CSS_MINIFIED : RESPONSIVE_CSS;
const visibility = minify ? VISIBILITY_CSS_MINIFIED : VISIBILITY_CSS;
const animation = minify ? ANIMATION_CSS_MINIFIED : ANIMATION_CSS;
const fonts = options.includeFonts !== false ? `\n ${GOOGLE_FONTS_LINK}` : '';
// §7 back-compat: even a caller that doesn't pass `design` (legacy call
// sites, e.g. tests not yet updated) still gets the token/base/a11y CSS --
// every project already has design defaults, so DEFAULT_SITE_DESIGN is the
// correct stand-in rather than skipping the block entirely.
const design = options.design || DEFAULT_SITE_DESIGN;
const fonts = options.includeFonts !== false ? `\n ${buildFontsLink(design)}` : '';
const headCode = options.headCode ? `\n ${options.headCode}` : '';
const seoMeta = buildSeoMeta(options, title);
const tokenCss = buildTokenCss(design);
// Only include animation CSS + script if body contains data-animation
const hasAnimations = bodyHtml.includes('data-animation');
@@ -204,8 +371,8 @@ function wrapInDocument(bodyHtml: string, options: ExportOptions): string {
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${escapeHtml(title)}</title>${fonts}
<style>${reset}${responsive}${visibility}${animationBlock}</style>${headCode}
${seoMeta}${fonts}
<style>${reset}${responsive}${visibility}${animationBlock}${tokenCss}</style>${headCode}
</head>
<body>
${bodyHtml}${animationScript}