Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88df4f2888 |
@@ -30,46 +30,3 @@ describe('SearchBar.toHtml XSS hardening (placeholder/buttonText/showButton)', (
|
||||
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,29 +1,19 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr } from '../../utils/escape';
|
||||
|
||||
interface SearchBarProps {
|
||||
placeholder?: string;
|
||||
buttonText?: string;
|
||||
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;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
export const SearchBar: UserComponent<SearchBarProps> = ({
|
||||
placeholder = 'Search...',
|
||||
buttonText = 'Search',
|
||||
showButton = true,
|
||||
action = '/',
|
||||
style = {},
|
||||
}) => {
|
||||
const {
|
||||
@@ -37,8 +27,6 @@ export const SearchBar: UserComponent<SearchBarProps> = ({
|
||||
<form
|
||||
ref={(ref: HTMLFormElement | null): void => { if (ref) connect(drag(ref)); }}
|
||||
role="search"
|
||||
action={action}
|
||||
method="GET"
|
||||
onSubmit={(e) => e.preventDefault()}
|
||||
style={{
|
||||
display: 'flex',
|
||||
@@ -63,7 +51,6 @@ export const SearchBar: UserComponent<SearchBarProps> = ({
|
||||
/>
|
||||
<input
|
||||
type="search"
|
||||
name="q"
|
||||
placeholder={placeholder}
|
||||
style={{
|
||||
width: '100%',
|
||||
@@ -114,13 +101,7 @@ SearchBar.craft = {
|
||||
placeholder: 'Search...',
|
||||
buttonText: 'Search',
|
||||
showButton: true,
|
||||
action: '/',
|
||||
style: {},
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
@@ -136,7 +117,6 @@ SearchBar.craft = {
|
||||
placeholder = 'Search...',
|
||||
buttonText = 'Search',
|
||||
showButton = true,
|
||||
action = '/',
|
||||
style = {},
|
||||
} = props;
|
||||
|
||||
@@ -153,19 +133,11 @@ 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>`
|
||||
: '';
|
||||
|
||||
// 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 {
|
||||
html: `<form role="search" action="${actionAttr}" method="GET"${formStyle ? ` style="${formStyle}"` : ''}>
|
||||
html: `<form role="search"${formStyle ? ` style="${formStyle}"` : ''}>
|
||||
<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>
|
||||
<input type="search" name="q" placeholder="${escapeAttr(placeholder)}" style="${inputStyleStr}" />
|
||||
<input type="search" placeholder="${escapeAttr(placeholder)}" style="${inputStyleStr}" />
|
||||
</div>
|
||||
${btnHtml}
|
||||
</form>`,
|
||||
|
||||
@@ -126,73 +126,3 @@ describe('ContactForm.toHtml field type attribute sanitization', () => {
|
||||
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,17 +4,8 @@ import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||
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 {
|
||||
type: ContactFormFieldType;
|
||||
type: 'text' | 'email' | 'tel' | 'textarea' | 'select';
|
||||
label: string;
|
||||
name: string;
|
||||
placeholder: string;
|
||||
@@ -34,11 +25,6 @@ interface ContactFormProps {
|
||||
inputBorder?: string;
|
||||
recipientEmail?: string;
|
||||
thankYouUrl?: string;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
const defaultFields: ContactFormField[] = [
|
||||
@@ -171,11 +157,6 @@ ContactForm.craft = {
|
||||
inputBorder: '#d1d5db',
|
||||
recipientEmail: '',
|
||||
thankYouUrl: '',
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
|
||||
@@ -22,19 +22,4 @@ describe('FormButton.toHtml', () => {
|
||||
expect(html).toContain('&');
|
||||
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,11 +6,6 @@ import { escapeHtml } from '../../utils/escape';
|
||||
interface FormButtonProps {
|
||||
text?: string;
|
||||
style?: CSSProperties;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
export const FormButton: UserComponent<FormButtonProps> = ({
|
||||
@@ -63,11 +58,6 @@ FormButton.craft = {
|
||||
fontSize: '16px',
|
||||
border: 'none',
|
||||
},
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
|
||||
@@ -52,20 +52,3 @@ describe('FormContainer.toHtml method attribute sanitization', () => {
|
||||
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,11 +12,6 @@ interface FormContainerProps {
|
||||
thankYouUrl?: string;
|
||||
style?: CSSProperties;
|
||||
children?: React.ReactNode;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
export const FormContainer: UserComponent<FormContainerProps> = ({
|
||||
@@ -64,11 +59,6 @@ FormContainer.craft = {
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #e4e4e7',
|
||||
},
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
|
||||
@@ -72,20 +72,3 @@ describe('InputField.toHtml type attribute sanitization', () => {
|
||||
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,11 +10,6 @@ interface InputFieldProps {
|
||||
placeholder?: string;
|
||||
required?: boolean;
|
||||
style?: CSSProperties;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
export const InputField: UserComponent<InputFieldProps> = ({
|
||||
@@ -82,11 +77,6 @@ InputField.craft = {
|
||||
placeholder: 'Enter your name',
|
||||
required: false,
|
||||
style: {},
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
|
||||
@@ -6,7 +6,7 @@ const toHtml = (SubscribeForm as any).toHtml;
|
||||
describe('SubscribeForm.toHtml hardcoded attributes stay hardcoded (no raw prop breakout)', () => {
|
||||
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, '');
|
||||
expect(html).toMatch(/<form action="[^"]*" method="POST"/);
|
||||
expect(html).toContain('<form method="POST"');
|
||||
expect(html).not.toContain('<script');
|
||||
});
|
||||
|
||||
@@ -37,45 +37,3 @@ describe('SubscribeForm.toHtml hardcoded attributes stay hardcoded (no raw prop
|
||||
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,7 +1,6 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||
import { escapeHtml, escapeAttr } from '../../utils/escape';
|
||||
|
||||
interface SubscribeFormProps {
|
||||
@@ -11,17 +10,6 @@ interface SubscribeFormProps {
|
||||
buttonColor?: string;
|
||||
layout?: 'inline' | 'stacked';
|
||||
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> = ({
|
||||
@@ -122,13 +110,6 @@ SubscribeForm.craft = {
|
||||
buttonColor: '#3b82f6',
|
||||
layout: 'inline',
|
||||
style: { backgroundColor: '#f8fafc' },
|
||||
recipientEmail: '',
|
||||
thankYouUrl: '',
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
@@ -139,7 +120,7 @@ SubscribeForm.craft = {
|
||||
|
||||
/* ---------- HTML export ---------- */
|
||||
|
||||
(SubscribeForm as any).toHtml = (props: SubscribeFormProps, _childrenHtml: string, nodeId?: string) => {
|
||||
(SubscribeForm as any).toHtml = (props: SubscribeFormProps, _childrenHtml: string) => {
|
||||
const {
|
||||
heading = 'Subscribe to our newsletter',
|
||||
placeholder = 'Enter your email',
|
||||
@@ -185,21 +166,11 @@ SubscribeForm.craft = {
|
||||
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 {
|
||||
html: `${marker}<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>
|
||||
html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>
|
||||
${headingHtml}
|
||||
<form action="${actionAttr}" method="POST"${formStyle ? ` style="${formStyle}"` : ''}>
|
||||
${honeypot ? ` ${honeypot}\n` : ''} <input type="email" name="email" placeholder="${escapeAttr(placeholder)}" required style="${inputStyleStr}" />
|
||||
<form method="POST"${formStyle ? ` style="${formStyle}"` : ''}>
|
||||
<input type="email" name="email" placeholder="${escapeAttr(placeholder)}" required style="${inputStyleStr}" />
|
||||
<button type="submit"${btnStyle ? ` style="${btnStyle}"` : ''}>${escapeHtml(buttonText)}</button>
|
||||
</form>
|
||||
</div>`,
|
||||
|
||||
@@ -63,20 +63,3 @@ describe('TextareaField.toHtml rows attribute sanitization', () => {
|
||||
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,11 +10,6 @@ interface TextareaFieldProps {
|
||||
rows?: number;
|
||||
required?: boolean;
|
||||
style?: CSSProperties;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
export const TextareaField: UserComponent<TextareaFieldProps> = ({
|
||||
@@ -84,11 +79,6 @@ TextareaField.craft = {
|
||||
rows: 4,
|
||||
required: false,
|
||||
style: {},
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import React from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import {
|
||||
BG_COLORS,
|
||||
SPACING_PRESETS,
|
||||
RADIUS_PRESETS,
|
||||
SHADOW_PRESETS,
|
||||
} from '../../../constants/presets';
|
||||
import {
|
||||
StylePanelProps,
|
||||
@@ -12,152 +10,21 @@ import {
|
||||
ColorSwatchGrid,
|
||||
PresetButtonGrid,
|
||||
CollapsibleSection,
|
||||
ArrayPropEditor,
|
||||
SpacingControl,
|
||||
BorderControl,
|
||||
BorderValue,
|
||||
AnimationControl,
|
||||
VisibilityControl,
|
||||
buildBorderShorthand,
|
||||
labelStyle,
|
||||
inputStyle,
|
||||
smallInputStyle,
|
||||
btnActiveStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} 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 ---------- */
|
||||
export const FormStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const { actions } = useEditor();
|
||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
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 (
|
||||
<>
|
||||
{/* 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
|
||||
and FormContainer (both have recipientEmail/thankYouUrl props). */}
|
||||
{nodeProps.recipientEmail !== undefined && (
|
||||
@@ -176,35 +43,13 @@ export const FormStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProp
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Form action/method (FormContainer). SearchBar also has an `action`
|
||||
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 && (
|
||||
{/* Form action/method */}
|
||||
{nodeProps.action !== undefined && (
|
||||
<div style={sectionGap}>
|
||||
<label style={labelStyle}>Form Action URL</label>
|
||||
<input type="text" value={nodeProps.action || ''} onChange={(e) => setProp('action', e.target.value)} placeholder="https://..." style={inputStyle} />
|
||||
</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 && (
|
||||
<div style={sectionGap}>
|
||||
<label style={labelStyle}>Method</label>
|
||||
@@ -297,64 +142,6 @@ export const FormStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProp
|
||||
<PresetButtonGrid presets={RADIUS_PRESETS} activeValue={style.borderRadius as string} onSelect={(v) => setPropStyle('borderRadius', v)} />
|
||||
</div>
|
||||
</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 {
|
||||
TEXT_COLORS,
|
||||
BG_COLORS,
|
||||
@@ -17,12 +17,85 @@ import {
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
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) ---------- */
|
||||
export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Record<string, any>; typeName: string }> = ({
|
||||
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);
|
||||
|
||||
@@ -35,9 +108,15 @@ export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Recor
|
||||
const arrayProps = allProps.filter(([_, val]) => Array.isArray(val));
|
||||
|
||||
const style = nodeProps.style || {};
|
||||
const hasCodeProp = typeof nodeProps.code === 'string';
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Raw HTML (HtmlBlock's `code` prop) -- dedicated CodeEditor modal */}
|
||||
{hasCodeProp && (
|
||||
<HtmlCodeField value={nodeProps.code} onChange={(v) => setPropValue('code', v)} />
|
||||
)}
|
||||
|
||||
{/* String props */}
|
||||
{stringProps.length > 0 && (
|
||||
<CollapsibleSection title="Properties">
|
||||
|
||||
@@ -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 { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
import { Modal } from '../../ui/Modal';
|
||||
import { CodeEditor } from '../../ui/CodeEditor';
|
||||
|
||||
interface HeadCodeModalProps {
|
||||
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.
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
<div style={{ flex: 1, minHeight: 300 }}>
|
||||
<CodeEditor
|
||||
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>"}
|
||||
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>
|
||||
|
||||
{/* Footer */}
|
||||
<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