Compare commits
8
Commits
enh-nav
...
8f17b74e2b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f17b74e2b | ||
|
|
d07bc7789d | ||
|
|
b03425ac39 | ||
|
|
5b19ae97af | ||
|
|
88df4f2888 | ||
|
|
e1b4ab735c | ||
|
|
ff1e8fc096 | ||
|
|
0419291259 |
@@ -52,3 +52,69 @@ describe('ButtonLink.toHtml text escaping (attacker-controlled `text` prop)', ()
|
|||||||
expect(html).toContain('>Click Me</a>');
|
expect(html).toContain('>Click Me</a>');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ButtonLink.toHtml hover state (scoped <style> block)', () => {
|
||||||
|
test('no hover props -- no <style> block, no class added', () => {
|
||||||
|
const { html } = toHtml({ href: '#', text: 'x' }, '', 'node-1');
|
||||||
|
expect(html).not.toContain('<style>');
|
||||||
|
expect(html).not.toContain('class=');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hoverBg/hoverColor emit a scoped :hover rule scoped to the node id', () => {
|
||||||
|
const { html } = toHtml({ href: '#', text: 'x', hoverBg: '#111111', hoverColor: '#eeeeee' }, '', 'node-42');
|
||||||
|
expect(html).toMatch(/<style>\.btn_[a-z0-9]+:hover\{background-color:#111111;color:#eeeeee\}<\/style>/);
|
||||||
|
expect(html).toMatch(/class="btn_[a-z0-9]+"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('two different node ids produce different scope classes (no collision)', () => {
|
||||||
|
const a = toHtml({ href: '#', text: 'x', hoverBg: '#111111' }, '', 'node-a').html;
|
||||||
|
const b = toHtml({ href: '#', text: 'x', hoverBg: '#111111' }, '', 'node-b').html;
|
||||||
|
const scopeOf = (html: string) => html.match(/btn_[a-z0-9]+/)?.[0];
|
||||||
|
expect(scopeOf(a)).toBeTruthy();
|
||||||
|
expect(scopeOf(a)).not.toBe(scopeOf(b));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an XSS breakout attempt in hoverBg cannot close the <style> element', () => {
|
||||||
|
const malicious = '</style><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ href: '#', text: 'x', hoverBg: malicious }, '', 'node-1');
|
||||||
|
expect(html).not.toContain('</style><script>');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a rule-breakout attempt in hoverColor cannot inject a second selector/rule', () => {
|
||||||
|
const malicious = 'red;}body{background:red';
|
||||||
|
const { html } = toHtml({ href: '#', text: 'x', hoverColor: malicious }, '', 'node-1');
|
||||||
|
expect(html).not.toContain('}body{');
|
||||||
|
expect(html).not.toContain(';}');
|
||||||
|
// The whole export is still exactly one <style> element -- no new rule
|
||||||
|
// or element was opened by the malicious value.
|
||||||
|
expect((html.match(/<style>/g) || []).length).toBe(1);
|
||||||
|
expect((html.match(/<\/style>/g) || []).length).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ButtonLink.craft.props exposes target + hover + box-model + animation/visibility', () => {
|
||||||
|
test('target defaults to _self, hoverBg/hoverColor blank', () => {
|
||||||
|
const props = (ButtonLink as any).craft.props;
|
||||||
|
expect(props.target).toBe('_self');
|
||||||
|
expect(props.hoverBg).toBe('');
|
||||||
|
expect(props.hoverColor).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (ButtonLink as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model keys', () => {
|
||||||
|
const style = (ButtonLink as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,13 +1,24 @@
|
|||||||
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, cssValue, scopeId } from '../../utils/escape';
|
||||||
|
|
||||||
interface ButtonLinkProps {
|
interface ButtonLinkProps {
|
||||||
text?: string;
|
text?: string;
|
||||||
href?: string;
|
href?: string;
|
||||||
target?: '_self' | '_blank';
|
target?: '_self' | '_blank';
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
/** Background color applied on `:hover` via a scoped `<style>` block
|
||||||
|
* (editor preview does not show hover state -- only the published
|
||||||
|
* export). Blank means "no hover background override". */
|
||||||
|
hoverBg?: string;
|
||||||
|
/** Text color applied on `:hover`, same scoped `<style>` block. */
|
||||||
|
hoverColor?: string;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ButtonLink: UserComponent<ButtonLinkProps> = ({
|
export const ButtonLink: UserComponent<ButtonLinkProps> = ({
|
||||||
@@ -15,6 +26,8 @@ export const ButtonLink: UserComponent<ButtonLinkProps> = ({
|
|||||||
href = '#',
|
href = '#',
|
||||||
target = '_self',
|
target = '_self',
|
||||||
style = {},
|
style = {},
|
||||||
|
hoverBg = '',
|
||||||
|
hoverColor = '',
|
||||||
}) => {
|
}) => {
|
||||||
const {
|
const {
|
||||||
connectors: { connect, drag },
|
connectors: { connect, drag },
|
||||||
@@ -23,6 +36,8 @@ export const ButtonLink: UserComponent<ButtonLinkProps> = ({
|
|||||||
selected: node.events.selected,
|
selected: node.events.selected,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const [hovered, setHovered] = React.useState(false);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<a
|
<a
|
||||||
ref={(ref: HTMLAnchorElement | null) => { if (ref) connect(drag(ref)); }}
|
ref={(ref: HTMLAnchorElement | null) => { if (ref) connect(drag(ref)); }}
|
||||||
@@ -32,12 +47,16 @@ export const ButtonLink: UserComponent<ButtonLinkProps> = ({
|
|||||||
// Prevent navigation inside editor
|
// Prevent navigation inside editor
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}}
|
}}
|
||||||
|
onMouseEnter={() => setHovered(true)}
|
||||||
|
onMouseLeave={() => setHovered(false)}
|
||||||
style={{
|
style={{
|
||||||
display: 'inline-block',
|
display: 'inline-block',
|
||||||
textDecoration: 'none',
|
textDecoration: 'none',
|
||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
outline: selected ? '2px solid #3b82f6' : 'none',
|
outline: selected ? '2px solid #3b82f6' : 'none',
|
||||||
...style,
|
...style,
|
||||||
|
...(hovered && hoverBg ? { backgroundColor: hoverBg } : {}),
|
||||||
|
...(hovered && hoverColor ? { color: hoverColor } : {}),
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{text}
|
{text}
|
||||||
@@ -53,6 +72,8 @@ ButtonLink.craft = {
|
|||||||
text: 'Click Me',
|
text: 'Click Me',
|
||||||
href: '#',
|
href: '#',
|
||||||
target: '_self',
|
target: '_self',
|
||||||
|
hoverBg: '',
|
||||||
|
hoverColor: '',
|
||||||
style: {
|
style: {
|
||||||
backgroundColor: '#3b82f6',
|
backgroundColor: '#3b82f6',
|
||||||
color: '#ffffff',
|
color: '#ffffff',
|
||||||
@@ -61,7 +82,15 @@ ButtonLink.craft = {
|
|||||||
fontWeight: '600',
|
fontWeight: '600',
|
||||||
fontSize: '16px',
|
fontSize: '16px',
|
||||||
border: 'none',
|
border: 'none',
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
},
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
@@ -72,7 +101,7 @@ ButtonLink.craft = {
|
|||||||
|
|
||||||
/* ---------- HTML export ---------- */
|
/* ---------- HTML export ---------- */
|
||||||
|
|
||||||
(ButtonLink as any).toHtml = (props: ButtonLinkProps, _childrenHtml: string) => {
|
(ButtonLink as any).toHtml = (props: ButtonLinkProps, _childrenHtml: string, nodeId?: string) => {
|
||||||
const styleStr = cssPropsToString({
|
const styleStr = cssPropsToString({
|
||||||
display: 'inline-block',
|
display: 'inline-block',
|
||||||
textDecoration: 'none',
|
textDecoration: 'none',
|
||||||
@@ -80,7 +109,28 @@ ButtonLink.craft = {
|
|||||||
});
|
});
|
||||||
const escapedText = escapeHtml(props.text || '');
|
const escapedText = escapeHtml(props.text || '');
|
||||||
const targetAttr = props.target === '_blank' ? ' target="_blank" rel="noopener noreferrer"' : '';
|
const targetAttr = props.target === '_blank' ? ' target="_blank" rel="noopener noreferrer"' : '';
|
||||||
|
|
||||||
|
// Scoped hover style -- same pattern as Navbar/Menu: a deterministic,
|
||||||
|
// per-node class (via scopeId) avoids two ButtonLink instances on the
|
||||||
|
// same page colliding on a shared `.btn-link:hover` rule. hoverBg/
|
||||||
|
// hoverColor are sanitized through cssValue -- they land inside a
|
||||||
|
// `<style>` element, the worst-case XSS sink (an unescaped `<`/`>` or
|
||||||
|
// `{`/`}` could close the rule/element and open a `<script>`).
|
||||||
|
const hoverBg = cssValue(props.hoverBg);
|
||||||
|
const hoverColor = cssValue(props.hoverColor);
|
||||||
|
let hoverCss = '';
|
||||||
|
let cls = '';
|
||||||
|
if (hoverBg || hoverColor) {
|
||||||
|
const scope = scopeId(nodeId, (props.href || '') + (props.text || ''), 'btn');
|
||||||
|
cls = ` class="${scope}"`;
|
||||||
|
const decls = [
|
||||||
|
hoverBg ? `background-color:${hoverBg}` : '',
|
||||||
|
hoverColor ? `color:${hoverColor}` : '',
|
||||||
|
].filter(Boolean).join(';');
|
||||||
|
hoverCss = `<style>.${scope}:hover{${decls}}</style>`;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
html: `<a href="${escapeAttr(safeUrl(props.href || '#'))}"${targetAttr}${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</a>`,
|
html: `${hoverCss}<a href="${escapeAttr(safeUrl(props.href || '#'))}"${targetAttr}${cls}${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</a>`,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -56,3 +56,54 @@ describe('Heading.toHtml text escaping (attacker-controlled `text` prop)', () =>
|
|||||||
expect(html).toBe('<h2>Hello world</h2>');
|
expect(html).toBe('<h2>Hello world</h2>');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Heading.toHtml typography depth (line-height/letter-spacing/transform/style/decoration)', () => {
|
||||||
|
test('line-height, letter-spacing, text-transform all flow into the style attribute', () => {
|
||||||
|
const { html } = toHtml({
|
||||||
|
text: 'x',
|
||||||
|
level: 'h2',
|
||||||
|
style: { lineHeight: '1.25', letterSpacing: '0.05em', textTransform: 'uppercase' },
|
||||||
|
}, '');
|
||||||
|
expect(html).toContain('line-height:1.25');
|
||||||
|
expect(html).toContain('letter-spacing:0.05em');
|
||||||
|
expect(html).toContain('text-transform:uppercase');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('italic + underline toggles emit font-style and text-decoration', () => {
|
||||||
|
const { html } = toHtml({
|
||||||
|
text: 'x',
|
||||||
|
level: 'h2',
|
||||||
|
style: { fontStyle: 'italic', textDecoration: 'underline' },
|
||||||
|
}, '');
|
||||||
|
expect(html).toContain('font-style:italic');
|
||||||
|
expect(html).toContain('text-decoration:underline');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a custom font-size (not one of the presets) still flows through', () => {
|
||||||
|
const { html } = toHtml({ text: 'x', level: 'h2', style: { fontSize: '42px' } }, '');
|
||||||
|
expect(html).toContain('font-size:42px');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Heading.craft.props exposes the box-model + animation/visibility rollout', () => {
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (Heading as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model + typography-depth keys', () => {
|
||||||
|
const style = (Heading as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style).toHaveProperty('lineHeight');
|
||||||
|
expect(style).toHaveProperty('letterSpacing');
|
||||||
|
expect(style).toHaveProperty('textTransform');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -100,7 +100,22 @@ Heading.craft = {
|
|||||||
fontFamily: 'Inter, sans-serif',
|
fontFamily: 'Inter, sans-serif',
|
||||||
color: '#1f2937',
|
color: '#1f2937',
|
||||||
marginBottom: '16px',
|
marginBottom: '16px',
|
||||||
|
lineHeight: '',
|
||||||
|
letterSpacing: '',
|
||||||
|
textTransform: '' as CSSProperties['textTransform'],
|
||||||
|
fontStyle: '' as CSSProperties['fontStyle'],
|
||||||
|
textDecoration: '',
|
||||||
|
marginTop: '', marginRight: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
},
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -30,3 +30,46 @@ describe('SearchBar.toHtml XSS hardening (placeholder/buttonText/showButton)', (
|
|||||||
expect(html).toMatch(/border-radius:(8px 0 0 8px|8px)/);
|
expect(html).toMatch(/border-radius:(8px 0 0 8px|8px)/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// F2: SearchBar was purely decorative -- no action/method/input name, so
|
||||||
|
// submitting did nothing. It now emits a real GET form.
|
||||||
|
describe('SearchBar.toHtml is a functional GET search form (not decorative)', () => {
|
||||||
|
test('defaults to a GET form action="/" with the query input named "q"', () => {
|
||||||
|
const { html } = toHtml({}, '');
|
||||||
|
expect(html).toMatch(/<form role="search" action="\/" method="GET"/);
|
||||||
|
expect(html).toContain('<input type="search" name="q"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a configured action (real search-results page) is used verbatim', () => {
|
||||||
|
const { html } = toHtml({ action: '/search' }, '');
|
||||||
|
expect(html).toContain('action="/search"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a javascript: action is blocked via safeUrl and falls back to "/"', () => {
|
||||||
|
const { html } = toHtml({ action: 'javascript:alert(1)' }, '');
|
||||||
|
expect(html).toContain('action="/"');
|
||||||
|
expect(html).not.toContain('javascript:');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an empty/whitespace action falls back to "/"', () => {
|
||||||
|
const { html } = toHtml({ action: ' ' }, '');
|
||||||
|
expect(html).toContain('action="/"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('SearchBar.toHtml box-model style passthrough', () => {
|
||||||
|
test('margin/border/box-shadow/opacity flow through via the style prop', () => {
|
||||||
|
const { html } = toHtml({ style: { marginBottom: '14px', border: '1px solid #aaa', boxShadow: '0 1px 4px rgba(0,0,0,.1)', opacity: '0.9' } }, '');
|
||||||
|
expect(html).toContain('margin-bottom:14px');
|
||||||
|
expect(html).toContain('border:1px solid #aaa');
|
||||||
|
expect(html).toContain('opacity:0.9');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('SearchBar.craft.props includes animation/visibility defaults', () => {
|
||||||
|
test('has blank/false defaults', () => {
|
||||||
|
expect(SearchBar.craft!.props).toMatchObject({
|
||||||
|
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,19 +1,29 @@
|
|||||||
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 } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
||||||
|
|
||||||
interface SearchBarProps {
|
interface SearchBarProps {
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
buttonText?: string;
|
buttonText?: string;
|
||||||
showButton?: boolean;
|
showButton?: boolean;
|
||||||
|
/** Where the search GET request is submitted -- a real search-results page
|
||||||
|
* if the site has one, or '/' (site root) by default. The query is sent
|
||||||
|
* as `?q=...`, the conventional param name search-results pages look for. */
|
||||||
|
action?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const SearchBar: UserComponent<SearchBarProps> = ({
|
export const SearchBar: UserComponent<SearchBarProps> = ({
|
||||||
placeholder = 'Search...',
|
placeholder = 'Search...',
|
||||||
buttonText = 'Search',
|
buttonText = 'Search',
|
||||||
showButton = true,
|
showButton = true,
|
||||||
|
action = '/',
|
||||||
style = {},
|
style = {},
|
||||||
}) => {
|
}) => {
|
||||||
const {
|
const {
|
||||||
@@ -27,6 +37,8 @@ export const SearchBar: UserComponent<SearchBarProps> = ({
|
|||||||
<form
|
<form
|
||||||
ref={(ref: HTMLFormElement | null): void => { if (ref) connect(drag(ref)); }}
|
ref={(ref: HTMLFormElement | null): void => { if (ref) connect(drag(ref)); }}
|
||||||
role="search"
|
role="search"
|
||||||
|
action={action}
|
||||||
|
method="GET"
|
||||||
onSubmit={(e) => e.preventDefault()}
|
onSubmit={(e) => e.preventDefault()}
|
||||||
style={{
|
style={{
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
@@ -51,6 +63,7 @@ export const SearchBar: UserComponent<SearchBarProps> = ({
|
|||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="search"
|
type="search"
|
||||||
|
name="q"
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
style={{
|
style={{
|
||||||
width: '100%',
|
width: '100%',
|
||||||
@@ -101,7 +114,13 @@ SearchBar.craft = {
|
|||||||
placeholder: 'Search...',
|
placeholder: 'Search...',
|
||||||
buttonText: 'Search',
|
buttonText: 'Search',
|
||||||
showButton: true,
|
showButton: true,
|
||||||
|
action: '/',
|
||||||
style: {},
|
style: {},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
@@ -117,6 +136,7 @@ SearchBar.craft = {
|
|||||||
placeholder = 'Search...',
|
placeholder = 'Search...',
|
||||||
buttonText = 'Search',
|
buttonText = 'Search',
|
||||||
showButton = true,
|
showButton = true,
|
||||||
|
action = '/',
|
||||||
style = {},
|
style = {},
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
@@ -133,11 +153,19 @@ SearchBar.craft = {
|
|||||||
? `<button type="submit" style="padding:12px 20px;font-size:15px;font-weight:600;font-family:Inter,sans-serif;color:#ffffff;background-color:#3b82f6;border:none;border-radius:0 8px 8px 0;cursor:pointer;white-space:nowrap;display:flex;align-items:center;gap:6px"><i class="fa fa-search" style="font-size:13px" aria-hidden="true"></i>${escapeHtml(buttonText)}</button>`
|
? `<button type="submit" style="padding:12px 20px;font-size:15px;font-weight:600;font-family:Inter,sans-serif;color:#ffffff;background-color:#3b82f6;border:none;border-radius:0 8px 8px 0;cursor:pointer;white-space:nowrap;display:flex;align-items:center;gap:6px"><i class="fa fa-search" style="font-size:13px" aria-hidden="true"></i>${escapeHtml(buttonText)}</button>`
|
||||||
: '';
|
: '';
|
||||||
|
|
||||||
|
// F2: previously a purely decorative <form> -- no action/method/input
|
||||||
|
// name at all, so submitting did nothing. A real GET to `action` with the
|
||||||
|
// query in the conventional `q` param makes this a functioning search
|
||||||
|
// form on publish (routes to a real search-results page if the site has
|
||||||
|
// one, or reloads '/' with ?q=... by default). `safeUrl` blocks
|
||||||
|
// javascript:/vbscript:/data:text/html breakout via the action attribute.
|
||||||
|
const actionAttr = escapeAttr(safeUrl(action) || '/');
|
||||||
|
|
||||||
return {
|
return {
|
||||||
html: `<form role="search"${formStyle ? ` style="${formStyle}"` : ''}>
|
html: `<form role="search" action="${actionAttr}" method="GET"${formStyle ? ` style="${formStyle}"` : ''}>
|
||||||
<div style="position:relative;flex:1">
|
<div style="position:relative;flex:1">
|
||||||
<i class="fa fa-search" style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:#9ca3af;font-size:14px;pointer-events:none" aria-hidden="true"></i>
|
<i class="fa fa-search" style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:#9ca3af;font-size:14px;pointer-events:none" aria-hidden="true"></i>
|
||||||
<input type="search" placeholder="${escapeAttr(placeholder)}" style="${inputStyleStr}" />
|
<input type="search" name="q" placeholder="${escapeAttr(placeholder)}" style="${inputStyleStr}" />
|
||||||
</div>
|
</div>
|
||||||
${btnHtml}
|
${btnHtml}
|
||||||
</form>`,
|
</form>`,
|
||||||
|
|||||||
@@ -20,3 +20,48 @@ describe('TextBlock.toHtml text escaping (attacker-controlled `text` prop)', ()
|
|||||||
expect(html).toBe('<p>Hello world</p>');
|
expect(html).toBe('<p>Hello world</p>');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('TextBlock.toHtml typography depth (line-height/letter-spacing/transform/style/decoration)', () => {
|
||||||
|
test('line-height, letter-spacing, text-transform all flow into the style attribute', () => {
|
||||||
|
const { html } = toHtml({
|
||||||
|
text: 'x',
|
||||||
|
style: { lineHeight: '1.75', letterSpacing: '-0.02em', textTransform: 'capitalize' },
|
||||||
|
}, '');
|
||||||
|
expect(html).toContain('line-height:1.75');
|
||||||
|
expect(html).toContain('letter-spacing:-0.02em');
|
||||||
|
expect(html).toContain('text-transform:capitalize');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('italic + underline toggles emit font-style and text-decoration', () => {
|
||||||
|
const { html } = toHtml({ text: 'x', style: { fontStyle: 'italic', textDecoration: 'underline' } }, '');
|
||||||
|
expect(html).toContain('font-style:italic');
|
||||||
|
expect(html).toContain('text-decoration:underline');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a custom font-size (not one of the presets) still flows through', () => {
|
||||||
|
const { html } = toHtml({ text: 'x', style: { fontSize: '19px' } }, '');
|
||||||
|
expect(html).toContain('font-size:19px');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TextBlock.craft.props exposes the box-model + animation/visibility rollout', () => {
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (TextBlock as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model + typography-depth keys', () => {
|
||||||
|
const style = (TextBlock as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style).toHaveProperty('letterSpacing');
|
||||||
|
expect(style).toHaveProperty('textTransform');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -83,7 +83,21 @@ TextBlock.craft = {
|
|||||||
fontSize: '16px',
|
fontSize: '16px',
|
||||||
lineHeight: '1.6',
|
lineHeight: '1.6',
|
||||||
color: '#3f3f46',
|
color: '#3f3f46',
|
||||||
|
letterSpacing: '',
|
||||||
|
textTransform: '' as CSSProperties['textTransform'],
|
||||||
|
fontStyle: '' as CSSProperties['fontStyle'],
|
||||||
|
textDecoration: '',
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
},
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -126,3 +126,73 @@ describe('ContactForm.toHtml field type attribute sanitization', () => {
|
|||||||
expect(html).toContain('type="email"');
|
expect(html).toContain('type="email"');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// F1: the field editor (FormStylePanel) can now create fields of every type
|
||||||
|
// in sanitizeInputType's allowlist, plus textarea/select. Verify each
|
||||||
|
// renders with the right control, label/for association, and required flag.
|
||||||
|
describe('ContactForm.toHtml renders every configured field type/label/required', () => {
|
||||||
|
const cases: { type: string; tag: string }[] = [
|
||||||
|
{ type: 'text', tag: 'input' },
|
||||||
|
{ type: 'email', tag: 'input' },
|
||||||
|
{ type: 'tel', tag: 'input' },
|
||||||
|
{ type: 'number', tag: 'input' },
|
||||||
|
{ type: 'password', tag: 'input' },
|
||||||
|
{ type: 'url', tag: 'input' },
|
||||||
|
{ type: 'search', tag: 'input' },
|
||||||
|
{ type: 'date', tag: 'input' },
|
||||||
|
{ type: 'checkbox', tag: 'input' },
|
||||||
|
{ type: 'radio', tag: 'input' },
|
||||||
|
];
|
||||||
|
|
||||||
|
test.each(cases)('type=$type renders a sanitized <$tag type="$type"> with label + for/id wiring', ({ type, tag }) => {
|
||||||
|
const fields = [{ type: type as any, label: `Field ${type}`, name: `f_${type}`, placeholder: '', required: true }];
|
||||||
|
const { html } = toHtml({ fields }, '');
|
||||||
|
expect(html).toContain(`<${tag}`);
|
||||||
|
expect(html).toContain(`type="${type}"`);
|
||||||
|
expect(html).toContain(`Field ${type}`);
|
||||||
|
// required renders the input attribute AND the visual asterisk
|
||||||
|
expect(html).toMatch(/ required/);
|
||||||
|
expect(html).toContain('*</span>');
|
||||||
|
const labelFor = html.match(/<label for="([^"]+)"/)![1];
|
||||||
|
expect(html).toContain(`id="${labelFor}"`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('type=textarea renders a <textarea>, not an <input>', () => {
|
||||||
|
const fields = [{ type: 'textarea' as const, label: 'Message', name: 'message', placeholder: '', required: false }];
|
||||||
|
const { html } = toHtml({ fields }, '');
|
||||||
|
expect(html).toMatch(/<textarea[^>]*name="message"/);
|
||||||
|
expect(html).not.toMatch(/<input[^>]*name="message"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('type=select renders a <select> with escaped <option> values from field.options', () => {
|
||||||
|
const fields = [{ type: 'select' as const, label: 'Plan', name: 'plan', placeholder: 'Choose one', required: false, options: ['Basic', 'Pro', '"><script>alert(1)</script>'] }];
|
||||||
|
const { html } = toHtml({ fields }, '');
|
||||||
|
expect(html).toMatch(/<select[^>]*name="plan"/);
|
||||||
|
expect(html).toContain('<option value="Basic">Basic</option>');
|
||||||
|
expect(html).toContain('<option value="Pro">Pro</option>');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-required field omits both the required attribute and the asterisk', () => {
|
||||||
|
const fields = [{ type: 'text' as const, label: 'Nickname', name: 'nickname', placeholder: '', required: false }];
|
||||||
|
const { html } = toHtml({ fields }, '');
|
||||||
|
expect(html).not.toMatch(/ required/);
|
||||||
|
expect(html).not.toContain('*</span>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Box-model / animation / visibility rollout (common enh-batch pattern):
|
||||||
|
// these are top-level props consumed generically by the export's
|
||||||
|
// buildDataAttrs() -- this just confirms the defaults are present on
|
||||||
|
// craft.props so the panel controls render and the props survive save/load.
|
||||||
|
describe('ContactForm.craft.props includes animation/visibility defaults', () => {
|
||||||
|
test('has blank/false defaults for animation, animationDelay, hideOnDesktop/Tablet/Mobile', () => {
|
||||||
|
expect(ContactForm.craft!.props).toMatchObject({
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -4,8 +4,17 @@ import { cssPropsToString } from '../../utils/style-helpers';
|
|||||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||||
import { escapeHtml, escapeAttr, slugId, cssValue, sanitizeInputType } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, slugId, cssValue, sanitizeInputType } from '../../utils/escape';
|
||||||
|
|
||||||
|
// The allowlist enforced at export time lives in `sanitizeInputType`
|
||||||
|
// (utils/escape.ts) -- this union is a superset (it also covers 'textarea'
|
||||||
|
// and 'select', which take their own render branches instead of an
|
||||||
|
// `<input type>`), kept in sync by hand since TS unions can't import a
|
||||||
|
// runtime array.
|
||||||
|
export type ContactFormFieldType =
|
||||||
|
| 'text' | 'email' | 'tel' | 'number' | 'password' | 'url' | 'search' | 'date'
|
||||||
|
| 'checkbox' | 'radio' | 'textarea' | 'select';
|
||||||
|
|
||||||
interface ContactFormField {
|
interface ContactFormField {
|
||||||
type: 'text' | 'email' | 'tel' | 'textarea' | 'select';
|
type: ContactFormFieldType;
|
||||||
label: string;
|
label: string;
|
||||||
name: string;
|
name: string;
|
||||||
placeholder: string;
|
placeholder: string;
|
||||||
@@ -25,6 +34,11 @@ interface ContactFormProps {
|
|||||||
inputBorder?: string;
|
inputBorder?: string;
|
||||||
recipientEmail?: string;
|
recipientEmail?: string;
|
||||||
thankYouUrl?: string;
|
thankYouUrl?: string;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultFields: ContactFormField[] = [
|
const defaultFields: ContactFormField[] = [
|
||||||
@@ -157,6 +171,11 @@ ContactForm.craft = {
|
|||||||
inputBorder: '#d1d5db',
|
inputBorder: '#d1d5db',
|
||||||
recipientEmail: '',
|
recipientEmail: '',
|
||||||
thankYouUrl: '',
|
thankYouUrl: '',
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -22,4 +22,19 @@ describe('FormButton.toHtml', () => {
|
|||||||
expect(html).toContain('&');
|
expect(html).toContain('&');
|
||||||
expect(html).toContain('"quoted"');
|
expect(html).toContain('"quoted"');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('box-model style (margin/border/box-shadow/opacity) flows through via the style prop', () => {
|
||||||
|
const { html } = toHtml({ text: 'Submit', style: { marginTop: '12px', border: '2px solid #000', boxShadow: '0 2px 4px rgba(0,0,0,.2)', opacity: '0.8' } }, '');
|
||||||
|
expect(html).toContain('margin-top:12px');
|
||||||
|
expect(html).toContain('border:2px solid #000');
|
||||||
|
expect(html).toContain('opacity:0.8');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('FormButton.craft.props includes animation/visibility defaults', () => {
|
||||||
|
test('has blank/false defaults', () => {
|
||||||
|
expect(FormButton.craft!.props).toMatchObject({
|
||||||
|
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,6 +6,11 @@ import { escapeHtml } from '../../utils/escape';
|
|||||||
interface FormButtonProps {
|
interface FormButtonProps {
|
||||||
text?: string;
|
text?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FormButton: UserComponent<FormButtonProps> = ({
|
export const FormButton: UserComponent<FormButtonProps> = ({
|
||||||
@@ -58,6 +63,11 @@ FormButton.craft = {
|
|||||||
fontSize: '16px',
|
fontSize: '16px',
|
||||||
border: 'none',
|
border: 'none',
|
||||||
},
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -52,3 +52,20 @@ describe('FormContainer.toHtml method attribute sanitization', () => {
|
|||||||
expect(html).toContain('method="GET"');
|
expect(html).toContain('method="GET"');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('FormContainer.toHtml box-model style passthrough', () => {
|
||||||
|
test('margin/border/box-shadow/opacity flow through via the style prop', () => {
|
||||||
|
const { html } = toHtml({ action: '/legacy', style: { marginTop: '20px', border: '3px dashed #ccc', boxShadow: '0 4px 8px rgba(0,0,0,.2)', opacity: '0.95' } }, '');
|
||||||
|
expect(html).toContain('margin-top:20px');
|
||||||
|
expect(html).toContain('border:3px dashed #ccc');
|
||||||
|
expect(html).toContain('opacity:0.95');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('FormContainer.craft.props includes animation/visibility defaults', () => {
|
||||||
|
test('has blank/false defaults', () => {
|
||||||
|
expect(FormContainer.craft!.props).toMatchObject({
|
||||||
|
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -12,6 +12,11 @@ interface FormContainerProps {
|
|||||||
thankYouUrl?: string;
|
thankYouUrl?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FormContainer: UserComponent<FormContainerProps> = ({
|
export const FormContainer: UserComponent<FormContainerProps> = ({
|
||||||
@@ -59,6 +64,11 @@ FormContainer.craft = {
|
|||||||
borderRadius: '8px',
|
borderRadius: '8px',
|
||||||
border: '1px solid #e4e4e7',
|
border: '1px solid #e4e4e7',
|
||||||
},
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -72,3 +72,20 @@ describe('InputField.toHtml type attribute sanitization', () => {
|
|||||||
expect(html).toContain('type="number"');
|
expect(html).toContain('type="number"');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('InputField.toHtml box-model style passthrough', () => {
|
||||||
|
test('margin/border/box-shadow/opacity flow through via the style prop', () => {
|
||||||
|
const { html } = toHtml({ label: 'Name', name: 'name', style: { marginBottom: '8px', border: '1px solid #333', boxShadow: '0 1px 2px rgba(0,0,0,.1)', opacity: '0.9' } }, '');
|
||||||
|
expect(html).toContain('margin-bottom:8px');
|
||||||
|
expect(html).toContain('border:1px solid #333');
|
||||||
|
expect(html).toContain('opacity:0.9');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('InputField.craft.props includes animation/visibility defaults', () => {
|
||||||
|
test('has blank/false defaults', () => {
|
||||||
|
expect(InputField.craft!.props).toMatchObject({
|
||||||
|
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ interface InputFieldProps {
|
|||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const InputField: UserComponent<InputFieldProps> = ({
|
export const InputField: UserComponent<InputFieldProps> = ({
|
||||||
@@ -77,6 +82,11 @@ InputField.craft = {
|
|||||||
placeholder: 'Enter your name',
|
placeholder: 'Enter your name',
|
||||||
required: false,
|
required: false,
|
||||||
style: {},
|
style: {},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ const toHtml = (SubscribeForm as any).toHtml;
|
|||||||
describe('SubscribeForm.toHtml hardcoded attributes stay hardcoded (no raw prop breakout)', () => {
|
describe('SubscribeForm.toHtml hardcoded attributes stay hardcoded (no raw prop breakout)', () => {
|
||||||
test('form method is always POST regardless of any injected props', () => {
|
test('form method is always POST regardless of any injected props', () => {
|
||||||
const { html } = toHtml({ heading: 'Join us', method: 'GET"><script>alert(1)</script>' } as any, '');
|
const { html } = toHtml({ heading: 'Join us', method: 'GET"><script>alert(1)</script>' } as any, '');
|
||||||
expect(html).toContain('<form method="POST"');
|
expect(html).toMatch(/<form action="[^"]*" method="POST"/);
|
||||||
expect(html).not.toContain('<script');
|
expect(html).not.toContain('<script');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -37,3 +37,45 @@ describe('SubscribeForm.toHtml hardcoded attributes stay hardcoded (no raw prop
|
|||||||
expect(html).toContain('>Go<');
|
expect(html).toContain('>Go<');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// F1: SubscribeForm previously emitted `<form method="POST">` with no action
|
||||||
|
// at all -- a published subscribe form silently did nothing on submit.
|
||||||
|
// Wired through the same relay contract as ContactForm/FormContainer
|
||||||
|
// (utils/form-relay-wiring.ts) so setting a recipient makes it functional.
|
||||||
|
describe('SubscribeForm.toHtml is functional (not a dead POST)', () => {
|
||||||
|
test('without a recipient: still has a real (non-empty) action -- "#" fallback, not a bare method="POST"', () => {
|
||||||
|
const { html } = toHtml({}, '');
|
||||||
|
expect(html).toMatch(/<form action="#" method="POST"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('with recipientEmail: emits the relay marker, placeholder action, and honeypot -- a working submission path', () => {
|
||||||
|
const { html } = toHtml({ recipientEmail: 'news@example.com', thankYouUrl: '/thanks' }, '', 'node-sub1');
|
||||||
|
expect(html).toMatch(/<!--WHP-FORM id="F_[0-9a-z]+" recipient="news@example.com" thankyou="\/thanks"-->/);
|
||||||
|
expect(html).toMatch(/action="__WHP_FORM_ACTION__F_[0-9a-z]+__"/);
|
||||||
|
expect(html).toContain('name="_gotcha"');
|
||||||
|
const mid = html.match(/id="(F_[0-9a-z]+)"/)![1];
|
||||||
|
expect(html).toContain(`__WHP_FORM_ACTION__${mid}__`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the email input keeps its name="email" so the relay receives it', () => {
|
||||||
|
const { html } = toHtml({ recipientEmail: 'news@example.com' }, '', 'node-sub2');
|
||||||
|
expect(html).toContain('name="email"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('SubscribeForm.toHtml box-model style passthrough', () => {
|
||||||
|
test('margin/border/box-shadow/opacity flow through via the style prop', () => {
|
||||||
|
const { html } = toHtml({ style: { marginTop: '16px', border: '1px solid #ddd', boxShadow: '0 2px 6px rgba(0,0,0,.15)', opacity: '0.85' } }, '');
|
||||||
|
expect(html).toContain('margin-top:16px');
|
||||||
|
expect(html).toContain('border:1px solid #ddd');
|
||||||
|
expect(html).toContain('opacity:0.85');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('SubscribeForm.craft.props includes animation/visibility defaults', () => {
|
||||||
|
test('has blank/false defaults', () => {
|
||||||
|
expect(SubscribeForm.craft!.props).toMatchObject({
|
||||||
|
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,6 +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 { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||||
import { escapeHtml, escapeAttr } from '../../utils/escape';
|
import { escapeHtml, escapeAttr } from '../../utils/escape';
|
||||||
|
|
||||||
interface SubscribeFormProps {
|
interface SubscribeFormProps {
|
||||||
@@ -10,6 +11,17 @@ interface SubscribeFormProps {
|
|||||||
buttonColor?: string;
|
buttonColor?: string;
|
||||||
layout?: 'inline' | 'stacked';
|
layout?: 'inline' | 'stacked';
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
/** "Send submissions to" address -- same relay contract as ContactForm/
|
||||||
|
* FormContainer (see utils/form-relay-wiring.ts). Blank = no relay; the
|
||||||
|
* published form then has no working action at all, which is the bug
|
||||||
|
* this prop exists to fix. */
|
||||||
|
recipientEmail?: string;
|
||||||
|
thankYouUrl?: string;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const SubscribeForm: UserComponent<SubscribeFormProps> = ({
|
export const SubscribeForm: UserComponent<SubscribeFormProps> = ({
|
||||||
@@ -110,6 +122,13 @@ SubscribeForm.craft = {
|
|||||||
buttonColor: '#3b82f6',
|
buttonColor: '#3b82f6',
|
||||||
layout: 'inline',
|
layout: 'inline',
|
||||||
style: { backgroundColor: '#f8fafc' },
|
style: { backgroundColor: '#f8fafc' },
|
||||||
|
recipientEmail: '',
|
||||||
|
thankYouUrl: '',
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
@@ -120,7 +139,7 @@ SubscribeForm.craft = {
|
|||||||
|
|
||||||
/* ---------- HTML export ---------- */
|
/* ---------- HTML export ---------- */
|
||||||
|
|
||||||
(SubscribeForm as any).toHtml = (props: SubscribeFormProps, _childrenHtml: string) => {
|
(SubscribeForm as any).toHtml = (props: SubscribeFormProps, _childrenHtml: string, nodeId?: string) => {
|
||||||
const {
|
const {
|
||||||
heading = 'Subscribe to our newsletter',
|
heading = 'Subscribe to our newsletter',
|
||||||
placeholder = 'Enter your email',
|
placeholder = 'Enter your email',
|
||||||
@@ -166,11 +185,21 @@ SubscribeForm.craft = {
|
|||||||
whiteSpace: 'nowrap',
|
whiteSpace: 'nowrap',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Same relay contract as ContactForm/FormContainer: a recipientEmail wires
|
||||||
|
// the form through the WHP form-sender relay (marker + placeholder action
|
||||||
|
// + honeypot, provisioned/rewritten at publish time). Previously this form
|
||||||
|
// always emitted `<form method="POST">` with NO action at all -- a
|
||||||
|
// published subscribe form silently did nothing on submit. Falling back to
|
||||||
|
// `formAction`-less relay wiring (fallbackAction undefined -> '#') keeps
|
||||||
|
// the old no-recipient case visually identical (action="#") while making
|
||||||
|
// the relay path actually functional once an admin sets an email.
|
||||||
|
const { marker, actionAttr, honeypot } = relayFormWiring(props.recipientEmail, props.thankYouUrl, undefined, nodeId);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>
|
html: `${marker}<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>
|
||||||
${headingHtml}
|
${headingHtml}
|
||||||
<form method="POST"${formStyle ? ` style="${formStyle}"` : ''}>
|
<form action="${actionAttr}" method="POST"${formStyle ? ` style="${formStyle}"` : ''}>
|
||||||
<input type="email" name="email" placeholder="${escapeAttr(placeholder)}" required style="${inputStyleStr}" />
|
${honeypot ? ` ${honeypot}\n` : ''} <input type="email" name="email" placeholder="${escapeAttr(placeholder)}" required style="${inputStyleStr}" />
|
||||||
<button type="submit"${btnStyle ? ` style="${btnStyle}"` : ''}>${escapeHtml(buttonText)}</button>
|
<button type="submit"${btnStyle ? ` style="${btnStyle}"` : ''}>${escapeHtml(buttonText)}</button>
|
||||||
</form>
|
</form>
|
||||||
</div>`,
|
</div>`,
|
||||||
|
|||||||
@@ -63,3 +63,20 @@ describe('TextareaField.toHtml rows attribute sanitization', () => {
|
|||||||
expect(html).toContain('rows="8"');
|
expect(html).toContain('rows="8"');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('TextareaField.toHtml box-model style passthrough', () => {
|
||||||
|
test('margin/border/box-shadow/opacity flow through via the style prop', () => {
|
||||||
|
const { html } = toHtml({ label: 'Message', name: 'message', style: { marginTop: '10px', border: '1px solid #555', boxShadow: '0 1px 3px rgba(0,0,0,.15)', opacity: '0.7' } }, '');
|
||||||
|
expect(html).toContain('margin-top:10px');
|
||||||
|
expect(html).toContain('border:1px solid #555');
|
||||||
|
expect(html).toContain('opacity:0.7');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TextareaField.craft.props includes animation/visibility defaults', () => {
|
||||||
|
test('has blank/false defaults', () => {
|
||||||
|
expect(TextareaField.craft!.props).toMatchObject({
|
||||||
|
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ interface TextareaFieldProps {
|
|||||||
rows?: number;
|
rows?: number;
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const TextareaField: UserComponent<TextareaFieldProps> = ({
|
export const TextareaField: UserComponent<TextareaFieldProps> = ({
|
||||||
@@ -79,6 +84,11 @@ TextareaField.craft = {
|
|||||||
rows: 4,
|
rows: 4,
|
||||||
required: false,
|
required: false,
|
||||||
style: {},
|
style: {},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, test, expect } from 'vitest';
|
import { describe, test, expect } from 'vitest';
|
||||||
import { ImageBlock } from './ImageBlock';
|
import { ImageBlock, pxAttr } from './ImageBlock';
|
||||||
|
|
||||||
const toHtml = (ImageBlock as any).toHtml;
|
const toHtml = (ImageBlock as any).toHtml;
|
||||||
|
|
||||||
@@ -32,3 +32,95 @@ describe('ImageBlock.toHtml src/alt XSS hardening', () => {
|
|||||||
expect(html).toContain('alt="A photo"');
|
expect(html).toContain('alt="A photo"');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock.toHtml perf attributes (always emitted)', () => {
|
||||||
|
test('loading="lazy" and decoding="async" are always present', () => {
|
||||||
|
const { html } = toHtml({ src: 'https://example.com/photo.jpg' }, '');
|
||||||
|
expect(html).toContain('loading="lazy"');
|
||||||
|
expect(html).toContain('decoding="async"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('width/height attributes are emitted when the style has plain px values', () => {
|
||||||
|
const { html } = toHtml({ src: 'https://example.com/photo.jpg', style: { width: '400px', height: '300px' } }, '');
|
||||||
|
expect(html).toContain('width="400"');
|
||||||
|
expect(html).toContain('height="300"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('width/height attributes are omitted when the style value is not a plain px length', () => {
|
||||||
|
const { html } = toHtml({ src: 'https://example.com/photo.jpg', style: { width: '50%', height: 'auto' } }, '');
|
||||||
|
expect(html).not.toMatch(/\swidth="/);
|
||||||
|
expect(html).not.toMatch(/\sheight="/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('pxAttr', () => {
|
||||||
|
test('extracts the numeric portion of a plain px length', () => {
|
||||||
|
expect(pxAttr('400px')).toBe('400');
|
||||||
|
expect(pxAttr('12.5px')).toBe('12.5');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns undefined for non-px units, non-string, or unset values', () => {
|
||||||
|
expect(pxAttr('50%')).toBeUndefined();
|
||||||
|
expect(pxAttr('auto')).toBeUndefined();
|
||||||
|
expect(pxAttr(undefined)).toBeUndefined();
|
||||||
|
expect(pxAttr(400)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock.toHtml CSS framing crop (aspect-ratio + object-fit + object-position)', () => {
|
||||||
|
test('style.aspectRatio, objectFit, objectPosition all flow into the emitted style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{ src: 'https://example.com/photo.jpg', style: { aspectRatio: '16 / 9', objectFit: 'cover', objectPosition: 'center top' } },
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('aspect-ratio:16 / 9');
|
||||||
|
expect(html).toContain('object-fit:cover');
|
||||||
|
expect(html).toContain('object-position:center top');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||||
|
test('margin/padding/border/box-shadow/opacity all flow into the emitted style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{
|
||||||
|
src: 'https://example.com/photo.jpg',
|
||||||
|
style: {
|
||||||
|
marginTop: '10px', marginRight: '10px', marginBottom: '10px', marginLeft: '10px',
|
||||||
|
paddingTop: '5px',
|
||||||
|
border: '2px solid #ff0000',
|
||||||
|
boxShadow: '0 4px 8px rgba(0,0,0,0.12)',
|
||||||
|
opacity: '0.8',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('margin-top:10px');
|
||||||
|
expect(html).toContain('padding-top:5px');
|
||||||
|
expect(html).toContain('border:2px solid #ff0000');
|
||||||
|
expect(html).toContain('box-shadow:0 4px 8px rgba(0,0,0,0.12)');
|
||||||
|
expect(html).toContain('opacity:0.8');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock.craft.props exposes the box-model/animation/visibility rollout', () => {
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (ImageBlock as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model and crop keys', () => {
|
||||||
|
const style = (ImageBlock as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('aspectRatio');
|
||||||
|
expect(style).toHaveProperty('objectFit');
|
||||||
|
expect(style).toHaveProperty('objectPosition');
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -9,6 +9,23 @@ interface ImageBlockProps {
|
|||||||
src?: string;
|
src?: string;
|
||||||
alt?: string;
|
alt?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Extracts the numeric portion of a plain "<n>px" CSS length string, for
|
||||||
|
* emitting real `width`/`height` HTML attributes on the exported `<img>`
|
||||||
|
* (helps the browser reserve layout space before the image loads --
|
||||||
|
* avoiding CLS -- something a CSS-only width/height can't do on its own).
|
||||||
|
* Returns undefined for any other unit ('%', 'auto', '', etc.) so the
|
||||||
|
* attribute is simply omitted when the pixel size isn't known. */
|
||||||
|
export function pxAttr(v: unknown): string | undefined {
|
||||||
|
if (typeof v !== 'string') return undefined;
|
||||||
|
const m = v.trim().match(/^(\d+(?:\.\d+)?)px$/);
|
||||||
|
return m ? m[1] : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper: upload a file to the WHP API and return the proxy URL
|
// Helper: upload a file to the WHP API and return the proxy URL
|
||||||
@@ -83,7 +100,27 @@ export const ImageBlock: UserComponent<ImageBlockProps> = ({
|
|||||||
|
|
||||||
ImageBlock.craft = {
|
ImageBlock.craft = {
|
||||||
displayName: 'Image',
|
displayName: 'Image',
|
||||||
props: { src: PLACEHOLDER_SRC, alt: '', style: { width: '100%', height: 'auto' } },
|
props: {
|
||||||
|
src: PLACEHOLDER_SRC,
|
||||||
|
alt: '',
|
||||||
|
style: {
|
||||||
|
width: '100%',
|
||||||
|
height: 'auto',
|
||||||
|
aspectRatio: '',
|
||||||
|
objectFit: '' as CSSProperties['objectFit'],
|
||||||
|
objectPosition: '',
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
|
},
|
||||||
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
|
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -95,5 +132,8 @@ 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(safeImageUrl(src))}"${alt}${s ? ` style="${s}"` : ''} />` };
|
const widthAttr = pxAttr((props.style as any)?.width);
|
||||||
|
const heightAttr = pxAttr((props.style as any)?.height);
|
||||||
|
const dims = `${widthAttr ? ` width="${widthAttr}"` : ''}${heightAttr ? ` height="${heightAttr}"` : ''}`;
|
||||||
|
return { html: `<img src="${escapeAttr(safeImageUrl(src))}"${alt}${dims} loading="lazy" decoding="async"${s ? ` style="${s}"` : ''} />` };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -28,6 +28,49 @@ describe('MapEmbed.toHtml iframe src ampersand encoding (F-export review Minor)'
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('MapEmbed.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||||
|
test('margin/padding/border/box-shadow/opacity all flow into the wrapper style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{
|
||||||
|
address: 'New York, NY',
|
||||||
|
style: {
|
||||||
|
marginTop: '16px',
|
||||||
|
paddingRight: '4px',
|
||||||
|
border: '1px solid #cccccc',
|
||||||
|
boxShadow: '0 4px 8px rgba(0,0,0,0.12)',
|
||||||
|
opacity: '0.95',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('margin-top:16px');
|
||||||
|
expect(html).toContain('padding-right:4px');
|
||||||
|
expect(html).toContain('border:1px solid #cccccc');
|
||||||
|
expect(html).toContain('box-shadow:0 4px 8px rgba(0,0,0,0.12)');
|
||||||
|
expect(html).toContain('opacity:0.95');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MapEmbed.craft.props exposes the animation/visibility rollout', () => {
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (MapEmbed as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model keys', () => {
|
||||||
|
const style = (MapEmbed as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('MapEmbed.toHtml address/zoom/height XSS hardening', () => {
|
describe('MapEmbed.toHtml address/zoom/height XSS hardening', () => {
|
||||||
test('a malicious address cannot break out of the src or title attribute', () => {
|
test('a malicious address cannot break out of the src or title attribute', () => {
|
||||||
const malicious = 'X" onerror="alert(1)';
|
const malicious = 'X" onerror="alert(1)';
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ interface MapEmbedProps {
|
|||||||
zoom?: number;
|
zoom?: number;
|
||||||
height?: string;
|
height?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildMapUrl(address: string, zoom: number): string {
|
function buildMapUrl(address: string, zoom: number): string {
|
||||||
@@ -70,7 +75,18 @@ MapEmbed.craft = {
|
|||||||
address: 'New York, NY',
|
address: 'New York, NY',
|
||||||
zoom: 14,
|
zoom: 14,
|
||||||
height: '400px',
|
height: '400px',
|
||||||
style: {},
|
style: {
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -118,3 +118,75 @@ describe('VideoBlock.toHtml iframe src ampersand encoding (F-export review Minor
|
|||||||
expect(srcMatch![1]).not.toMatch(/&(?!amp;)/);
|
expect(srcMatch![1]).not.toMatch(/&(?!amp;)/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('VideoBlock.toHtml size + aspect ratio (frame honors style props, not a hardcoded 16:9)', () => {
|
||||||
|
test('direct file: style.width flows to the wrapper, style.aspectRatio flows to the <video>', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', style: { width: '50%', aspectRatio: '4 / 3' } }, '');
|
||||||
|
expect(html).toMatch(/<div style="[^"]*width:50%[^"]*"/);
|
||||||
|
expect(html).toMatch(/<video[^>]*style="[^"]*aspect-ratio:4 \/ 3[^"]*"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('direct file: no aspectRatio set -- no aspect-ratio declaration is forced onto the <video>', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4' }, '');
|
||||||
|
const videoTag = html.match(/<video[^>]*>/)![0];
|
||||||
|
expect(videoTag).not.toContain('aspect-ratio');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('YouTube/Vimeo: style.aspectRatio overrides the 16:9 default on the iframe container', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', style: { aspectRatio: '1 / 1' } }, '');
|
||||||
|
expect(html).toMatch(/<div[^>]*style="[^"]*aspect-ratio:1 \/ 1[^"]*"[^>]*><iframe/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('YouTube/Vimeo: defaults to 16 / 9 when no aspectRatio style is set', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789' }, '');
|
||||||
|
expect(html).toMatch(/<div[^>]*style="[^"]*aspect-ratio:16 \/ 9[^"]*"[^>]*><iframe/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('VideoBlock.toHtml poster + preload (file type)', () => {
|
||||||
|
test('poster attribute is emitted (escaped) and preload="metadata" is always present on a direct file', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', poster: 'https://example.com/poster.jpg' }, '');
|
||||||
|
expect(html).toContain('poster="https://example.com/poster.jpg"');
|
||||||
|
expect(html).toContain('preload="metadata"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no poster prop -- no poster attribute is emitted, but preload="metadata" still is', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4' }, '');
|
||||||
|
expect(html).not.toContain('poster=');
|
||||||
|
expect(html).toContain('preload="metadata"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious poster (javascript: scheme) is blocked by safeImageUrl', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', poster: 'javascript:alert(1)' }, '');
|
||||||
|
expect(html).not.toContain('javascript:');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a poster value cannot break out of the poster attribute', () => {
|
||||||
|
const malicious = 'https://example.com/x.jpg" onerror="alert(1)';
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', poster: malicious }, '');
|
||||||
|
expect(html).not.toContain('onerror="alert(1)"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('VideoBlock.craft.props exposes the box-model/animation/visibility rollout', () => {
|
||||||
|
test('poster, animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (VideoBlock as any).craft.props;
|
||||||
|
expect(props.poster).toBe('');
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model + size/aspect keys', () => {
|
||||||
|
const style = (VideoBlock as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('width');
|
||||||
|
expect(style).toHaveProperty('aspectRatio');
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
|||||||
import { useNode, Element, UserComponent } from '@craftjs/core';
|
import { useNode, Element, UserComponent } from '@craftjs/core';
|
||||||
import { Container } from '../layout/Container';
|
import { Container } from '../layout/Container';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeAttr, safeUrl } from '../../utils/escape';
|
import { escapeAttr, safeUrl, safeImageUrl } from '../../utils/escape';
|
||||||
|
|
||||||
/* ---------- Types ---------- */
|
/* ---------- Types ---------- */
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@ interface VideoBlockProps {
|
|||||||
videoUrl?: string;
|
videoUrl?: string;
|
||||||
videoType?: VideoType;
|
videoType?: VideoType;
|
||||||
embedUrl?: string;
|
embedUrl?: string;
|
||||||
|
poster?: string;
|
||||||
autoplay?: boolean;
|
autoplay?: boolean;
|
||||||
muted?: boolean;
|
muted?: boolean;
|
||||||
loop?: boolean;
|
loop?: boolean;
|
||||||
@@ -22,6 +23,11 @@ interface VideoBlockProps {
|
|||||||
innerMaxWidth?: string;
|
innerMaxWidth?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- URL detection ---------- */
|
/* ---------- URL detection ---------- */
|
||||||
@@ -120,6 +126,7 @@ export const VideoBlock: UserComponent<VideoBlockProps> = ({
|
|||||||
videoUrl = '',
|
videoUrl = '',
|
||||||
videoType: _videoTypeProp,
|
videoType: _videoTypeProp,
|
||||||
embedUrl: _embedUrlProp,
|
embedUrl: _embedUrlProp,
|
||||||
|
poster = '',
|
||||||
autoplay = false,
|
autoplay = false,
|
||||||
muted = true,
|
muted = true,
|
||||||
loop = false,
|
loop = false,
|
||||||
@@ -259,8 +266,7 @@ export const VideoBlock: UserComponent<VideoBlockProps> = ({
|
|||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
paddingBottom: '56.25%',
|
aspectRatio: (style as any)?.aspectRatio || '16 / 9',
|
||||||
height: 0,
|
|
||||||
overflow: 'hidden',
|
overflow: 'hidden',
|
||||||
borderRadius: (style as any)?.borderRadius || undefined,
|
borderRadius: (style as any)?.borderRadius || undefined,
|
||||||
}}
|
}}
|
||||||
@@ -269,8 +275,7 @@ export const VideoBlock: UserComponent<VideoBlockProps> = ({
|
|||||||
src={buildEmbedParams(embedUrl, { autoplay, muted, loop, controls })}
|
src={buildEmbedParams(embedUrl, { autoplay, muted, loop, controls })}
|
||||||
style={{
|
style={{
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
top: 0,
|
inset: 0,
|
||||||
left: 0,
|
|
||||||
width: '100%',
|
width: '100%',
|
||||||
height: '100%',
|
height: '100%',
|
||||||
border: 'none',
|
border: 'none',
|
||||||
@@ -284,14 +289,18 @@ export const VideoBlock: UserComponent<VideoBlockProps> = ({
|
|||||||
{type === 'file' && (
|
{type === 'file' && (
|
||||||
<video
|
<video
|
||||||
src={embedUrl}
|
src={embedUrl}
|
||||||
|
poster={poster || undefined}
|
||||||
autoPlay={autoplay}
|
autoPlay={autoplay}
|
||||||
muted={muted}
|
muted={muted}
|
||||||
loop={loop}
|
loop={loop}
|
||||||
controls={controls}
|
controls={controls}
|
||||||
|
preload="metadata"
|
||||||
playsInline
|
playsInline
|
||||||
style={{
|
style={{
|
||||||
display: 'block',
|
display: 'block',
|
||||||
width: '100%',
|
width: '100%',
|
||||||
|
aspectRatio: (style as any)?.aspectRatio || undefined,
|
||||||
|
objectFit: 'cover',
|
||||||
borderRadius: (style as any)?.borderRadius || undefined,
|
borderRadius: (style as any)?.borderRadius || undefined,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -310,6 +319,7 @@ VideoBlock.craft = {
|
|||||||
videoUrl: '',
|
videoUrl: '',
|
||||||
videoType: 'none',
|
videoType: 'none',
|
||||||
embedUrl: '',
|
embedUrl: '',
|
||||||
|
poster: '',
|
||||||
autoplay: false,
|
autoplay: false,
|
||||||
muted: true,
|
muted: true,
|
||||||
loop: false,
|
loop: false,
|
||||||
@@ -318,7 +328,20 @@ VideoBlock.craft = {
|
|||||||
overlayColor: '#000000',
|
overlayColor: '#000000',
|
||||||
overlayOpacity: 50,
|
overlayOpacity: 50,
|
||||||
innerMaxWidth: '1200px',
|
innerMaxWidth: '1200px',
|
||||||
style: {},
|
style: {
|
||||||
|
width: '',
|
||||||
|
aspectRatio: '',
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
@@ -334,6 +357,7 @@ VideoBlock.craft = {
|
|||||||
(VideoBlock as any).toHtml = (props: VideoBlockProps, childrenHtml: string) => {
|
(VideoBlock as any).toHtml = (props: VideoBlockProps, childrenHtml: string) => {
|
||||||
const {
|
const {
|
||||||
videoUrl = '',
|
videoUrl = '',
|
||||||
|
poster = '',
|
||||||
autoplay = false,
|
autoplay = false,
|
||||||
muted = true,
|
muted = true,
|
||||||
loop: doLoop = false,
|
loop: doLoop = false,
|
||||||
@@ -422,15 +446,13 @@ VideoBlock.craft = {
|
|||||||
const iframeSrc = buildEmbedParams(embedUrl, { autoplay, muted, loop: doLoop, controls });
|
const iframeSrc = buildEmbedParams(embedUrl, { autoplay, muted, loop: doLoop, controls });
|
||||||
const containerStyle = cssPropsToString({
|
const containerStyle = cssPropsToString({
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
paddingBottom: '56.25%',
|
aspectRatio: (style as any)?.aspectRatio || '16 / 9',
|
||||||
height: '0',
|
|
||||||
overflow: 'hidden',
|
overflow: 'hidden',
|
||||||
borderRadius: (style as any)?.borderRadius || undefined,
|
borderRadius: (style as any)?.borderRadius || undefined,
|
||||||
});
|
});
|
||||||
const iframeStyle = cssPropsToString({
|
const iframeStyle = cssPropsToString({
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
top: '0',
|
inset: '0',
|
||||||
left: '0',
|
|
||||||
width: '100%',
|
width: '100%',
|
||||||
height: '100%',
|
height: '100%',
|
||||||
border: 'none',
|
border: 'none',
|
||||||
@@ -447,13 +469,16 @@ VideoBlock.craft = {
|
|||||||
if (doLoop) vidAttrs.push('loop');
|
if (doLoop) vidAttrs.push('loop');
|
||||||
if (controls) vidAttrs.push('controls');
|
if (controls) vidAttrs.push('controls');
|
||||||
vidAttrs.push('playsinline');
|
vidAttrs.push('playsinline');
|
||||||
|
const posterAttr = poster ? ` poster="${escapeAttr(safeImageUrl(poster))}"` : '';
|
||||||
const vidStyle = cssPropsToString({
|
const vidStyle = cssPropsToString({
|
||||||
display: 'block',
|
display: 'block',
|
||||||
width: '100%',
|
width: '100%',
|
||||||
|
aspectRatio: (style as any)?.aspectRatio || undefined,
|
||||||
|
objectFit: 'cover',
|
||||||
borderRadius: (style as any)?.borderRadius || undefined,
|
borderRadius: (style as any)?.borderRadius || undefined,
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}><video src="${escapeAttr(safeUrl(embedUrl))}" ${vidAttrs.join(' ')}${vidStyle ? ` style="${vidStyle}"` : ''}></video></div>`,
|
html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}><video src="${escapeAttr(safeUrl(embedUrl))}"${posterAttr} preload="metadata" ${vidAttrs.join(' ')}${vidStyle ? ` style="${vidStyle}"` : ''}></video></div>`,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -139,3 +139,46 @@ describe('ContentSlider.toHtml interval is NOT runtime-type-checked -- must be c
|
|||||||
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},3000\);/);
|
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},3000\);/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ContentSlider.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||||
|
test('margin/padding/border/box-shadow/opacity all flow into the section style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{
|
||||||
|
slides,
|
||||||
|
style: {
|
||||||
|
marginBottom: '24px',
|
||||||
|
paddingTop: '8px',
|
||||||
|
border: '3px dashed #00ff00',
|
||||||
|
boxShadow: '0 10px 24px rgba(0,0,0,0.18)',
|
||||||
|
opacity: '0.75',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('margin-bottom:24px');
|
||||||
|
expect(html).toContain('padding-top:8px');
|
||||||
|
expect(html).toContain('border:3px dashed #00ff00');
|
||||||
|
expect(html).toContain('box-shadow:0 10px 24px rgba(0,0,0,0.18)');
|
||||||
|
expect(html).toContain('opacity:0.75');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ContentSlider.craft.props exposes the animation/visibility rollout', () => {
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (ContentSlider as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model keys', () => {
|
||||||
|
const style = (ContentSlider as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -21,6 +21,11 @@ interface ContentSliderProps {
|
|||||||
showArrows?: boolean;
|
showArrows?: boolean;
|
||||||
height?: string;
|
height?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultSlides: Slide[] = [
|
const defaultSlides: Slide[] = [
|
||||||
@@ -227,7 +232,18 @@ ContentSlider.craft = {
|
|||||||
showDots: true,
|
showDots: true,
|
||||||
showArrows: true,
|
showArrows: true,
|
||||||
height: '400px',
|
height: '400px',
|
||||||
style: {},
|
style: {
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -3,6 +3,73 @@ import { Gallery } from './Gallery';
|
|||||||
|
|
||||||
const toHtml = (Gallery as any).toHtml;
|
const toHtml = (Gallery as any).toHtml;
|
||||||
|
|
||||||
|
describe('Gallery.toHtml columns + lightbox controls (previously unexposed props)', () => {
|
||||||
|
test('columns drives the grid-template-columns repeat count', () => {
|
||||||
|
const { html } = toHtml({ images: [{ src: '/a.jpg', alt: 'a' }], columns: 5 }, '');
|
||||||
|
expect(html).toContain('grid-template-columns:repeat(5,1fr)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('lightbox=true adds the delegated-listener overlay markup (columns unaffected)', () => {
|
||||||
|
const { html } = toHtml({ images: [{ src: '/a.jpg', alt: 'a' }], columns: 4, lightbox: true }, '');
|
||||||
|
expect(html).toContain('grid-template-columns:repeat(4,1fr)');
|
||||||
|
expect(html).toContain('role="dialog"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-numeric columns value falls back safely (Number() coercion, not NaN in the template)', () => {
|
||||||
|
const { html } = toHtml({ images: [{ src: '/a.jpg' }], columns: 'not-a-number' as any }, '');
|
||||||
|
expect(html).toContain('grid-template-columns:repeat(3,1fr)');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Gallery.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||||
|
test('margin/padding/border/box-shadow/opacity all flow into the section style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{
|
||||||
|
images: [{ src: '/a.jpg', alt: 'a' }],
|
||||||
|
style: {
|
||||||
|
marginTop: '20px',
|
||||||
|
paddingLeft: '12px',
|
||||||
|
border: '1px solid #333333',
|
||||||
|
boxShadow: '0 1px 2px rgba(0,0,0,0.08)',
|
||||||
|
opacity: '0.9',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('margin-top:20px');
|
||||||
|
expect(html).toContain('padding-left:12px');
|
||||||
|
expect(html).toContain('border:1px solid #333333');
|
||||||
|
expect(html).toContain('box-shadow:0 1px 2px rgba(0,0,0,0.08)');
|
||||||
|
expect(html).toContain('opacity:0.9');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Gallery.craft.props exposes columns/lightbox + the animation/visibility rollout', () => {
|
||||||
|
test('columns and lightbox have their existing defaults', () => {
|
||||||
|
const props = (Gallery as any).craft.props;
|
||||||
|
expect(props.columns).toBe(3);
|
||||||
|
expect(props.lightbox).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (Gallery as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model keys', () => {
|
||||||
|
const style = (Gallery as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('Gallery.toHtml lightbox uses a delegated listener, not per-item onclick (A4.3)', () => {
|
describe('Gallery.toHtml lightbox uses a delegated listener, not per-item onclick (A4.3)', () => {
|
||||||
test('no per-item inline onclick with interpolated src', () => {
|
test('no per-item inline onclick with interpolated src', () => {
|
||||||
const { html } = toHtml({ images: [{ src: '/a.jpg', alt: 'a' }], lightbox: true }, '');
|
const { html } = toHtml({ images: [{ src: '/a.jpg', alt: 'a' }], lightbox: true }, '');
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ interface GalleryProps {
|
|||||||
gap?: string;
|
gap?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
lightbox?: boolean;
|
lightbox?: boolean;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const placeholderSvg = (index: number) => {
|
const placeholderSvg = (index: number) => {
|
||||||
@@ -112,8 +117,20 @@ Gallery.craft = {
|
|||||||
images: defaultImages,
|
images: defaultImages,
|
||||||
columns: 3,
|
columns: 3,
|
||||||
gap: '16px',
|
gap: '16px',
|
||||||
style: { backgroundColor: '#ffffff' },
|
style: {
|
||||||
|
backgroundColor: '#ffffff',
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
lightbox: false,
|
lightbox: false,
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
BG_COLORS,
|
BG_COLORS,
|
||||||
RADIUS_PRESETS,
|
RADIUS_PRESETS,
|
||||||
SPACING_PRESETS,
|
SPACING_PRESETS,
|
||||||
|
SHADOW_PRESETS,
|
||||||
} from '../../../constants/presets';
|
} from '../../../constants/presets';
|
||||||
import {
|
import {
|
||||||
StylePanelProps,
|
StylePanelProps,
|
||||||
@@ -11,16 +12,49 @@ import {
|
|||||||
ColorSwatchGrid,
|
ColorSwatchGrid,
|
||||||
PresetButtonGrid,
|
PresetButtonGrid,
|
||||||
TextInputField,
|
TextInputField,
|
||||||
|
ColorPickerField,
|
||||||
|
CollapsibleSection,
|
||||||
|
SpacingControl,
|
||||||
|
SpacingSide,
|
||||||
|
BorderControl,
|
||||||
|
BorderValue,
|
||||||
|
buildBorderShorthand,
|
||||||
|
AnimationControl,
|
||||||
|
VisibilityControl,
|
||||||
|
sectionGap,
|
||||||
|
labelStyle,
|
||||||
autoTextColor,
|
autoTextColor,
|
||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
|
|
||||||
|
function capitalize(s: string): string {
|
||||||
|
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parses a `border` shorthand string (e.g. "2px solid #ff0000") back into
|
||||||
|
* the {width,style,color} shape BorderControl edits. Only needs to
|
||||||
|
* round-trip values this same panel produced via buildBorderShorthand. */
|
||||||
|
function parseBorderShorthand(v: string | undefined): BorderValue {
|
||||||
|
if (!v || v === 'none') return { width: '', style: 'none', color: '#000000' };
|
||||||
|
const m = String(v).trim().match(/^(\d+(?:\.\d+)?(?:px|em|rem)?)\s+(\w+)\s+(.+)$/);
|
||||||
|
if (!m) return { width: '', style: 'none', color: '#000000' };
|
||||||
|
return { width: m[1], style: m[2], color: m[3] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** style.opacity is a CSS-length-free numeric string ("0.8") or blank
|
||||||
|
* (treated as fully opaque). Converts to a 0-100 integer for the UI. */
|
||||||
|
function opacityPercent(v: unknown): number {
|
||||||
|
if (v === undefined || v === null || v === '') return 100;
|
||||||
|
const n = parseFloat(String(v));
|
||||||
|
return Number.isFinite(n) ? Math.round(n * 100) : 100;
|
||||||
|
}
|
||||||
|
|
||||||
/* ---------- BUTTON ---------- */
|
/* ---------- BUTTON ---------- */
|
||||||
export const ButtonStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
export const ButtonStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||||
const { actions } = useEditor();
|
const { actions } = useEditor();
|
||||||
const style: CSSProperties = nodeProps.style || {};
|
const style: CSSProperties = nodeProps.style || {};
|
||||||
|
|
||||||
const { setPropStyle } = useNodeProp(selectedId);
|
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||||
|
|
||||||
const setButtonColor = useCallback(
|
const setButtonColor = useCallback(
|
||||||
(bgColor: string) => {
|
(bgColor: string) => {
|
||||||
@@ -61,6 +95,16 @@ export const ButtonStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePr
|
|||||||
actions.setProp(selectedId, (props: any) => { props.href = v; });
|
actions.setProp(selectedId, (props: any) => { props.href = v; });
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
<div className="guided-section">
|
||||||
|
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#e4e4e7', cursor: 'pointer' }}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={nodeProps.target === '_blank'}
|
||||||
|
onChange={(e) => setProp('target', e.target.checked ? '_blank' : '_self')}
|
||||||
|
/>
|
||||||
|
Open in new tab
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
<div className="guided-section">
|
<div className="guided-section">
|
||||||
<SectionLabel>Border Radius</SectionLabel>
|
<SectionLabel>Border Radius</SectionLabel>
|
||||||
<PresetButtonGrid
|
<PresetButtonGrid
|
||||||
@@ -77,6 +121,70 @@ export const ButtonStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePr
|
|||||||
onSelect={(v) => setPropStyle('padding', v)}
|
onSelect={(v) => setPropStyle('padding', v)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Hover state -- rendered into a scoped <style>...:hover{} block by
|
||||||
|
ButtonLink.toHtml (published export only; not shown live in the
|
||||||
|
editor canvas beyond the hover preview ButtonLink itself does). */}
|
||||||
|
<CollapsibleSection title="Hover State" defaultOpen={false}>
|
||||||
|
<ColorPickerField
|
||||||
|
label="Hover Background"
|
||||||
|
value={nodeProps.hoverBg || ''}
|
||||||
|
onChange={(v) => setProp('hoverBg', v)}
|
||||||
|
/>
|
||||||
|
<ColorPickerField
|
||||||
|
label="Hover Text Color"
|
||||||
|
value={nodeProps.hoverColor || ''}
|
||||||
|
onChange={(v) => setProp('hoverColor', v)}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
|
|
||||||
|
{/* Box model + border/effects + animation/visibility rollout */}
|
||||||
|
<CollapsibleSection title="Spacing" defaultOpen={false}>
|
||||||
|
<SpacingControl
|
||||||
|
label="Margin"
|
||||||
|
value={{ top: style.marginTop as string, right: style.marginRight as string, bottom: style.marginBottom as string, left: style.marginLeft as string }}
|
||||||
|
onChange={(side: SpacingSide, v: string) => setPropStyle(`margin${capitalize(side)}`, v)}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
|
<CollapsibleSection title="Border & Effects" defaultOpen={false}>
|
||||||
|
<BorderControl
|
||||||
|
value={parseBorderShorthand(style.border as string)}
|
||||||
|
onChange={(v) => setPropStyle('border', buildBorderShorthand(v))}
|
||||||
|
/>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Shadow</SectionLabel>
|
||||||
|
<PresetButtonGrid presets={SHADOW_PRESETS} activeValue={style.boxShadow as string} onSelect={(v) => setPropStyle('boxShadow', v)} />
|
||||||
|
</div>
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<label style={labelStyle}>Opacity: {opacityPercent(style.opacity)}%</label>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
value={opacityPercent(style.opacity)}
|
||||||
|
onChange={(e) => setPropStyle('opacity', String(Number(e.target.value) / 100))}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CollapsibleSection>
|
||||||
|
<CollapsibleSection title="Animation & Visibility" defaultOpen={false}>
|
||||||
|
<AnimationControl
|
||||||
|
value={{ animation: nodeProps.animation || 'none', animationDelay: nodeProps.animationDelay }}
|
||||||
|
onChange={(v) => { setProp('animation', v.animation); setProp('animationDelay', v.animationDelay); }}
|
||||||
|
/>
|
||||||
|
<VisibilityControl
|
||||||
|
value={{
|
||||||
|
hideOnDesktop: nodeProps.hideOnDesktop,
|
||||||
|
hideOnTablet: nodeProps.hideOnTablet,
|
||||||
|
hideOnMobile: nodeProps.hideOnMobile,
|
||||||
|
}}
|
||||||
|
onChange={(v) => {
|
||||||
|
setProp('hideOnDesktop', !!v.hideOnDesktop);
|
||||||
|
setProp('hideOnTablet', !!v.hideOnTablet);
|
||||||
|
setProp('hideOnMobile', !!v.hideOnMobile);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
import { useEditor } from '@craftjs/core';
|
||||||
import {
|
import {
|
||||||
BG_COLORS,
|
BG_COLORS,
|
||||||
SPACING_PRESETS,
|
SPACING_PRESETS,
|
||||||
RADIUS_PRESETS,
|
RADIUS_PRESETS,
|
||||||
|
SHADOW_PRESETS,
|
||||||
} from '../../../constants/presets';
|
} from '../../../constants/presets';
|
||||||
import {
|
import {
|
||||||
StylePanelProps,
|
StylePanelProps,
|
||||||
@@ -10,21 +12,152 @@ import {
|
|||||||
ColorSwatchGrid,
|
ColorSwatchGrid,
|
||||||
PresetButtonGrid,
|
PresetButtonGrid,
|
||||||
CollapsibleSection,
|
CollapsibleSection,
|
||||||
|
ArrayPropEditor,
|
||||||
|
SpacingControl,
|
||||||
|
BorderControl,
|
||||||
|
BorderValue,
|
||||||
|
AnimationControl,
|
||||||
|
VisibilityControl,
|
||||||
|
buildBorderShorthand,
|
||||||
labelStyle,
|
labelStyle,
|
||||||
inputStyle,
|
inputStyle,
|
||||||
|
smallInputStyle,
|
||||||
btnActiveStyle,
|
btnActiveStyle,
|
||||||
sectionGap,
|
sectionGap,
|
||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
|
|
||||||
|
/* The full sanitizeInputType (utils/escape.ts) allowlist, plus the two
|
||||||
|
fake "types" (textarea/select) that take their own ContactForm render
|
||||||
|
branch instead of an <input type>. Kept as a local list (rather than
|
||||||
|
importing the runtime array from utils/escape.ts) since this is
|
||||||
|
presentation-only -- the actual security boundary is enforced in
|
||||||
|
ContactForm.toHtml via sanitizeInputType, not here. */
|
||||||
|
const CONTACT_FIELD_TYPES = [
|
||||||
|
'text', 'email', 'tel', 'number', 'password', 'url', 'search', 'date',
|
||||||
|
'checkbox', 'radio', 'textarea', 'select',
|
||||||
|
];
|
||||||
|
|
||||||
|
const moveBtnStyle: React.CSSProperties = {
|
||||||
|
flex: 1, padding: '3px 6px', fontSize: 10, background: '#27272a', color: '#a1a1aa',
|
||||||
|
border: '1px solid #3f3f46', borderRadius: 4, cursor: 'pointer',
|
||||||
|
};
|
||||||
|
|
||||||
|
function parseBorderValue(v: unknown): BorderValue {
|
||||||
|
const s = typeof v === 'string' ? v.trim() : '';
|
||||||
|
if (!s || s === 'none') return { width: '', style: 'none', color: '' };
|
||||||
|
const m = s.match(/^(\S+)\s+(\S+)\s+(.+)$/);
|
||||||
|
if (!m) return { width: '', style: 'none', color: '' };
|
||||||
|
return { width: m[1], style: m[2], color: m[3] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const SPACING_SIDE_KEYS: { side: 'top' | 'right' | 'bottom' | 'left'; suffix: 'Top' | 'Right' | 'Bottom' | 'Left' }[] = [
|
||||||
|
{ side: 'top', suffix: 'Top' },
|
||||||
|
{ side: 'right', suffix: 'Right' },
|
||||||
|
{ side: 'bottom', suffix: 'Bottom' },
|
||||||
|
{ side: 'left', suffix: 'Left' },
|
||||||
|
];
|
||||||
|
|
||||||
/* ---------- FORM ---------- */
|
/* ---------- FORM ---------- */
|
||||||
export const FormStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
export const FormStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||||
|
const { actions } = useEditor();
|
||||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||||
|
|
||||||
const style = nodeProps.style || {};
|
const style = nodeProps.style || {};
|
||||||
|
|
||||||
|
const updateField = (index: number, patch: Record<string, any>) => {
|
||||||
|
actions.setProp(selectedId, (props: any) => {
|
||||||
|
const updated = [...(props.fields || [])];
|
||||||
|
updated[index] = { ...updated[index], ...patch };
|
||||||
|
props.fields = updated;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveField = (index: number, direction: -1 | 1) => {
|
||||||
|
actions.setProp(selectedId, (props: any) => {
|
||||||
|
const updated = [...(props.fields || [])];
|
||||||
|
const newIndex = index + direction;
|
||||||
|
if (newIndex < 0 || newIndex >= updated.length) return;
|
||||||
|
[updated[index], updated[newIndex]] = [updated[newIndex], updated[index]];
|
||||||
|
props.fields = updated;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
{/* ContactForm field editor: add/remove/reorder fields, set each
|
||||||
|
field's label, name, type (full allowlist + textarea/select),
|
||||||
|
options (select only), and required flag. */}
|
||||||
|
{nodeProps.fields !== undefined && Array.isArray(nodeProps.fields) && (
|
||||||
|
<CollapsibleSection title="Fields">
|
||||||
|
<ArrayPropEditor
|
||||||
|
selectedId={selectedId}
|
||||||
|
propKey="fields"
|
||||||
|
items={nodeProps.fields}
|
||||||
|
renderItem={(item: any, index: number) => (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={item.label || ''}
|
||||||
|
onChange={(e) => updateField(index, { label: e.target.value })}
|
||||||
|
placeholder="Label"
|
||||||
|
style={smallInputStyle}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={item.name || ''}
|
||||||
|
onChange={(e) => updateField(index, { name: e.target.value })}
|
||||||
|
placeholder="Field name (e.g. email)"
|
||||||
|
style={smallInputStyle}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={item.placeholder || ''}
|
||||||
|
onChange={(e) => updateField(index, { placeholder: e.target.value })}
|
||||||
|
placeholder="Placeholder"
|
||||||
|
style={smallInputStyle}
|
||||||
|
/>
|
||||||
|
<select
|
||||||
|
value={item.type || 'text'}
|
||||||
|
onChange={(e) => updateField(index, { type: e.target.value })}
|
||||||
|
style={{ ...smallInputStyle, cursor: 'pointer' }}
|
||||||
|
>
|
||||||
|
{CONTACT_FIELD_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
|
||||||
|
</select>
|
||||||
|
{item.type === 'select' && (
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={(item.options || []).join(', ')}
|
||||||
|
onChange={(e) => updateField(index, {
|
||||||
|
options: e.target.value.split(',').map((s: string) => s.trim()).filter(Boolean),
|
||||||
|
})}
|
||||||
|
placeholder="Options (comma-separated)"
|
||||||
|
style={smallInputStyle}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#e4e4e7', cursor: 'pointer' }}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={!!item.required}
|
||||||
|
onChange={(e) => updateField(index, { required: e.target.checked })}
|
||||||
|
/>
|
||||||
|
Required
|
||||||
|
</label>
|
||||||
|
<div style={{ display: 'flex', gap: 4 }}>
|
||||||
|
<button disabled={index === 0} onClick={() => moveField(index, -1)} style={{ ...moveBtnStyle, opacity: index === 0 ? 0.4 : 1 }} title="Move up">
|
||||||
|
<i className="fa fa-arrow-up" />
|
||||||
|
</button>
|
||||||
|
<button disabled={index === nodeProps.fields.length - 1} onClick={() => moveField(index, 1)} style={{ ...moveBtnStyle, opacity: index === nodeProps.fields.length - 1 ? 0.4 : 1 }} title="Move down">
|
||||||
|
<i className="fa fa-arrow-down" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
emptyItem={{ type: 'text', label: 'New Field', name: 'field', placeholder: '', required: false }}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Contact-form relay: where submissions are emailed. Present on ContactForm
|
{/* Contact-form relay: where submissions are emailed. Present on ContactForm
|
||||||
and FormContainer (both have recipientEmail/thankYouUrl props). */}
|
and FormContainer (both have recipientEmail/thankYouUrl props). */}
|
||||||
{nodeProps.recipientEmail !== undefined && (
|
{nodeProps.recipientEmail !== undefined && (
|
||||||
@@ -43,13 +176,35 @@ export const FormStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProp
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Form action/method */}
|
{/* Form action/method (FormContainer). SearchBar also has an `action`
|
||||||
{nodeProps.action !== undefined && (
|
prop but is distinguished via its unique `showButton` prop -- see
|
||||||
|
the dedicated Search block below -- so it doesn't get this label. */}
|
||||||
|
{nodeProps.action !== undefined && nodeProps.showButton === undefined && (
|
||||||
<div style={sectionGap}>
|
<div style={sectionGap}>
|
||||||
<label style={labelStyle}>Form Action URL</label>
|
<label style={labelStyle}>Form Action URL</label>
|
||||||
<input type="text" value={nodeProps.action || ''} onChange={(e) => setProp('action', e.target.value)} placeholder="https://..." style={inputStyle} />
|
<input type="text" value={nodeProps.action || ''} onChange={(e) => setProp('action', e.target.value)} placeholder="https://..." style={inputStyle} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* SearchBar: where the GET search request is submitted. */}
|
||||||
|
{nodeProps.showButton !== undefined && nodeProps.action !== undefined && (
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<label style={labelStyle}>Search Results Page</label>
|
||||||
|
<input type="text" value={nodeProps.action || ''} onChange={(e) => setProp('action', e.target.value)} placeholder="/ (site root) or /search" style={inputStyle} />
|
||||||
|
<p style={{ fontSize: 10, color: '#71717a', margin: '4px 0 0' }}>
|
||||||
|
Submits a GET request with the query as ?q=... to this URL.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{nodeProps.showButton !== undefined && (
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<label style={{ ...labelStyle, display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||||
|
<input type="checkbox" checked={nodeProps.showButton !== false} onChange={(e) => setProp('showButton', e.target.checked)} />
|
||||||
|
Show Search Button
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{nodeProps.method !== undefined && (
|
{nodeProps.method !== undefined && (
|
||||||
<div style={sectionGap}>
|
<div style={sectionGap}>
|
||||||
<label style={labelStyle}>Method</label>
|
<label style={labelStyle}>Method</label>
|
||||||
@@ -142,6 +297,64 @@ export const FormStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProp
|
|||||||
<PresetButtonGrid presets={RADIUS_PRESETS} activeValue={style.borderRadius as string} onSelect={(v) => setPropStyle('borderRadius', v)} />
|
<PresetButtonGrid presets={RADIUS_PRESETS} activeValue={style.borderRadius as string} onSelect={(v) => setPropStyle('borderRadius', v)} />
|
||||||
</div>
|
</div>
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
|
|
||||||
|
{/* Box model: margin/padding (per-side), border, shadow, opacity --
|
||||||
|
common enh-batch rollout, applies to the whole form family since
|
||||||
|
they all spread `style` onto their root element. */}
|
||||||
|
<CollapsibleSection title="Spacing, Border & Effects" defaultOpen={false}>
|
||||||
|
<SpacingControl
|
||||||
|
label="Margin"
|
||||||
|
value={{ top: style.marginTop, right: style.marginRight, bottom: style.marginBottom, left: style.marginLeft }}
|
||||||
|
onChange={(side, v) => setPropStyle(`margin${SPACING_SIDE_KEYS.find((s) => s.side === side)!.suffix}`, v)}
|
||||||
|
/>
|
||||||
|
<SpacingControl
|
||||||
|
label="Padding (per side)"
|
||||||
|
value={{ top: style.paddingTop, right: style.paddingRight, bottom: style.paddingBottom, left: style.paddingLeft }}
|
||||||
|
onChange={(side, v) => setPropStyle(`padding${SPACING_SIDE_KEYS.find((s) => s.side === side)!.suffix}`, v)}
|
||||||
|
/>
|
||||||
|
<BorderControl
|
||||||
|
value={parseBorderValue(style.border)}
|
||||||
|
onChange={(v) => setPropStyle('border', buildBorderShorthand(v))}
|
||||||
|
/>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Box Shadow</SectionLabel>
|
||||||
|
<PresetButtonGrid presets={SHADOW_PRESETS} activeValue={style.boxShadow as string} onSelect={(v) => setPropStyle('boxShadow', v)} />
|
||||||
|
</div>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Opacity</SectionLabel>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
value={style.opacity !== undefined && style.opacity !== '' ? Math.round(Number(style.opacity) * 100) : 100}
|
||||||
|
onChange={(e) => setPropStyle('opacity', String(Number(e.target.value) / 100))}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CollapsibleSection>
|
||||||
|
|
||||||
|
{/* Animation & Visibility -- gated on the blank/false defaults added to
|
||||||
|
each owned component's craft.props (ContactForm, FormContainer,
|
||||||
|
InputField, TextareaField, FormButton, SubscribeForm, SearchBar).
|
||||||
|
No toHtml change needed: the export's buildDataAttrs() already
|
||||||
|
emits data-animation/data-hide-* from these exact prop names for
|
||||||
|
every node. */}
|
||||||
|
{nodeProps.animation !== undefined && (
|
||||||
|
<CollapsibleSection title="Animation & Visibility" defaultOpen={false}>
|
||||||
|
<AnimationControl
|
||||||
|
value={{ animation: nodeProps.animation, animationDelay: nodeProps.animationDelay }}
|
||||||
|
onChange={(v) => { setProp('animation', v.animation); setProp('animationDelay', v.animationDelay); }}
|
||||||
|
/>
|
||||||
|
<VisibilityControl
|
||||||
|
value={{ hideOnDesktop: nodeProps.hideOnDesktop, hideOnTablet: nodeProps.hideOnTablet, hideOnMobile: nodeProps.hideOnMobile }}
|
||||||
|
onChange={(v) => {
|
||||||
|
setProp('hideOnDesktop', v.hideOnDesktop);
|
||||||
|
setProp('hideOnTablet', v.hideOnTablet);
|
||||||
|
setProp('hideOnMobile', v.hideOnMobile);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React from 'react';
|
import React, { useState } from 'react';
|
||||||
import {
|
import {
|
||||||
TEXT_COLORS,
|
TEXT_COLORS,
|
||||||
BG_COLORS,
|
BG_COLORS,
|
||||||
@@ -17,12 +17,85 @@ import {
|
|||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
import { ArrayItemFieldsEditor } from './ArrayItemFields';
|
import { ArrayItemFieldsEditor } from './ArrayItemFields';
|
||||||
|
import { Modal } from '../../../ui/Modal';
|
||||||
|
import { CodeEditor } from '../../../ui/CodeEditor';
|
||||||
|
|
||||||
|
/* ---------- "Edit HTML" modal for the HtmlBlock `code` prop ----------
|
||||||
|
`code` is raw HTML (potentially many lines, embedded <style>/<script>),
|
||||||
|
so it gets a dedicated syntax-highlighted CodeEditor in a modal instead
|
||||||
|
of falling into the generic single-line/textarea string-prop rendering
|
||||||
|
below (see GenericPropsEditor's SKIP of the `code` key). */
|
||||||
|
const HtmlCodeField: React.FC<{ value: string; onChange: (v: string) => void }> = ({ value, onChange }) => {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<CollapsibleSection title="HTML Code">
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen(true)}
|
||||||
|
style={{
|
||||||
|
width: '100%', padding: '8px 12px', fontSize: 12, fontWeight: 600,
|
||||||
|
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
|
||||||
|
background: '#27272a', color: '#e4e4e7', border: '1px solid #3f3f46',
|
||||||
|
borderRadius: 6, cursor: 'pointer',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<i className="fa fa-code" /> Edit HTML
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<Modal open={open} onClose={() => setOpen(false)} width="min(720px, 90vw)">
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
background: 'var(--color-bg-surface)',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
borderRadius: 12,
|
||||||
|
boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div style={{
|
||||||
|
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||||
|
padding: '14px 16px', borderBottom: '1px solid var(--color-border)',
|
||||||
|
}}>
|
||||||
|
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--color-text)' }}>Edit HTML</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
style={{
|
||||||
|
width: 28, height: 28, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||||
|
background: 'none', border: '1px solid var(--color-border)', borderRadius: 6,
|
||||||
|
color: 'var(--color-text-muted)', cursor: 'pointer', fontSize: 13,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<i className="fa fa-times" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div style={{ padding: 16 }}>
|
||||||
|
<CodeEditor value={value} onChange={onChange} language="html" height={420} />
|
||||||
|
</div>
|
||||||
|
<div style={{ padding: '10px 16px', borderTop: '1px solid var(--color-border)', display: 'flex', justifyContent: 'flex-end' }}>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
style={{
|
||||||
|
padding: '7px 20px', fontSize: 13, fontWeight: 600,
|
||||||
|
background: 'var(--color-accent)', color: '#fff', border: 'none', borderRadius: 6, cursor: 'pointer',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</CollapsibleSection>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
/* ---------- SMART GENERIC PROPS EDITOR (Fallback) ---------- */
|
/* ---------- SMART GENERIC PROPS EDITOR (Fallback) ---------- */
|
||||||
export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Record<string, any>; typeName: string }> = ({
|
export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Record<string, any>; typeName: string }> = ({
|
||||||
selectedId, nodeProps, typeName,
|
selectedId, nodeProps, typeName,
|
||||||
}) => {
|
}) => {
|
||||||
const SKIP_PROPS = new Set(['style', 'children', 'cssId', 'cssClass']);
|
const SKIP_PROPS = new Set(['style', 'children', 'cssId', 'cssClass', 'code']);
|
||||||
|
|
||||||
const { setProp: setPropValue, setPropStyle: setStyleValue } = useNodeProp(selectedId);
|
const { setProp: setPropValue, setPropStyle: setStyleValue } = useNodeProp(selectedId);
|
||||||
|
|
||||||
@@ -35,9 +108,15 @@ export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Recor
|
|||||||
const arrayProps = allProps.filter(([_, val]) => Array.isArray(val));
|
const arrayProps = allProps.filter(([_, val]) => Array.isArray(val));
|
||||||
|
|
||||||
const style = nodeProps.style || {};
|
const style = nodeProps.style || {};
|
||||||
|
const hasCodeProp = typeof nodeProps.code === 'string';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
{/* Raw HTML (HtmlBlock's `code` prop) -- dedicated CodeEditor modal */}
|
||||||
|
{hasCodeProp && (
|
||||||
|
<HtmlCodeField value={nodeProps.code} onChange={(v) => setPropValue('code', v)} />
|
||||||
|
)}
|
||||||
|
|
||||||
{/* String props */}
|
{/* String props */}
|
||||||
{stringProps.length > 0 && (
|
{stringProps.length > 0 && (
|
||||||
<CollapsibleSection title="Properties">
|
<CollapsibleSection title="Properties">
|
||||||
|
|||||||
@@ -2,30 +2,28 @@ import React, { CSSProperties } from 'react';
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import {
|
import {
|
||||||
IMAGE_RADIUS_PRESETS,
|
IMAGE_RADIUS_PRESETS,
|
||||||
|
OBJECT_FIT,
|
||||||
} from '../../../constants/presets';
|
} from '../../../constants/presets';
|
||||||
import {
|
import {
|
||||||
StylePanelProps,
|
StylePanelProps,
|
||||||
SectionLabel,
|
SectionLabel,
|
||||||
PresetButtonGrid,
|
PresetButtonGrid,
|
||||||
TextInputField,
|
TextInputField,
|
||||||
|
SizeControl,
|
||||||
|
AspectRatioControl,
|
||||||
|
FocalPointGrid,
|
||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||||
import { PLACEHOLDER_SRC } from '../../../components/media/ImageBlock';
|
import { PLACEHOLDER_SRC } from '../../../components/media/ImageBlock';
|
||||||
|
import { BoxModelSection, BorderEffectsSection, AnimVisSection } from './mediaBoxModel';
|
||||||
|
|
||||||
/* ---------- 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 }) => {
|
||||||
const { actions } = useEditor();
|
const { actions } = useEditor();
|
||||||
const style: CSSProperties = nodeProps.style || {};
|
const style: CSSProperties = nodeProps.style || {};
|
||||||
|
|
||||||
const { setPropStyle } = useNodeProp(selectedId);
|
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||||
|
|
||||||
const maxWidthPresets = [
|
|
||||||
{ label: '25%', value: '25%' },
|
|
||||||
{ label: '50%', value: '50%' },
|
|
||||||
{ label: '75%', value: '75%' },
|
|
||||||
{ label: '100%', value: '100%' },
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -49,6 +47,39 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Size -- Width absorbs the historical maxWidth presets (25/50/75/100%
|
||||||
|
are a subset of SizeControl's default preset row), Height is new. */}
|
||||||
|
<SizeControl
|
||||||
|
label="Width"
|
||||||
|
value={(style.maxWidth as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('maxWidth', v)}
|
||||||
|
/>
|
||||||
|
<SizeControl
|
||||||
|
label="Height"
|
||||||
|
value={(style.height as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('height', v)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Crop & Framing -- aspect-ratio + object-fit + object-position on the
|
||||||
|
<img> itself is a CSS framing crop (no server-side image processing
|
||||||
|
needed). */}
|
||||||
|
<AspectRatioControl
|
||||||
|
value={(style.aspectRatio as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('aspectRatio', v)}
|
||||||
|
/>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Object Fit</SectionLabel>
|
||||||
|
<PresetButtonGrid
|
||||||
|
presets={OBJECT_FIT}
|
||||||
|
activeValue={(style.objectFit as string) || ''}
|
||||||
|
onSelect={(v) => setPropStyle('objectFit', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<FocalPointGrid
|
||||||
|
value={(style.objectPosition as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('objectPosition', v)}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Border Radius */}
|
{/* Border Radius */}
|
||||||
<div className="guided-section">
|
<div className="guided-section">
|
||||||
<SectionLabel>Border Radius</SectionLabel>
|
<SectionLabel>Border Radius</SectionLabel>
|
||||||
@@ -59,15 +90,10 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Max Width */}
|
{/* Box model + animation/visibility rollout */}
|
||||||
<div className="guided-section">
|
<BoxModelSection style={style} setPropStyle={setPropStyle} />
|
||||||
<SectionLabel>Max Width</SectionLabel>
|
<BorderEffectsSection style={style} setPropStyle={setPropStyle} />
|
||||||
<PresetButtonGrid
|
<AnimVisSection nodeProps={nodeProps} setProp={setProp} />
|
||||||
presets={maxWidthPresets}
|
|
||||||
activeValue={style.maxWidth as string}
|
|
||||||
onSelect={(v) => setPropStyle('maxWidth', v)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import React from 'react';
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import {
|
import {
|
||||||
BG_COLORS,
|
BG_COLORS,
|
||||||
SPACING_PRESETS,
|
|
||||||
RADIUS_PRESETS,
|
RADIUS_PRESETS,
|
||||||
} from '../../../constants/presets';
|
} from '../../../constants/presets';
|
||||||
import {
|
import {
|
||||||
@@ -13,6 +12,8 @@ import {
|
|||||||
CollapsibleSection,
|
CollapsibleSection,
|
||||||
ColorPickerField,
|
ColorPickerField,
|
||||||
ArrayPropEditor,
|
ArrayPropEditor,
|
||||||
|
SizeControl,
|
||||||
|
AspectRatioControl,
|
||||||
labelStyle,
|
labelStyle,
|
||||||
inputStyle,
|
inputStyle,
|
||||||
smallInputStyle,
|
smallInputStyle,
|
||||||
@@ -20,6 +21,14 @@ import {
|
|||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||||
|
import { BoxModelSection, BorderEffectsSection, AnimVisSection } from './mediaBoxModel';
|
||||||
|
|
||||||
|
const GALLERY_COLUMN_PRESETS = [
|
||||||
|
{ label: '2', value: '2' },
|
||||||
|
{ label: '3', value: '3' },
|
||||||
|
{ label: '4', value: '4' },
|
||||||
|
{ label: '5', value: '5' },
|
||||||
|
];
|
||||||
|
|
||||||
/* ---------- MEDIA (Video / Gallery / Map / Slider) ---------- */
|
/* ---------- MEDIA (Video / Gallery / Map / Slider) ---------- */
|
||||||
export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||||
@@ -30,11 +39,48 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* Video URL */}
|
{/* Video source -- upload/browse/paste-URL (paste-URL still handles
|
||||||
|
YouTube/Vimeo; upload/browse handle files via detectVideoType's
|
||||||
|
serve_asset resolution). */}
|
||||||
{nodeProps.videoUrl !== undefined && (
|
{nodeProps.videoUrl !== undefined && (
|
||||||
<div style={sectionGap}>
|
<div className="guided-section">
|
||||||
<label style={labelStyle}>Video URL</label>
|
<SectionLabel>Video Source</SectionLabel>
|
||||||
<input type="text" value={nodeProps.videoUrl || ''} onChange={(e) => setProp('videoUrl', e.target.value)} placeholder="YouTube, Vimeo, or .mp4 URL" style={inputStyle} />
|
<AssetPicker
|
||||||
|
mediaType="video"
|
||||||
|
value={nodeProps.videoUrl || ''}
|
||||||
|
onChange={(url) => setProp('videoUrl', url)}
|
||||||
|
variant="full"
|
||||||
|
placeholder="Or paste a YouTube/Vimeo/.mp4 URL..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Video size -- width + aspect ratio for the video frame. */}
|
||||||
|
{nodeProps.videoUrl !== undefined && (
|
||||||
|
<>
|
||||||
|
<SizeControl
|
||||||
|
label="Width"
|
||||||
|
value={(style.width as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('width', v)}
|
||||||
|
/>
|
||||||
|
<AspectRatioControl
|
||||||
|
value={(style.aspectRatio as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('aspectRatio', v)}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Poster image (optional, file-type videos only in practice but
|
||||||
|
harmless to offer whenever the component has a poster prop). */}
|
||||||
|
{nodeProps.poster !== undefined && (
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Poster Image (optional)</SectionLabel>
|
||||||
|
<AssetPicker
|
||||||
|
mediaType="image"
|
||||||
|
value={nodeProps.poster || ''}
|
||||||
|
onChange={(url) => setProp('poster', url)}
|
||||||
|
variant="full"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -80,6 +126,26 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Gallery layout -- columns + lightbox (existing-but-previously-unexposed props). */}
|
||||||
|
{nodeProps.images !== undefined && Array.isArray(nodeProps.images) && (
|
||||||
|
<>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Columns</SectionLabel>
|
||||||
|
<PresetButtonGrid
|
||||||
|
presets={GALLERY_COLUMN_PRESETS}
|
||||||
|
activeValue={String(nodeProps.columns ?? 3)}
|
||||||
|
onSelect={(v) => setProp('columns', Number(v))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<label style={{ ...labelStyle, display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||||
|
<input type="checkbox" checked={!!nodeProps.lightbox} onChange={(e) => setProp('lightbox', e.target.checked)} />
|
||||||
|
Enable Lightbox
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Gallery items */}
|
{/* Gallery items */}
|
||||||
{nodeProps.images !== undefined && Array.isArray(nodeProps.images) && (
|
{nodeProps.images !== undefined && Array.isArray(nodeProps.images) && (
|
||||||
<CollapsibleSection title="Images">
|
<CollapsibleSection title="Images">
|
||||||
@@ -178,21 +244,23 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Background & padding */}
|
{/* Background & radius */}
|
||||||
<CollapsibleSection title="Style" defaultOpen={false}>
|
<CollapsibleSection title="Style" defaultOpen={false}>
|
||||||
<div className="guided-section">
|
<div className="guided-section">
|
||||||
<SectionLabel>Background</SectionLabel>
|
<SectionLabel>Background</SectionLabel>
|
||||||
<ColorSwatchGrid colors={BG_COLORS} activeValue={style.backgroundColor} onSelect={(v: string) => setPropStyle('backgroundColor', v)} />
|
<ColorSwatchGrid colors={BG_COLORS} activeValue={style.backgroundColor} onSelect={(v: string) => setPropStyle('backgroundColor', v)} />
|
||||||
</div>
|
</div>
|
||||||
<div className="guided-section">
|
|
||||||
<SectionLabel>Padding</SectionLabel>
|
|
||||||
<PresetButtonGrid presets={SPACING_PRESETS} activeValue={style.padding as string} onSelect={(v) => setPropStyle('padding', v)} />
|
|
||||||
</div>
|
|
||||||
<div className="guided-section">
|
<div className="guided-section">
|
||||||
<SectionLabel>Border Radius</SectionLabel>
|
<SectionLabel>Border Radius</SectionLabel>
|
||||||
<PresetButtonGrid presets={RADIUS_PRESETS} activeValue={style.borderRadius as string} onSelect={(v) => setPropStyle('borderRadius', v)} />
|
<PresetButtonGrid presets={RADIUS_PRESETS} activeValue={style.borderRadius as string} onSelect={(v) => setPropStyle('borderRadius', v)} />
|
||||||
</div>
|
</div>
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
|
|
||||||
|
{/* Box model + animation/visibility rollout (Video/Gallery/Map/Slider
|
||||||
|
all carry these props now, so it's safe to render unconditionally). */}
|
||||||
|
<BoxModelSection style={style} setPropStyle={setPropStyle} />
|
||||||
|
<BorderEffectsSection style={style} setPropStyle={setPropStyle} />
|
||||||
|
<AnimVisSection nodeProps={nodeProps} setProp={setProp} />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
|
||||||
|
/* Same DOM-harness pattern as MediaStylePanel.slides.test.tsx -- mock
|
||||||
|
@craftjs/core's useEditor so setProp calls can be observed without
|
||||||
|
mounting a real <Editor> tree, and mock utils/assets so AssetPicker
|
||||||
|
doesn't hit the network. */
|
||||||
|
const setPropSpy = vi.fn((_id: string, updater: (p: any) => void) => {
|
||||||
|
updater(lastProps);
|
||||||
|
});
|
||||||
|
let lastProps: any;
|
||||||
|
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useEditor: () => ({ actions: { setProp: setPropSpy } }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../../../utils/assets', () => ({
|
||||||
|
uploadAsset: vi.fn(),
|
||||||
|
listAssets: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { MediaStylePanel } from './MediaStylePanel';
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function unmount() {
|
||||||
|
act(() => { root.unmount(); });
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
function q<T extends Element = Element>(testId: string): T | null {
|
||||||
|
return container.querySelector(`[data-testid="${testId}"]`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function qAll<T extends Element = Element>(testId: string): T[] {
|
||||||
|
return Array.from(container.querySelectorAll(`[data-testid="${testId}"]`));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setValue(input: HTMLInputElement, value: string) {
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')!.set!;
|
||||||
|
setter.call(input, value);
|
||||||
|
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
setPropSpy.mockClear();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (container) unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MediaStylePanel Video source uses AssetPicker (upload/browse/paste-URL), not a plain text input', () => {
|
||||||
|
test('renders a full-variant AssetPicker (not the old plain input) for videoUrl', () => {
|
||||||
|
lastProps = { videoUrl: '', poster: '', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
|
||||||
|
expect(q('asset-picker-full')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('applying a pasted URL via the AssetPicker writes videoUrl (not some other key)', () => {
|
||||||
|
lastProps = { videoUrl: '', poster: '', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
|
||||||
|
|
||||||
|
// The Video Source AssetPicker is the first url-input on the page (the
|
||||||
|
// Poster picker is a second, separate AssetPicker instance below it).
|
||||||
|
const urlInput = qAll<HTMLInputElement>('asset-picker-url-input')[0];
|
||||||
|
expect(urlInput).toBeTruthy();
|
||||||
|
setValue(urlInput, 'https://example.com/clip.mp4');
|
||||||
|
|
||||||
|
const applyBtn = qAll<HTMLButtonElement>('asset-picker-apply')[0];
|
||||||
|
act(() => {
|
||||||
|
applyBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(setPropSpy).toHaveBeenCalled();
|
||||||
|
expect(lastProps.videoUrl).toBe('https://example.com/clip.mp4');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a video-shaped selection also renders a Poster AssetPicker (image) that writes `poster`', () => {
|
||||||
|
lastProps = { videoUrl: 'https://example.com/clip.mp4', poster: '', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
|
||||||
|
|
||||||
|
const pickers = qAll('asset-picker-full');
|
||||||
|
expect(pickers.length).toBe(2); // Video Source + Poster Image
|
||||||
|
|
||||||
|
const urlInputs = qAll<HTMLInputElement>('asset-picker-url-input');
|
||||||
|
const posterInput = urlInputs[1];
|
||||||
|
setValue(posterInput, 'https://example.com/poster.jpg');
|
||||||
|
const applyBtns = qAll<HTMLButtonElement>('asset-picker-apply');
|
||||||
|
act(() => {
|
||||||
|
applyBtns[1].dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(lastProps.poster).toBe('https://example.com/poster.jpg');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MediaStylePanel Video size controls (Width + Aspect Ratio) are gated on videoUrl', () => {
|
||||||
|
test('a video-shaped selection renders SizeControl + AspectRatioControl', () => {
|
||||||
|
lastProps = { videoUrl: '', poster: '', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
|
||||||
|
expect(q('size-control')).not.toBeNull();
|
||||||
|
expect(q('aspect-ratio-control')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a Map-shaped selection (no videoUrl) does NOT render the video size controls', () => {
|
||||||
|
lastProps = { address: 'New York, NY', zoom: 14, height: '400px', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="map-1" nodeProps={lastProps} />);
|
||||||
|
expect(q('size-control')).toBeNull();
|
||||||
|
expect(q('aspect-ratio-control')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function openCollapsibleByTitle(title: string) {
|
||||||
|
const btn = Array.from(container.querySelectorAll('button')).find((b) => b.textContent?.includes(title));
|
||||||
|
expect(btn).toBeTruthy();
|
||||||
|
act(() => {
|
||||||
|
btn!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MediaStylePanel box-model + animation/visibility rollout renders for every media type', () => {
|
||||||
|
test('a Map-shaped selection still gets Spacing / Border & Effects / Animation & Visibility sections (collapsed by default, open on click)', () => {
|
||||||
|
lastProps = { address: 'New York, NY', zoom: 14, height: '400px', style: {}, animation: '', hideOnDesktop: false };
|
||||||
|
render(<MediaStylePanel selectedId="map-1" nodeProps={lastProps} />);
|
||||||
|
|
||||||
|
openCollapsibleByTitle('Spacing');
|
||||||
|
expect(q('spacing-control')).not.toBeNull();
|
||||||
|
|
||||||
|
openCollapsibleByTitle('Border & Effects');
|
||||||
|
expect(q('border-control')).not.toBeNull();
|
||||||
|
|
||||||
|
openCollapsibleByTitle('Animation & Visibility');
|
||||||
|
expect(q('animation-control')).not.toBeNull();
|
||||||
|
expect(q('visibility-control')).not.toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,20 +4,69 @@ import {
|
|||||||
FONT_FAMILIES,
|
FONT_FAMILIES,
|
||||||
TEXT_SIZES,
|
TEXT_SIZES,
|
||||||
FONT_WEIGHTS,
|
FONT_WEIGHTS,
|
||||||
|
LINE_HEIGHTS,
|
||||||
|
LETTER_SPACINGS,
|
||||||
|
SHADOW_PRESETS,
|
||||||
} from '../../../constants/presets';
|
} from '../../../constants/presets';
|
||||||
import {
|
import {
|
||||||
StylePanelProps,
|
StylePanelProps,
|
||||||
SectionLabel,
|
SectionLabel,
|
||||||
ColorSwatchGrid,
|
ColorSwatchGrid,
|
||||||
PresetButtonGrid,
|
PresetButtonGrid,
|
||||||
|
NumericUnitInput,
|
||||||
|
CollapsibleSection,
|
||||||
|
SpacingControl,
|
||||||
|
SpacingSide,
|
||||||
|
BorderControl,
|
||||||
|
BorderValue,
|
||||||
|
buildBorderShorthand,
|
||||||
|
AnimationControl,
|
||||||
|
VisibilityControl,
|
||||||
|
sectionGap,
|
||||||
|
labelStyle,
|
||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
|
|
||||||
|
/* Text-transform is a small fixed enum with no natural home in the shared
|
||||||
|
foundation presets (constants/presets.ts is import-only for this
|
||||||
|
package), so it lives here as a package-local preset list. */
|
||||||
|
const TEXT_TRANSFORMS: { label: string; value: string }[] = [
|
||||||
|
{ label: 'None', value: 'none' },
|
||||||
|
{ label: 'UPPER', value: 'uppercase' },
|
||||||
|
{ label: 'lower', value: 'lowercase' },
|
||||||
|
{ label: 'Capitalize', value: 'capitalize' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function capitalize(s: string): string {
|
||||||
|
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parses a `border` shorthand string (e.g. "2px solid #ff0000") back into
|
||||||
|
* the {width,style,color} shape BorderControl edits. Only needs to
|
||||||
|
* round-trip values this same panel produced via buildBorderShorthand. */
|
||||||
|
function parseBorderShorthand(v: string | undefined): BorderValue {
|
||||||
|
if (!v || v === 'none') return { width: '', style: 'none', color: '#000000' };
|
||||||
|
const m = String(v).trim().match(/^(\d+(?:\.\d+)?(?:px|em|rem)?)\s+(\w+)\s+(.+)$/);
|
||||||
|
if (!m) return { width: '', style: 'none', color: '#000000' };
|
||||||
|
return { width: m[1], style: m[2], color: m[3] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** style.opacity is a CSS-length-free numeric string ("0.8") or blank
|
||||||
|
* (treated as fully opaque). Converts to a 0-100 integer for the UI. */
|
||||||
|
function opacityPercent(v: unknown): number {
|
||||||
|
if (v === undefined || v === null || v === '') return 100;
|
||||||
|
const n = parseFloat(String(v));
|
||||||
|
return Number.isFinite(n) ? Math.round(n * 100) : 100;
|
||||||
|
}
|
||||||
|
|
||||||
/* ---------- TEXT ---------- */
|
/* ---------- TEXT ---------- */
|
||||||
export const TextStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
export const TextStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||||
const style: CSSProperties = nodeProps.style || {};
|
const style: CSSProperties = nodeProps.style || {};
|
||||||
|
|
||||||
const { setPropStyle } = useNodeProp(selectedId);
|
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||||
|
|
||||||
|
const isItalic = style.fontStyle === 'italic';
|
||||||
|
const isUnderline = style.textDecoration === 'underline';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -44,6 +93,15 @@ export const TextStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProp
|
|||||||
activeValue={style.fontSize as string}
|
activeValue={style.fontSize as string}
|
||||||
onSelect={(v) => setPropStyle('fontSize', v)}
|
onSelect={(v) => setPropStyle('fontSize', v)}
|
||||||
/>
|
/>
|
||||||
|
<div style={{ marginTop: 6 }}>
|
||||||
|
<NumericUnitInput
|
||||||
|
value={TEXT_SIZES.some((p) => p.value === style.fontSize) ? '' : ((style.fontSize as string) || '')}
|
||||||
|
onChange={(v) => setPropStyle('fontSize', v)}
|
||||||
|
units={['px', 'em', 'rem', '%']}
|
||||||
|
placeholder="custom"
|
||||||
|
testId="text-fontsize-custom"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="guided-section">
|
<div className="guided-section">
|
||||||
<SectionLabel>Font Weight</SectionLabel>
|
<SectionLabel>Font Weight</SectionLabel>
|
||||||
@@ -53,6 +111,53 @@ export const TextStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProp
|
|||||||
onSelect={(v) => setPropStyle('fontWeight', v)}
|
onSelect={(v) => setPropStyle('fontWeight', v)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Style</SectionLabel>
|
||||||
|
<div style={{ display: 'flex', gap: 6 }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`preset-btn ${isItalic ? 'active' : ''}`}
|
||||||
|
style={{ flex: 1, fontStyle: 'italic' }}
|
||||||
|
onClick={() => setPropStyle('fontStyle', isItalic ? 'normal' : 'italic')}
|
||||||
|
title="Italic"
|
||||||
|
>
|
||||||
|
<i className="fa fa-italic" /> Italic
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`preset-btn ${isUnderline ? 'active' : ''}`}
|
||||||
|
style={{ flex: 1, textDecoration: 'underline' }}
|
||||||
|
onClick={() => setPropStyle('textDecoration', isUnderline ? 'none' : 'underline')}
|
||||||
|
title="Underline"
|
||||||
|
>
|
||||||
|
<i className="fa fa-underline" /> Underline
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Text Transform</SectionLabel>
|
||||||
|
<PresetButtonGrid
|
||||||
|
presets={TEXT_TRANSFORMS}
|
||||||
|
activeValue={(style.textTransform as string) || 'none'}
|
||||||
|
onSelect={(v) => setPropStyle('textTransform', v === 'none' ? '' : v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Line Height</SectionLabel>
|
||||||
|
<PresetButtonGrid
|
||||||
|
presets={LINE_HEIGHTS}
|
||||||
|
activeValue={String(style.lineHeight || '')}
|
||||||
|
onSelect={(v) => setPropStyle('lineHeight', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Letter Spacing</SectionLabel>
|
||||||
|
<PresetButtonGrid
|
||||||
|
presets={LETTER_SPACINGS}
|
||||||
|
activeValue={String(style.letterSpacing || '')}
|
||||||
|
onSelect={(v) => setPropStyle('letterSpacing', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div className="guided-section">
|
<div className="guided-section">
|
||||||
<SectionLabel>Alignment</SectionLabel>
|
<SectionLabel>Alignment</SectionLabel>
|
||||||
<div className="preset-grid align-grid">
|
<div className="preset-grid align-grid">
|
||||||
@@ -68,6 +173,59 @@ export const TextStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProp
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Box model + border/effects + animation/visibility rollout */}
|
||||||
|
<CollapsibleSection title="Spacing" defaultOpen={false}>
|
||||||
|
<SpacingControl
|
||||||
|
label="Margin"
|
||||||
|
value={{ top: style.marginTop as string, right: style.marginRight as string, bottom: style.marginBottom as string, left: style.marginLeft as string }}
|
||||||
|
onChange={(side: SpacingSide, v: string) => setPropStyle(`margin${capitalize(side)}`, v)}
|
||||||
|
/>
|
||||||
|
<SpacingControl
|
||||||
|
label="Padding"
|
||||||
|
value={{ top: style.paddingTop as string, right: style.paddingRight as string, bottom: style.paddingBottom as string, left: style.paddingLeft as string }}
|
||||||
|
onChange={(side: SpacingSide, v: string) => setPropStyle(`padding${capitalize(side)}`, v)}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
|
<CollapsibleSection title="Border & Effects" defaultOpen={false}>
|
||||||
|
<BorderControl
|
||||||
|
value={parseBorderShorthand(style.border as string)}
|
||||||
|
onChange={(v) => setPropStyle('border', buildBorderShorthand(v))}
|
||||||
|
/>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Shadow</SectionLabel>
|
||||||
|
<PresetButtonGrid presets={SHADOW_PRESETS} activeValue={style.boxShadow as string} onSelect={(v) => setPropStyle('boxShadow', v)} />
|
||||||
|
</div>
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<label style={labelStyle}>Opacity: {opacityPercent(style.opacity)}%</label>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
value={opacityPercent(style.opacity)}
|
||||||
|
onChange={(e) => setPropStyle('opacity', String(Number(e.target.value) / 100))}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CollapsibleSection>
|
||||||
|
<CollapsibleSection title="Animation & Visibility" defaultOpen={false}>
|
||||||
|
<AnimationControl
|
||||||
|
value={{ animation: nodeProps.animation || 'none', animationDelay: nodeProps.animationDelay }}
|
||||||
|
onChange={(v) => { setProp('animation', v.animation); setProp('animationDelay', v.animationDelay); }}
|
||||||
|
/>
|
||||||
|
<VisibilityControl
|
||||||
|
value={{
|
||||||
|
hideOnDesktop: nodeProps.hideOnDesktop,
|
||||||
|
hideOnTablet: nodeProps.hideOnTablet,
|
||||||
|
hideOnMobile: nodeProps.hideOnMobile,
|
||||||
|
}}
|
||||||
|
onChange={(v) => {
|
||||||
|
setProp('hideOnDesktop', !!v.hideOnDesktop);
|
||||||
|
setProp('hideOnTablet', !!v.hideOnTablet);
|
||||||
|
setProp('hideOnMobile', !!v.hideOnMobile);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { SHADOW_PRESETS } from '../../../constants/presets';
|
||||||
|
import {
|
||||||
|
SectionLabel,
|
||||||
|
PresetButtonGrid,
|
||||||
|
CollapsibleSection,
|
||||||
|
SpacingControl,
|
||||||
|
SpacingSide,
|
||||||
|
BorderControl,
|
||||||
|
BorderValue,
|
||||||
|
buildBorderShorthand,
|
||||||
|
AnimationControl,
|
||||||
|
VisibilityControl,
|
||||||
|
sectionGap,
|
||||||
|
labelStyle,
|
||||||
|
} from './shared';
|
||||||
|
|
||||||
|
/* ==========================================================================
|
||||||
|
Shared box-model / border+effects / animation+visibility sections for the
|
||||||
|
MEDIA package's panels (ImageStylePanel + MediaStylePanel). Kept local to
|
||||||
|
this package (not in shared.tsx, which is foundation/import-only) since
|
||||||
|
it's just DRY-ing the identical JSX block across ImageBlock/VideoBlock/
|
||||||
|
Gallery/ContentSlider/MapEmbed rather than a genuinely cross-package
|
||||||
|
reusable control.
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
function capitalize(s: string): string {
|
||||||
|
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parses a `border` shorthand string (e.g. "2px solid #ff0000") back into
|
||||||
|
* the {width,style,color} shape BorderControl edits. Only needs to
|
||||||
|
* round-trip values this same panel produced via buildBorderShorthand --
|
||||||
|
* not arbitrary author-supplied CSS. */
|
||||||
|
export function parseBorderShorthand(v: string | undefined): BorderValue {
|
||||||
|
if (!v || v === 'none') return { width: '', style: 'none', color: '#000000' };
|
||||||
|
const m = String(v).trim().match(/^(\d+(?:\.\d+)?(?:px|em|rem)?)\s+(\w+)\s+(.+)$/);
|
||||||
|
if (!m) return { width: '', style: 'none', color: '#000000' };
|
||||||
|
return { width: m[1], style: m[2], color: m[3] };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BoxModelSectionProps {
|
||||||
|
style: Record<string, any>;
|
||||||
|
setPropStyle: (prop: string, value: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Margin + Padding, per-side, via the shared SpacingControl. */
|
||||||
|
export const BoxModelSection: React.FC<BoxModelSectionProps> = ({ style, setPropStyle }) => {
|
||||||
|
const sideSetter = (kind: 'margin' | 'padding') => (side: SpacingSide, value: string) =>
|
||||||
|
setPropStyle(`${kind}${capitalize(side)}`, value);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CollapsibleSection title="Spacing" defaultOpen={false}>
|
||||||
|
<SpacingControl
|
||||||
|
label="Margin"
|
||||||
|
value={{ top: style.marginTop, right: style.marginRight, bottom: style.marginBottom, left: style.marginLeft }}
|
||||||
|
onChange={sideSetter('margin')}
|
||||||
|
/>
|
||||||
|
<SpacingControl
|
||||||
|
label="Padding"
|
||||||
|
value={{ top: style.paddingTop, right: style.paddingRight, bottom: style.paddingBottom, left: style.paddingLeft }}
|
||||||
|
onChange={sideSetter('padding')}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** style.opacity is stored as a CSS-length-free numeric string ("0.8") or
|
||||||
|
* may be blank/undefined (treated as fully opaque). Converts to a 0-100
|
||||||
|
* integer for the range input / label. */
|
||||||
|
function opacityPercent(v: unknown): number {
|
||||||
|
if (v === undefined || v === null || v === '') return 100;
|
||||||
|
const n = parseFloat(String(v));
|
||||||
|
return Number.isFinite(n) ? Math.round(n * 100) : 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BorderEffectsSectionProps {
|
||||||
|
style: Record<string, any>;
|
||||||
|
setPropStyle: (prop: string, value: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Border (width/style/color) + box-shadow preset + opacity slider. */
|
||||||
|
export const BorderEffectsSection: React.FC<BorderEffectsSectionProps> = ({ style, setPropStyle }) => (
|
||||||
|
<CollapsibleSection title="Border & Effects" defaultOpen={false}>
|
||||||
|
<BorderControl
|
||||||
|
value={parseBorderShorthand(style.border)}
|
||||||
|
onChange={(v) => setPropStyle('border', buildBorderShorthand(v))}
|
||||||
|
/>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Shadow</SectionLabel>
|
||||||
|
<PresetButtonGrid presets={SHADOW_PRESETS} activeValue={style.boxShadow} onSelect={(v) => setPropStyle('boxShadow', v)} />
|
||||||
|
</div>
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<label style={labelStyle}>Opacity: {opacityPercent(style.opacity)}%</label>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
value={opacityPercent(style.opacity)}
|
||||||
|
onChange={(e) => setPropStyle('opacity', String(Number(e.target.value) / 100))}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CollapsibleSection>
|
||||||
|
);
|
||||||
|
|
||||||
|
export interface AnimVisSectionProps {
|
||||||
|
nodeProps: Record<string, any>;
|
||||||
|
setProp: (key: string, value: any) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Entrance animation + responsive hide toggles -- top-level props consumed
|
||||||
|
* directly by html-export.ts's buildDataAttrs (no toHtml change needed). */
|
||||||
|
export const AnimVisSection: React.FC<AnimVisSectionProps> = ({ nodeProps, setProp }) => (
|
||||||
|
<CollapsibleSection title="Animation & Visibility" defaultOpen={false}>
|
||||||
|
<AnimationControl
|
||||||
|
value={{ animation: nodeProps.animation || 'none', animationDelay: nodeProps.animationDelay }}
|
||||||
|
onChange={(v) => { setProp('animation', v.animation); setProp('animationDelay', v.animationDelay); }}
|
||||||
|
/>
|
||||||
|
<VisibilityControl
|
||||||
|
value={{
|
||||||
|
hideOnDesktop: nodeProps.hideOnDesktop,
|
||||||
|
hideOnTablet: nodeProps.hideOnTablet,
|
||||||
|
hideOnMobile: nodeProps.hideOnMobile,
|
||||||
|
}}
|
||||||
|
onChange={(v) => {
|
||||||
|
setProp('hideOnDesktop', !!v.hideOnDesktop);
|
||||||
|
setProp('hideOnTablet', !!v.hideOnTablet);
|
||||||
|
setProp('hideOnMobile', !!v.hideOnMobile);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
|
);
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { describe, test, expect, vi, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { HeadCodeModal } from './HeadCodeModal';
|
||||||
|
import { SiteDesignProvider, useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
|
|
||||||
|
/* ---------- DOM test harness -- same react-dom/client + `act` pattern used
|
||||||
|
throughout src/ui/*.test.tsx (no @testing-library/react in this repo). ---------- */
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (container) {
|
||||||
|
act(() => { root.unmount(); });
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
document.body.style.overflow = '';
|
||||||
|
});
|
||||||
|
|
||||||
|
// Exposes the current headCode so assertions can read it back after a
|
||||||
|
// simulated edit -- CodeEditor writes through `updateDesign`, this just
|
||||||
|
// surfaces the result.
|
||||||
|
function Harness({ onReady }: { onReady: (headCode: string) => void }) {
|
||||||
|
const { design } = useSiteDesign();
|
||||||
|
onReady(design.headCode);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('HeadCodeModal', () => {
|
||||||
|
// HeadCodeModal portals its content to document.body (see the comment in
|
||||||
|
// HeadCodeModal.tsx), so the rendered DOM lives outside `container` --
|
||||||
|
// query document.body instead.
|
||||||
|
|
||||||
|
test('renders the CodeEditor (fallback textarea path) seeded with the current headCode', () => {
|
||||||
|
render(
|
||||||
|
<SiteDesignProvider>
|
||||||
|
<HeadCodeModal open onClose={vi.fn()} />
|
||||||
|
</SiteDesignProvider>,
|
||||||
|
);
|
||||||
|
// CodeMirror loads via async dynamic import (see CodeEditor.test.tsx);
|
||||||
|
// synchronously after mount the fallback textarea is what's live.
|
||||||
|
const textarea = document.body.querySelector<HTMLTextAreaElement>('[data-testid="code-editor-fallback"]');
|
||||||
|
expect(textarea).not.toBeNull();
|
||||||
|
expect(textarea!.value).toBe('');
|
||||||
|
expect(textarea!.dataset.language).toBe('html');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('typing in the editor writes through to SiteDesignContext.headCode', () => {
|
||||||
|
let latestHeadCode = '';
|
||||||
|
render(
|
||||||
|
<SiteDesignProvider>
|
||||||
|
<HeadCodeModal open onClose={vi.fn()} />
|
||||||
|
<Harness onReady={(v) => { latestHeadCode = v; }} />
|
||||||
|
</SiteDesignProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const textarea = document.body.querySelector<HTMLTextAreaElement>('[data-testid="code-editor-fallback"]')!;
|
||||||
|
act(() => {
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')!.set!;
|
||||||
|
setter.call(textarea, '<meta name="x" content="y">');
|
||||||
|
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(latestHeadCode).toBe('<meta name="x" content="y">');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not render when closed', () => {
|
||||||
|
render(
|
||||||
|
<SiteDesignProvider>
|
||||||
|
<HeadCodeModal open={false} onClose={vi.fn()} />
|
||||||
|
</SiteDesignProvider>,
|
||||||
|
);
|
||||||
|
expect(document.body.querySelector('[data-testid="code-editor-fallback"]')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,6 +2,7 @@ import React from 'react';
|
|||||||
import { createPortal } from 'react-dom';
|
import { createPortal } from 'react-dom';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
import { Modal } from '../../ui/Modal';
|
import { Modal } from '../../ui/Modal';
|
||||||
|
import { CodeEditor } from '../../ui/CodeEditor';
|
||||||
|
|
||||||
interface HeadCodeModalProps {
|
interface HeadCodeModalProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -55,28 +56,16 @@ export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) =
|
|||||||
Code added here will be injected into the <code style={{ background: 'rgba(255,255,255,0.08)', padding: '1px 4px', borderRadius: 3, fontSize: 11 }}><head></code> of every page on your site. Use it for analytics, custom fonts, or global CSS.
|
Code added here will be injected into the <code style={{ background: 'rgba(255,255,255,0.08)', padding: '1px 4px', borderRadius: 3, fontSize: 11 }}><head></code> of every page on your site. Use it for analytics, custom fonts, or global CSS.
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<textarea
|
<div style={{ flex: 1, minHeight: 300 }}>
|
||||||
|
<CodeEditor
|
||||||
value={design.headCode || ''}
|
value={design.headCode || ''}
|
||||||
onChange={(e) => updateDesign({ headCode: e.target.value })}
|
onChange={(code) => updateDesign({ headCode: code })}
|
||||||
|
language="html"
|
||||||
|
height="100%"
|
||||||
placeholder={"<!-- Google Analytics -->\n<script async src=\"https://...\"></script>\n\n<!-- Custom Fonts -->\n<link href=\"https://fonts.googleapis.com/...\" rel=\"stylesheet\">\n\n<style>\n /* Global CSS overrides */\n body { }\n</style>"}
|
placeholder={"<!-- Google Analytics -->\n<script async src=\"https://...\"></script>\n\n<!-- Custom Fonts -->\n<link href=\"https://fonts.googleapis.com/...\" rel=\"stylesheet\">\n\n<style>\n /* Global CSS overrides */\n body { }\n</style>"}
|
||||||
style={{
|
|
||||||
flex: 1,
|
|
||||||
minHeight: 300,
|
|
||||||
padding: 14,
|
|
||||||
background: '#0d0d0f',
|
|
||||||
color: '#e4e4e7',
|
|
||||||
border: '1px solid #3f3f46',
|
|
||||||
borderRadius: 8,
|
|
||||||
fontFamily: 'Source Code Pro, Consolas, monospace',
|
|
||||||
fontSize: 13,
|
|
||||||
lineHeight: 1.6,
|
|
||||||
resize: 'vertical',
|
|
||||||
outline: 'none',
|
|
||||||
tabSize: 2,
|
|
||||||
}}
|
|
||||||
spellCheck={false}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Footer */}
|
{/* Footer */}
|
||||||
<div style={{
|
<div style={{
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import { describe, test, expect, vi, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { CodeEditor } from './CodeEditor';
|
||||||
|
|
||||||
|
/* ---------- DOM test harness (no @testing-library/react in this repo; see
|
||||||
|
src/ui/AssetPicker.test.tsx / src/ui/Modal.test.tsx for the same
|
||||||
|
react-dom/client + react-dom/test-utils `act` pattern). ----------
|
||||||
|
|
||||||
|
CodeMirror is loaded via dynamic import() (see CodeEditor.tsx), which is
|
||||||
|
always async -- even for an already-resolved/cached module, `import()`
|
||||||
|
only settles on a later microtask. That means immediately after the
|
||||||
|
initial synchronous `act(() => root.render(...))` below, the component is
|
||||||
|
still in its 'loading' state and renders the <textarea> fallback. These
|
||||||
|
tests deliberately assert against that first-tick DOM (never awaiting
|
||||||
|
the CodeMirror promise), so they exercise exactly the fallback path a
|
||||||
|
real headless/offline environment would fall back to, deterministically
|
||||||
|
and without needing to mock @codemirror/*. */
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (container) {
|
||||||
|
act(() => { root.unmount(); });
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function fallbackTextarea(): HTMLTextAreaElement {
|
||||||
|
const el = container.querySelector<HTMLTextAreaElement>('[data-testid="code-editor-fallback"]');
|
||||||
|
if (!el) throw new Error('fallback textarea not found');
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('CodeEditor', () => {
|
||||||
|
test('shows the textarea fallback immediately (CodeMirror loads async)', () => {
|
||||||
|
render(<CodeEditor value="<p>hi</p>" onChange={vi.fn()} />);
|
||||||
|
const textarea = fallbackTextarea();
|
||||||
|
expect(textarea.value).toBe('<p>hi</p>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the CodeMirror mount root is hidden while the fallback is showing', () => {
|
||||||
|
render(<CodeEditor value="" onChange={vi.fn()} />);
|
||||||
|
const cmRoot = container.querySelector<HTMLDivElement>('[data-testid="code-editor-cm-root"]');
|
||||||
|
expect(cmRoot?.style.display).toBe('none');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onChange fires with the new value when typing in the fallback textarea', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<CodeEditor value="<p>hi</p>" onChange={onChange} />);
|
||||||
|
const textarea = fallbackTextarea();
|
||||||
|
act(() => {
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')!.set!;
|
||||||
|
setter.call(textarea, '<p>updated</p>');
|
||||||
|
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
});
|
||||||
|
expect(onChange).toHaveBeenCalledWith('<p>updated</p>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts a language prop without throwing (html/css/javascript/auto)', () => {
|
||||||
|
for (const language of ['html', 'css', 'javascript', 'auto'] as const) {
|
||||||
|
expect(() => render(<CodeEditor value="" onChange={vi.fn()} language={language} />)).not.toThrow();
|
||||||
|
const textarea = fallbackTextarea();
|
||||||
|
expect(textarea.dataset.language).toBe(language);
|
||||||
|
act(() => { root.unmount(); });
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('defaults to html language when none is passed', () => {
|
||||||
|
render(<CodeEditor value="" onChange={vi.fn()} />);
|
||||||
|
expect(fallbackTextarea().dataset.language).toBe('html');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('respects a custom height', () => {
|
||||||
|
render(<CodeEditor value="" onChange={vi.fn()} height={480} />);
|
||||||
|
expect((container.firstElementChild as HTMLElement).style.height).toBe('480px');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
import React, { useEffect, useRef, useState } from 'react';
|
||||||
|
import type { EditorView as EditorViewType } from '@codemirror/view';
|
||||||
|
|
||||||
|
export type CodeEditorLanguage = 'html' | 'css' | 'javascript' | 'auto';
|
||||||
|
|
||||||
|
export interface CodeEditorProps {
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
/** 'auto' behaves like 'html' -- the HTML language mode already highlights
|
||||||
|
* embedded <script>/<style> blocks, which covers the common "auto" case
|
||||||
|
* of mixed markup. */
|
||||||
|
language?: CodeEditorLanguage;
|
||||||
|
height?: number | string;
|
||||||
|
placeholder?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------------------------------------
|
||||||
|
Lazy-loaded CodeMirror 6.
|
||||||
|
|
||||||
|
All @codemirror/* packages are pulled in via dynamic import() so they
|
||||||
|
land in their own chunk(s) (see vite.config.ts chunkFileNames) instead of
|
||||||
|
bloating the main editor.js bundle -- most sessions never open a code
|
||||||
|
editor. The module set is fetched once (module-level promise, shared
|
||||||
|
across every CodeEditor instance on the page) and cached forever.
|
||||||
|
|
||||||
|
While the import is in flight -- or if it ever fails (offline, CDN
|
||||||
|
hiccup, an environment where CodeMirror can't mount e.g. some headless
|
||||||
|
test runners) -- callers get a plain <textarea> so editing never breaks,
|
||||||
|
just loses syntax highlighting/autocomplete.
|
||||||
|
---------------------------------------------------------------- */
|
||||||
|
|
||||||
|
interface CmModules {
|
||||||
|
EditorState: typeof import('@codemirror/state').EditorState;
|
||||||
|
EditorView: typeof import('@codemirror/view').EditorView;
|
||||||
|
keymap: typeof import('@codemirror/view').keymap;
|
||||||
|
lineNumbers: typeof import('@codemirror/view').lineNumbers;
|
||||||
|
highlightActiveLine: typeof import('@codemirror/view').highlightActiveLine;
|
||||||
|
highlightActiveLineGutter: typeof import('@codemirror/view').highlightActiveLineGutter;
|
||||||
|
drawSelection: typeof import('@codemirror/view').drawSelection;
|
||||||
|
defaultKeymap: typeof import('@codemirror/commands').defaultKeymap;
|
||||||
|
history: typeof import('@codemirror/commands').history;
|
||||||
|
historyKeymap: typeof import('@codemirror/commands').historyKeymap;
|
||||||
|
indentWithTab: typeof import('@codemirror/commands').indentWithTab;
|
||||||
|
syntaxHighlighting: typeof import('@codemirror/language').syntaxHighlighting;
|
||||||
|
defaultHighlightStyle: typeof import('@codemirror/language').defaultHighlightStyle;
|
||||||
|
bracketMatching: typeof import('@codemirror/language').bracketMatching;
|
||||||
|
indentOnInput: typeof import('@codemirror/language').indentOnInput;
|
||||||
|
foldGutter: typeof import('@codemirror/language').foldGutter;
|
||||||
|
autocompletion: typeof import('@codemirror/autocomplete').autocompletion;
|
||||||
|
completionKeymap: typeof import('@codemirror/autocomplete').completionKeymap;
|
||||||
|
closeBrackets: typeof import('@codemirror/autocomplete').closeBrackets;
|
||||||
|
closeBracketsKeymap: typeof import('@codemirror/autocomplete').closeBracketsKeymap;
|
||||||
|
html: typeof import('@codemirror/lang-html').html;
|
||||||
|
css: typeof import('@codemirror/lang-css').css;
|
||||||
|
javascript: typeof import('@codemirror/lang-javascript').javascript;
|
||||||
|
oneDark: typeof import('@codemirror/theme-one-dark').oneDark;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cmModulesPromise: Promise<CmModules> | null = null;
|
||||||
|
|
||||||
|
function loadCodeMirror(): Promise<CmModules> {
|
||||||
|
if (!cmModulesPromise) {
|
||||||
|
cmModulesPromise = Promise.all([
|
||||||
|
import('@codemirror/state'),
|
||||||
|
import('@codemirror/view'),
|
||||||
|
import('@codemirror/commands'),
|
||||||
|
import('@codemirror/language'),
|
||||||
|
import('@codemirror/autocomplete'),
|
||||||
|
import('@codemirror/lang-html'),
|
||||||
|
import('@codemirror/lang-css'),
|
||||||
|
import('@codemirror/lang-javascript'),
|
||||||
|
import('@codemirror/theme-one-dark'),
|
||||||
|
]).then(([state, view, commands, language, autocomplete, langHtml, langCss, langJs, theme]) => ({
|
||||||
|
EditorState: state.EditorState,
|
||||||
|
EditorView: view.EditorView,
|
||||||
|
keymap: view.keymap,
|
||||||
|
lineNumbers: view.lineNumbers,
|
||||||
|
highlightActiveLine: view.highlightActiveLine,
|
||||||
|
highlightActiveLineGutter: view.highlightActiveLineGutter,
|
||||||
|
drawSelection: view.drawSelection,
|
||||||
|
defaultKeymap: commands.defaultKeymap,
|
||||||
|
history: commands.history,
|
||||||
|
historyKeymap: commands.historyKeymap,
|
||||||
|
indentWithTab: commands.indentWithTab,
|
||||||
|
syntaxHighlighting: language.syntaxHighlighting,
|
||||||
|
defaultHighlightStyle: language.defaultHighlightStyle,
|
||||||
|
bracketMatching: language.bracketMatching,
|
||||||
|
indentOnInput: language.indentOnInput,
|
||||||
|
foldGutter: language.foldGutter,
|
||||||
|
autocompletion: autocomplete.autocompletion,
|
||||||
|
completionKeymap: autocomplete.completionKeymap,
|
||||||
|
closeBrackets: autocomplete.closeBrackets,
|
||||||
|
closeBracketsKeymap: autocomplete.closeBracketsKeymap,
|
||||||
|
html: langHtml.html,
|
||||||
|
css: langCss.css,
|
||||||
|
javascript: langJs.javascript,
|
||||||
|
oneDark: theme.oneDark,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
return cmModulesPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
function languageExtension(mods: CmModules, language: CodeEditorLanguage) {
|
||||||
|
switch (language) {
|
||||||
|
case 'css':
|
||||||
|
return mods.css();
|
||||||
|
case 'javascript':
|
||||||
|
return mods.javascript();
|
||||||
|
case 'html':
|
||||||
|
case 'auto':
|
||||||
|
default:
|
||||||
|
// lang-html already highlights + completes embedded <script>/<style>
|
||||||
|
// blocks as JS/CSS, which is exactly what "auto" wants for mixed
|
||||||
|
// HTML snippets (head code, HTML blocks).
|
||||||
|
return mods.html({ autoCloseTags: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fallbackStyle: React.CSSProperties = {
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
padding: 14,
|
||||||
|
background: '#0d0d0f',
|
||||||
|
color: '#e4e4e7',
|
||||||
|
border: '1px solid #3f3f46',
|
||||||
|
borderRadius: 8,
|
||||||
|
fontFamily: 'Source Code Pro, Consolas, monospace',
|
||||||
|
fontSize: 13,
|
||||||
|
lineHeight: 1.6,
|
||||||
|
resize: 'none',
|
||||||
|
outline: 'none',
|
||||||
|
tabSize: 2,
|
||||||
|
boxSizing: 'border-box',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const CodeEditor: React.FC<CodeEditorProps> = ({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
language = 'html',
|
||||||
|
height = 320,
|
||||||
|
placeholder,
|
||||||
|
}) => {
|
||||||
|
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const viewRef = useRef<EditorViewType | null>(null);
|
||||||
|
const onChangeRef = useRef(onChange);
|
||||||
|
onChangeRef.current = onChange;
|
||||||
|
// Tracks the last value this component itself emitted, so the
|
||||||
|
// value-sync effect below doesn't stomp on in-progress typing when the
|
||||||
|
// parent re-renders with the exact same string it was just handed.
|
||||||
|
const lastEmittedRef = useRef(value);
|
||||||
|
const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
setStatus('loading');
|
||||||
|
|
||||||
|
loadCodeMirror()
|
||||||
|
.then((mods) => {
|
||||||
|
if (cancelled || !containerRef.current) return;
|
||||||
|
const updateListener = mods.EditorView.updateListener.of((update) => {
|
||||||
|
if (update.docChanged) {
|
||||||
|
const next = update.state.doc.toString();
|
||||||
|
lastEmittedRef.current = next;
|
||||||
|
onChangeRef.current(next);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const state = mods.EditorState.create({
|
||||||
|
doc: value,
|
||||||
|
extensions: [
|
||||||
|
mods.lineNumbers(),
|
||||||
|
mods.highlightActiveLineGutter(),
|
||||||
|
mods.highlightActiveLine(),
|
||||||
|
mods.history(),
|
||||||
|
mods.foldGutter(),
|
||||||
|
mods.drawSelection(),
|
||||||
|
mods.indentOnInput(),
|
||||||
|
mods.syntaxHighlighting(mods.defaultHighlightStyle, { fallback: true }),
|
||||||
|
mods.bracketMatching(),
|
||||||
|
mods.closeBrackets(),
|
||||||
|
mods.autocompletion(),
|
||||||
|
mods.keymap.of([
|
||||||
|
...mods.closeBracketsKeymap,
|
||||||
|
...mods.historyKeymap,
|
||||||
|
...mods.completionKeymap,
|
||||||
|
...mods.defaultKeymap,
|
||||||
|
mods.indentWithTab,
|
||||||
|
]),
|
||||||
|
languageExtension(mods, language),
|
||||||
|
mods.oneDark,
|
||||||
|
mods.EditorView.lineWrapping,
|
||||||
|
updateListener,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const view = new mods.EditorView({ state, parent: containerRef.current });
|
||||||
|
viewRef.current = view;
|
||||||
|
setStatus('ready');
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error('CodeEditor: CodeMirror failed to load, falling back to a plain textarea', err);
|
||||||
|
if (!cancelled) setStatus('error');
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
viewRef.current?.destroy();
|
||||||
|
viewRef.current = null;
|
||||||
|
};
|
||||||
|
// Re-mount on language change (language is fixed for HTML/CSS/JS
|
||||||
|
// targets in this app -- it never flips on an already-open editor --
|
||||||
|
// but re-creating cleanly if it ever does is simpler/safer than trying
|
||||||
|
// to reconfigure the LanguageSupport extension in place).
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [language]);
|
||||||
|
|
||||||
|
// Keep the live CodeMirror doc in sync if `value` changes from outside
|
||||||
|
// (e.g. the modal is reused for a different field) without clobbering
|
||||||
|
// the cursor position/selection on every keystroke-driven re-render.
|
||||||
|
useEffect(() => {
|
||||||
|
const view = viewRef.current;
|
||||||
|
if (!view || status !== 'ready') return;
|
||||||
|
if (value === lastEmittedRef.current) return;
|
||||||
|
const current = view.state.doc.toString();
|
||||||
|
if (current === value) return;
|
||||||
|
view.dispatch({ changes: { from: 0, to: current.length, insert: value } });
|
||||||
|
lastEmittedRef.current = value;
|
||||||
|
}, [value, status]);
|
||||||
|
|
||||||
|
const showFallback = status !== 'ready';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ position: 'relative', height, minHeight: height }}>
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
data-testid="code-editor-cm-root"
|
||||||
|
style={{
|
||||||
|
height: '100%',
|
||||||
|
overflow: 'auto',
|
||||||
|
borderRadius: 8,
|
||||||
|
border: '1px solid #3f3f46',
|
||||||
|
display: showFallback ? 'none' : 'block',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{showFallback && (
|
||||||
|
<textarea
|
||||||
|
data-testid="code-editor-fallback"
|
||||||
|
data-language={language}
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
placeholder={status === 'loading' ? (placeholder || 'Loading editor…') : placeholder}
|
||||||
|
spellCheck={false}
|
||||||
|
style={fallbackStyle}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user