Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da558fd52d | ||
|
|
8aeadefa88 | ||
|
|
2066059c35 | ||
|
|
473fe8d421 | ||
|
|
5d6ae7946b | ||
|
|
1c85ab93eb | ||
|
|
67228f24b4 | ||
|
|
613a44c4d4 | ||
|
|
5685670895 | ||
|
|
72f85a97e5 | ||
|
|
ab28ad8f2c | ||
|
|
05e00c572d | ||
|
|
458069afb6 | ||
|
|
b3e5009aec | ||
|
|
eeb0660d83 | ||
|
|
138e1a8273 | ||
|
|
1b12b79a0d | ||
|
|
621bb21d52 | ||
|
|
3f3c6fb851 | ||
|
|
802938ec1a | ||
|
|
3e43aee6e9 | ||
|
|
bf4a9f48eb | ||
|
|
86455413d0 | ||
|
|
0cbc58f8d1 | ||
|
|
92841e3f35 | ||
|
|
e892ee0e53 |
+2
-1
@@ -1,6 +1,7 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Editor } from '@craftjs/core';
|
import { Editor } from '@craftjs/core';
|
||||||
import { EditorShell } from './editor/EditorShell';
|
import { EditorShell } from './editor/EditorShell';
|
||||||
|
import { RenderNode } from './editor/RenderNode';
|
||||||
import { componentResolver } from './components/resolver';
|
import { componentResolver } from './components/resolver';
|
||||||
import { WhpConfig } from './types';
|
import { WhpConfig } from './types';
|
||||||
import { EditorConfigProvider } from './state/EditorConfigContext';
|
import { EditorConfigProvider } from './state/EditorConfigContext';
|
||||||
@@ -23,7 +24,7 @@ export const App: React.FC<AppProps> = ({ whpConfig }) => {
|
|||||||
return (
|
return (
|
||||||
<EditorConfigProvider config={whpConfig}>
|
<EditorConfigProvider config={whpConfig}>
|
||||||
<SiteDesignProvider>
|
<SiteDesignProvider>
|
||||||
<Editor resolver={componentResolver} enabled={true}>
|
<Editor resolver={componentResolver} enabled={true} onRender={RenderNode}>
|
||||||
<PageProvider>
|
<PageProvider>
|
||||||
<SitesmithProvider>
|
<SitesmithProvider>
|
||||||
<EditorShell />
|
<EditorShell />
|
||||||
|
|||||||
@@ -21,3 +21,46 @@ describe('purifyHtml', () => {
|
|||||||
expect(purifyHtml('<form><input name="x"></form>')).not.toContain('<form');
|
expect(purifyHtml('<form><input name="x"></form>')).not.toContain('<form');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('purifyHtml iframe sandboxing (M-6)', () => {
|
||||||
|
test('forces a restrictive sandbox attribute onto every iframe', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/"></iframe>');
|
||||||
|
expect(out).toMatch(/<iframe[^>]*\bsandbox="[^"]+"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sandbox value omits allow-top-navigation (no top-level nav escape)', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/"></iframe>');
|
||||||
|
const sandbox = out.match(/sandbox="([^"]*)"/)![1];
|
||||||
|
expect(sandbox).not.toMatch(/allow-top-navigation/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legitimate embeds (YouTube) still work and get sandboxed too', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://www.youtube.com/embed/abc" allowfullscreen></iframe>');
|
||||||
|
expect(out).toContain('youtube.com/embed/abc');
|
||||||
|
expect(out).toMatch(/<iframe[^>]*\bsandbox="[^"]+"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('adds referrerpolicy=no-referrer to iframes', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/"></iframe>');
|
||||||
|
expect(out).toContain('referrerpolicy="no-referrer"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script/on* attributes are still stripped alongside the sandboxed iframe', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/" onload="alert(1)"></iframe><script>alert(2)</script>');
|
||||||
|
expect(out).not.toContain('onload');
|
||||||
|
expect(out).not.toContain('<script');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('repeated calls do not leak/accumulate the hook (no duplicate sandbox attr, no cross-call state)', () => {
|
||||||
|
purifyHtml('<iframe src="https://a.example/"></iframe>');
|
||||||
|
purifyHtml('<iframe src="https://b.example/"></iframe>');
|
||||||
|
const out = purifyHtml('<iframe src="https://c.example/"></iframe>');
|
||||||
|
const sandboxMatches = out.match(/sandbox="/g) || [];
|
||||||
|
expect(sandboxMatches.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-iframe element sanitized alongside an iframe is not touched by the hook', () => {
|
||||||
|
const out = purifyHtml('<p>hi</p><iframe src="https://example.com/"></iframe>');
|
||||||
|
expect(out).toContain('<p>hi</p>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -24,14 +24,42 @@ const PURIFY_CONFIG = {
|
|||||||
'href','src','alt','title','target','rel',
|
'href','src','alt','title','target','rel',
|
||||||
'width','height','class',
|
'width','height','class',
|
||||||
'allowfullscreen','allow','frameborder',
|
'allowfullscreen','allow','frameborder',
|
||||||
|
'sandbox','referrerpolicy',
|
||||||
],
|
],
|
||||||
ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|data:image\/[a-z]+;base64,):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
|
ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|data:image\/[a-z]+;base64,):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
|
||||||
FORBID_TAGS: ['script','style','object','embed','link','meta','form','input','button','select','textarea'],
|
FORBID_TAGS: ['script','style','object','embed','link','meta','form','input','button','select','textarea'],
|
||||||
FORBID_ATTR: [/^on/i],
|
FORBID_ATTR: [/^on/i],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// M-6: `<iframe>` is allowed (maps/video embeds are a legitimate use case)
|
||||||
|
// but an iframe with a `src` and NO `sandbox` attribute is a clickjacking/
|
||||||
|
// phishing vector (DOMPurify already strips <script>/on*=, but an
|
||||||
|
// unsandboxed iframe still gets full script execution, same-origin-ish
|
||||||
|
// access via document.domain tricks, top-level navigation, etc., inside
|
||||||
|
// itself). This hook force-sets a restrictive sandbox on every iframe that
|
||||||
|
// survives sanitization, keeping `allow-scripts`/`allow-same-origin`/
|
||||||
|
// `allow-popups`/`allow-forms` (needed for interactive maps/video/oauth
|
||||||
|
// popups) but deliberately omitting `allow-top-navigation` so an embedded
|
||||||
|
// page can never redirect/hijack the parent tab.
|
||||||
|
const IFRAME_SANDBOX_HOOK = (node: Element): void => {
|
||||||
|
if (node.nodeName === 'IFRAME') {
|
||||||
|
node.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups allow-forms');
|
||||||
|
node.setAttribute('referrerpolicy', 'no-referrer');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export function purifyHtml(input: string): string {
|
export function purifyHtml(input: string): string {
|
||||||
|
// Hook is added immediately before sanitize() and removed immediately
|
||||||
|
// after, scoped tightly to this single call -- so it can never leak onto
|
||||||
|
// (or accumulate duplicate copies across) any other DOMPurify.sanitize()
|
||||||
|
// call elsewhere in the app, and repeated purifyHtml() calls never stack
|
||||||
|
// multiple copies of the same hook.
|
||||||
|
DOMPurify.addHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK);
|
||||||
|
try {
|
||||||
return DOMPurify.sanitize(input || '', PURIFY_CONFIG as any) as unknown as string;
|
return DOMPurify.sanitize(input || '', PURIFY_CONFIG as any) as unknown as string;
|
||||||
|
} finally {
|
||||||
|
DOMPurify.removeHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK as any);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '', style = {} }) => {
|
export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '', style = {} }) => {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
|||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl } from '../../utils/escape';
|
||||||
|
|
||||||
/* ---------- Types ---------- */
|
/* ---------- Types ---------- */
|
||||||
|
|
||||||
@@ -104,7 +104,7 @@ Logo.craft = {
|
|||||||
let innerHtml: string;
|
let innerHtml: string;
|
||||||
if (props.type === 'image' && props.imageSrc) {
|
if (props.type === 'image' && props.imageSrc) {
|
||||||
const imgStyle = cssPropsToString({ width: props.imageWidth || '120px', height: 'auto', display: 'block' });
|
const imgStyle = cssPropsToString({ width: props.imageWidth || '120px', height: 'auto', display: 'block' });
|
||||||
innerHtml = `<img src="${escapeAttr(safeUrl(props.imageSrc))}" alt="${escapeAttr(props.text || 'Logo')}"${imgStyle ? ` style="${imgStyle}"` : ''} />`;
|
innerHtml = `<img src="${escapeAttr(safeImageUrl(props.imageSrc))}" alt="${escapeAttr(props.text || 'Logo')}"${imgStyle ? ` style="${imgStyle}"` : ''} />`;
|
||||||
} else {
|
} else {
|
||||||
const spanStyle = cssPropsToString({
|
const spanStyle = cssPropsToString({
|
||||||
fontWeight: props.fontWeight || '700',
|
fontWeight: props.fontWeight || '700',
|
||||||
|
|||||||
@@ -5,28 +5,84 @@ const toHtml = (Navbar as any).toHtml;
|
|||||||
|
|
||||||
describe('Navbar.toHtml hamburger accessibility (F2.3)', () => {
|
describe('Navbar.toHtml hamburger accessibility (F2.3)', () => {
|
||||||
test('mobile toggle button has an accessible name, aria-expanded, and aria-controls', () => {
|
test('mobile toggle button has an accessible name, aria-expanded, and aria-controls', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: true }, '');
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
expect(html).toMatch(/class="navbar-hamburger"[^>]*aria-label="Toggle navigation menu"/);
|
expect(html).toMatch(/class="navbar-hamburger"[^>]*aria-label="Toggle navigation menu"/);
|
||||||
expect(html).toMatch(/aria-expanded="false"/);
|
expect(html).toMatch(/aria-expanded="false"/);
|
||||||
expect(html).toMatch(/aria-controls="navbar-links"/);
|
expect(html).toMatch(/aria-controls="[^"]+"/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('aria-controls target id exists on the links container', () => {
|
test('aria-controls target id exists on the links container', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: true }, '');
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
expect(html).toContain('id="navbar-links"');
|
const controls = html.match(/aria-controls="([^"]+)"/)![1];
|
||||||
|
expect(html).toContain(`id="${controls}"`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('toggle script flips aria-expanded on click', () => {
|
test('toggle script flips aria-expanded on click', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: true }, '');
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
expect(html).toMatch(/setAttribute\(['"]aria-expanded['"]/);
|
expect(html).toMatch(/setAttribute\(['"]aria-expanded['"]/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('no mobile menu: no hamburger button emitted', () => {
|
test('no mobile menu: no hamburger button emitted', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: false }, '');
|
const { html } = toHtml({ showMobileMenu: false }, '', 'node-nav1');
|
||||||
expect(html).not.toContain('navbar-hamburger');
|
expect(html).not.toContain('navbar-hamburger');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Navbar.toHtml node-scoped ids/hover styles (M-1: two navbars must not collide)', () => {
|
||||||
|
test('no bare unscoped id="navbar-links" is emitted', () => {
|
||||||
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
expect(html).not.toContain('id="navbar-links"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('two different node ids produce different links-container ids', () => {
|
||||||
|
const { html: html1 } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
const { html: html2 } = toHtml({ showMobileMenu: true }, '', 'node-nav2');
|
||||||
|
const id1 = html1.match(/id="([^"]+)"/)![1];
|
||||||
|
const id2 = html2.match(/id="([^"]+)"/)![1];
|
||||||
|
expect(id1).not.toBe(id2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('aria-controls always equals the actual links-container id', () => {
|
||||||
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
const controls = html.match(/aria-controls="([^"]+)"/)![1];
|
||||||
|
const linksId = html.match(/id="([^"]+)"/)![1];
|
||||||
|
expect(controls).toBe(linksId);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hover style selectors are scoped per-instance, not bare .navbar-link/.navbar-cta', () => {
|
||||||
|
const { html } = toHtml({ hoverColor: '#ff0000' }, '', 'node-nav1');
|
||||||
|
// A selector rule that STARTS the line with .navbar-link:hover (i.e. not
|
||||||
|
// preceded by a per-instance ancestor class) would be the old, unscoped,
|
||||||
|
// globally-colliding form.
|
||||||
|
expect(html).not.toMatch(/^\s*\.navbar-link:hover/m);
|
||||||
|
expect(html).not.toMatch(/^\s*\.navbar-cta:hover/m);
|
||||||
|
// still present, just scoped under a per-instance ancestor class
|
||||||
|
expect(html).toMatch(/\.navbar-link:hover/);
|
||||||
|
expect(html).toMatch(/\.[\w-]+ \.navbar-link:hover/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('two navbars with different hoverColor do not leak style onto each other (scoped selectors differ)', () => {
|
||||||
|
const { html: html1 } = toHtml({ hoverColor: '#ff0000' }, '', 'node-nav1');
|
||||||
|
const { html: html2 } = toHtml({ hoverColor: '#00ff00' }, '', 'node-nav2');
|
||||||
|
const scope1 = html1.match(/<style>\s*\.([\w-]+)\s/)![1];
|
||||||
|
const scope2 = html2.match(/<style>\s*\.([\w-]+)\s/)![1];
|
||||||
|
expect(scope1).not.toBe(scope2);
|
||||||
|
expect(html1).toContain(`.${scope1} .navbar-link:hover`);
|
||||||
|
expect(html2).toContain(`.${scope2} .navbar-link:hover`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal single navbar still renders its hover style (visual output preserved)', () => {
|
||||||
|
const { html } = toHtml({ hoverColor: '#ff0000' }, '', 'node-nav1');
|
||||||
|
expect(html).toMatch(/:hover\s*\{\s*color:\s*#ff0000/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('same node id -> identical output across calls (deterministic)', () => {
|
||||||
|
const { html: html1 } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
const { html: html2 } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
expect(html1).toBe(html2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
|
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
|
||||||
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
|
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
|
||||||
const malicious = '#fff}</style><script>alert(1)</script><style>{';
|
const malicious = '#fff}</style><script>alert(1)</script><style>{';
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { CSSProperties, useState } from 'react';
|
|||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl, cssValue, scopeId } from '../../utils/escape';
|
||||||
|
|
||||||
/* ---------- Types ---------- */
|
/* ---------- Types ---------- */
|
||||||
|
|
||||||
@@ -210,7 +210,7 @@ Navbar.craft = {
|
|||||||
|
|
||||||
/* ---------- HTML export ---------- */
|
/* ---------- HTML export ---------- */
|
||||||
|
|
||||||
(Navbar as any).toHtml = (props: NavbarProps, _childrenHtml: string) => {
|
(Navbar as any).toHtml = (props: NavbarProps, _childrenHtml: string, nodeId?: string) => {
|
||||||
// Sanitized once here -- these are raw string-interpolation sinks below
|
// Sanitized once here -- these are raw string-interpolation sinks below
|
||||||
// (hoverCol/bgColor go into a <style> block, the worst case: </style>
|
// (hoverCol/bgColor go into a <style> block, the worst case: </style>
|
||||||
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
|
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
|
||||||
@@ -224,6 +224,19 @@ Navbar.craft = {
|
|||||||
const sticky = props.isSticky;
|
const sticky = props.isSticky;
|
||||||
const mobile = props.showMobileMenu;
|
const mobile = props.showMobileMenu;
|
||||||
const logoUrl = props.logoUrl || '/';
|
const logoUrl = props.logoUrl || '/';
|
||||||
|
const links0 = props.links || defaultLinks;
|
||||||
|
|
||||||
|
// M-1: deterministic AND unique per-instance scope, keyed on the Craft
|
||||||
|
// node id. Two Navbars on the same page previously emitted an identical
|
||||||
|
// fixed id="navbar-links" (invalid duplicate-id HTML, ambiguous
|
||||||
|
// aria-controls target) and unscoped `.navbar-link:hover`/`.navbar-cta:hover`
|
||||||
|
// rules in each instance's own <style> block -- since both blocks target
|
||||||
|
// the SAME global selector, the later one in the DOM silently overrides
|
||||||
|
// the earlier one's hover color/behavior for BOTH navbars. Scoping the
|
||||||
|
// links-container id and adding a per-instance class on the <nav> root
|
||||||
|
// (used to prefix the hover selectors) eliminates both collisions.
|
||||||
|
const scope = scopeId(nodeId, JSON.stringify(links0) + alignment + pad, 'nav');
|
||||||
|
const linksId = `${scope}_links`;
|
||||||
|
|
||||||
const navStyle = cssPropsToString({
|
const navStyle = cssPropsToString({
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
@@ -239,7 +252,7 @@ Navbar.craft = {
|
|||||||
let logoHtml: string;
|
let logoHtml: string;
|
||||||
if (props.logoType === 'image' && props.logoImage) {
|
if (props.logoType === 'image' && props.logoImage) {
|
||||||
const imgStyle = cssPropsToString({ width: props.logoWidth || '120px', height: 'auto', display: 'block' });
|
const imgStyle = cssPropsToString({ width: props.logoWidth || '120px', height: 'auto', display: 'block' });
|
||||||
logoHtml = `<a href="${escapeAttr(safeUrl(logoUrl))}" style="text-decoration:none;display:flex;align-items:center;flex-shrink:0"><img src="${escapeAttr(safeUrl(props.logoImage))}" alt="${escapeAttr(props.logoText || 'Logo')}"${imgStyle ? ` style="${imgStyle}"` : ''} /></a>`;
|
logoHtml = `<a href="${escapeAttr(safeUrl(logoUrl))}" style="text-decoration:none;display:flex;align-items:center;flex-shrink:0"><img src="${escapeAttr(safeImageUrl(props.logoImage))}" alt="${escapeAttr(props.logoText || 'Logo')}"${imgStyle ? ` style="${imgStyle}"` : ''} /></a>`;
|
||||||
} else {
|
} else {
|
||||||
const logoStyle = cssPropsToString({
|
const logoStyle = cssPropsToString({
|
||||||
fontWeight: '700',
|
fontWeight: '700',
|
||||||
@@ -272,21 +285,23 @@ Navbar.craft = {
|
|||||||
// via aria-expanded, kept in sync with the .navbar-open class by the
|
// via aria-expanded, kept in sync with the .navbar-open class by the
|
||||||
// inline onclick handler.
|
// inline onclick handler.
|
||||||
const hamburgerHtml = mobile
|
const hamburgerHtml = mobile
|
||||||
? `\n <button class="navbar-hamburger" aria-label="Toggle navigation menu" aria-expanded="false" aria-controls="navbar-links" onclick="var m=this.parentElement.querySelector('.navbar-links');var open=m.classList.toggle('navbar-open');this.setAttribute('aria-expanded', open ? 'true' : 'false');" style="display:none;background:none;border:none;cursor:pointer;padding:4px;flex-direction:column;gap:4px">
|
? `\n <button class="navbar-hamburger" aria-label="Toggle navigation menu" aria-expanded="false" aria-controls="${escapeAttr(linksId)}" onclick="var m=document.getElementById('${linksId}');var open=m.classList.toggle('navbar-open');this.setAttribute('aria-expanded', open ? 'true' : 'false');" style="display:none;background:none;border:none;cursor:pointer;padding:4px;flex-direction:column;gap:4px">
|
||||||
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
||||||
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
||||||
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
||||||
</button>`
|
</button>`
|
||||||
: '';
|
: '';
|
||||||
|
|
||||||
// Hover CSS
|
// Hover CSS -- scoped under `.${scope}` (a class on the <nav> root, added
|
||||||
|
// below) so it can only ever match THIS instance's links/CTA, never bleed
|
||||||
|
// into or get overridden by another Navbar instance's rules.
|
||||||
const hoverCss = `<style>
|
const hoverCss = `<style>
|
||||||
.navbar-link:hover { color: ${hoverCol} !important; }
|
.${scope} .navbar-link:hover { color: ${hoverCol} !important; }
|
||||||
.navbar-cta:hover { filter: brightness(1.1); }${mobile ? `
|
.${scope} .navbar-cta:hover { filter: brightness(1.1); }${mobile ? `
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.navbar-hamburger { display: flex !important; }
|
.${scope} .navbar-hamburger { display: flex !important; }
|
||||||
.navbar-links { display: none !important; position: absolute; top: 100%; left: 0; right: 0; flex-direction: column !important; background-color: ${bgColor}; padding: 12px 24px; gap: 12px !important; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
|
.${scope} .navbar-links { display: none !important; position: absolute; top: 100%; left: 0; right: 0; flex-direction: column !important; background-color: ${bgColor}; padding: 12px 24px; gap: 12px !important; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
|
||||||
.navbar-links.navbar-open { display: flex !important; }
|
.${scope} .navbar-links.navbar-open { display: flex !important; }
|
||||||
}` : ''}
|
}` : ''}
|
||||||
</style>`;
|
</style>`;
|
||||||
|
|
||||||
@@ -309,9 +324,9 @@ Navbar.craft = {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
html: `${hoverCss}
|
html: `${hoverCss}
|
||||||
<nav${navStyle ? ` style="${navStyle}${mobile ? ';position:relative' : ''}"` : ''}>
|
<nav class="${scope}"${navStyle ? ` style="${navStyle}${mobile ? ';position:relative' : ''}"` : ''}>
|
||||||
${logoHtml}${hamburgerHtml}
|
${logoHtml}${hamburgerHtml}
|
||||||
<div class="navbar-links" id="navbar-links" style="display:flex;align-items:center;gap:24px">
|
<div class="navbar-links" id="${linksId}" style="display:flex;align-items:center;gap:24px">
|
||||||
${linksHtmlWithClass}
|
${linksHtmlWithClass}
|
||||||
</div>
|
</div>
|
||||||
</nav>`,
|
</nav>`,
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
|
||||||
|
/* ImageBlock only needs useNode from @craftjs/core. Mock it following the
|
||||||
|
DOM-harness pattern in src/components/basic/Footer.editguard.test.tsx (no
|
||||||
|
@testing-library/react in this repo) so we can render the real component
|
||||||
|
tree and inspect the emitted <img src> without a real <Editor>. */
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useNode: (collect?: (node: any) => any) => {
|
||||||
|
const node = { events: { selected: false } };
|
||||||
|
return {
|
||||||
|
connectors: { connect: (el: any) => el, drag: (el: any) => el },
|
||||||
|
actions: { setProp: vi.fn() },
|
||||||
|
...(collect ? collect(node) : {}),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { ImageBlock } from './ImageBlock';
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock render falls back to the placeholder for an explicit empty src (Bug 1)', () => {
|
||||||
|
test('src="" (explicit, overrides the default parameter) still renders a non-empty placeholder src', () => {
|
||||||
|
render(<ImageBlock src="" alt="Image" />);
|
||||||
|
const img = container.querySelector('img')!;
|
||||||
|
expect(img.getAttribute('src')).not.toBe('');
|
||||||
|
expect(img.getAttribute('src')).toMatch(/^data:image\/svg\+xml/);
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('src=undefined (default parameter path) still renders the placeholder (unchanged behavior)', () => {
|
||||||
|
render(<ImageBlock alt="Image" />);
|
||||||
|
const img = container.querySelector('img')!;
|
||||||
|
expect(img.getAttribute('src')).not.toBe('');
|
||||||
|
expect(img.getAttribute('src')).toMatch(/^data:image\/svg\+xml/);
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a real src is rendered unchanged', () => {
|
||||||
|
render(<ImageBlock src="https://example.com/photo.jpg" alt="A photo" />);
|
||||||
|
const img = container.querySelector('img')!;
|
||||||
|
expect(img.getAttribute('src')).toBe('https://example.com/photo.jpg');
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import React, { CSSProperties, useCallback, useRef } from 'react';
|
import React, { CSSProperties, useCallback, useRef } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeAttr, safeUrl } from '../../utils/escape';
|
import { escapeAttr, safeImageUrl } from '../../utils/escape';
|
||||||
|
|
||||||
const PLACEHOLDER_SRC = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300'%3E%3Cdefs%3E%3ClinearGradient id='bg' x1='0' y1='0' x2='0' y2='1'%3E%3Cstop offset='0%25' stop-color='%23f1f5f9'/%3E%3Cstop offset='100%25' stop-color='%23e2e8f0'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect fill='url(%23bg)' width='400' height='300' rx='12'/%3E%3Crect x='2' y='2' width='396' height='296' rx='10' fill='none' stroke='%23cbd5e1' stroke-width='2' stroke-dasharray='8 4'/%3E%3Cg transform='translate(200,110)'%3E%3Crect x='-28' y='-28' width='56' height='56' rx='12' fill='%23cbd5e1' opacity='0.5'/%3E%3Cpath d='M-12 8 L-4 -2 L2 4 L8 -6 L16 8Z' fill='%2394a3b8'/%3E%3Ccircle cx='-6' cy='-10' r='5' fill='%2394a3b8'/%3E%3C/g%3E%3Ctext x='200' y='160' text-anchor='middle' fill='%2364748b' font-family='Inter,sans-serif' font-size='15' font-weight='500'%3EDrop image here%3C/text%3E%3Ctext x='200' y='182' text-anchor='middle' fill='%2394a3b8' font-family='Inter,sans-serif' font-size='12'%3Eor click to upload%3C/text%3E%3C/svg%3E";
|
export const PLACEHOLDER_SRC = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300'%3E%3Cdefs%3E%3ClinearGradient id='bg' x1='0' y1='0' x2='0' y2='1'%3E%3Cstop offset='0%25' stop-color='%23f1f5f9'/%3E%3Cstop offset='100%25' stop-color='%23e2e8f0'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect fill='url(%23bg)' width='400' height='300' rx='12'/%3E%3Crect x='2' y='2' width='396' height='296' rx='10' fill='none' stroke='%23cbd5e1' stroke-width='2' stroke-dasharray='8 4'/%3E%3Cg transform='translate(200,110)'%3E%3Crect x='-28' y='-28' width='56' height='56' rx='12' fill='%23cbd5e1' opacity='0.5'/%3E%3Cpath d='M-12 8 L-4 -2 L2 4 L8 -6 L16 8Z' fill='%2394a3b8'/%3E%3Ccircle cx='-6' cy='-10' r='5' fill='%2394a3b8'/%3E%3C/g%3E%3Ctext x='200' y='160' text-anchor='middle' fill='%2364748b' font-family='Inter,sans-serif' font-size='15' font-weight='500'%3EDrop image here%3C/text%3E%3Ctext x='200' y='182' text-anchor='middle' fill='%2394a3b8' font-family='Inter,sans-serif' font-size='12'%3Eor click to upload%3C/text%3E%3C/svg%3E";
|
||||||
|
|
||||||
interface ImageBlockProps {
|
interface ImageBlockProps {
|
||||||
src?: string;
|
src?: string;
|
||||||
@@ -66,7 +66,7 @@ export const ImageBlock: UserComponent<ImageBlockProps> = ({
|
|||||||
imgRef.current = ref;
|
imgRef.current = ref;
|
||||||
if (ref) connect(drag(ref));
|
if (ref) connect(drag(ref));
|
||||||
}}
|
}}
|
||||||
src={src}
|
src={src || PLACEHOLDER_SRC}
|
||||||
alt={alt || 'Image'}
|
alt={alt || 'Image'}
|
||||||
onDrop={handleDrop}
|
onDrop={handleDrop}
|
||||||
onDragOver={handleDragOver}
|
onDragOver={handleDragOver}
|
||||||
@@ -95,5 +95,5 @@ ImageBlock.craft = {
|
|||||||
}
|
}
|
||||||
const s = cssPropsToString({ display: 'block', maxWidth: '100%', ...props.style });
|
const s = cssPropsToString({ display: 'block', maxWidth: '100%', ...props.style });
|
||||||
const alt = props.alt ? ` alt="${escapeAttr(props.alt)}"` : ' alt=""';
|
const alt = props.alt ? ` alt="${escapeAttr(props.alt)}"` : ' alt=""';
|
||||||
return { html: `<img src="${escapeAttr(safeUrl(src))}"${alt}${s ? ` style="${s}"` : ''} />` };
|
return { html: `<img src="${escapeAttr(safeImageUrl(src))}"${alt}${s ? ` style="${s}"` : ''} />` };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -109,6 +109,15 @@ describe('ContentSlider.toHtml renders slide.imageSrc as a background-image (INT
|
|||||||
expect(html).not.toContain('background-image:url(');
|
expect(html).not.toContain('background-image:url(');
|
||||||
expect(html).toContain('background-color:#123456');
|
expect(html).toContain('background-color:#123456');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a slide with a data:image/svg+xml imageSrc exports a non-empty background-image url (safeImageUrl, not safeUrl)', () => {
|
||||||
|
const svgDataUri = 'data:image/svg+xml,%3Csvg%2F%3E';
|
||||||
|
const slidesWithSvg = [
|
||||||
|
{ type: 'image' as const, imageSrc: svgDataUri, heading: 'One' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ slides: slidesWithSvg }, '');
|
||||||
|
expect(html).toContain(`background-image:url('${svgDataUri}')`);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('ContentSlider.toHtml interval is NOT runtime-type-checked -- must be coerced before it reaches the inline <script> numeric context', () => {
|
describe('ContentSlider.toHtml interval is NOT runtime-type-checked -- must be coerced before it reaches the inline <script> numeric context', () => {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { CSSProperties, useState, useEffect, useRef, useCallback } from 'react';
|
import React, { CSSProperties, useState, useEffect, useRef, useCallback } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl, scopeId, cssValue } from '../../utils/escape';
|
||||||
|
|
||||||
interface Slide {
|
interface Slide {
|
||||||
type: 'image' | 'content';
|
type: 'image' | 'content';
|
||||||
@@ -283,7 +283,7 @@ ContentSlider.craft = {
|
|||||||
// sink (a malicious value could break out of the style="..." attribute).
|
// sink (a malicious value could break out of the style="..." attribute).
|
||||||
const safeBgColor = cssValue(slide.bgColor) || '#3b82f6';
|
const safeBgColor = cssValue(slide.bgColor) || '#3b82f6';
|
||||||
const bgStyle = hasBgImage
|
const bgStyle = hasBgImage
|
||||||
? `background-image:url('${escapeAttr(safeUrl(slide.imageSrc!))}');background-size:cover;background-position:center`
|
? `background-image:url('${escapeAttr(safeImageUrl(slide.imageSrc!))}');background-size:cover;background-position:center`
|
||||||
: slide.bgColor?.startsWith('linear-gradient')
|
: slide.bgColor?.startsWith('linear-gradient')
|
||||||
? `background-image:${safeBgColor}`
|
? `background-image:${safeBgColor}`
|
||||||
: `background-color:${safeBgColor}`;
|
: `background-color:${safeBgColor}`;
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { FeaturesGrid } from './FeaturesGrid';
|
||||||
|
|
||||||
|
const toHtml = (FeaturesGrid as any).toHtml;
|
||||||
|
|
||||||
|
describe('FeaturesGrid.toHtml image sink uses safeImageUrl (data:image/svg+xml allowed)', () => {
|
||||||
|
test('feat.image as a data:image/svg+xml value emits a non-empty <img src>', () => {
|
||||||
|
const svgDataUri = 'data:image/svg+xml,%3Csvg%2F%3E';
|
||||||
|
const features = [
|
||||||
|
{ title: 'Feature', description: 'Desc', icon: '⚡', image: svgDataUri, imageAlt: 'alt' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ features }, '');
|
||||||
|
expect(html).toContain(`<img src="${svgDataUri}"`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('feat.buttonUrl stays on safeUrl (data:image/svg+xml blocked as a navigation target)', () => {
|
||||||
|
const features = [
|
||||||
|
{ title: 'Feature', description: 'Desc', icon: '⚡', buttonText: 'Go', buttonUrl: 'data:image/svg+xml,<svg onload=alert(1)>' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ features }, '');
|
||||||
|
expect(html).toMatch(/<a href=""/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { CSSProperties } from 'react';
|
import React, { CSSProperties } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl } from '../../utils/escape';
|
||||||
|
|
||||||
interface FeatureItem {
|
interface FeatureItem {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -116,7 +116,7 @@ FeaturesGrid.craft = {
|
|||||||
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
||||||
const cards = (props.features || defaultFeatures).map((feat) => {
|
const cards = (props.features || defaultFeatures).map((feat) => {
|
||||||
const media = feat.image
|
const media = feat.image
|
||||||
? `<img src="${escapeAttr(safeUrl(feat.image))}" alt="${escapeAttr(feat.imageAlt || feat.title || '')}" style="max-width:100%;height:auto;margin-bottom:16px;border-radius:8px">`
|
? `<img src="${escapeAttr(safeImageUrl(feat.image))}" alt="${escapeAttr(feat.imageAlt || feat.title || '')}" style="max-width:100%;height:auto;margin-bottom:16px;border-radius:8px">`
|
||||||
: `<div style="font-size:36px;margin-bottom:16px">${escapeHtml(feat.icon)}</div>`;
|
: `<div style="font-size:36px;margin-bottom:16px">${escapeHtml(feat.icon)}</div>`;
|
||||||
const button = feat.buttonText
|
const button = feat.buttonText
|
||||||
? `\n <a href="${escapeAttr(safeUrl(feat.buttonUrl || '#'))}" style="display:inline-block;margin-top:16px;padding:10px 24px;background:#3b82f6;color:#fff;border-radius:8px;text-decoration:none;font-size:14px;font-weight:600">${escapeHtml(feat.buttonText)}</a>`
|
? `\n <a href="${escapeAttr(safeUrl(feat.buttonUrl || '#'))}" style="display:inline-block;margin-top:16px;padding:10px 24px;background:#3b82f6;color:#fff;border-radius:8px;text-decoration:none;font-size:14px;font-weight:600">${escapeHtml(feat.buttonText)}</a>`
|
||||||
|
|||||||
@@ -93,3 +93,59 @@ describe('Gallery.toHtml deterministic + unique scope ids (thread node id, no Ma
|
|||||||
expect(html1).toBe(html2);
|
expect(html1).toBe(html2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Gallery.toHtml default SVG placeholder images survive export (Bug 2 regression)', () => {
|
||||||
|
test('a default data:image/svg+xml image emits a non-empty img src, not src=""', () => {
|
||||||
|
const { html } = toHtml({}, ''); // no images prop -> component default SVG placeholders
|
||||||
|
expect(html).not.toContain('src=""');
|
||||||
|
expect(html).toMatch(/src="data:image\/svg\+xml[^"]*"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an explicit data:image/svg+xml gallery image src is preserved (not stripped to empty)', () => {
|
||||||
|
const svg = 'data:image/svg+xml,%3Csvg%2F%3E';
|
||||||
|
const { html } = toHtml({ images: [{ src: svg, alt: 'a' }] }, '');
|
||||||
|
expect(html).toContain(`src="${svg}"`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('lightbox data-lb-src also preserves data:image/svg+xml (still an image context)', () => {
|
||||||
|
const svg = 'data:image/svg+xml,%3Csvg%2F%3E';
|
||||||
|
const { html } = toHtml({ images: [{ src: svg, alt: 'a' }], lightbox: true }, '');
|
||||||
|
expect(html).toContain(`data-lb-src="${svg}"`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a javascript: gallery image src still yields an empty src (safeImageUrl still blocks it)', () => {
|
||||||
|
const { html } = toHtml({ images: [{ src: 'javascript:alert(1)', alt: 'a' }] }, '');
|
||||||
|
expect(html).toContain('src=""');
|
||||||
|
expect(html).not.toContain('javascript:');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Gallery.toHtml lightbox focus management (M-2)', () => {
|
||||||
|
const props = { images: [{ src: '/a.jpg', alt: 'a' }], lightbox: true };
|
||||||
|
|
||||||
|
test('overlay includes a focusable close control with an accessible name and tabindex', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
// A close control: a button (or the dialog container) with an accessible
|
||||||
|
// name (aria-label) and an explicit tabindex so it's keyboard-focusable.
|
||||||
|
expect(html).toMatch(/aria-label="[^"]*[Cc]lose[^"]*"[^>]*tabindex="-?\d+"|tabindex="-?\d+"[^>]*aria-label="[^"]*[Cc]lose[^"]*"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script saves document.activeElement on open (for focus restore)', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
expect(html).toMatch(/document\.activeElement/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script moves focus to the close control / dialog on open', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
expect(html).toMatch(/\.focus\(\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script restores the previously-saved focus on close', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
// The close function references a stored "last focused element" variable
|
||||||
|
// and calls .focus() on it, not just moving focus INTO the dialog.
|
||||||
|
const closeFnMatch = html.match(/function\s+\w+_close\s*\(\)\s*\{[^}]*\}/);
|
||||||
|
expect(closeFnMatch).not.toBeNull();
|
||||||
|
expect(closeFnMatch![0]).toMatch(/\.focus\(\)/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { CSSProperties } from 'react';
|
import React, { CSSProperties } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeImageUrl, scopeId, cssValue } from '../../utils/escape';
|
||||||
|
|
||||||
interface GalleryImage {
|
interface GalleryImage {
|
||||||
src: string;
|
src: string;
|
||||||
@@ -154,10 +154,10 @@ Gallery.craft = {
|
|||||||
// inline onclick with an interpolated src -- a single delegated click
|
// inline onclick with an interpolated src -- a single delegated click
|
||||||
// listener below reads it, so a src containing a quote can't break out
|
// listener below reads it, so a src containing a quote can't break out
|
||||||
// of a per-item event-handler string.
|
// of a per-item event-handler string.
|
||||||
const lbAttr = lightbox ? ` data-lb-src="${escapeAttr(safeUrl(img.src || ''))}" role="button" tabindex="0"` : '';
|
const lbAttr = lightbox ? ` data-lb-src="${escapeAttr(safeImageUrl(img.src || ''))}" role="button" tabindex="0"` : '';
|
||||||
const itemStyle = lightbox ? 'cursor:pointer;position:relative;overflow:hidden;border-radius:8px' : 'position:relative;overflow:hidden;border-radius:8px';
|
const itemStyle = lightbox ? 'cursor:pointer;position:relative;overflow:hidden;border-radius:8px' : 'position:relative;overflow:hidden;border-radius:8px';
|
||||||
return `<div${lbAttr} style="${itemStyle}">
|
return `<div${lbAttr} style="${itemStyle}">
|
||||||
<img src="${escapeAttr(safeUrl(img.src || ''))}" alt="${escapeAttr(img.alt)}" style="width:100%;height:200px;object-fit:cover;display:block;border-radius:8px;background-color:#f1f5f9" />
|
<img src="${escapeAttr(safeImageUrl(img.src || ''))}" alt="${escapeAttr(img.alt)}" style="width:100%;height:200px;object-fit:cover;display:block;border-radius:8px;background-color:#f1f5f9" />
|
||||||
${caption}
|
${caption}
|
||||||
</div>`;
|
</div>`;
|
||||||
}).join('\n ');
|
}).join('\n ');
|
||||||
@@ -166,16 +166,37 @@ Gallery.craft = {
|
|||||||
let gridIdAttr = '';
|
let gridIdAttr = '';
|
||||||
if (lightbox) {
|
if (lightbox) {
|
||||||
gridIdAttr = ` id="${galleryId}_grid"`;
|
gridIdAttr = ` id="${galleryId}_grid"`;
|
||||||
|
// M-2: focus management for the lightbox dialog.
|
||||||
|
// - OPEN: stash `document.activeElement` (the thumbnail that triggered
|
||||||
|
// the open) in a module-scoped var, then move focus onto the close
|
||||||
|
// button -- so a screen-reader/keyboard user lands inside the dialog
|
||||||
|
// instead of focus staying on (or silently falling back to <body>)
|
||||||
|
// behind the now-visible overlay.
|
||||||
|
// - Tab trap: while the overlay is open, every Tab keypress is
|
||||||
|
// intercepted and refocuses the close button (the dialog's only
|
||||||
|
// focusable control besides Escape/click-to-close), so focus can
|
||||||
|
// never wander out into the page content hidden behind the overlay.
|
||||||
|
// - CLOSE (Escape, backdrop click, or the close button): restore focus
|
||||||
|
// to the element stashed on open.
|
||||||
lightboxHtml = `
|
lightboxHtml = `
|
||||||
<div id="${galleryId}_overlay" role="dialog" aria-modal="true" aria-label="Image preview" onclick="${galleryId}_close()" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:9999;justify-content:center;align-items:center;cursor:pointer">
|
<div id="${galleryId}_overlay" role="dialog" aria-modal="true" aria-label="Image preview" onclick="${galleryId}_close()" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:9999;justify-content:center;align-items:center;cursor:pointer">
|
||||||
|
<button type="button" id="${galleryId}_closebtn" aria-label="Close preview" tabindex="-1" onclick="event.stopPropagation();${galleryId}_close()" style="position:absolute;top:16px;right:16px;width:36px;height:36px;border-radius:50%;border:none;background:rgba(255,255,255,0.15);color:#ffffff;font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center">×</button>
|
||||||
<img id="${galleryId}_img" src="" alt="" style="max-width:90%;max-height:90%;object-fit:contain;border-radius:8px" />
|
<img id="${galleryId}_img" src="" alt="" style="max-width:90%;max-height:90%;object-fit:contain;border-radius:8px" />
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
function ${galleryId}_close(){document.getElementById('${galleryId}_overlay').style.display='none';}
|
var ${galleryId}_lastFocus = null;
|
||||||
|
function ${galleryId}_close(){
|
||||||
|
document.getElementById('${galleryId}_overlay').style.display='none';
|
||||||
|
if(${galleryId}_lastFocus && ${galleryId}_lastFocus.focus) ${galleryId}_lastFocus.focus();
|
||||||
|
${galleryId}_lastFocus = null;
|
||||||
|
}
|
||||||
function ${galleryId}_open(src){
|
function ${galleryId}_open(src){
|
||||||
|
${galleryId}_lastFocus = document.activeElement;
|
||||||
var o = document.getElementById('${galleryId}_overlay');
|
var o = document.getElementById('${galleryId}_overlay');
|
||||||
document.getElementById('${galleryId}_img').src = src;
|
document.getElementById('${galleryId}_img').src = src;
|
||||||
o.style.display = 'flex';
|
o.style.display = 'flex';
|
||||||
|
var c = document.getElementById('${galleryId}_closebtn');
|
||||||
|
if(c) c.focus();
|
||||||
}
|
}
|
||||||
document.getElementById('${galleryId}_grid').addEventListener('click', function(e){
|
document.getElementById('${galleryId}_grid').addEventListener('click', function(e){
|
||||||
var t = e.target.closest('[data-lb-src]');
|
var t = e.target.closest('[data-lb-src]');
|
||||||
@@ -190,7 +211,14 @@ document.getElementById('${galleryId}_grid').addEventListener('keydown', functio
|
|||||||
${galleryId}_open(t.getAttribute('data-lb-src'));
|
${galleryId}_open(t.getAttribute('data-lb-src'));
|
||||||
});
|
});
|
||||||
document.addEventListener('keydown', function(e){
|
document.addEventListener('keydown', function(e){
|
||||||
if(e.key==='Escape'){ ${galleryId}_close(); }
|
var o = document.getElementById('${galleryId}_overlay');
|
||||||
|
if(!o || o.style.display==='none') return;
|
||||||
|
if(e.key==='Escape'){ ${galleryId}_close(); return; }
|
||||||
|
if(e.key==='Tab'){
|
||||||
|
e.preventDefault();
|
||||||
|
var c = document.getElementById('${galleryId}_closebtn');
|
||||||
|
if(c) c.focus();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
</script>`;
|
</script>`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useMemo, useRef, useEffect } from 'react';
|
import React, { useMemo, useRef, useEffect } from 'react';
|
||||||
import { Frame, Element } from '@craftjs/core';
|
import { Frame, Element, useEditor } from '@craftjs/core';
|
||||||
import { Container } from '../components/layout/Container';
|
import { Container } from '../components/layout/Container';
|
||||||
import { usePages } from '../state/PageContext';
|
import { usePages } from '../state/PageContext';
|
||||||
import { DeviceMode } from '../types';
|
import { DeviceMode } from '../types';
|
||||||
@@ -8,6 +8,8 @@ import { exportBodyHtml } from '../utils/html-export';
|
|||||||
|
|
||||||
interface CanvasProps {
|
interface CanvasProps {
|
||||||
device: DeviceMode;
|
device: DeviceMode;
|
||||||
|
/** Item 10: when false, applies `.guides-off` to hide the dashed drop-target guides. */
|
||||||
|
showGuides: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -81,19 +83,47 @@ const ZonePreview: React.FC<{ craftState: string | null; zone: 'header' | 'foote
|
|||||||
<div
|
<div
|
||||||
ref={containerRef}
|
ref={containerRef}
|
||||||
data-zone-preview={zone}
|
data-zone-preview={zone}
|
||||||
|
className="zone-preview-sep"
|
||||||
style={{
|
style={{
|
||||||
width: '100%',
|
width: '100%',
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
pointerEvents: 'none',
|
pointerEvents: 'none',
|
||||||
userSelect: 'none',
|
userSelect: 'none',
|
||||||
borderBottom: zone === 'header' ? '1px dashed rgba(245,158,11,0.3)' : 'none',
|
borderBottom: zone === 'header' ? '1px dashed rgba(148,163,184,0.25)' : 'none',
|
||||||
borderTop: zone === 'footer' ? '1px dashed rgba(245,158,11,0.3)' : 'none',
|
borderTop: zone === 'footer' ? '1px dashed rgba(148,163,184,0.25)' : 'none',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
/**
|
||||||
|
* First-run hint shown over the canvas drop area once the current page's
|
||||||
|
* root node exists and has no children yet. Hidden the instant something
|
||||||
|
* is dropped in, and while a drag is in progress (so it never fights the
|
||||||
|
* drop-target UI). `pointer-events: none` (see .empty-canvas-hint in
|
||||||
|
* editor.css) keeps it from intercepting clicks/drops meant for the
|
||||||
|
* underlying empty canvas.
|
||||||
|
*/
|
||||||
|
export const EmptyCanvasHint: React.FC = () => {
|
||||||
|
const { isEmpty, isDragging } = useEditor((state) => {
|
||||||
|
const root = state.nodes['ROOT'];
|
||||||
|
return {
|
||||||
|
isEmpty: !!root && root.data.nodes.length === 0,
|
||||||
|
isDragging: state.events.dragged.size > 0,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!isEmpty || isDragging) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="empty-canvas-hint">
|
||||||
|
<i className="fa fa-cubes" aria-hidden />
|
||||||
|
<span>Drag blocks from the left panel, or pick a Template to start.</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const Canvas: React.FC<CanvasProps> = ({ device, showGuides }) => {
|
||||||
const width = DEVICE_WIDTHS[device];
|
const width = DEVICE_WIDTHS[device];
|
||||||
const { isEditingHeader, isEditingFooter, headerPage, footerPage } = usePages();
|
const { isEditingHeader, isEditingFooter, headerPage, footerPage } = usePages();
|
||||||
|
|
||||||
@@ -110,7 +140,7 @@ export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
|||||||
return (
|
return (
|
||||||
<div className="editor-canvas">
|
<div className="editor-canvas">
|
||||||
<div
|
<div
|
||||||
className="canvas-device-frame"
|
className={`canvas-device-frame${showGuides ? '' : ' guides-off'}`}
|
||||||
style={{
|
style={{
|
||||||
width,
|
width,
|
||||||
maxWidth: '100%',
|
maxWidth: '100%',
|
||||||
@@ -140,6 +170,7 @@ export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
|||||||
<ZonePreview craftState={headerPage.craftState} zone="header" />
|
<ZonePreview craftState={headerPage.craftState} zone="header" />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<div style={{ position: 'relative' }}>
|
||||||
<Frame>
|
<Frame>
|
||||||
<Element
|
<Element
|
||||||
is={Container}
|
is={Container}
|
||||||
@@ -148,6 +179,8 @@ export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
|||||||
style={frameStyle}
|
style={frameStyle}
|
||||||
/>
|
/>
|
||||||
</Frame>
|
</Frame>
|
||||||
|
{isEditingRegularPage && <EmptyCanvasHint />}
|
||||||
|
</div>
|
||||||
|
|
||||||
{isEditingRegularPage && (
|
{isEditingRegularPage && (
|
||||||
<ZonePreview craftState={footerPage.craftState} zone="footer" />
|
<ZonePreview craftState={footerPage.craftState} zone="footer" />
|
||||||
|
|||||||
@@ -9,8 +9,34 @@ import { useContextMenu } from '../hooks/useContextMenu';
|
|||||||
import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts';
|
import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts';
|
||||||
import { DeviceMode } from '../types';
|
import { DeviceMode } from '../types';
|
||||||
|
|
||||||
|
const SHOW_GUIDES_STORAGE_KEY = 'craft-show-guides';
|
||||||
|
|
||||||
|
function loadShowGuides(): boolean {
|
||||||
|
try {
|
||||||
|
const stored = window.localStorage.getItem(SHOW_GUIDES_STORAGE_KEY);
|
||||||
|
return stored === null ? true : stored === '1';
|
||||||
|
} catch {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const EditorShell: React.FC = () => {
|
export const EditorShell: React.FC = () => {
|
||||||
const [device, setDevice] = useState<DeviceMode>('desktop');
|
const [device, setDevice] = useState<DeviceMode>('desktop');
|
||||||
|
// Item 10: canvas dashed "guide" outlines toggle -- default ON, persisted
|
||||||
|
// so the choice survives a reload. Lifted here (rather than owned by
|
||||||
|
// TopBar or Canvas alone) because the toggle button lives in TopBar but
|
||||||
|
// the `.guides-off` class it drives is applied to Canvas's
|
||||||
|
// `.canvas-device-frame`, mirroring how `device` is already lifted for
|
||||||
|
// the same reason.
|
||||||
|
const [showGuides, setShowGuidesState] = useState<boolean>(loadShowGuides);
|
||||||
|
const setShowGuides = useCallback((next: boolean) => {
|
||||||
|
setShowGuidesState(next);
|
||||||
|
try {
|
||||||
|
window.localStorage.setItem(SHOW_GUIDES_STORAGE_KEY, next ? '1' : '0');
|
||||||
|
} catch {
|
||||||
|
// Storage unavailable (private browsing, etc.) -- in-memory state still works.
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
const { menuState, show: showMenu, hide: hideMenu } = useContextMenu();
|
const { menuState, show: showMenu, hide: hideMenu } = useContextMenu();
|
||||||
const { query } = useEditor();
|
const { query } = useEditor();
|
||||||
|
|
||||||
@@ -34,11 +60,16 @@ export const EditorShell: React.FC = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="editor-app">
|
<div className="editor-app">
|
||||||
<TopBar device={device} onDeviceChange={setDevice} />
|
<TopBar
|
||||||
|
device={device}
|
||||||
|
onDeviceChange={setDevice}
|
||||||
|
showGuides={showGuides}
|
||||||
|
onToggleGuides={() => setShowGuides(!showGuides)}
|
||||||
|
/>
|
||||||
<div className="editor-container">
|
<div className="editor-container">
|
||||||
<LeftPanel />
|
<LeftPanel />
|
||||||
<div onContextMenu={handleContextMenu} style={{ flex: 1, display: 'flex', minWidth: 0 }}>
|
<div onContextMenu={handleContextMenu} style={{ flex: 1, display: 'flex', minWidth: 0 }}>
|
||||||
<Canvas device={device} />
|
<Canvas device={device} showGuides={showGuides} />
|
||||||
</div>
|
</div>
|
||||||
<RightPanel />
|
<RightPanel />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
|
||||||
|
/* Same DOM-harness pattern as Footer.editguard.test.tsx: mock @craftjs/core's
|
||||||
|
useEditor so we can drive editor state without a real <Editor> tree. */
|
||||||
|
let mockNodes: Record<string, { data: { nodes: string[] } }> = {};
|
||||||
|
let mockDraggedSize = 0;
|
||||||
|
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useEditor: (collect: (state: any) => any) =>
|
||||||
|
collect({
|
||||||
|
nodes: mockNodes,
|
||||||
|
events: { dragged: { size: mockDraggedSize } },
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { EmptyCanvasHint } from './Canvas';
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockNodes = {};
|
||||||
|
mockDraggedSize = 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('EmptyCanvasHint', () => {
|
||||||
|
test('renders nothing before ROOT has mounted (no root node yet)', () => {
|
||||||
|
render(<EmptyCanvasHint />);
|
||||||
|
expect(container.querySelector('.empty-canvas-hint')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renders the hint once ROOT exists with zero children', () => {
|
||||||
|
mockNodes = { ROOT: { data: { nodes: [] } } };
|
||||||
|
render(<EmptyCanvasHint />);
|
||||||
|
expect(container.querySelector('.empty-canvas-hint')).not.toBeNull();
|
||||||
|
expect(container.textContent).toContain('Drag blocks from the left panel');
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hides once the page has content', () => {
|
||||||
|
mockNodes = { ROOT: { data: { nodes: ['node-1'] } } };
|
||||||
|
render(<EmptyCanvasHint />);
|
||||||
|
expect(container.querySelector('.empty-canvas-hint')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hides while a drag is in progress, even on an empty root', () => {
|
||||||
|
mockNodes = { ROOT: { data: { nodes: [] } } };
|
||||||
|
mockDraggedSize = 1;
|
||||||
|
render(<EmptyCanvasHint />);
|
||||||
|
expect(container.querySelector('.empty-canvas-hint')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
|
||||||
|
/* Same DOM-harness pattern as Footer.editguard.test.tsx: mock @craftjs/core
|
||||||
|
so RenderNode (the <Editor onRender> override) can be driven without a
|
||||||
|
real Editor tree. document.body doubles as the portal target, same as
|
||||||
|
the component itself uses. */
|
||||||
|
let mockNode: {
|
||||||
|
id: string;
|
||||||
|
selected: boolean;
|
||||||
|
hovered: boolean;
|
||||||
|
dom: HTMLElement | null;
|
||||||
|
displayName: string;
|
||||||
|
parent: string | null;
|
||||||
|
isCanvas: boolean;
|
||||||
|
};
|
||||||
|
const selectNodeSpy = vi.fn();
|
||||||
|
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useEditor: () => ({ actions: { selectNode: selectNodeSpy } }),
|
||||||
|
useNode: (collect?: (node: any) => any) => {
|
||||||
|
const node = {
|
||||||
|
events: { selected: mockNode.selected, hovered: mockNode.hovered },
|
||||||
|
dom: mockNode.dom,
|
||||||
|
data: {
|
||||||
|
custom: {},
|
||||||
|
displayName: mockNode.displayName,
|
||||||
|
parent: mockNode.parent,
|
||||||
|
isCanvas: mockNode.isCanvas,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { id: mockNode.id, ...(collect ? collect(node) : {}) };
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { RenderNode } from './RenderNode';
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
let nodeDom: HTMLElement;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
nodeDom = document.createElement('div');
|
||||||
|
document.body.appendChild(nodeDom);
|
||||||
|
mockNode = {
|
||||||
|
id: 'node-1',
|
||||||
|
selected: false,
|
||||||
|
hovered: false,
|
||||||
|
dom: nodeDom,
|
||||||
|
displayName: 'Heading',
|
||||||
|
parent: 'ROOT',
|
||||||
|
isCanvas: false,
|
||||||
|
};
|
||||||
|
selectNodeSpy.mockClear();
|
||||||
|
});
|
||||||
|
|
||||||
|
const rendered = <span data-testid="inner">hello</span>;
|
||||||
|
|
||||||
|
describe('RenderNode (Editor onRender override)', () => {
|
||||||
|
test('passes render through untouched when not selected', () => {
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(container.querySelector('[data-testid="inner"]')).not.toBeNull();
|
||||||
|
expect(document.querySelector('.component-indicator')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shows the badge with the displayName when selected', () => {
|
||||||
|
mockNode.selected = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
const badge = document.querySelector('.component-indicator');
|
||||||
|
expect(badge).not.toBeNull();
|
||||||
|
expect(badge?.textContent).toContain('Heading');
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
document.querySelector('.component-indicator')?.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('never shows a badge for ROOT even if "selected"', () => {
|
||||||
|
mockNode.selected = true;
|
||||||
|
mockNode.id = 'ROOT';
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(document.querySelector('.component-indicator')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('chevron click selects the parent node', () => {
|
||||||
|
mockNode.selected = true;
|
||||||
|
mockNode.parent = 'parent-42';
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
const chevron = document.querySelector('.component-indicator-parent-btn') as HTMLElement;
|
||||||
|
expect(chevron).not.toBeNull();
|
||||||
|
act(() => {
|
||||||
|
chevron.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
|
||||||
|
});
|
||||||
|
expect(selectNodeSpy).toHaveBeenCalledWith('parent-42');
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
document.querySelector('.component-indicator')?.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no chevron when there is no parent', () => {
|
||||||
|
mockNode.selected = true;
|
||||||
|
mockNode.parent = null;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(document.querySelector('.component-indicator-parent-btn')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
document.querySelector('.component-indicator')?.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tags a droppable (isCanvas) node dom with data-craft-node', () => {
|
||||||
|
mockNode.isCanvas = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-node')).toBe(true);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not tag a non-canvas (leaf) node dom with data-craft-node', () => {
|
||||||
|
mockNode.isCanvas = false;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-node')).toBe(false);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('never tags ROOT with data-craft-node even though ROOT is a canvas', () => {
|
||||||
|
mockNode.id = 'ROOT';
|
||||||
|
mockNode.isCanvas = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-node')).toBe(false);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tags the dom with data-craft-hovered when the Craft hovered event is set (Layers panel hover sync)', () => {
|
||||||
|
mockNode.hovered = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-hovered')).toBe(true);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('removes data-craft-hovered once the hovered event clears', () => {
|
||||||
|
mockNode.hovered = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-hovered')).toBe(true);
|
||||||
|
mockNode.hovered = false;
|
||||||
|
act(() => {
|
||||||
|
root.render(<RenderNode render={rendered} />);
|
||||||
|
});
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-hovered')).toBe(false);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import React, { useCallback, useEffect, useRef } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import { useEditor, useNode } from '@craftjs/core';
|
||||||
|
|
||||||
|
interface RenderNodeProps {
|
||||||
|
render: React.ReactElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Craft.js `<Editor onRender>` override -- wraps every node's render output.
|
||||||
|
* For the currently-selected node it portals a floating badge (component
|
||||||
|
* displayName + a "select parent" chevron) positioned over the node's real
|
||||||
|
* DOM element. Non-selected nodes (the overwhelming majority) and ROOT pass
|
||||||
|
* straight through as a Fragment, so this never touches layout, never
|
||||||
|
* appears in `toHtml` export (that walks the Craft node tree, not this
|
||||||
|
* portal), and doesn't wrap every node in extra DOM.
|
||||||
|
*
|
||||||
|
* It also imperatively tags each node's real DOM element with two
|
||||||
|
* editor-only data attributes (never part of `toHtml` export, which walks
|
||||||
|
* the Craft node tree, not the live DOM):
|
||||||
|
* - `data-craft-node`: set on actual Craft.js droppable containers
|
||||||
|
* (`node.data.isCanvas`, excluding ROOT). `editor.css`'s dashed "guide"
|
||||||
|
* outlines target this attribute instead of blanket tag selectors
|
||||||
|
* (div/section/header/...), so a component's own internal wrapper markup
|
||||||
|
* no longer picks up a guide outline it isn't a real drop target for.
|
||||||
|
* - `data-craft-hovered`: mirrors `node.events.hovered` (Craft's hover
|
||||||
|
* event set). Craft's own `connectors.connect()` (called by every
|
||||||
|
* component) wires a native mouseover/mouseleave listener to this event
|
||||||
|
* internally, so a plain mouse hover over any connected node sets it --
|
||||||
|
* this attribute is a real-mouse-hover canvas highlight. (The Layers
|
||||||
|
* panel's row-hover -> canvas-highlight sync, item 12, uses a sibling
|
||||||
|
* `data-layer-hovered` attribute written directly by LayersPanel.tsx
|
||||||
|
* instead of this event, since the action that would drive it here
|
||||||
|
* -- `actions.setNodeEvent` -- is stripped from the public `useEditor()`
|
||||||
|
* API at runtime.) editor.css matches both attributes for the same
|
||||||
|
* outline and suppresses both under `.guides-off`.
|
||||||
|
*/
|
||||||
|
export const RenderNode: React.FC<RenderNodeProps> = ({ render }) => {
|
||||||
|
const { actions } = useEditor();
|
||||||
|
const { id, isSelected, dom, name, parent, isCanvas, isHovered } = useNode((node) => ({
|
||||||
|
isSelected: node.events.selected,
|
||||||
|
isHovered: node.events.hovered,
|
||||||
|
dom: node.dom,
|
||||||
|
name: (node.data.props?.aiName as string) || node.data.displayName,
|
||||||
|
parent: node.data.parent,
|
||||||
|
isCanvas: node.data.isCanvas,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const badgeRef = useRef<HTMLDivElement>(null);
|
||||||
|
const active = isSelected && id !== 'ROOT' && !!dom;
|
||||||
|
|
||||||
|
const updatePosition = useCallback(() => {
|
||||||
|
if (!dom || !badgeRef.current) return;
|
||||||
|
const rect = dom.getBoundingClientRect();
|
||||||
|
const badgeHeight = 22;
|
||||||
|
badgeRef.current.style.left = `${Math.max(rect.left, 0)}px`;
|
||||||
|
badgeRef.current.style.top = `${Math.max(rect.top - badgeHeight, 0)}px`;
|
||||||
|
}, [dom]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return;
|
||||||
|
updatePosition();
|
||||||
|
window.addEventListener('resize', updatePosition);
|
||||||
|
document.addEventListener('scroll', updatePosition, true);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('resize', updatePosition);
|
||||||
|
document.removeEventListener('scroll', updatePosition, true);
|
||||||
|
};
|
||||||
|
}, [active, updatePosition]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!dom) return;
|
||||||
|
if (isCanvas && id !== 'ROOT') {
|
||||||
|
dom.setAttribute('data-craft-node', '');
|
||||||
|
} else {
|
||||||
|
dom.removeAttribute('data-craft-node');
|
||||||
|
}
|
||||||
|
}, [dom, isCanvas, id]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!dom) return;
|
||||||
|
if (isHovered) {
|
||||||
|
dom.setAttribute('data-craft-hovered', '');
|
||||||
|
} else {
|
||||||
|
dom.removeAttribute('data-craft-hovered');
|
||||||
|
}
|
||||||
|
}, [dom, isHovered]);
|
||||||
|
|
||||||
|
if (!active) return <>{render}</>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{render}
|
||||||
|
{createPortal(
|
||||||
|
<div ref={badgeRef} className="component-indicator" style={{ position: 'fixed' }}>
|
||||||
|
<span>{name}</span>
|
||||||
|
{parent && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="component-indicator-parent-btn"
|
||||||
|
title="Select parent"
|
||||||
|
aria-label={`Select parent of ${name}`}
|
||||||
|
onMouseDown={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
actions.selectNode(parent);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<i className="fa fa-chevron-up" aria-hidden />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { describe, test, expect } from 'vitest';
|
import { describe, test, expect } from 'vitest';
|
||||||
import { buildSavePayload } from './useWhpApi';
|
import { buildSavePayload } from './useWhpApi';
|
||||||
import { PageData } from '../types';
|
import { PageData } from '../types';
|
||||||
|
import { DEFAULT_SITE_DESIGN } from '../state/SiteDesignContext';
|
||||||
|
|
||||||
const pageA: PageData = { id: 'home', name: 'Home', slug: 'index', craftState: 'STORED_HOME' };
|
const pageA: PageData = { id: 'home', name: 'Home', slug: 'index', craftState: 'STORED_HOME' };
|
||||||
const pageB: PageData = { id: 'page_2', name: 'About', slug: 'about', craftState: 'STORED_ABOUT' };
|
const pageB: PageData = { id: 'page_2', name: 'About', slug: 'about', craftState: 'STORED_ABOUT' };
|
||||||
@@ -19,6 +20,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: '__header__',
|
activePageId: '__header__',
|
||||||
isEditingHeader: true,
|
isEditingHeader: true,
|
||||||
isEditingFooter: false,
|
isEditingFooter: false,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
// The fresh live canvas must be reflected in header_craft_state, not the stale stored one.
|
// The fresh live canvas must be reflected in header_craft_state, not the stale stored one.
|
||||||
@@ -52,6 +55,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: '__footer__',
|
activePageId: '__footer__',
|
||||||
isEditingHeader: false,
|
isEditingHeader: false,
|
||||||
isEditingFooter: true,
|
isEditingFooter: true,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(payload.footer_craft_state).toBe('LIVE_FOOTER');
|
expect(payload.footer_craft_state).toBe('LIVE_FOOTER');
|
||||||
@@ -75,6 +80,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: 'home',
|
activePageId: 'home',
|
||||||
isEditingHeader: false,
|
isEditingHeader: false,
|
||||||
isEditingFooter: false,
|
isEditingFooter: false,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Live canvas goes to the active page and top-level slots.
|
// Live canvas goes to the active page and top-level slots.
|
||||||
@@ -105,6 +112,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: 'home',
|
activePageId: 'home',
|
||||||
isEditingHeader: false,
|
isEditingHeader: false,
|
||||||
isEditingFooter: false,
|
isEditingFooter: false,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
// The live edit must land in pages_craft_state[0] (index.html slot),
|
// The live edit must land in pages_craft_state[0] (index.html slot),
|
||||||
@@ -116,4 +125,26 @@ describe('buildSavePayload', () => {
|
|||||||
// The other page is untouched.
|
// The other page is untouched.
|
||||||
expect(payload.pages_craft_state.find((p) => p.id === 'p2')?.craftState).toBe('STORED_ABOUT_2');
|
expect(payload.pages_craft_state.find((p) => p.id === 'p2')?.craftState).toBe('STORED_ABOUT_2');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('head code + design tokens are included in the save payload', () => {
|
||||||
|
const design = { ...DEFAULT_SITE_DESIGN, headCode: '<meta name="x">' };
|
||||||
|
|
||||||
|
const payload = buildSavePayload({
|
||||||
|
siteId: 1,
|
||||||
|
siteName: 'Test Site',
|
||||||
|
liveCraftState: 'LIVE_PAGE_HOME',
|
||||||
|
pages: [pageA, pageB],
|
||||||
|
headerPage,
|
||||||
|
footerPage,
|
||||||
|
activePageId: 'home',
|
||||||
|
isEditingHeader: false,
|
||||||
|
isEditingFooter: false,
|
||||||
|
headCode: '<meta name="x">',
|
||||||
|
design,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(payload.head_code).toBe('<meta name="x">');
|
||||||
|
expect(payload.design).toEqual(design);
|
||||||
|
expect(payload.design.headCode).toBe('<meta name="x">');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useCallback } from 'react';
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { useEditorConfig } from '../state/EditorConfigContext';
|
import { useEditorConfig } from '../state/EditorConfigContext';
|
||||||
import { usePages } from '../state/PageContext';
|
import { usePages } from '../state/PageContext';
|
||||||
|
import { useSiteDesign, SiteDesign } from '../state/SiteDesignContext';
|
||||||
import { exportBodyHtml } from '../utils/html-export';
|
import { exportBodyHtml } from '../utils/html-export';
|
||||||
import { PageData } from '../types';
|
import { PageData } from '../types';
|
||||||
|
|
||||||
@@ -18,6 +19,10 @@ export interface BuildSavePayloadInput {
|
|||||||
isEditingHeader: boolean;
|
isEditingHeader: boolean;
|
||||||
/** True when the live canvas is showing the footer zone (activePageId === '__footer__'). */
|
/** True when the live canvas is showing the footer zone (activePageId === '__footer__'). */
|
||||||
isEditingFooter: boolean;
|
isEditingFooter: boolean;
|
||||||
|
/** Site-wide custom `<head>` code (also present on `design.headCode`). */
|
||||||
|
headCode: string;
|
||||||
|
/** Full site design tokens object -- lets load() restore colors/fonts/headCode. */
|
||||||
|
design: SiteDesign;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,6 +50,8 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
|||||||
activePageId,
|
activePageId,
|
||||||
isEditingHeader,
|
isEditingHeader,
|
||||||
isEditingFooter,
|
isEditingFooter,
|
||||||
|
headCode,
|
||||||
|
design,
|
||||||
} = input;
|
} = input;
|
||||||
|
|
||||||
const isPageActive = !isEditingHeader && !isEditingFooter;
|
const isPageActive = !isEditingHeader && !isEditingFooter;
|
||||||
@@ -173,6 +180,8 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
|||||||
header_craft_state: headerCraftState,
|
header_craft_state: headerCraftState,
|
||||||
footer_craft_state: footerCraftState,
|
footer_craft_state: footerCraftState,
|
||||||
pages_craft_state: pagesGrapesjs,
|
pages_craft_state: pagesGrapesjs,
|
||||||
|
head_code: headCode,
|
||||||
|
design,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,6 +200,7 @@ export function useWhpApi() {
|
|||||||
setPagesCraftState,
|
setPagesCraftState,
|
||||||
setActivePageIdDirect,
|
setActivePageIdDirect,
|
||||||
} = usePages();
|
} = usePages();
|
||||||
|
const { design, updateDesign } = useSiteDesign();
|
||||||
|
|
||||||
const save = useCallback(async () => {
|
const save = useCallback(async () => {
|
||||||
if (!isWHP || !whpConfig) return null;
|
if (!isWHP || !whpConfig) return null;
|
||||||
@@ -210,6 +220,8 @@ export function useWhpApi() {
|
|||||||
activePageId,
|
activePageId,
|
||||||
isEditingHeader,
|
isEditingHeader,
|
||||||
isEditingFooter,
|
isEditingFooter,
|
||||||
|
headCode: design.headCode,
|
||||||
|
design,
|
||||||
});
|
});
|
||||||
|
|
||||||
const resp = await fetch(`${whpConfig.apiUrl}?action=save`, {
|
const resp = await fetch(`${whpConfig.apiUrl}?action=save`, {
|
||||||
@@ -221,7 +233,7 @@ export function useWhpApi() {
|
|||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
return resp.json();
|
return resp.json();
|
||||||
}, [isWHP, whpConfig, query, pages, activePageId, headerPage, footerPage, isEditingHeader, isEditingFooter]);
|
}, [isWHP, whpConfig, query, pages, activePageId, headerPage, footerPage, isEditingHeader, isEditingFooter, design]);
|
||||||
|
|
||||||
const publish = useCallback(async () => {
|
const publish = useCallback(async () => {
|
||||||
if (!isWHP || !whpConfig) return null;
|
if (!isWHP || !whpConfig) return null;
|
||||||
@@ -255,6 +267,17 @@ export function useWhpApi() {
|
|||||||
if (data.success && data.project) {
|
if (data.success && data.project) {
|
||||||
const proj = data.project;
|
const proj = data.project;
|
||||||
|
|
||||||
|
// Restore site design tokens (colors/fonts/headCode) so the editor
|
||||||
|
// reflects what was last saved. Prefer the full `design` object when
|
||||||
|
// present; fall back to just `head_code` for older project.json files
|
||||||
|
// saved before this field existed (backward-compatible: defaults for
|
||||||
|
// everything else).
|
||||||
|
if (proj.design && typeof proj.design === 'object') {
|
||||||
|
updateDesign(proj.design);
|
||||||
|
} else if (typeof proj.head_code === 'string') {
|
||||||
|
updateDesign({ headCode: proj.head_code });
|
||||||
|
}
|
||||||
|
|
||||||
// Restore header craft state
|
// Restore header craft state
|
||||||
if (proj.header_craft_state) {
|
if (proj.header_craft_state) {
|
||||||
setHeaderCraftState(typeof proj.header_craft_state === 'string'
|
setHeaderCraftState(typeof proj.header_craft_state === 'string'
|
||||||
@@ -300,7 +323,7 @@ export function useWhpApi() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
}, [isWHP, whpConfig, actions, setHeaderCraftState, setFooterCraftState, setPagesCraftState, setActivePageIdDirect, isEditingHeader, isEditingFooter]);
|
}, [isWHP, whpConfig, actions, setHeaderCraftState, setFooterCraftState, setPagesCraftState, setActivePageIdDirect, isEditingHeader, isEditingFooter, updateDesign]);
|
||||||
|
|
||||||
const uploadAsset = useCallback(
|
const uploadAsset = useCallback(
|
||||||
async (file: File) => {
|
async (file: File) => {
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ interface ContextMenuProps {
|
|||||||
|
|
||||||
interface MenuItem {
|
interface MenuItem {
|
||||||
label: string;
|
label: string;
|
||||||
|
/** Font Awesome icon suffix (e.g. 'magic' for fa-magic), rendered before the label. */
|
||||||
|
icon?: string;
|
||||||
shortcut?: string;
|
shortcut?: string;
|
||||||
action: () => void;
|
action: () => void;
|
||||||
danger?: boolean;
|
danger?: boolean;
|
||||||
@@ -189,25 +191,29 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
|
|
||||||
const items: MenuItem[] = [
|
const items: MenuItem[] = [
|
||||||
{
|
{
|
||||||
label: '✨ Ask Sitesmith',
|
label: 'Ask Sitesmith',
|
||||||
|
icon: 'magic',
|
||||||
action: askSitesmith,
|
action: askSitesmith,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
dividerAfter: true,
|
dividerAfter: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Duplicate',
|
label: 'Duplicate',
|
||||||
|
icon: 'clone',
|
||||||
shortcut: 'Ctrl+D',
|
shortcut: 'Ctrl+D',
|
||||||
action: duplicate,
|
action: duplicate,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Copy',
|
label: 'Copy',
|
||||||
|
icon: 'files-o',
|
||||||
shortcut: 'Ctrl+C',
|
shortcut: 'Ctrl+C',
|
||||||
action: copyNode,
|
action: copyNode,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Paste',
|
label: 'Paste',
|
||||||
|
icon: 'clipboard',
|
||||||
shortcut: 'Ctrl+V',
|
shortcut: 'Ctrl+V',
|
||||||
action: pasteNode,
|
action: pasteNode,
|
||||||
disabled: !getClipboardNodeId(),
|
disabled: !getClipboardNodeId(),
|
||||||
@@ -215,22 +221,26 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Move Up',
|
label: 'Move Up',
|
||||||
|
icon: 'arrow-up',
|
||||||
action: moveUp,
|
action: moveUp,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Move Down',
|
label: 'Move Down',
|
||||||
|
icon: 'arrow-down',
|
||||||
action: moveDown,
|
action: moveDown,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Select Parent',
|
label: 'Select Parent',
|
||||||
|
icon: 'level-up',
|
||||||
action: selectParent,
|
action: selectParent,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
dividerAfter: true,
|
dividerAfter: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Delete',
|
label: 'Delete',
|
||||||
|
icon: 'trash',
|
||||||
shortcut: 'Del',
|
shortcut: 'Del',
|
||||||
action: deleteNode,
|
action: deleteNode,
|
||||||
danger: true,
|
danger: true,
|
||||||
@@ -291,7 +301,10 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
(e.target as HTMLElement).style.background = 'transparent';
|
(e.target as HTMLElement).style.background = 'transparent';
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<span>{item.label}</span>
|
<span>
|
||||||
|
{item.icon && <i className={`fa fa-${item.icon}`} style={{ marginRight: 6, width: 12 }} />}
|
||||||
|
{item.label}
|
||||||
|
</span>
|
||||||
{item.shortcut && (
|
{item.shortcut && (
|
||||||
<span
|
<span
|
||||||
style={{
|
style={{
|
||||||
|
|||||||
@@ -107,23 +107,39 @@ export const AssetsPanel: React.FC = () => {
|
|||||||
{loading ? 'Uploading...' : 'Upload File'}
|
{loading ? 'Uploading...' : 'Upload File'}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Drop zone */}
|
{/* Drop zone -- a single element that doubles as the empty state.
|
||||||
|
Previously this was a small always-visible dropzone PLUS a
|
||||||
|
separate italic "No assets uploaded yet" line stacked underneath
|
||||||
|
it when empty; merged into one tall dropzone (icon + copy,
|
||||||
|
click-or-drag) so the empty state isn't two redundant messages.
|
||||||
|
Once assets exist it collapses back to a slim persistent drop
|
||||||
|
target above the grid. */}
|
||||||
<div
|
<div
|
||||||
onDrop={handleDrop}
|
onDrop={handleDrop}
|
||||||
onDragOver={handleDragOver}
|
onDragOver={handleDragOver}
|
||||||
onDragLeave={handleDragLeave}
|
onDragLeave={handleDragLeave}
|
||||||
|
{...(assets.length === 0 ? clickableProps(() => fileInputRef.current?.click()) : {})}
|
||||||
style={{
|
style={{
|
||||||
padding: 20,
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
gap: 8,
|
||||||
|
padding: assets.length === 0 ? '36px 20px' : 16,
|
||||||
border: `2px dashed ${isDragOver ? 'var(--color-accent)' : 'var(--color-border)'}`,
|
border: `2px dashed ${isDragOver ? 'var(--color-accent)' : 'var(--color-border)'}`,
|
||||||
borderRadius: 'var(--radius-md)',
|
borderRadius: 'var(--radius-md)',
|
||||||
background: isDragOver ? 'var(--color-accent-subtle)' : 'transparent',
|
background: isDragOver ? 'var(--color-accent-subtle)' : 'transparent',
|
||||||
textAlign: 'center',
|
textAlign: 'center',
|
||||||
color: isDragOver ? 'var(--color-accent)' : 'var(--color-text-dim)',
|
color: isDragOver ? 'var(--color-accent)' : 'var(--color-text-dim)',
|
||||||
fontSize: 11,
|
fontSize: 11,
|
||||||
|
cursor: assets.length === 0 ? 'pointer' : 'default',
|
||||||
transition: 'all var(--transition-fast)',
|
transition: 'all var(--transition-fast)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Drop files here to upload
|
{assets.length === 0 && (
|
||||||
|
<i className="fa fa-cloud-upload" aria-hidden style={{ fontSize: 28, opacity: 0.5 }} />
|
||||||
|
)}
|
||||||
|
{assets.length === 0 ? 'Drag images here or click to upload' : 'Drop files here to upload'}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Error message */}
|
{/* Error message */}
|
||||||
@@ -143,20 +159,6 @@ export const AssetsPanel: React.FC = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Asset grid */}
|
{/* Asset grid */}
|
||||||
{assets.length === 0 && !loading && (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
textAlign: 'center',
|
|
||||||
padding: 20,
|
|
||||||
color: 'var(--color-text-dim)',
|
|
||||||
fontSize: 12,
|
|
||||||
fontStyle: 'italic',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
No assets uploaded yet
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
display: 'grid',
|
display: 'grid',
|
||||||
@@ -296,7 +298,7 @@ export const AssetsPanel: React.FC = () => {
|
|||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
✕
|
<i className="fa fa-times" aria-hidden />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -328,7 +330,7 @@ export const AssetsPanel: React.FC = () => {
|
|||||||
onMouseEnter={(e) => { (e.target as HTMLElement).style.opacity = '1'; }}
|
onMouseEnter={(e) => { (e.target as HTMLElement).style.opacity = '1'; }}
|
||||||
onMouseLeave={(e) => { (e.target as HTMLElement).style.opacity = '0.7'; }}
|
onMouseLeave={(e) => { (e.target as HTMLElement).style.opacity = '0.7'; }}
|
||||||
>
|
>
|
||||||
✕
|
<i className="fa fa-times" aria-hidden />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ const categories: CategoryDef[] = [
|
|||||||
label: 'Media',
|
label: 'Media',
|
||||||
blocks: [
|
blocks: [
|
||||||
{ id: 'image', label: 'Image', icon: 'fa-image',
|
{ id: 'image', label: 'Image', icon: 'fa-image',
|
||||||
component: <ImageBlock src="" alt="Image" style={{ maxWidth: '100%', height: 'auto', display: 'block', borderRadius: '8px' }} /> },
|
component: <ImageBlock alt="Image" style={{ maxWidth: '100%', height: 'auto', display: 'block', borderRadius: '8px' }} /> },
|
||||||
{ id: 'video', label: 'Video', icon: 'fa-play-circle',
|
{ id: 'video', label: 'Video', icon: 'fa-play-circle',
|
||||||
component: <VideoBlock videoUrl="" isBackground={false} /> },
|
component: <VideoBlock videoUrl="" isBackground={false} /> },
|
||||||
{ id: 'map-embed', label: 'Map', icon: 'fa-map-marker',
|
{ id: 'map-embed', label: 'Map', icon: 'fa-map-marker',
|
||||||
|
|||||||
@@ -1,14 +1,74 @@
|
|||||||
import React, { useCallback } from 'react';
|
import React, { useCallback, useEffect, useRef } from 'react';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { clickableProps } from '../../utils/a11y';
|
import { clickableProps } from '../../utils/a11y';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-type icon lookup keyed by the component's `craft.displayName` (the
|
||||||
|
* same human label `LayerNode` already resolves and shows as the row text).
|
||||||
|
* Mirrors the icon choices in `BlocksPanel.tsx` where a block exists for the
|
||||||
|
* type; the remaining entries (Navbar, Container, Section, Columns,
|
||||||
|
* Background Section, Map, Video, Image, form fields, and the richer
|
||||||
|
* section blocks not draggable from the Basic/Sections categories) get a
|
||||||
|
* sensible FA4 icon of their own. Unknown/future types fall back to
|
||||||
|
* `DEFAULT_ICON`.
|
||||||
|
*/
|
||||||
|
const TYPE_ICONS: Record<string, string> = {
|
||||||
|
// Layout
|
||||||
|
Container: 'fa-square-o',
|
||||||
|
Section: 'fa-window-maximize',
|
||||||
|
Columns: 'fa-th-large',
|
||||||
|
'Background Section': 'fa-picture-o',
|
||||||
|
// Basic
|
||||||
|
Heading: 'fa-header',
|
||||||
|
Text: 'fa-paragraph',
|
||||||
|
Button: 'fa-square',
|
||||||
|
Logo: 'fa-bookmark',
|
||||||
|
Menu: 'fa-bars',
|
||||||
|
Navbar: 'fa-bars',
|
||||||
|
Footer: 'fa-window-minimize',
|
||||||
|
Divider: 'fa-minus',
|
||||||
|
Spacer: 'fa-arrows-v',
|
||||||
|
Icon: 'fa-star',
|
||||||
|
'Star Rating': 'fa-star-half-o',
|
||||||
|
'Social Links': 'fa-share-alt',
|
||||||
|
'Search Bar': 'fa-search',
|
||||||
|
HTML: 'fa-code',
|
||||||
|
// Media
|
||||||
|
Image: 'fa-image',
|
||||||
|
Video: 'fa-play-circle',
|
||||||
|
Map: 'fa-map-marker',
|
||||||
|
// Sections
|
||||||
|
Hero: 'fa-star-o',
|
||||||
|
'Features Grid': 'fa-th-large',
|
||||||
|
'CTA Section': 'fa-bullhorn',
|
||||||
|
'Call to Action': 'fa-bullhorn',
|
||||||
|
Countdown: 'fa-clock-o',
|
||||||
|
Testimonials: 'fa-quote-left',
|
||||||
|
'Content Slider': 'fa-sliders',
|
||||||
|
'Number Counter': 'fa-sort-numeric-asc',
|
||||||
|
Accordion: 'fa-list',
|
||||||
|
Tabs: 'fa-folder-o',
|
||||||
|
'Pricing Table': 'fa-usd',
|
||||||
|
Gallery: 'fa-th',
|
||||||
|
// Forms
|
||||||
|
Form: 'fa-wpforms',
|
||||||
|
Input: 'fa-i-cursor',
|
||||||
|
Textarea: 'fa-align-left',
|
||||||
|
'Submit Button': 'fa-paper-plane',
|
||||||
|
'Contact Form': 'fa-envelope',
|
||||||
|
'Subscribe Form': 'fa-paper-plane',
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_ICON = 'fa-cube';
|
||||||
|
const ROOT_ICON = 'fa-desktop';
|
||||||
|
|
||||||
interface LayerNodeProps {
|
interface LayerNodeProps {
|
||||||
nodeId: string;
|
nodeId: string;
|
||||||
depth: number;
|
depth: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
||||||
const { node, selectedId, actions } = useEditor((state) => {
|
const { node, selectedId, actions, query } = useEditor((state) => {
|
||||||
const n = state.nodes[nodeId];
|
const n = state.nodes[nodeId];
|
||||||
const selectedIds = state.events.selected;
|
const selectedIds = state.events.selected;
|
||||||
const selId = selectedIds ? Array.from(selectedIds)[0] : null;
|
const selId = selectedIds ? Array.from(selectedIds)[0] : null;
|
||||||
@@ -18,28 +78,76 @@ const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const isSelected = selectedId === nodeId;
|
||||||
|
|
||||||
const handleActivate = useCallback(() => {
|
const handleActivate = useCallback(() => {
|
||||||
actions.selectNode(nodeId);
|
actions.selectNode(nodeId);
|
||||||
}, [actions, nodeId]);
|
}, [actions, nodeId]);
|
||||||
|
|
||||||
|
// Layers-panel <-> canvas hover sync (Item 12): tags the target node's own
|
||||||
|
// DOM element (found via `query`) with `data-layer-hovered` directly.
|
||||||
|
// `RenderNode.tsx` mirrors Craft's *own* `hovered` node event onto
|
||||||
|
// `data-craft-hovered` for the (separate, mouse-driven) canvas hover
|
||||||
|
// outline -- editor.css's rule matches both attributes. This panel can't
|
||||||
|
// reuse that path: `setNodeEvent` is a private action that `useEditor()`
|
||||||
|
// strips from its `actions` return at runtime (see
|
||||||
|
// @craftjs/core/dist/esm's `xe()` action stripper, not just its TypeScript
|
||||||
|
// type), so calling it here throws. Writing our own attribute directly is
|
||||||
|
// a supported, version-stable way to get the same highlight.
|
||||||
|
const hoveredDomRef = useRef<HTMLElement | null>(null);
|
||||||
|
|
||||||
|
const handleMouseEnter = useCallback(
|
||||||
|
(e: React.MouseEvent<HTMLElement> | React.FocusEvent<HTMLElement>) => {
|
||||||
|
const dom = query.node(nodeId).get()?.dom;
|
||||||
|
if (dom) {
|
||||||
|
dom.setAttribute('data-layer-hovered', '');
|
||||||
|
hoveredDomRef.current = dom;
|
||||||
|
}
|
||||||
|
if (!isSelected) {
|
||||||
|
(e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[query, nodeId, isSelected],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleMouseLeave = useCallback(
|
||||||
|
(e: React.MouseEvent<HTMLElement> | React.FocusEvent<HTMLElement>) => {
|
||||||
|
hoveredDomRef.current?.removeAttribute('data-layer-hovered');
|
||||||
|
hoveredDomRef.current = null;
|
||||||
|
if (!isSelected) {
|
||||||
|
(e.currentTarget as HTMLElement).style.background = 'transparent';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[isSelected],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Safety net: if this row unmounts (e.g. the user switches away from the
|
||||||
|
// Layers tab, or the tree re-shuffles) while still hovered, clear the
|
||||||
|
// attribute so it doesn't get stuck highlighted on the canvas forever.
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
hoveredDomRef.current?.removeAttribute('data-layer-hovered');
|
||||||
|
hoveredDomRef.current = null;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
if (!node) return null;
|
if (!node) return null;
|
||||||
|
|
||||||
const isSelected = selectedId === nodeId;
|
|
||||||
const nodeType = node.data.type;
|
|
||||||
const resolvedName = typeof nodeType === 'object' && nodeType !== null && 'resolvedName' in nodeType
|
|
||||||
? (nodeType as any).resolvedName
|
|
||||||
: typeof nodeType === 'string' ? nodeType : undefined;
|
|
||||||
const displayName = (node.data.props?.aiName as string) || node.data.displayName || (node.data.type as any)?.resolvedName || 'Node';
|
const displayName = (node.data.props?.aiName as string) || node.data.displayName || (node.data.type as any)?.resolvedName || 'Node';
|
||||||
const childNodeIds: string[] = node.data.nodes || [];
|
const childNodeIds: string[] = node.data.nodes || [];
|
||||||
const linkedNodeIds: string[] = Object.values(node.data.linkedNodes || {}) as string[];
|
const linkedNodeIds: string[] = Object.values(node.data.linkedNodes || {}) as string[];
|
||||||
const allChildren = [...childNodeIds, ...linkedNodeIds];
|
const allChildren = [...childNodeIds, ...linkedNodeIds];
|
||||||
const isRoot = nodeId === 'ROOT';
|
const isRoot = nodeId === 'ROOT';
|
||||||
|
const icon = isRoot ? ROOT_ICON : TYPE_ICONS[displayName] || DEFAULT_ICON;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div
|
<div
|
||||||
{...clickableProps(handleActivate)}
|
{...clickableProps(handleActivate)}
|
||||||
|
onMouseEnter={handleMouseEnter}
|
||||||
|
onMouseLeave={handleMouseLeave}
|
||||||
style={{
|
style={{
|
||||||
|
position: 'relative',
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
padding: '5px 8px',
|
padding: '5px 8px',
|
||||||
@@ -56,30 +164,53 @@ const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
|||||||
textOverflow: 'ellipsis',
|
textOverflow: 'ellipsis',
|
||||||
userSelect: 'none',
|
userSelect: 'none',
|
||||||
}}
|
}}
|
||||||
onMouseEnter={(e) => {
|
onFocus={handleMouseEnter}
|
||||||
if (!isSelected) {
|
onBlur={handleMouseLeave}
|
||||||
(e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)';
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onMouseLeave={(e) => {
|
|
||||||
if (!isSelected) {
|
|
||||||
(e.currentTarget as HTMLElement).style.background = 'transparent';
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{/* Indentation indicator */}
|
{/* Indent guides: one vertical line per ancestor depth level,
|
||||||
{allChildren.length > 0 && (
|
aligned under each ancestor's disclosure/icon column so nested
|
||||||
<span style={{ marginRight: 4, fontSize: 8, color: 'var(--color-text-dim)' }}>
|
rows read as a tree instead of a flat, ever-further-indented list. */}
|
||||||
|
{Array.from({ length: depth }).map((_, level) => (
|
||||||
|
<span
|
||||||
|
key={level}
|
||||||
|
aria-hidden="true"
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
left: `${8 + level * 16 + 4}px`,
|
||||||
|
top: 0,
|
||||||
|
bottom: 0,
|
||||||
|
width: 1,
|
||||||
|
background: 'var(--color-border)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Indentation/disclosure indicator */}
|
||||||
|
{allChildren.length > 0 ? (
|
||||||
|
<span style={{ marginRight: 4, fontSize: 8, color: 'var(--color-text-dim)', flexShrink: 0 }}>
|
||||||
▼
|
▼
|
||||||
</span>
|
</span>
|
||||||
)}
|
) : (
|
||||||
{allChildren.length === 0 && (
|
<span style={{ marginRight: 4, fontSize: 8, color: 'transparent', flexShrink: 0 }}>
|
||||||
<span style={{ marginRight: 4, fontSize: 8, color: 'transparent' }}>
|
|
||||||
▼
|
▼
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Component type icon and name */}
|
{/* Component type icon */}
|
||||||
|
<i
|
||||||
|
className={`fa ${icon}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
style={{
|
||||||
|
marginRight: 6,
|
||||||
|
fontSize: 11,
|
||||||
|
width: 12,
|
||||||
|
textAlign: 'center',
|
||||||
|
flexShrink: 0,
|
||||||
|
color: isSelected ? 'var(--color-accent)' : 'var(--color-text-dim)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Name */}
|
||||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||||
{isRoot ? 'Canvas (Root)' : displayName}
|
{isRoot ? 'Canvas (Root)' : displayName}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -58,18 +58,23 @@ export const PagesPanel: React.FC = () => {
|
|||||||
.replace(/-+/g, '-');
|
.replace(/-+/g, '-');
|
||||||
};
|
};
|
||||||
|
|
||||||
/* ---------- Zone button style ---------- */
|
/* ---------- Zone row style ----------
|
||||||
const zoneButtonStyle = (isActive: boolean): React.CSSProperties => ({
|
* Same neutral surface language as the page-list rows below (Item 11) --
|
||||||
|
* header/footer are just two more items in the tree, not a louder,
|
||||||
|
* differently-colored category. The active/editing state reuses the same
|
||||||
|
* accent-outline treatment the page list already uses for the active page,
|
||||||
|
* so there's one consistent "this is what's currently open" affordance. */
|
||||||
|
const zoneRowStyle = (isActive: boolean): React.CSSProperties => ({
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
gap: 8,
|
gap: 8,
|
||||||
width: '100%',
|
width: '100%',
|
||||||
padding: '10px 12px',
|
padding: '7px 10px',
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
fontWeight: 600,
|
fontWeight: isActive ? 600 : 500,
|
||||||
color: isActive ? '#f59e0b' : '#fbbf24',
|
color: isActive ? 'var(--color-accent)' : 'var(--color-text-muted)',
|
||||||
background: isActive ? 'rgba(245, 158, 11, 0.15)' : 'rgba(245, 158, 11, 0.06)',
|
background: isActive ? 'var(--color-accent-subtle)' : 'var(--color-bg-elevated)',
|
||||||
border: `1px solid ${isActive ? 'rgba(245, 158, 11, 0.5)' : 'rgba(245, 158, 11, 0.2)'}`,
|
border: `1px solid ${isActive ? 'var(--color-accent)' : 'var(--color-border)'}`,
|
||||||
borderRadius: 'var(--radius-md)',
|
borderRadius: 'var(--radius-md)',
|
||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
transition: 'all var(--transition-fast)',
|
transition: 'all var(--transition-fast)',
|
||||||
@@ -78,57 +83,35 @@ export const PagesPanel: React.FC = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||||
{/* Header/Footer zone buttons */}
|
{/* Header/Footer zone rows */}
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 8 }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 8 }}>
|
||||||
<button
|
<button
|
||||||
onClick={editHeader}
|
onClick={editHeader}
|
||||||
style={zoneButtonStyle(isEditingHeader)}
|
className="zone-row"
|
||||||
|
style={zoneRowStyle(isEditingHeader)}
|
||||||
|
title="Appears on all pages"
|
||||||
>
|
>
|
||||||
<i className="fa fa-window-maximize" style={{ fontSize: 13 }} />
|
<i className="fa fa-window-maximize" style={{ fontSize: 12, width: 14, textAlign: 'center', flexShrink: 0 }} />
|
||||||
<div style={{ flex: 1 }}>
|
<span style={{ flex: 1 }}>Header</span>
|
||||||
<div>Edit Header</div>
|
{isEditingHeader ? (
|
||||||
<div style={{ fontSize: 10, opacity: 0.7, fontWeight: 400, marginTop: 1 }}>
|
<i className="fa fa-check-circle" style={{ fontSize: 11 }} aria-hidden />
|
||||||
Appears on all pages
|
) : (
|
||||||
</div>
|
<i className="fa fa-pencil zone-row-pencil" style={{ fontSize: 11 }} aria-hidden />
|
||||||
</div>
|
|
||||||
{isEditingHeader && (
|
|
||||||
<span style={{
|
|
||||||
fontSize: 9,
|
|
||||||
fontWeight: 700,
|
|
||||||
textTransform: 'uppercase',
|
|
||||||
letterSpacing: '0.5px',
|
|
||||||
background: 'rgba(245, 158, 11, 0.25)',
|
|
||||||
padding: '2px 6px',
|
|
||||||
borderRadius: 'var(--radius-sm)',
|
|
||||||
}}>
|
|
||||||
Editing
|
|
||||||
</span>
|
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={editFooter}
|
onClick={editFooter}
|
||||||
style={zoneButtonStyle(isEditingFooter)}
|
className="zone-row"
|
||||||
|
style={zoneRowStyle(isEditingFooter)}
|
||||||
|
title="Appears on all pages"
|
||||||
>
|
>
|
||||||
<i className="fa fa-window-minimize" style={{ fontSize: 13 }} />
|
<i className="fa fa-window-minimize" style={{ fontSize: 12, width: 14, textAlign: 'center', flexShrink: 0 }} />
|
||||||
<div style={{ flex: 1 }}>
|
<span style={{ flex: 1 }}>Footer</span>
|
||||||
<div>Edit Footer</div>
|
{isEditingFooter ? (
|
||||||
<div style={{ fontSize: 10, opacity: 0.7, fontWeight: 400, marginTop: 1 }}>
|
<i className="fa fa-check-circle" style={{ fontSize: 11 }} aria-hidden />
|
||||||
Appears on all pages
|
) : (
|
||||||
</div>
|
<i className="fa fa-pencil zone-row-pencil" style={{ fontSize: 11 }} aria-hidden />
|
||||||
</div>
|
|
||||||
{isEditingFooter && (
|
|
||||||
<span style={{
|
|
||||||
fontSize: 9,
|
|
||||||
fontWeight: 700,
|
|
||||||
textTransform: 'uppercase',
|
|
||||||
letterSpacing: '0.5px',
|
|
||||||
background: 'rgba(245, 158, 11, 0.25)',
|
|
||||||
padding: '2px 6px',
|
|
||||||
borderRadius: 'var(--radius-sm)',
|
|
||||||
}}>
|
|
||||||
Editing
|
|
||||||
</span>
|
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -328,18 +311,21 @@ export const PagesPanel: React.FC = () => {
|
|||||||
title="This is the landing page — published as the root URL (index.html)"
|
title="This is the landing page — published as the root URL (index.html)"
|
||||||
style={{
|
style={{
|
||||||
fontSize: 9,
|
fontSize: 9,
|
||||||
fontWeight: 700,
|
fontWeight: 600,
|
||||||
textTransform: 'uppercase',
|
letterSpacing: '0.3px',
|
||||||
letterSpacing: '0.5px',
|
color: 'var(--color-text-muted)',
|
||||||
color: '#fbbf24',
|
background: 'transparent',
|
||||||
background: 'rgba(245, 158, 11, 0.15)',
|
border: '1px solid var(--color-border-light)',
|
||||||
border: '1px solid rgba(245, 158, 11, 0.35)',
|
|
||||||
padding: '1px 5px',
|
padding: '1px 5px',
|
||||||
borderRadius: 'var(--radius-sm)',
|
borderRadius: 'var(--radius-sm)',
|
||||||
flexShrink: 0,
|
flexShrink: 0,
|
||||||
|
display: 'inline-flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 4,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<i className="fa fa-home" style={{ marginRight: 3 }} />Landing
|
<i className="fa fa-home" aria-hidden="true" style={{ fontSize: 8, color: 'inherit' }} />
|
||||||
|
Landing
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -359,7 +345,8 @@ export const PagesPanel: React.FC = () => {
|
|||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
onClick={() => startEditing(page)}
|
onClick={() => startEditing(page)}
|
||||||
title="Rename"
|
data-tooltip="Rename"
|
||||||
|
aria-label={`Rename ${page.name}`}
|
||||||
style={{
|
style={{
|
||||||
width: 24,
|
width: 24,
|
||||||
height: 24,
|
height: 24,
|
||||||
@@ -374,12 +361,13 @@ export const PagesPanel: React.FC = () => {
|
|||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
✎
|
<i className="fa fa-pencil" aria-hidden="true" />
|
||||||
</button>
|
</button>
|
||||||
{pages.length > 1 && !isLanding && (
|
{pages.length > 1 && !isLanding && (
|
||||||
<button
|
<button
|
||||||
onClick={() => setDeleteConfirmId(page.id)}
|
onClick={() => setDeleteConfirmId(page.id)}
|
||||||
title="Delete"
|
data-tooltip="Delete"
|
||||||
|
aria-label={`Delete ${page.name}`}
|
||||||
style={{
|
style={{
|
||||||
width: 24,
|
width: 24,
|
||||||
height: 24,
|
height: 24,
|
||||||
@@ -394,7 +382,7 @@ export const PagesPanel: React.FC = () => {
|
|||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
✕
|
<i className="fa fa-trash" aria-hidden="true" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||||
|
import { PLACEHOLDER_SRC } from '../../../components/media/ImageBlock';
|
||||||
|
|
||||||
/* ---------- IMAGE (with upload/browse/drop) ---------- */
|
/* ---------- IMAGE (with upload/browse/drop) ---------- */
|
||||||
export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||||
@@ -33,7 +34,7 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
<SectionLabel>Image Source</SectionLabel>
|
<SectionLabel>Image Source</SectionLabel>
|
||||||
<AssetPicker
|
<AssetPicker
|
||||||
value={nodeProps.src || ''}
|
value={nodeProps.src || ''}
|
||||||
onChange={(url) => actions.setProp(selectedId, (props: any) => { props.src = url; })}
|
onChange={(url) => actions.setProp(selectedId, (props: any) => { props.src = url || PLACEHOLDER_SRC; })}
|
||||||
variant="full"
|
variant="full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { defaultPresetGridColumns } from './shared';
|
||||||
|
import { RADIUS_PRESETS, SPACING_PRESETS, IMAGE_RADIUS_PRESETS, FONT_WEIGHTS, TEXT_SIZES, FONT_FAMILIES } from '../../../constants/presets';
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Regression: 5-item preset sets (RADIUS_PRESETS, SPACING_PRESETS,
|
||||||
|
* IMAGE_RADIUS_PRESETS, FONT_WEIGHTS, and NavStylePanel's ad-hoc
|
||||||
|
* GAP_PRESETS) left a lone orphan button on its own row under the old
|
||||||
|
* fixed 4-column .preset-grid. PresetButtonGrid now derives a column
|
||||||
|
* count from the preset length instead.
|
||||||
|
*/
|
||||||
|
describe('defaultPresetGridColumns', () => {
|
||||||
|
it('gives 5-item sets their own single row (no orphan)', () => {
|
||||||
|
expect(defaultPresetGridColumns(RADIUS_PRESETS.length)).toBe(5);
|
||||||
|
expect(defaultPresetGridColumns(SPACING_PRESETS.length)).toBe(5);
|
||||||
|
expect(defaultPresetGridColumns(IMAGE_RADIUS_PRESETS.length)).toBe(5);
|
||||||
|
expect(defaultPresetGridColumns(FONT_WEIGHTS.length)).toBe(5);
|
||||||
|
expect(defaultPresetGridColumns(5)).toBe(5); // NavStylePanel's GAP_PRESETS
|
||||||
|
});
|
||||||
|
|
||||||
|
it('splits 6-item sets into two even rows of 3 (was 4+2 uneven)', () => {
|
||||||
|
expect(defaultPresetGridColumns(TEXT_SIZES.length)).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the classic 4-column grid for sets that already divide evenly', () => {
|
||||||
|
expect(defaultPresetGridColumns(FONT_FAMILIES.length)).toBe(4); // 8 items
|
||||||
|
expect(defaultPresetGridColumns(4)).toBe(4);
|
||||||
|
expect(defaultPresetGridColumns(3)).toBe(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never leaves a single orphan on the final row for any count 1-12', () => {
|
||||||
|
for (let n = 1; n <= 12; n++) {
|
||||||
|
const cols = defaultPresetGridColumns(n);
|
||||||
|
const isLoneOrphan = n > cols && n % cols === 1;
|
||||||
|
expect(isLoneOrphan).toBe(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -84,9 +84,30 @@ interface PresetButtonGridProps {
|
|||||||
presets: { label: string; value: string }[];
|
presets: { label: string; value: string }[];
|
||||||
activeValue: string | undefined;
|
activeValue: string | undefined;
|
||||||
onSelect: (value: string) => void;
|
onSelect: (value: string) => void;
|
||||||
|
/** Explicit column count. When omitted, a column count is derived from
|
||||||
|
* `presets.length` (see `defaultPresetGridColumns`) so odd-sized preset
|
||||||
|
* sets (5, 6, ...) don't leave a lone orphan button dangling on its own
|
||||||
|
* row under the fixed 4-column grid. */
|
||||||
|
columns?: number;
|
||||||
}
|
}
|
||||||
export const PresetButtonGrid: React.FC<PresetButtonGridProps> = ({ presets, activeValue, onSelect }) => (
|
|
||||||
<div className="preset-grid">
|
/** Picks a column count that avoids a single orphan on the last row.
|
||||||
|
* 4-or-fewer presets keep the classic single row of 4. 5 gets its own
|
||||||
|
* row (5 cols). 6 splits into two even rows of 3. Anything else falls
|
||||||
|
* back to a 4- or 3-column grid depending on which divides evenly. */
|
||||||
|
export function defaultPresetGridColumns(count: number): number {
|
||||||
|
if (count <= 4) return 4;
|
||||||
|
if (count === 5) return 5;
|
||||||
|
if (count === 6) return 3;
|
||||||
|
if (count % 4 === 0) return 4;
|
||||||
|
if (count % 3 === 0) return 3;
|
||||||
|
return 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PresetButtonGrid: React.FC<PresetButtonGridProps> = ({ presets, activeValue, onSelect, columns }) => {
|
||||||
|
const cols = columns ?? defaultPresetGridColumns(presets.length);
|
||||||
|
return (
|
||||||
|
<div className="preset-grid" style={{ gridTemplateColumns: `repeat(${cols}, 1fr)` }}>
|
||||||
{presets.map((p) => (
|
{presets.map((p) => (
|
||||||
<button
|
<button
|
||||||
key={p.value}
|
key={p.value}
|
||||||
@@ -98,6 +119,7 @@ export const PresetButtonGrid: React.FC<PresetButtonGridProps> = ({ presets, act
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
interface GradientSwatchGridProps {
|
interface GradientSwatchGridProps {
|
||||||
activeValue: string | undefined;
|
activeValue: string | undefined;
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ export const SitesmithButton: React.FC<Props> = ({ onClick }) => {
|
|||||||
color: '#fff', border: 'none', padding: '6px 12px', borderRadius: 6, cursor: 'pointer', fontWeight: 500,
|
color: '#fff', border: 'none', padding: '6px 12px', borderRadius: 6, cursor: 'pointer', fontWeight: 500,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
✨ Sitesmith
|
<i className="fa fa-magic" aria-hidden style={{ marginRight: 6 }} /> Sitesmith
|
||||||
{locked && <span aria-hidden style={{ marginLeft: 6, fontSize: 12 }}>🔒</span>}
|
{locked && <i className="fa fa-lock" aria-hidden style={{ marginLeft: 6, fontSize: 12 }} />}
|
||||||
{capped && !locked && <span aria-hidden style={{ marginLeft: 6, fontSize: 11, opacity: 0.85 }}>(cap)</span>}
|
{capped && !locked && <span aria-hidden style={{ marginLeft: 6, fontSize: 11, opacity: 0.85 }}>(cap)</span>}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -103,7 +103,10 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
|
|||||||
>
|
>
|
||||||
<div style={panel}>
|
<div style={panel}>
|
||||||
<div style={header}>
|
<div style={header}>
|
||||||
<div style={{ fontWeight: 600, color: '#fff' }}>✨ Sitesmith</div>
|
<div style={{ fontWeight: 600, color: '#fff' }}>
|
||||||
|
<i className="fa fa-magic" aria-hidden style={{ marginRight: 6 }} />
|
||||||
|
Sitesmith
|
||||||
|
</div>
|
||||||
{summary && summary.enabled && (
|
{summary && summary.enabled && (
|
||||||
<div style={{ fontSize: 12, color: '#a1a1aa', marginLeft: 16 }}>
|
<div style={{ fontSize: 12, color: '#a1a1aa', marginLeft: 16 }}>
|
||||||
{summary.monthly_used} / {summary.monthly_cap} this month
|
{summary.monthly_used} / {summary.monthly_cap} this month
|
||||||
@@ -136,7 +139,7 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
|
|||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
)}
|
)}
|
||||||
<button onClick={onClose} aria-label="Close" style={closeBtn}>✕</button>
|
<button onClick={onClose} aria-label="Close" style={closeBtn}><i className="fa fa-times" aria-hidden /></button>
|
||||||
</div>
|
</div>
|
||||||
<div style={body}>
|
<div style={body}>
|
||||||
<UpgradeBanner summary={summary} />
|
<UpgradeBanner summary={summary} />
|
||||||
|
|||||||
@@ -8,9 +8,10 @@ import {
|
|||||||
TemplateComponent,
|
TemplateComponent,
|
||||||
TemplateCategory,
|
TemplateCategory,
|
||||||
} from '../../templates';
|
} from '../../templates';
|
||||||
import { componentResolver } from '../../components/resolver';
|
|
||||||
import { clickableProps } from '../../utils/a11y';
|
import { clickableProps } from '../../utils/a11y';
|
||||||
import { Modal } from '../../ui/Modal';
|
import { Modal } from '../../ui/Modal';
|
||||||
|
import { buildNodeTree } from '../../utils/craft-tree';
|
||||||
|
import { templateComponentToTreeNode } from '../../templates/apply-template';
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Types
|
// Types
|
||||||
@@ -77,28 +78,31 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
return allTemplates.filter((t) => t.category === activeTab);
|
return allTemplates.filter((t) => t.category === activeTab);
|
||||||
}, [activeTab]);
|
}, [activeTab]);
|
||||||
|
|
||||||
// Resolve a TemplateComponent type name to its React component
|
|
||||||
const resolverMap = componentResolver as Record<string, React.ComponentType<any>>;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add all components from a template definition onto the current (empty) canvas ROOT.
|
* Add all components from a template definition onto the current (empty) canvas ROOT.
|
||||||
* Uses Craft.js parseReactElement + addNodeTree which correctly builds valid node structures.
|
* Converts each `TemplateComponent` (the plain `{type, props, children?}`
|
||||||
|
* shape templates author) to a `SerializedTreeNode` and runs it through
|
||||||
|
* `buildNodeTree` (sanitize -> flatten -> materialize), the same tree pipeline
|
||||||
|
* already used for AI-generated content. This recurses into nested
|
||||||
|
* `children` (e.g. a header/footer `Container` wrapping `Logo`/`Menu`, or a
|
||||||
|
* page `Section` wrapping a `Heading`) AND correctly routes them through a
|
||||||
|
* component's SHELL_INNER linked canvas / linked columns where needed --
|
||||||
|
* see `templates/apply-template.ts` for the two bugs this fixes (dropped
|
||||||
|
* children, and a naive `parseReactElement` tree crashing `Section`/
|
||||||
|
* `BackgroundSection`/`FormContainer`/`ColumnLayout`).
|
||||||
*/
|
*/
|
||||||
const addTemplateComponents = useCallback(
|
const addTemplateComponents = useCallback(
|
||||||
(components: TemplateComponent[]) => {
|
(components: TemplateComponent[]) => {
|
||||||
for (const comp of components) {
|
for (const comp of components) {
|
||||||
const Component = resolverMap[comp.type];
|
try {
|
||||||
if (!Component) {
|
const tree = buildNodeTree(query, templateComponentToTreeNode(comp));
|
||||||
console.warn(`Template references unknown component type: ${comp.type}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const element = React.createElement(Component, comp.props);
|
|
||||||
const tree = query.parseReactElement(element).toNodeTree();
|
|
||||||
actions.addNodeTree(tree, 'ROOT');
|
actions.addNodeTree(tree, 'ROOT');
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to build template component tree for type "${comp.type}":`, e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[query, actions, resolverMap],
|
[query, actions],
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -247,8 +251,14 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
Choose a template to get started quickly
|
Choose a template to get started quickly
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<button onClick={onClose} style={closeButtonStyle} title="Close">
|
<button
|
||||||
✕
|
onClick={onClose}
|
||||||
|
style={closeButtonStyle}
|
||||||
|
title="Close"
|
||||||
|
onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)'; (e.currentTarget as HTMLElement).style.color = 'var(--color-text)'; }}
|
||||||
|
onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.background = 'transparent'; (e.currentTarget as HTMLElement).style.color = '#71717a'; }}
|
||||||
|
>
|
||||||
|
<i className="fa fa-times" aria-hidden />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -262,6 +272,12 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
...tabStyle,
|
...tabStyle,
|
||||||
...(activeTab === tab.value ? tabActiveStyle : {}),
|
...(activeTab === tab.value ? tabActiveStyle : {}),
|
||||||
}}
|
}}
|
||||||
|
onMouseEnter={(e) => {
|
||||||
|
if (activeTab !== tab.value) (e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)';
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e) => {
|
||||||
|
if (activeTab !== tab.value) (e.currentTarget as HTMLElement).style.background = 'transparent';
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{tab.label}
|
{tab.label}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -13,9 +13,12 @@ import { useSitesmithModal } from '../../state/SitesmithContext';
|
|||||||
interface TopBarProps {
|
interface TopBarProps {
|
||||||
device: DeviceMode;
|
device: DeviceMode;
|
||||||
onDeviceChange: (device: DeviceMode) => void;
|
onDeviceChange: (device: DeviceMode) => void;
|
||||||
|
/** Item 10: canvas dashed guide outlines, default ON. */
|
||||||
|
showGuides: boolean;
|
||||||
|
onToggleGuides: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuides, onToggleGuides }) => {
|
||||||
const { whpConfig, isWHP } = useEditorConfig();
|
const { whpConfig, isWHP } = useEditorConfig();
|
||||||
const { actions, query, canUndo, canRedo } = useEditor((_state, query) => ({
|
const { actions, query, canUndo, canRedo } = useEditor((_state, query) => ({
|
||||||
canUndo: query.history.canUndo(),
|
canUndo: query.history.canUndo(),
|
||||||
@@ -148,6 +151,16 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`topbar-btn guides-toggle icon-only${showGuides ? ' active' : ''}`}
|
||||||
|
onClick={onToggleGuides}
|
||||||
|
aria-pressed={showGuides}
|
||||||
|
aria-label={showGuides ? 'Hide canvas guides' : 'Show canvas guides'}
|
||||||
|
data-tooltip={showGuides ? 'Hide guides' : 'Show guides'}
|
||||||
|
>
|
||||||
|
<i className={`fa ${showGuides ? 'fa-th' : 'fa-th-large'}`} aria-hidden />
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="topbar-right">
|
<div className="topbar-right">
|
||||||
@@ -161,10 +174,15 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
|||||||
<button className="topbar-btn" title="Templates" aria-label="Templates" onClick={() => setTemplateModalOpen(true)}>
|
<button className="topbar-btn" title="Templates" aria-label="Templates" onClick={() => setTemplateModalOpen(true)}>
|
||||||
<i className="fa fa-th-large" /> Templates
|
<i className="fa fa-th-large" /> Templates
|
||||||
</button>
|
</button>
|
||||||
<button className="topbar-btn" title="Custom Head Code" aria-label="Custom Head Code" onClick={() => setHeadCodeModalOpen(true)}>
|
<button
|
||||||
<i className="fa fa-code" /> Code
|
className="topbar-btn icon-only"
|
||||||
|
aria-label="Custom Head Code"
|
||||||
|
data-tooltip="Code"
|
||||||
|
onClick={() => setHeadCodeModalOpen(true)}
|
||||||
|
>
|
||||||
|
<i className="fa fa-code" />
|
||||||
</button>
|
</button>
|
||||||
<button className="topbar-btn" title="Preview" aria-label="Preview" onClick={() => {
|
<button className="topbar-btn icon-only" aria-label="Preview" data-tooltip="Preview" onClick={() => {
|
||||||
try {
|
try {
|
||||||
const serialized = query.serialize();
|
const serialized = query.serialize();
|
||||||
import('../../utils/html-export').then(({ exportToHtml, exportBodyHtml }) => {
|
import('../../utils/html-export').then(({ exportToHtml, exportBodyHtml }) => {
|
||||||
@@ -218,7 +236,7 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
|||||||
console.error('Preview failed:', e);
|
console.error('Preview failed:', e);
|
||||||
}
|
}
|
||||||
}}>
|
}}>
|
||||||
<i className="fa fa-eye" /> Preview
|
<i className="fa fa-eye" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Draft/Published status badge */}
|
{/* Draft/Published status badge */}
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { Editor, useEditor } from '@craftjs/core';
|
||||||
|
import { componentResolver } from '../../components/resolver';
|
||||||
|
import { allTemplates } from '../../templates';
|
||||||
|
import { buildNodeTree } from '../../utils/craft-tree';
|
||||||
|
import { templateComponentToTreeNode } from '../../templates/apply-template';
|
||||||
|
import { exportBodyHtml } from '../../utils/html-export';
|
||||||
|
import { DEFAULT_HEADER_STATE } from '../../state/PageContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression test for: loading a template makes the header/footer ZONE
|
||||||
|
* PREVIEW (`ZonePreview` in `editor/Canvas.tsx`, which calls
|
||||||
|
* `exportBodyHtml(craftState)`) render as an empty strip -- no nav links, no
|
||||||
|
* logo, no footer text -- and (a second bug found while fixing the first)
|
||||||
|
* makes a template page's `Section`-wrapped content crash the live editor
|
||||||
|
* entirely.
|
||||||
|
*
|
||||||
|
* This drives the EXACT same path `TemplateModal.tsx`'s `applyZone` /
|
||||||
|
* `addTemplateComponents` uses to load a template's header/footer/page
|
||||||
|
* content onto the live Craft.js canvas (`buildNodeTree` +
|
||||||
|
* `actions.addNodeTree(tree, 'ROOT')`), then serializes it
|
||||||
|
* (`query.serialize()`, exactly what `PageContext`'s `switchPage` /
|
||||||
|
* `saveCurrentState` do right after `TemplateModal` finishes applying a
|
||||||
|
* zone/page) and feeds the result through `exportBodyHtml` -- the same
|
||||||
|
* function `ZonePreview` calls, and the same function `handlePublish` uses
|
||||||
|
* to compose the published header/footer HTML. So this also covers whether
|
||||||
|
* published output is affected (it was).
|
||||||
|
*/
|
||||||
|
let api: any;
|
||||||
|
function Harness() {
|
||||||
|
const { actions, query } = useEditor();
|
||||||
|
api = { actions, query };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mount() {
|
||||||
|
const container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
let root!: Root;
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(
|
||||||
|
<Editor resolver={componentResolver}>
|
||||||
|
<Harness />
|
||||||
|
</Editor>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
container,
|
||||||
|
unmount: () => {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mirrors TemplateModal.tsx's addTemplateComponents(). */
|
||||||
|
function addTemplateComponents(components: any[]) {
|
||||||
|
for (const comp of components) {
|
||||||
|
const tree = buildNodeTree(api.query, templateComponentToTreeNode(comp));
|
||||||
|
api.actions.addNodeTree(tree, 'ROOT');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY_HEADER_ROOT =
|
||||||
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{},"tag":"header"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
||||||
|
|
||||||
|
const EMPTY_CANVAS_ROOT =
|
||||||
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{},"tag":"div"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
||||||
|
|
||||||
|
describe('template header/footer zone export (loading a template)', () => {
|
||||||
|
test('sanity check: the DEFAULT header (fresh project, no template) exports its content', () => {
|
||||||
|
const { html } = exportBodyHtml(DEFAULT_HEADER_STATE);
|
||||||
|
expect(html).toContain('MySite');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a template header (SaaS Landing) exports its real nav/logo content -- not an empty strip', () => {
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing');
|
||||||
|
expect(tpl).toBeDefined();
|
||||||
|
expect(tpl!.header.components.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const { unmount } = mount();
|
||||||
|
act(() => {
|
||||||
|
api.actions.deserialize(EMPTY_HEADER_ROOT);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
addTemplateComponents(tpl!.header.components);
|
||||||
|
});
|
||||||
|
|
||||||
|
const serialized = api.query.serialize();
|
||||||
|
const { html } = exportBodyHtml(serialized);
|
||||||
|
|
||||||
|
// The template's logo text and a real nav link -- if these are missing,
|
||||||
|
// the header rendered as an empty strip (the reported bug).
|
||||||
|
expect(html).toContain('FlowStack');
|
||||||
|
expect(html).toContain('Features');
|
||||||
|
expect(html).toContain('Start Free');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a template footer (SaaS Landing) exports its real copyright/tagline content -- not an empty strip', () => {
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing');
|
||||||
|
expect(tpl).toBeDefined();
|
||||||
|
expect(tpl!.footer.components.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const { unmount } = mount();
|
||||||
|
act(() => {
|
||||||
|
api.actions.deserialize(
|
||||||
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{},"tag":"footer"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
addTemplateComponents(tpl!.footer.components);
|
||||||
|
});
|
||||||
|
|
||||||
|
const serialized = api.query.serialize();
|
||||||
|
const { html } = exportBodyHtml(serialized);
|
||||||
|
|
||||||
|
expect(html).toContain('FlowStack, Inc.');
|
||||||
|
expect(html).toContain('Ship products faster');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a template page Section with nested children (SaaS Landing Home) builds + exports without crashing', () => {
|
||||||
|
// Regression for the SECOND bug surfaced while fixing the first: naively
|
||||||
|
// rebuilding nested children via React.createElement + parseReactElement
|
||||||
|
// crashes any component with an internal SHELL_INNER linked canvas
|
||||||
|
// (Section/BackgroundSection/FormContainer) or linked columns
|
||||||
|
// (ColumnLayout). The SaaS Landing home page's second component is a
|
||||||
|
// `Section` wrapping a `Heading` ("Trusted by 10,000+ development
|
||||||
|
// teams...") -- exactly this shape.
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing');
|
||||||
|
const homePage = tpl!.pages[0];
|
||||||
|
const sectionComp = homePage.content.components.find((c) => c.type === 'Section');
|
||||||
|
expect(sectionComp).toBeDefined();
|
||||||
|
expect(sectionComp!.children?.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const { unmount } = mount();
|
||||||
|
act(() => {
|
||||||
|
api.actions.deserialize(EMPTY_CANVAS_ROOT);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
act(() => {
|
||||||
|
addTemplateComponents([sectionComp!]);
|
||||||
|
});
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
const serialized = api.query.serialize();
|
||||||
|
const { html } = exportBodyHtml(serialized);
|
||||||
|
expect(html).toContain('Trusted by 10,000+ development teams');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,7 +2,7 @@ import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { createRoot, Root } from 'react-dom/client';
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
import { act } from 'react-dom/test-utils';
|
import { act } from 'react-dom/test-utils';
|
||||||
import { PageProvider, usePages, uniqueSlug } from './PageContext';
|
import { PageProvider, usePages, uniqueSlug, nextPageId } from './PageContext';
|
||||||
|
|
||||||
/* PageContext only needs `useEditor` from @craftjs/core (for query.serialize /
|
/* PageContext only needs `useEditor` from @craftjs/core (for query.serialize /
|
||||||
actions.deserialize during page switches) — mock just that so PageProvider
|
actions.deserialize during page switches) — mock just that so PageProvider
|
||||||
@@ -15,11 +15,10 @@ vi.mock('@craftjs/core', () => ({
|
|||||||
}),
|
}),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
/* addPage mints ids from `Date.now()`. Two adds inside the same test can land
|
/* addPage mints ids via nextPageId() (timestamp + monotonic counter, M-3),
|
||||||
in the same millisecond and collide on id, which is an existing, unrelated
|
so same-millisecond calls no longer collide on id. Date.now() is still
|
||||||
bug (id collision, not slug collision) — out of scope here but it makes
|
pinned/advanced here for determinism across the slug-dedupe assertions
|
||||||
these tests flaky since a colliding id defeats the "other pages" slug
|
below, independent of wall-clock timing. */
|
||||||
lookup. Force distinct ids so the slug-dedupe assertions below are stable. */
|
|
||||||
let dateNowSpy: ReturnType<typeof vi.spyOn>;
|
let dateNowSpy: ReturnType<typeof vi.spyOn>;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
let counter = 1_700_000_000_000;
|
let counter = 1_700_000_000_000;
|
||||||
@@ -48,6 +47,23 @@ function unmount() {
|
|||||||
container.remove();
|
container.remove();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
describe('nextPageId (M-3: no same-millisecond id collision)', () => {
|
||||||
|
test('two calls yield distinct ids even when Date.now() is pinned to a constant', () => {
|
||||||
|
const spy = vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000);
|
||||||
|
try {
|
||||||
|
const id1 = nextPageId();
|
||||||
|
const id2 = nextPageId();
|
||||||
|
expect(id1).not.toBe(id2);
|
||||||
|
} finally {
|
||||||
|
spy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ids are prefixed with "page_"', () => {
|
||||||
|
expect(nextPageId()).toMatch(/^page_/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('uniqueSlug', () => {
|
describe('uniqueSlug', () => {
|
||||||
test('returns base unchanged when no collision', () => {
|
test('returns base unchanged when no collision', () => {
|
||||||
expect(uniqueSlug('about', ['index', 'contact'])).toBe('about');
|
expect(uniqueSlug('about', ['index', 'contact'])).toBe('about');
|
||||||
|
|||||||
@@ -43,6 +43,20 @@ interface PageContextValue {
|
|||||||
const HEADER_ID = '__header__';
|
const HEADER_ID = '__header__';
|
||||||
const FOOTER_ID = '__footer__';
|
const FOOTER_ID = '__footer__';
|
||||||
|
|
||||||
|
// M-3: `page_${Date.now()}` alone collides when two pages are minted inside
|
||||||
|
// the same millisecond (addPage called twice in quick succession, or two AI
|
||||||
|
// replaceAllPages entries) -- then rename/delete/save operate on both pages
|
||||||
|
// at once since they share an id. A module-scoped monotonic counter,
|
||||||
|
// combined with the timestamp, guarantees uniqueness regardless of how many
|
||||||
|
// ids are minted within the same millisecond. This is state/id-minting code
|
||||||
|
// (not toHtml/export), so Date.now() here is fine -- see task-minors-brief.md.
|
||||||
|
let pageIdCounter = 0;
|
||||||
|
|
||||||
|
/** Mints a unique page id: timestamp (base36) + a monotonic per-process counter (base36). */
|
||||||
|
export function nextPageId(): string {
|
||||||
|
return 'page_' + Date.now().toString(36) + '_' + (++pageIdCounter).toString(36);
|
||||||
|
}
|
||||||
|
|
||||||
const EMPTY_CANVAS =
|
const EMPTY_CANVAS =
|
||||||
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{"minHeight":"100vh","backgroundColor":"#ffffff"},"tag":"div"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{"minHeight":"100vh","backgroundColor":"#ffffff"},"tag":"div"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
||||||
|
|
||||||
@@ -105,6 +119,13 @@ export function treeToCraftState(tree: SerializedTreeNode): string {
|
|||||||
// Container), so there was no menu to edit and the empty zone rendered as a
|
// Container), so there was no menu to edit and the empty zone rendered as a
|
||||||
// stray band above the page. Seeding a real Navbar gives every new site an
|
// stray band above the page. Seeding a real Navbar gives every new site an
|
||||||
// editable menu-with-links out of the box (and removes the empty-header gap).
|
// editable menu-with-links out of the box (and removes the empty-header gap).
|
||||||
|
//
|
||||||
|
// Item 15: the nav used to link Home/About/Services/Contact, but a brand
|
||||||
|
// new site only has a "Home" page -- About/Services/Contact were dead links
|
||||||
|
// on first click. Rather than seeding three empty placeholder pages nobody
|
||||||
|
// asked for, the simpler default is a nav with just the one real page (Home)
|
||||||
|
// plus a CTA button, which is inert (`href: '#'`) rather than pointing at a
|
||||||
|
// page that doesn't exist. Users add pages/links as their site grows.
|
||||||
// Node shape matches treeToCraftState() / Craft's actions.deserialize().
|
// Node shape matches treeToCraftState() / Craft's actions.deserialize().
|
||||||
export const DEFAULT_HEADER_STATE = JSON.stringify({
|
export const DEFAULT_HEADER_STATE = JSON.stringify({
|
||||||
ROOT: {
|
ROOT: {
|
||||||
@@ -130,9 +151,7 @@ export const DEFAULT_HEADER_STATE = JSON.stringify({
|
|||||||
logoFontSize: '20px',
|
logoFontSize: '20px',
|
||||||
links: [
|
links: [
|
||||||
{ text: 'Home', href: '/' },
|
{ text: 'Home', href: '/' },
|
||||||
{ text: 'About', href: '#about' },
|
{ text: 'Get Started', href: '#', isCta: true },
|
||||||
{ text: 'Services', href: '#services' },
|
|
||||||
{ text: 'Contact', href: '#contact', isCta: true },
|
|
||||||
],
|
],
|
||||||
backgroundColor: '#ffffff',
|
backgroundColor: '#ffffff',
|
||||||
textColor: '#3f3f46',
|
textColor: '#3f3f46',
|
||||||
@@ -338,7 +357,7 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
|||||||
const addPage = useCallback(
|
const addPage = useCallback(
|
||||||
(name: string, slug: string) => {
|
(name: string, slug: string) => {
|
||||||
const requestedSlug = slug || slugify(name);
|
const requestedSlug = slug || slugify(name);
|
||||||
const id = `page_${Date.now()}`;
|
const id = nextPageId();
|
||||||
|
|
||||||
// Save current page first
|
// Save current page first
|
||||||
saveCurrentState();
|
saveCurrentState();
|
||||||
@@ -452,7 +471,7 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
|||||||
const slug = i === 0 ? 'index' : uniqueSlug(slugify(p.name), seenSlugs);
|
const slug = i === 0 ? 'index' : uniqueSlug(slugify(p.name), seenSlugs);
|
||||||
seenSlugs.push(slug);
|
seenSlugs.push(slug);
|
||||||
return {
|
return {
|
||||||
id: i === 0 ? 'home' : `page_${Date.now()}_${i}`,
|
id: i === 0 ? 'home' : nextPageId(),
|
||||||
name: p.name,
|
name: p.name,
|
||||||
slug,
|
slug,
|
||||||
craftState: treeToCraftState(p.tree),
|
craftState: treeToCraftState(p.tree),
|
||||||
|
|||||||
@@ -23,8 +23,14 @@ describe('DEFAULT_HEADER_STATE seed', () => {
|
|||||||
const { html } = exportBodyHtml(DEFAULT_HEADER_STATE);
|
const { html } = exportBodyHtml(DEFAULT_HEADER_STATE);
|
||||||
expect(html).toContain('<nav');
|
expect(html).toContain('<nav');
|
||||||
expect(html).toContain('MySite');
|
expect(html).toContain('MySite');
|
||||||
for (const link of ['Home', 'About', 'Services', 'Contact']) {
|
// Item 15: the default nav only links pages/anchors that actually exist
|
||||||
|
// on a brand new site (just "Home") plus an inert CTA -- no dead links
|
||||||
|
// to About/Services/Contact pages that were never seeded.
|
||||||
|
for (const link of ['Home', 'Get Started']) {
|
||||||
expect(html).toContain(link);
|
expect(html).toContain(link);
|
||||||
}
|
}
|
||||||
|
expect(html).not.toContain('About');
|
||||||
|
expect(html).not.toContain('Services');
|
||||||
|
expect(html).not.toContain('Contact');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+128
-47
@@ -16,8 +16,8 @@
|
|||||||
--color-border: #2d2d3a;
|
--color-border: #2d2d3a;
|
||||||
--color-border-light: #3f3f46;
|
--color-border-light: #3f3f46;
|
||||||
--color-text: #e4e4e7;
|
--color-text: #e4e4e7;
|
||||||
--color-text-muted: #71717a;
|
--color-text-muted: #8b8b96;
|
||||||
--color-text-dim: #52525b;
|
--color-text-dim: #6e6e78;
|
||||||
--color-accent: #3b82f6;
|
--color-accent: #3b82f6;
|
||||||
--color-accent-hover: #2563eb;
|
--color-accent-hover: #2563eb;
|
||||||
--color-accent-subtle: rgba(59, 130, 246, 0.12);
|
--color-accent-subtle: rgba(59, 130, 246, 0.12);
|
||||||
@@ -136,7 +136,7 @@ body {
|
|||||||
color: var(--color-text);
|
color: var(--color-text);
|
||||||
background: transparent;
|
background: transparent;
|
||||||
border: 1px solid var(--color-border);
|
border: 1px solid var(--color-border);
|
||||||
border-radius: 20px;
|
border-radius: var(--radius-md);
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
transition: background var(--transition-fast), border-color var(--transition-fast),
|
transition: background var(--transition-fast), border-color var(--transition-fast),
|
||||||
@@ -198,6 +198,19 @@ body {
|
|||||||
margin: 0 4px;
|
margin: 0 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Icon-only topbar buttons (Show Guides, Code, Preview) -- square-ish
|
||||||
|
footprint instead of the label+icon pill, tooltip via [data-tooltip]. */
|
||||||
|
.topbar-btn.icon-only {
|
||||||
|
gap: 0;
|
||||||
|
padding: 6px 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-btn.guides-toggle.active {
|
||||||
|
color: var(--color-accent);
|
||||||
|
background: var(--color-accent-subtle);
|
||||||
|
border-color: var(--color-accent);
|
||||||
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------------------
|
/* --------------------------------------------------------------------------
|
||||||
Device Switcher
|
Device Switcher
|
||||||
-------------------------------------------------------------------------- */
|
-------------------------------------------------------------------------- */
|
||||||
@@ -704,7 +717,7 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.block-item-icon {
|
.block-item-icon {
|
||||||
font-size: 18px;
|
font-size: 20px;
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
transition: color var(--transition-fast);
|
transition: color var(--transition-fast);
|
||||||
}
|
}
|
||||||
@@ -714,7 +727,7 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.block-item-label {
|
.block-item-label {
|
||||||
font-size: 10px;
|
font-size: 11px;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
text-align: center;
|
text-align: center;
|
||||||
@@ -1002,63 +1015,80 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------------------
|
/* --------------------------------------------------------------------------
|
||||||
Editor Visual Guides — dashed outlines for containers/columns/sections
|
Editor Visual Guides — dashed outlines for real drop targets only
|
||||||
-------------------------------------------------------------------------- */
|
-------------------------------------------------------------------------- */
|
||||||
|
|
||||||
/* All block-level elements in the canvas get a subtle dashed border */
|
/* Only actual Craft.js droppable containers get a guide outline -- these are
|
||||||
.canvas-device-frame div,
|
tagged with `data-craft-node` in RenderNode.tsx (the `<Editor onRender>`
|
||||||
.canvas-device-frame section,
|
override) based on `node.data.isCanvas`, not a blanket tag selector. A
|
||||||
.canvas-device-frame header,
|
component's own internal wrapper `<div>`s (e.g. Section's inner max-width
|
||||||
.canvas-device-frame footer,
|
container) are real DOM elements but not Craft nodes, so they never get
|
||||||
.canvas-device-frame main,
|
this attribute and never get a guide outline -- this is what stops
|
||||||
.canvas-device-frame article,
|
finished sections from showing 3-4 nested dashed boxes. */
|
||||||
.canvas-device-frame nav,
|
.canvas-device-frame [data-craft-node] {
|
||||||
.canvas-device-frame form {
|
|
||||||
outline: 1px dashed rgba(148, 163, 184, 0.2);
|
outline: 1px dashed rgba(148, 163, 184, 0.2);
|
||||||
outline-offset: -1px;
|
outline-offset: -1px;
|
||||||
transition: outline-color 0.15s;
|
transition: outline-color 0.15s;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Don't outline the outermost root wrapper or tiny utility divs */
|
|
||||||
.canvas-device-frame > div {
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Rows (flex containers) get a slightly more visible border */
|
/* Rows (flex containers) get a slightly more visible border */
|
||||||
.canvas-device-frame div[style*="display: flex"],
|
.canvas-device-frame [data-craft-node][style*="display: flex"],
|
||||||
.canvas-device-frame div[style*="display:flex"] {
|
.canvas-device-frame [data-craft-node][style*="display:flex"] {
|
||||||
outline: 1px dashed rgba(148, 163, 184, 0.35);
|
outline: 1px dashed rgba(148, 163, 184, 0.35);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Empty containers: more visible + minimum height so they're clickable */
|
/* Empty containers: more visible + minimum height so they're clickable */
|
||||||
.canvas-device-frame div:empty,
|
.canvas-device-frame [data-craft-node]:empty {
|
||||||
.canvas-device-frame section:empty,
|
|
||||||
.canvas-device-frame main:empty,
|
|
||||||
.canvas-device-frame header:empty,
|
|
||||||
.canvas-device-frame footer:empty {
|
|
||||||
outline: 2px dashed rgba(148, 163, 184, 0.4);
|
outline: 2px dashed rgba(148, 163, 184, 0.4);
|
||||||
min-height: 60px;
|
min-height: 60px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Hover highlights */
|
/* Hover highlights */
|
||||||
.canvas-device-frame div:hover,
|
.canvas-device-frame [data-craft-node]:hover {
|
||||||
.canvas-device-frame section:hover,
|
|
||||||
.canvas-device-frame header:hover,
|
|
||||||
.canvas-device-frame footer:hover,
|
|
||||||
.canvas-device-frame main:hover,
|
|
||||||
.canvas-device-frame nav:hover {
|
|
||||||
outline-color: rgba(59, 130, 246, 0.5);
|
outline-color: rgba(59, 130, 246, 0.5);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Header/footer zones get a distinct amber color */
|
/* `data-craft-hovered` is set (presence, no value) in RenderNode.tsx,
|
||||||
.canvas-device-frame [data-zone="header"],
|
mirroring Craft's own `hovered` node event. Craft.js's `connectors.connect()`
|
||||||
.canvas-device-frame [data-zone="footer"] {
|
(called by every component) wires that event to a native
|
||||||
outline: 1px dashed rgba(245, 158, 11, 0.4);
|
mouseover/mouseleave listener on each node's dom internally, so this
|
||||||
|
rule is a real mouse-hover highlight for any node (container or leaf).
|
||||||
|
Scoped under `.canvas-device-frame` and suppressed by `.guides-off` so
|
||||||
|
"Show guides: off" stays airtight. */
|
||||||
|
.canvas-device-frame [data-craft-hovered] {
|
||||||
|
outline: 2px dashed var(--color-accent) !important;
|
||||||
|
outline-offset: -1px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.canvas-device-frame [data-zone="header"]:hover,
|
/* `data-layer-hovered` is set directly by the Layers panel (LayersPanel.tsx)
|
||||||
.canvas-device-frame [data-zone="footer"]:hover {
|
on its own row hover/focus -- a separate producer (writing straight to the
|
||||||
outline-color: rgba(245, 158, 11, 0.7);
|
target's dom rather than through Craft's `hovered` event, since the
|
||||||
|
action that drives it is stripped from the public `useEditor()` API at
|
||||||
|
runtime) that drives a highlight when hovering a layer row. This is a
|
||||||
|
deliberate locator action (not a structural drop-target guide), so it
|
||||||
|
uses a SOLID outline -- visually distinct from the dashed structural
|
||||||
|
guides -- and is intentionally NOT suppressed by `.guides-off`: hiding
|
||||||
|
guides shouldn't blind the Layers-panel hover→canvas locator. */
|
||||||
|
.canvas-device-frame [data-layer-hovered] {
|
||||||
|
outline: 2px solid var(--color-accent) !important;
|
||||||
|
outline-offset: -1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* "Show guides" topbar toggle (TopBar.tsx) -- flips this class on
|
||||||
|
.canvas-device-frame to hide structural drop-target guides and the
|
||||||
|
mouse-hover highlight at once. Default ON. `[data-layer-hovered]` is
|
||||||
|
deliberately excluded -- see rule above. */
|
||||||
|
.canvas-device-frame.guides-off [data-craft-node],
|
||||||
|
.canvas-device-frame.guides-off [data-craft-hovered] {
|
||||||
|
outline: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Header/footer zone-preview separator (Canvas.tsx ZonePreview) -- a neutral
|
||||||
|
dashed rule marking where the editable page meets the read-only
|
||||||
|
header/footer preview. It's a structural guide, so it hides with the
|
||||||
|
rest when "Show guides" is off. */
|
||||||
|
.canvas-device-frame.guides-off .zone-preview-sep {
|
||||||
|
border-color: transparent !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------------------
|
/* --------------------------------------------------------------------------
|
||||||
@@ -1069,17 +1099,16 @@ body {
|
|||||||
outline-offset: -1px;
|
outline-offset: -1px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.craftjs-renderer [data-hovered="true"] {
|
/* Component indicator badge (floats over the selected node via a portal --
|
||||||
outline: 1px dashed var(--color-accent) !important;
|
position/top/left are set inline per-node, see RenderNode.tsx) */
|
||||||
outline-offset: -1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Component indicator badge */
|
|
||||||
.component-indicator {
|
.component-indicator {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: -22px;
|
top: -22px;
|
||||||
left: 0;
|
left: 0;
|
||||||
padding: 2px 8px;
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 2px 6px 2px 8px;
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #ffffff;
|
color: #ffffff;
|
||||||
@@ -1090,6 +1119,28 @@ body {
|
|||||||
z-index: 10;
|
z-index: 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.component-indicator-parent-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
padding: 0;
|
||||||
|
border: none;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: rgba(255, 255, 255, 0.2);
|
||||||
|
color: #ffffff;
|
||||||
|
font-size: 8px;
|
||||||
|
line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
pointer-events: auto;
|
||||||
|
transition: background var(--transition-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.component-indicator-parent-btn:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------------------
|
/* --------------------------------------------------------------------------
|
||||||
Scrollbar Styling
|
Scrollbar Styling
|
||||||
-------------------------------------------------------------------------- */
|
-------------------------------------------------------------------------- */
|
||||||
@@ -1127,6 +1178,21 @@ body {
|
|||||||
scrollbar-color: var(--color-border) transparent;
|
scrollbar-color: var(--color-border) transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------------
|
||||||
|
Pages Panel — Header/Footer zone rows (Item 11)
|
||||||
|
Compact rows in the same neutral surface language as the page list, with
|
||||||
|
a pencil hint that only appears on hover instead of a permanently-loud
|
||||||
|
"Editing" pill.
|
||||||
|
-------------------------------------------------------------------------- */
|
||||||
|
.zone-row-pencil {
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity var(--transition-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.zone-row:hover .zone-row-pencil {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------------------
|
/* --------------------------------------------------------------------------
|
||||||
Tooltip
|
Tooltip
|
||||||
-------------------------------------------------------------------------- */
|
-------------------------------------------------------------------------- */
|
||||||
@@ -1157,6 +1223,16 @@ body {
|
|||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Topbar sits flush against the top of the viewport (`body { overflow:
|
||||||
|
hidden }`), so the default "tooltip above the trigger" placement gets
|
||||||
|
clipped off-screen for topbar buttons -- flip those to render below
|
||||||
|
instead. Left-panel/canvas tooltips keep the default above placement,
|
||||||
|
which has room to render there. */
|
||||||
|
.topbar [data-tooltip]::after {
|
||||||
|
bottom: auto;
|
||||||
|
top: calc(100% + 6px);
|
||||||
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------------------
|
/* --------------------------------------------------------------------------
|
||||||
Notifications / Toasts
|
Notifications / Toasts
|
||||||
-------------------------------------------------------------------------- */
|
-------------------------------------------------------------------------- */
|
||||||
@@ -1225,6 +1301,8 @@ body {
|
|||||||
Empty Canvas State
|
Empty Canvas State
|
||||||
-------------------------------------------------------------------------- */
|
-------------------------------------------------------------------------- */
|
||||||
.empty-canvas-hint {
|
.empty-canvas-hint {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -1234,6 +1312,9 @@ body {
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
gap: 12px;
|
gap: 12px;
|
||||||
|
/* Overlays the drop area without intercepting drags/clicks meant for the
|
||||||
|
underlying (empty) canvas root -- see Canvas.tsx. */
|
||||||
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.empty-canvas-hint i {
|
.empty-canvas-hint i {
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { templateComponentToTreeNode } from './apply-template';
|
||||||
|
|
||||||
|
describe('templateComponentToTreeNode', () => {
|
||||||
|
test('converts a childless TemplateComponent to a SerializedTreeNode with an empty `nodes` array', () => {
|
||||||
|
const node = templateComponentToTreeNode({ type: 'Heading', props: { text: 'Hi' } });
|
||||||
|
expect(node).toEqual({
|
||||||
|
type: { resolvedName: 'Heading' },
|
||||||
|
props: { text: 'Hi' },
|
||||||
|
nodes: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('regression: recursively converts nested `children` into `nodes` (previously dropped entirely)', () => {
|
||||||
|
const node = templateComponentToTreeNode({
|
||||||
|
type: 'Container',
|
||||||
|
props: { tag: 'header' },
|
||||||
|
children: [
|
||||||
|
{ type: 'Logo', props: { text: 'FlowStack' } },
|
||||||
|
{ type: 'Menu', props: { links: [] } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(node.nodes).toHaveLength(2);
|
||||||
|
expect(node.nodes![0]).toEqual({ type: { resolvedName: 'Logo' }, props: { text: 'FlowStack' }, nodes: [] });
|
||||||
|
expect(node.nodes![1]).toEqual({ type: { resolvedName: 'Menu' }, props: { links: [] }, nodes: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('recurses more than one level deep', () => {
|
||||||
|
const node = templateComponentToTreeNode({
|
||||||
|
type: 'Section',
|
||||||
|
props: {},
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
type: 'ColumnLayout',
|
||||||
|
props: { columns: 1 },
|
||||||
|
children: [{ type: 'TextBlock', props: { text: 'deep' } }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const col = node.nodes![0];
|
||||||
|
expect(col.type.resolvedName).toBe('ColumnLayout');
|
||||||
|
expect(col.nodes![0]).toEqual({ type: { resolvedName: 'TextBlock' }, props: { text: 'deep' }, nodes: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not mutate the input TemplateComponent', () => {
|
||||||
|
const comp = { type: 'Heading', props: { text: 'Hi' } };
|
||||||
|
const frozen = JSON.parse(JSON.stringify(comp));
|
||||||
|
templateComponentToTreeNode(comp);
|
||||||
|
expect(comp).toEqual(frozen);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import type { SerializedTreeNode } from '../types/sitesmith';
|
||||||
|
import { TemplateComponent } from './definitions';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a template's `TemplateComponent` tree (the plain
|
||||||
|
* `{ type, props, children? }` shape authored in `templates/definitions.ts`)
|
||||||
|
* into a `SerializedTreeNode` (the shape `craft-tree.ts`'s `buildNodeTree` /
|
||||||
|
* `sanitizeAiTree` / `flattenTreeForCraft` pipeline already knows how to
|
||||||
|
* materialize into a real Craft.js `NodeTree`).
|
||||||
|
*
|
||||||
|
* Bug this fixes: `TemplateModal`'s `addTemplateComponents` used to call
|
||||||
|
* `React.createElement(Component, comp.props)` with no children argument,
|
||||||
|
* which silently dropped every nested `children` array authored in
|
||||||
|
* definitions.ts -- e.g. `makeHeader()`'s `Container > Logo + Menu`,
|
||||||
|
* `makeFooterContent()`'s `Container > TextBlock...`, or a page `Section`
|
||||||
|
* wrapping a `Heading`/`TextBlock`/`ButtonLink`. The resulting Craft.js node
|
||||||
|
* ended up with `nodes: []`, so the header/footer zone preview
|
||||||
|
* (`ZonePreview` in `editor/Canvas.tsx`, via `exportBodyHtml`) -- and the
|
||||||
|
* same-path published HTML (`handlePublish` composes header/footer HTML
|
||||||
|
* from the same serialized state) -- rendered as an empty strip instead of
|
||||||
|
* the real nav/footer/section content.
|
||||||
|
*
|
||||||
|
* A follow-up attempt fixed that by building a real nested React element
|
||||||
|
* tree (`React.createElement(Component, props, ...children)`) and handing
|
||||||
|
* it to `query.parseReactElement(...).toNodeTree()`. That approach breaks
|
||||||
|
* for any component with an internal SHELL_INNER-style linked canvas
|
||||||
|
* (`Section`, `BackgroundSection`, `FormContainer` -- see `SHELL_INNER` in
|
||||||
|
* `craft-tree.ts`) or linked columns (`ColumnLayout`): `parseReactElement`
|
||||||
|
* statically walks the JSX tree and has no way to know that e.g. `Section`
|
||||||
|
* routes its `children` into a nested `<Element id="section-inner" canvas>`
|
||||||
|
* at render time, not directly under itself. Feeding it raw nested children
|
||||||
|
* produces a tree where Craft.js has to auto-materialize that linked node on
|
||||||
|
* first render -- which stores the wrong `type` and crashes with "component
|
||||||
|
* type (undefined) does not exist in the resolver" the moment the section
|
||||||
|
* renders (reproduced live: loading the SaaS Landing template crashed the
|
||||||
|
* whole editor on its "Trusted by 10,000+ development teams" `Section`).
|
||||||
|
*
|
||||||
|
* Converting to `SerializedTreeNode` and reusing `buildNodeTree` sidesteps
|
||||||
|
* both bugs at once: it's the same tree-building pipeline already used (and
|
||||||
|
* tested) for AI-generated content in `apply-ai-response.ts`, which already
|
||||||
|
* knows how to route content through SHELL_INNER / linked columns correctly.
|
||||||
|
*/
|
||||||
|
export function templateComponentToTreeNode(comp: TemplateComponent): SerializedTreeNode {
|
||||||
|
return {
|
||||||
|
type: { resolvedName: comp.type },
|
||||||
|
props: { ...comp.props },
|
||||||
|
nodes: (comp.children || []).map(templateComponentToTreeNode),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import type { NodeTree } from '@craftjs/core';
|
|
||||||
import { usePages } from '../state/PageContext';
|
import { usePages } from '../state/PageContext';
|
||||||
import { SitesmithResponse, SerializedTreeNode, SitesmithPatchOp } from '../types/sitesmith';
|
import { SitesmithResponse, SerializedTreeNode, SitesmithPatchOp } from '../types/sitesmith';
|
||||||
import { sanitizeAiTree, flattenTreeForCraft } from './craft-tree';
|
import { sanitizeAiTree, buildNodeTree } from './craft-tree';
|
||||||
|
|
||||||
// Re-exported for existing callers/tests that import sanitizeAiTree from
|
// Re-exported for existing callers/tests that import sanitizeAiTree/
|
||||||
// this module — the implementation now lives in craft-tree.ts alongside the
|
// buildNodeTree from this module — the implementation lives in craft-tree.ts
|
||||||
// shared flattener, since treeToState (PageContext.tsx) needs the same
|
// alongside the shared flattener: `templates/apply-template.ts` needs the
|
||||||
// validation this module pioneered.
|
// exact same tree-materialization logic to load template header/footer/page
|
||||||
export { sanitizeAiTree };
|
// content (see the doc comment on `buildNodeTree` in craft-tree.ts).
|
||||||
|
export { sanitizeAiTree, buildNodeTree };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* update_props may never touch these keys, regardless of what the AI sends.
|
* update_props may never touch these keys, regardless of what the AI sends.
|
||||||
@@ -18,52 +18,6 @@ export { sanitizeAiTree };
|
|||||||
*/
|
*/
|
||||||
const PROTECTED_UPDATE_PROPS_KEYS = new Set<string>(['node_id']);
|
const PROTECTED_UPDATE_PROPS_KEYS = new Set<string>(['node_id']);
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a Craft.js `NodeTree` from a `SerializedTreeNode` using `query.parseFreshNode`.
|
|
||||||
* This is the correct way to construct a tree for `actions.addNodeTree()` when
|
|
||||||
* inserting/replacing sections or individual nodes.
|
|
||||||
*/
|
|
||||||
function buildNodeTree(query: any, tree: SerializedTreeNode): NodeTree {
|
|
||||||
// Validate + sanitize at the AI boundary before touching Craft.js at all:
|
|
||||||
// unknown resolvedNames are dropped (never reach parseFreshNode/addNodeTree,
|
|
||||||
// which would throw), and ids are repaired ('ROOT'/empty/colliding →
|
|
||||||
// regenerated) against the live document's existing node ids so a new
|
|
||||||
// AI-supplied id can never clobber or duplicate one already on the canvas.
|
|
||||||
const existingIds = new Set<string>(
|
|
||||||
typeof query?.getNodes === 'function' ? Object.keys(query.getNodes()) : [],
|
|
||||||
);
|
|
||||||
const sanitized = sanitizeAiTree(tree, existingIds);
|
|
||||||
if (!sanitized) {
|
|
||||||
throw new Error('sitesmith: AI tree root has an unknown/invalid component type; nothing to build');
|
|
||||||
}
|
|
||||||
|
|
||||||
// sanitizeAiTree() has already guaranteed every node has a valid, unique,
|
|
||||||
// non-'ROOT' node_id and a registered resolvedName — the shared flattener
|
|
||||||
// just needs to do the structural walk (linkedNodes/SHELL_INNER/style
|
|
||||||
// normalization) common to every tree-flattening caller in this codebase.
|
|
||||||
const flat = flattenTreeForCraft(sanitized);
|
|
||||||
|
|
||||||
const craftNodes: Record<string, any> = {};
|
|
||||||
for (const [id, flatNode] of Object.entries(flat.nodes)) {
|
|
||||||
if (flat.syntheticIds.has(id)) {
|
|
||||||
// The SHELL_INNER wrapper Container is synthesized by the flattener,
|
|
||||||
// not present in the AI's tree — build it directly rather than
|
|
||||||
// through query.parseFreshNode(), which would merge in Container's
|
|
||||||
// default `craft.props` (e.g. default padding) and change its look.
|
|
||||||
craftNodes[id] = {
|
|
||||||
id,
|
|
||||||
data: { ...flatNode },
|
|
||||||
events: { selected: false, hovered: false, dragged: false },
|
|
||||||
rules: { canDrag: () => true, canMoveIn: () => true, canMoveOut: () => true, canDrop: () => true },
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
craftNodes[id] = (query.parseFreshNode({ id, data: { ...flatNode } }) as any).toNode();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { rootNodeId: flat.rootNodeId, nodes: craftNodes };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Find the Craft.js node id that corresponds to an AI node_id value.
|
* Find the Craft.js node id that corresponds to an AI node_id value.
|
||||||
* Checks `data.props.node_id` first, then falls back to raw id equality.
|
* Checks `data.props.node_id` first, then falls back to raw id equality.
|
||||||
|
|||||||
@@ -225,6 +225,105 @@ export function flattenTreeForCraft(tree: SerializedTreeNode): FlattenTreeResult
|
|||||||
return { rootNodeId, nodes, syntheticIds };
|
return { rootNodeId, nodes, syntheticIds };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a Craft.js `NodeTree` from a `SerializedTreeNode` using
|
||||||
|
* `query.parseFreshNode`. This is the correct way to construct a tree for
|
||||||
|
* `actions.addNodeTree()` when inserting/replacing sections, individual
|
||||||
|
* nodes, or (via `templates/apply-template.ts`) a template's header/footer/
|
||||||
|
* page content -- anything whose input isn't already a live Craft.js state.
|
||||||
|
*
|
||||||
|
* Originally lived in `apply-ai-response.ts` (the AI-response path pioneered
|
||||||
|
* it); moved here alongside `sanitizeAiTree`/`flattenTreeForCraft` once
|
||||||
|
* `templates/apply-template.ts` needed the exact same tree-materialization
|
||||||
|
* logic — building a node tree by hand via `React.createElement` +
|
||||||
|
* `query.parseReactElement` does NOT correctly route content through a
|
||||||
|
* `Section`/`BackgroundSection`/`FormContainer`'s internal SHELL_INNER
|
||||||
|
* linked canvas or `ColumnLayout`'s linked columns (see the `SHELL_INNER`
|
||||||
|
* comment above): Craft.js would auto-materialize that linked node at
|
||||||
|
* render time with a botched `type` field and crash `toNodeTree` with
|
||||||
|
* "component type (undefined) does not exist in the resolver". Going through
|
||||||
|
* `sanitizeAiTree` + `flattenTreeForCraft` (as this function does) avoids
|
||||||
|
* that entirely.
|
||||||
|
*/
|
||||||
|
export function buildNodeTree(query: any, tree: SerializedTreeNode): NodeTree {
|
||||||
|
// Validate + sanitize at the boundary before touching Craft.js at all:
|
||||||
|
// unknown resolvedNames are dropped (never reach parseFreshNode/addNodeTree,
|
||||||
|
// which would throw), and ids are repaired ('ROOT'/empty/colliding →
|
||||||
|
// regenerated) against the live document's existing node ids so a new
|
||||||
|
// caller-supplied id can never clobber or duplicate one already on the canvas.
|
||||||
|
const existingIds = new Set<string>(
|
||||||
|
typeof query?.getNodes === 'function' ? Object.keys(query.getNodes()) : [],
|
||||||
|
);
|
||||||
|
const sanitized = sanitizeAiTree(tree, existingIds);
|
||||||
|
if (!sanitized) {
|
||||||
|
throw new Error('craft-tree: tree root has an unknown/invalid component type; nothing to build');
|
||||||
|
}
|
||||||
|
|
||||||
|
// sanitizeAiTree() has already guaranteed every node has a valid, unique,
|
||||||
|
// non-'ROOT' node_id and a registered resolvedName — flattenTreeForCraft
|
||||||
|
// just needs to do the structural walk (linkedNodes/SHELL_INNER/style
|
||||||
|
// normalization) common to every tree-flattening caller in this codebase.
|
||||||
|
const flat = flattenTreeForCraft(sanitized);
|
||||||
|
|
||||||
|
const craftNodes: Record<string, any> = {};
|
||||||
|
for (const [id, flatNode] of Object.entries(flat.nodes)) {
|
||||||
|
// Live Craft.js nodes need `data.type` to be the ACTUAL component
|
||||||
|
// reference (the function/class from `componentResolver`) -- not the
|
||||||
|
// `{ resolvedName }` wrapper object `flattenTreeForCraft` produces (that
|
||||||
|
// wrapper is the *serialized* form used by `actions.deserialize()`/
|
||||||
|
// `query.serialize()`, a different Craft.js entry point), and not a
|
||||||
|
// plain resolvedName string either.
|
||||||
|
//
|
||||||
|
// A plain string passes `parseFreshNode`'s own validation (it special-
|
||||||
|
// cases strings) AND `actions.addNodeTree`'s, so that alone looks fine --
|
||||||
|
// but it's wrong for RENDERING: Craft.js's node renderer does
|
||||||
|
// `React.createElement(data.type, props)` directly, so a string type
|
||||||
|
// makes React treat e.g. "Section" as a literal (invalid, lowercase-
|
||||||
|
// expected) HTML tag name instead of resolving it to the real `Section`
|
||||||
|
// component. Symptom: "is using incorrect casing" console warnings and
|
||||||
|
// the component's own render logic (and thus its content) never runs --
|
||||||
|
// reproduced live by loading a template: the header/footer rendered fine
|
||||||
|
// but the page canvas went blank. The `{ resolvedName }` wrapper object
|
||||||
|
// fails even earlier, at `parseFreshNode`/`addNodeTree`'s own validation
|
||||||
|
// ("component type (undefined) does not exist in the resolver"), because
|
||||||
|
// their resolution only accepts a string or a component reference.
|
||||||
|
//
|
||||||
|
// None of this was caught by the pre-existing mocked test for this
|
||||||
|
// function (in apply-ai-response.test.ts) because its fake
|
||||||
|
// `parseFreshNode` just echoes the input back unchanged rather than
|
||||||
|
// exercising Craft.js's real validation/rendering.
|
||||||
|
const resolvedComponent = (componentResolver as Record<string, unknown>)[flatNode.type.resolvedName];
|
||||||
|
|
||||||
|
if (flat.syntheticIds.has(id)) {
|
||||||
|
// The SHELL_INNER wrapper Container is synthesized by the flattener,
|
||||||
|
// not present in the input tree — build it directly rather than
|
||||||
|
// through query.parseFreshNode(), which would merge in Container's
|
||||||
|
// default `craft.props` (e.g. default padding) and change its look.
|
||||||
|
//
|
||||||
|
// `actions.addNodeTree`'s own validation for a non-string `data.type`
|
||||||
|
// checks `resolver[data.name]` (NOT a reverse lookup from `data.type`
|
||||||
|
// like `parseFreshNode` does) -- so `data.name` must be set to the
|
||||||
|
// resolvedName string here too, or this synthetic node fails that
|
||||||
|
// check with "component type (Container) does not exist in the
|
||||||
|
// resolver" the moment `addNodeTree` runs, even though `resolvedComponent`
|
||||||
|
// itself is perfectly valid.
|
||||||
|
craftNodes[id] = {
|
||||||
|
id,
|
||||||
|
data: { ...flatNode, type: resolvedComponent, name: flatNode.type.resolvedName },
|
||||||
|
events: { selected: false, hovered: false, dragged: false },
|
||||||
|
rules: { canDrag: () => true, canMoveIn: () => true, canMoveOut: () => true, canDrop: () => true },
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
craftNodes[id] = (query.parseFreshNode({
|
||||||
|
id,
|
||||||
|
data: { ...flatNode, type: resolvedComponent },
|
||||||
|
}) as any).toNode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { rootNodeId: flat.rootNodeId, nodes: craftNodes };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a deep-cloned NodeTree where every node id in the tree
|
* Returns a deep-cloned NodeTree where every node id in the tree
|
||||||
* (rootNodeId, the `nodes` map keys, each `node.id`, each internal
|
* (rootNodeId, the `nodes` map keys, each `node.id`, each internal
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, test, expect } from 'vitest';
|
import { describe, test, expect } from 'vitest';
|
||||||
import { escapeHtml, escapeAttr, safeUrl, stableHash, scopeId, sanitizeFormMethod, sanitizeInputType } from './escape';
|
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl, stableHash, scopeId, sanitizeFormMethod, sanitizeInputType } from './escape';
|
||||||
|
|
||||||
describe('escapeHtml', () => {
|
describe('escapeHtml', () => {
|
||||||
test('escapes &, <, >, "', () => {
|
test('escapes &, <, >, "', () => {
|
||||||
@@ -71,6 +71,24 @@ describe('safeUrl', () => {
|
|||||||
expect(safeUrl(s)).toBe(s);
|
expect(safeUrl(s)).toBe(s);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('M-5: blocks data:image/svg+xml (can execute script when navigated to directly)', () => {
|
||||||
|
expect(safeUrl('data:image/svg+xml,<svg onload=alert(1)>')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-5: blocks data:image/svg+xml;base64 variant', () => {
|
||||||
|
expect(safeUrl('data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-5: blocks obfuscated (whitespace/case) data:image/svg+xml', () => {
|
||||||
|
expect(safeUrl(' DATA:IMAGE/SVG+XML,<svg onload=alert(1)>')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-5: still allows other data:image/* types unchanged', () => {
|
||||||
|
expect(safeUrl('data:image/jpeg;base64,/9j/4AAQ')).toBe('data:image/jpeg;base64,/9j/4AAQ');
|
||||||
|
expect(safeUrl('data:image/gif;base64,R0lGOD')).toBe('data:image/gif;base64,R0lGOD');
|
||||||
|
expect(safeUrl('data:image/webp;base64,UklGR')).toBe('data:image/webp;base64,UklGR');
|
||||||
|
});
|
||||||
|
|
||||||
test.each([
|
test.each([
|
||||||
'https://x.com/a?b=1&c=2',
|
'https://x.com/a?b=1&c=2',
|
||||||
'http://x',
|
'http://x',
|
||||||
@@ -94,6 +112,73 @@ describe('safeUrl', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('safeImageUrl (Bug 2: image-context sink -- data:image/svg+xml is safe as an <img>/CSS url() target)', () => {
|
||||||
|
test('allows data:image/svg+xml (a raw, non-base64 SVG data URI, as Gallery/ImageBlock placeholders use)', () => {
|
||||||
|
const s = 'data:image/svg+xml,<svg/>';
|
||||||
|
expect(safeImageUrl(s)).toBe(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('allows data:image/svg+xml;base64 variant', () => {
|
||||||
|
const s = 'data:image/svg+xml;base64,PHN2Zy8+';
|
||||||
|
expect(safeImageUrl(s)).toBe(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('allows other data:image/* types unchanged', () => {
|
||||||
|
expect(safeImageUrl('data:image/png;base64,x')).toBe('data:image/png;base64,x');
|
||||||
|
expect(safeImageUrl('data:image/jpeg;base64,x')).toBe('data:image/jpeg;base64,x');
|
||||||
|
expect(safeImageUrl('data:image/webp;base64,x')).toBe('data:image/webp;base64,x');
|
||||||
|
expect(safeImageUrl('data:image/gif;base64,x')).toBe('data:image/gif;base64,x');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('still blocks javascript: scheme', () => {
|
||||||
|
expect(safeImageUrl('javascript:alert(1)')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('still blocks vbscript: scheme', () => {
|
||||||
|
expect(safeImageUrl('vbscript:msgbox(1)')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('still blocks data:text/html', () => {
|
||||||
|
expect(safeImageUrl('data:text/html,x')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('still blocks non-image data: types generally (e.g. data:application/...)', () => {
|
||||||
|
expect(safeImageUrl('data:application/javascript,alert(1)')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('blocks obfuscated (whitespace/case) javascript: scheme, same as safeUrl', () => {
|
||||||
|
expect(safeImageUrl(' JavaScript:alert(1)')).toBe('');
|
||||||
|
expect(safeImageUrl('java\tscript:alert(1)')).toBe('');
|
||||||
|
expect(safeImageUrl('javascript:alert(1)')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('allows ordinary http(s)/relative urls unchanged, same as safeUrl', () => {
|
||||||
|
expect(safeImageUrl('https://example.com/photo.jpg')).toBe('https://example.com/photo.jpg');
|
||||||
|
expect(safeImageUrl('/assets/photo.jpg')).toBe('/assets/photo.jpg');
|
||||||
|
expect(safeImageUrl('')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('coerces non-string to empty string', () => {
|
||||||
|
expect(safeImageUrl(null as any)).toBe('');
|
||||||
|
expect(safeImageUrl(undefined as any)).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tightened allowlist: blocks a bogus MIME that merely starts with "image" but has no slash (e.g. data:imagehtml/...)', () => {
|
||||||
|
expect(safeImageUrl('data:imagehtml/svg+xml,x')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tightened allowlist: still allows legit data:image/* subtypes', () => {
|
||||||
|
expect(safeImageUrl('data:image/png;base64,x')).toBe('data:image/png;base64,x');
|
||||||
|
expect(safeImageUrl('data:image/svg+xml,<svg/>')).toBe('data:image/svg+xml,<svg/>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('safeUrl still blocks data:image/svg+xml (href/iframe/navigation context unchanged by safeImageUrl addition)', () => {
|
||||||
|
test('safeUrl(data:image/svg+xml,...) is still blocked', () => {
|
||||||
|
expect(safeUrl('data:image/svg+xml,<svg onload=alert(1)>')).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('stableHash', () => {
|
describe('stableHash', () => {
|
||||||
test('same input always produces the same output', () => {
|
test('same input always produces the same output', () => {
|
||||||
expect(stableHash('hello')).toBe(stableHash('hello'));
|
expect(stableHash('hello')).toBe(stableHash('hello'));
|
||||||
@@ -120,8 +205,24 @@ describe('scopeId', () => {
|
|||||||
expect(id1).not.toBe(id2);
|
expect(id1).not.toBe(id2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('node id is slugified (non-alphanumeric characters stripped, lowercased)', () => {
|
test('output is a valid CSS ident: prefix_hash', () => {
|
||||||
expect(scopeId('Node ID! 123', 'seed', 'sb')).toBe('sb_nodeid123');
|
expect(scopeId('Node ID! 123', 'seed', 'sb')).toMatch(/^sb_[a-z0-9]+$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-4: case-differing node ids do not collapse to the same scope (no case-fold collision)', () => {
|
||||||
|
expect(scopeId('AbC', 'seed', 'sb')).not.toBe(scopeId('abc', 'seed', 'sb'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-4: punctuation-differing node ids do not collapse to the same scope', () => {
|
||||||
|
expect(scopeId('a-b', 'seed', 'sb')).not.toBe(scopeId('ab', 'seed', 'sb'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-4: same input always yields the identical scope id', () => {
|
||||||
|
expect(scopeId('some-node-id', 'seed', 'sb')).toBe(scopeId('some-node-id', 'seed', 'sb'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-4: output always matches a valid CSS ident pattern', () => {
|
||||||
|
expect(scopeId('Weird!! Node--ID__123', 'seed', 'sb')).toMatch(/^[a-z]+_[a-z0-9]+$/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('no nodeId (legacy 2-arg call sites) falls back to a deterministic hash of the seed, not Math.random', () => {
|
test('no nodeId (legacy 2-arg call sites) falls back to a deterministic hash of the seed, not Math.random', () => {
|
||||||
|
|||||||
+72
-17
@@ -36,7 +36,14 @@ export function escapeAttr(s: string): string {
|
|||||||
// Dangerous scheme prefixes, checked against a normalized copy with all
|
// Dangerous scheme prefixes, checked against a normalized copy with all
|
||||||
// colons removed (see safeUrl) so that colon-splicing obfuscation like
|
// colons removed (see safeUrl) so that colon-splicing obfuscation like
|
||||||
// "java:script:alert(1)" can't slip past a literal "javascript:" check.
|
// "java:script:alert(1)" can't slip past a literal "javascript:" check.
|
||||||
const DANGEROUS_SCHEME_PREFIXES = ['javascript', 'vbscript', 'datatext/html'];
|
// M-5: `data:image/svg+xml` is blocked alongside `data:text/html` -- an SVG
|
||||||
|
// document can carry an inline <script>/onload= just like an HTML document,
|
||||||
|
// so it executes script when loaded as a document/navigation target (e.g. an
|
||||||
|
// <a href> or window.open), even though it's nominally an "image" MIME type.
|
||||||
|
// Other `data:image/*` types (png/jpeg/gif/webp, ...) stay allowed below --
|
||||||
|
// only this specific scriptable subtype is blocked, regardless of a
|
||||||
|
// trailing `;base64` or other parameters.
|
||||||
|
const DANGEROUS_SCHEME_PREFIXES = ['javascript', 'vbscript', 'datatext/html', 'dataimage/svg+xml'];
|
||||||
|
|
||||||
/** Decodes &#NN; and &#xNN; numeric HTML entities (used to obfuscate scheme names). */
|
/** Decodes &#NN; and &#xNN; numeric HTML entities (used to obfuscate scheme names). */
|
||||||
function decodeNumericEntities(s: string): string {
|
function decodeNumericEntities(s: string): string {
|
||||||
@@ -57,20 +64,7 @@ export function safeUrl(s: string): string {
|
|||||||
const trimmed = s.trim();
|
const trimmed = s.trim();
|
||||||
if (trimmed === '') return '';
|
if (trimmed === '') return '';
|
||||||
|
|
||||||
// Build a normalized copy for scheme detection only: decode numeric HTML
|
const collapsed = normalizeForSchemeCheck(trimmed);
|
||||||
// entities (catches e.g. j -> 'j'), strip whitespace/control chars,
|
|
||||||
// and lowercase.
|
|
||||||
const normalized = decodeNumericEntities(trimmed)
|
|
||||||
.replace(/[\x00-\x20]+/g, '')
|
|
||||||
.toLowerCase();
|
|
||||||
|
|
||||||
// Strip any colons before matching the scheme prefix. This defeats
|
|
||||||
// obfuscation that splices extra colons into the scheme name itself
|
|
||||||
// (e.g. decoding : mid-word produces "java:script:alert(1)", which
|
|
||||||
// would otherwise dodge a literal "^javascript:" check) while still
|
|
||||||
// reliably catching the real "javascript:"/"vbscript:"/"data:text/html"
|
|
||||||
// prefixes once their own colon is removed.
|
|
||||||
const collapsed = normalized.replace(/:/g, '');
|
|
||||||
|
|
||||||
if (DANGEROUS_SCHEME_PREFIXES.some((prefix) => collapsed.startsWith(prefix))) {
|
if (DANGEROUS_SCHEME_PREFIXES.some((prefix) => collapsed.startsWith(prefix))) {
|
||||||
return '';
|
return '';
|
||||||
@@ -79,6 +73,61 @@ export function safeUrl(s: string): string {
|
|||||||
return trimmed;
|
return trimmed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Image-context variant of `safeUrl` for IMAGE sinks only (`<img src>`, CSS
|
||||||
|
* `url(...)` backgrounds). `data:image/svg+xml` is safe here -- loaded as an
|
||||||
|
* image, an SVG is rasterized and never executes an inline <script>/onload=
|
||||||
|
* the way it would as a navigation/iframe document -- so, unlike `safeUrl`,
|
||||||
|
* this ALLOWS every `data:image/*` subtype (svg+xml, png, jpeg, gif, webp,
|
||||||
|
* ..., with or without `;base64`).
|
||||||
|
*
|
||||||
|
* Still blocks `javascript:` / `vbscript:` (same obfuscation-resistant
|
||||||
|
* normalization as `safeUrl`), and -- because this is an image sink, not a
|
||||||
|
* general-purpose URL sink -- treats `data:` as an ALLOWLIST rather than a
|
||||||
|
* blocklist: any `data:` URI whose type is NOT `image/*` (`data:text/html`,
|
||||||
|
* `data:application/javascript`, `data:text/javascript`, etc.) is blocked
|
||||||
|
* too, since none of those are legitimate image sources.
|
||||||
|
*
|
||||||
|
* Do NOT use this for href/iframe/form-action/navigation sinks -- keep
|
||||||
|
* those on `safeUrl`, which still blocks `data:image/svg+xml`.
|
||||||
|
*/
|
||||||
|
export function safeImageUrl(s: unknown): string {
|
||||||
|
if (typeof s !== 'string') return '';
|
||||||
|
|
||||||
|
const trimmed = s.trim();
|
||||||
|
if (trimmed === '') return '';
|
||||||
|
|
||||||
|
const collapsed = normalizeForSchemeCheck(trimmed);
|
||||||
|
|
||||||
|
if (collapsed.startsWith('javascript') || collapsed.startsWith('vbscript')) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
if (collapsed.startsWith('data') && !collapsed.startsWith('dataimage/')) {
|
||||||
|
// A data: URI whose MIME type isn't image/* -- e.g. data:text/html,
|
||||||
|
// data:application/javascript, data:text/javascript. No legitimate
|
||||||
|
// image source needs these; block unconditionally.
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalizes a trimmed URL string for scheme-prefix matching only: decodes
|
||||||
|
// numeric HTML entities (catches e.g. j -> 'j'), strips whitespace /
|
||||||
|
// control chars, lowercases, then strips every colon. Stripping colons
|
||||||
|
// defeats obfuscation that splices extra colons into the scheme name itself
|
||||||
|
// (e.g. decoding : mid-word produces "java:script:alert(1)", which would
|
||||||
|
// otherwise dodge a literal "^javascript:" check) while still reliably
|
||||||
|
// catching the real "javascript:"/"vbscript:"/"data:..." prefixes once their
|
||||||
|
// own colon is removed. Used for prefix `.startsWith()` checks only -- the
|
||||||
|
// original (non-collapsed) string is always what gets returned/emitted.
|
||||||
|
function normalizeForSchemeCheck(trimmed: string): string {
|
||||||
|
return decodeNumericEntities(trimmed)
|
||||||
|
.replace(/[\x00-\x20]+/g, '')
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/:/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Neutralizes CSS-context breakout for a single design-token value (color,
|
* Neutralizes CSS-context breakout for a single design-token value (color,
|
||||||
* length, gradient, etc.) so it is safe to interpolate RAW into either CSS
|
* length, gradient, etc.) so it is safe to interpolate RAW into either CSS
|
||||||
@@ -151,8 +200,14 @@ export function stableHash(seed: string): string {
|
|||||||
* available.
|
* available.
|
||||||
*/
|
*/
|
||||||
export function scopeId(nodeId: string | undefined, fallbackSeed: string, prefix: string): string {
|
export function scopeId(nodeId: string | undefined, fallbackSeed: string, prefix: string): string {
|
||||||
const slug = (nodeId || '').toString().toLowerCase().replace(/[^a-z0-9]+/g, '');
|
// M-4: hash the raw node id (via the same djb2 `stableHash` used for the
|
||||||
return `${prefix}_${slug || stableHash(fallbackSeed)}`;
|
// fallback path below) rather than lowercasing + stripping punctuation
|
||||||
|
// into a slug. A slug collapses distinct ids that differ only by
|
||||||
|
// case/punctuation (e.g. "AbC" and "abc", or "a-b" and "ab") onto the same
|
||||||
|
// scope; hashing the untouched string keeps them distinct while staying
|
||||||
|
// deterministic and producing a valid CSS ident (prefix + '_' + [a-z0-9]+).
|
||||||
|
const seed = (nodeId || '').toString();
|
||||||
|
return `${prefix}_${stableHash(seed || fallbackSeed)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shared enum allowlists for `toHtml` attribute sinks fed by props that are
|
// Shared enum allowlists for `toHtml` attribute sinks fed by props that are
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { CSSProperties } from 'react';
|
import { CSSProperties } from 'react';
|
||||||
import { escapeAttr, safeUrl } from './escape';
|
import { escapeAttr, safeImageUrl } from './escape';
|
||||||
|
|
||||||
const camelToKebab = (str: string): string =>
|
const camelToKebab = (str: string): string =>
|
||||||
str.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
|
str.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
|
||||||
@@ -41,8 +41,12 @@ function sanitizeCssValue(raw: string): string {
|
|||||||
// Neutralize the url(...) reference: validate/strip the scheme and
|
// Neutralize the url(...) reference: validate/strip the scheme and
|
||||||
// re-wrap in single quotes with the contents escaped for attribute
|
// re-wrap in single quotes with the contents escaped for attribute
|
||||||
// safety. This is already fully safe, `;` and all.
|
// safety. This is already fully safe, `;` and all.
|
||||||
|
// Image-context sink (background/mask/border-image url()): use
|
||||||
|
// safeImageUrl, not safeUrl -- a data:image/svg+xml background is safe
|
||||||
|
// (rasterized, never executed as a document) and must survive here, the
|
||||||
|
// same way it must survive on an <img src>.
|
||||||
const inner = m[2];
|
const inner = m[2];
|
||||||
out += `url('${escapeAttr(safeUrl(inner.trim()))}')`;
|
out += `url('${escapeAttr(safeImageUrl(inner.trim()))}')`;
|
||||||
lastIndex = URL_RE.lastIndex;
|
lastIndex = URL_RE.lastIndex;
|
||||||
}
|
}
|
||||||
out += sanitizeBreakoutChars(raw.slice(lastIndex));
|
out += sanitizeBreakoutChars(raw.slice(lastIndex));
|
||||||
|
|||||||
Reference in New Issue
Block a user