Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1b4ab735c |
@@ -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,
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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,4 +1,4 @@
|
|||||||
import React, { useState } from 'react';
|
import React from 'react';
|
||||||
import {
|
import {
|
||||||
TEXT_COLORS,
|
TEXT_COLORS,
|
||||||
BG_COLORS,
|
BG_COLORS,
|
||||||
@@ -17,85 +17,12 @@ 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', 'code']);
|
const SKIP_PROPS = new Set(['style', 'children', 'cssId', 'cssClass']);
|
||||||
|
|
||||||
const { setProp: setPropValue, setPropStyle: setStyleValue } = useNodeProp(selectedId);
|
const { setProp: setPropValue, setPropStyle: setStyleValue } = useNodeProp(selectedId);
|
||||||
|
|
||||||
@@ -108,15 +35,9 @@ 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">
|
||||||
|
|||||||
@@ -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>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,85 +0,0 @@
|
|||||||
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,7 +2,6 @@ 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;
|
||||||
@@ -56,16 +55,28 @@ 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>
|
||||||
|
|
||||||
<div style={{ flex: 1, minHeight: 300 }}>
|
<textarea
|
||||||
<CodeEditor
|
|
||||||
value={design.headCode || ''}
|
value={design.headCode || ''}
|
||||||
onChange={(code) => updateDesign({ headCode: code })}
|
onChange={(e) => updateDesign({ headCode: e.target.value })}
|
||||||
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={{
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
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');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,257 +0,0 @@
|
|||||||
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