Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a426e3513 | ||
|
|
9750a6c2bf |
@@ -80,3 +80,56 @@ describe('ColumnLayout.toHtml XSS hardening (gap into <style>)', () => {
|
||||
expect(html).toMatch(/calc\(50% - 24px\)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ColumnLayout.toHtml vertical alignment (align-items on the flex row)', () => {
|
||||
test('style.alignItems flows into the emitted style attribute (aligns uneven columns)', () => {
|
||||
const { html } = toHtml({ columns: 2, split: '50-50', gap: '16px', style: { alignItems: 'center' } }, '<div>A</div><div>B</div>');
|
||||
expect(html).toContain('align-items:center');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ColumnLayout.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||
test('margin/padding/border/box-shadow/opacity all flow into the emitted style attribute', () => {
|
||||
const { html } = toHtml(
|
||||
{
|
||||
columns: 2,
|
||||
split: '50-50',
|
||||
gap: '16px',
|
||||
style: {
|
||||
marginTop: '10px', marginRight: '10px', marginBottom: '10px', marginLeft: '10px',
|
||||
paddingTop: '5px',
|
||||
border: '2px solid #ff0000',
|
||||
boxShadow: '0 4px 8px rgba(0,0,0,0.12)',
|
||||
opacity: '0.8',
|
||||
},
|
||||
},
|
||||
'<div>A</div><div>B</div>',
|
||||
);
|
||||
expect(html).toContain('margin-top:10px');
|
||||
expect(html).toContain('padding-top:5px');
|
||||
expect(html).toContain('border:2px solid #ff0000');
|
||||
expect(html).toContain('box-shadow:0 4px 8px rgba(0,0,0,0.12)');
|
||||
expect(html).toContain('opacity:0.8');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ColumnLayout.craft.props exposes the vertical-alignment/box-model/animation/visibility rollout', () => {
|
||||
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||
const props = (ColumnLayout 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 alignItems and box-model keys', () => {
|
||||
const style = (ColumnLayout as any).craft.props.style;
|
||||
expect(style).toHaveProperty('alignItems');
|
||||
expect(style).toHaveProperty('marginTop');
|
||||
expect(style).toHaveProperty('paddingTop');
|
||||
expect(style.border).toBe('none');
|
||||
expect(style.boxShadow).toBe('none');
|
||||
expect(style.opacity).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,6 +20,11 @@ interface ColumnLayoutProps {
|
||||
style?: CSSProperties;
|
||||
children?: React.ReactNode;
|
||||
anchorId?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
}
|
||||
|
||||
const splitToWidths: Record<string, string[]> = {
|
||||
@@ -102,8 +107,20 @@ ColumnLayout.craft = {
|
||||
columns: 2,
|
||||
split: '50-50',
|
||||
gap: '16px',
|
||||
style: {},
|
||||
style: {
|
||||
alignItems: '',
|
||||
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||
border: 'none',
|
||||
boxShadow: 'none',
|
||||
opacity: '1',
|
||||
},
|
||||
anchorId: '',
|
||||
animation: '',
|
||||
animationDelay: '0',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
|
||||
@@ -63,3 +63,88 @@ describe('Container.toHtml tag allowlist (adversarial re-review, same class as C
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Container.toHtml vertical alignment (justify-content + min-height)', () => {
|
||||
// Regression lock: Container/Section must NOT unconditionally become a
|
||||
// flex container. Flex-blockifies in-flow children, forcing components
|
||||
// that deliberately render display:inline-block (ButtonLink, Icon) to
|
||||
// stack vertically instead of sitting side-by-side -- a real visual
|
||||
// regression for existing published pages that never touch vertical
|
||||
// alignment.
|
||||
test('does NOT become a flex container when no vertical alignment is set (plain block flow preserved)', () => {
|
||||
const { html } = toHtml({}, 'child');
|
||||
expect(html).not.toContain('display:flex');
|
||||
expect(html).not.toContain('flex-direction');
|
||||
});
|
||||
|
||||
test('does NOT become a flex container from min-height alone (min-height must not itself trigger flex)', () => {
|
||||
const { html } = toHtml({ style: { minHeight: '400px' } }, 'child');
|
||||
expect(html).not.toContain('display:flex');
|
||||
expect(html).not.toContain('flex-direction');
|
||||
expect(html).toContain('min-height:400px');
|
||||
});
|
||||
|
||||
test('becomes a column flex container when style.justifyContent is set (feature still works)', () => {
|
||||
const { html } = toHtml({ style: { justifyContent: 'center' } }, 'child');
|
||||
expect(html).toContain('display:flex');
|
||||
expect(html).toContain('flex-direction:column');
|
||||
expect(html).toContain('justify-content:center');
|
||||
});
|
||||
|
||||
test('style.minHeight flows into the emitted style attribute', () => {
|
||||
const { html } = toHtml({ style: { minHeight: '400px' } }, 'child');
|
||||
expect(html).toContain('min-height:400px');
|
||||
});
|
||||
|
||||
test('justify-content and min-height still flow through in boxed (contentWidth) mode', () => {
|
||||
const { html } = toHtml({ contentWidth: 'boxed', style: { justifyContent: 'flex-end', minHeight: '500px' } }, 'child');
|
||||
expect(html).toContain('display:flex');
|
||||
expect(html).toContain('flex-direction:column');
|
||||
expect(html).toContain('justify-content:flex-end');
|
||||
expect(html).toContain('min-height:500px');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Container.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||
test('margin/padding/border/box-shadow/opacity all flow into the emitted style attribute', () => {
|
||||
const { html } = toHtml(
|
||||
{
|
||||
style: {
|
||||
marginTop: '10px', marginRight: '10px', marginBottom: '10px', marginLeft: '10px',
|
||||
paddingTop: '5px',
|
||||
border: '2px solid #ff0000',
|
||||
boxShadow: '0 4px 8px rgba(0,0,0,0.12)',
|
||||
opacity: '0.8',
|
||||
},
|
||||
},
|
||||
'child',
|
||||
);
|
||||
expect(html).toContain('margin-top:10px');
|
||||
expect(html).toContain('padding-top:5px');
|
||||
expect(html).toContain('border:2px solid #ff0000');
|
||||
expect(html).toContain('box-shadow:0 4px 8px rgba(0,0,0,0.12)');
|
||||
expect(html).toContain('opacity:0.8');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Container.craft.props exposes the vertical-alignment/box-model/animation/visibility rollout', () => {
|
||||
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||
const props = (Container 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 vertical-alignment and box-model keys', () => {
|
||||
const style = (Container as any).craft.props.style;
|
||||
expect(style).toHaveProperty('justifyContent');
|
||||
expect(style).toHaveProperty('minHeight');
|
||||
expect(style).toHaveProperty('marginTop');
|
||||
expect(style).toHaveProperty('paddingTop');
|
||||
expect(style.border).toBe('none');
|
||||
expect(style.boxShadow).toBe('none');
|
||||
expect(style.opacity).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -43,6 +43,20 @@ const flexAlignFromTextAlign = (textAlign: CSSProperties['textAlign']): CSSPrope
|
||||
return {};
|
||||
};
|
||||
|
||||
// Container only becomes display:flex/flex-direction:column at its root
|
||||
// (both in the editor render below and in toHtml) when the user has
|
||||
// actually set `style.justifyContent` (the Vertical Alignment control,
|
||||
// paired with `style.minHeight`) -- i.e. the flex conversion is gated on
|
||||
// vertical-align actually being in use, not unconditional. In-flow children
|
||||
// of a flex container get CSS-blockified, which would force components that
|
||||
// deliberately render `display:inline-block` (ButtonLink, Icon) to stack
|
||||
// vertically instead of sitting side-by-side -- a real visual regression for
|
||||
// any container/section that never touches vertical alignment, not a no-op.
|
||||
// So plain block flow (no `display`/`flex-direction` at all) is preserved
|
||||
// unless vertical-align is set. `flexAlignFromTextAlign` above still
|
||||
// supplies its own conditional flex conversion (cross-axis alignItems from
|
||||
// `textAlign`) independently -- unrelated to this gate.
|
||||
|
||||
export const Container: UserComponent<ContainerProps> = ({
|
||||
style = {},
|
||||
tag = 'div',
|
||||
@@ -58,10 +72,12 @@ export const Container: UserComponent<ContainerProps> = ({
|
||||
const safeTag = sanitizeContainerTag(tag);
|
||||
const needsBoxedWrapper = contentWidth === 'boxed';
|
||||
const flexStyles = flexAlignFromTextAlign(style.textAlign);
|
||||
const hasVerticalAlign = !!style.justifyContent;
|
||||
|
||||
const outerStyle: CSSProperties = {
|
||||
minHeight: '40px',
|
||||
...style,
|
||||
...(hasVerticalAlign ? { display: 'flex', flexDirection: 'column' } : {}),
|
||||
...(fullWidth ? { width: '100vw', marginLeft: 'calc(-50vw + 50%)' } : {}),
|
||||
...(needsBoxedWrapper ? {} : flexStyles),
|
||||
};
|
||||
@@ -93,13 +109,27 @@ export const Container: UserComponent<ContainerProps> = ({
|
||||
Container.craft = {
|
||||
displayName: 'Container',
|
||||
props: {
|
||||
style: { padding: '20px', minHeight: '100px' },
|
||||
style: {
|
||||
padding: '20px',
|
||||
minHeight: '100px',
|
||||
justifyContent: '',
|
||||
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||
border: 'none',
|
||||
boxShadow: 'none',
|
||||
opacity: '1',
|
||||
},
|
||||
tag: 'div',
|
||||
fullWidth: false,
|
||||
contentWidth: 'full',
|
||||
anchorId: '',
|
||||
cssId: '',
|
||||
cssClass: '',
|
||||
animation: '',
|
||||
animationDelay: '0',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
@@ -114,9 +144,11 @@ Container.craft = {
|
||||
const tag = sanitizeContainerTag(props.tag);
|
||||
const isBoxed = props.contentWidth === 'boxed';
|
||||
const flexStyles = flexAlignFromTextAlign(props.style?.textAlign);
|
||||
const hasVerticalAlign = !!props.style?.justifyContent;
|
||||
|
||||
const outerCss: CSSProperties = {
|
||||
...props.style,
|
||||
...(hasVerticalAlign ? { display: 'flex', flexDirection: 'column' } : {}),
|
||||
...(isBoxed ? {} : flexStyles),
|
||||
};
|
||||
|
||||
|
||||
@@ -73,3 +73,78 @@ describe('Section.toHtml shape divider color/height XSS hardening', () => {
|
||||
expect(html).not.toContain('<svg');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Section.toHtml vertical alignment (justify-content + min-height)', () => {
|
||||
// Regression lock: same rationale as Container -- see Container.toHtml.test.ts.
|
||||
// Section must not unconditionally become a flex container, or it
|
||||
// blockifies inline-block children (ButtonLink, Icon) that are meant to
|
||||
// sit side-by-side in existing published sections.
|
||||
test('does NOT become a flex container when no vertical alignment is set (plain block flow preserved)', () => {
|
||||
const { html } = toHtml({}, 'child');
|
||||
expect(html).not.toContain('display:flex');
|
||||
expect(html).not.toContain('flex-direction');
|
||||
});
|
||||
|
||||
test('does NOT become a flex container from min-height alone (min-height must not itself trigger flex)', () => {
|
||||
const { html } = toHtml({ style: { minHeight: '600px' } }, 'child');
|
||||
expect(html).not.toContain('display:flex');
|
||||
expect(html).not.toContain('flex-direction');
|
||||
expect(html).toContain('min-height:600px');
|
||||
});
|
||||
|
||||
test('becomes a column flex container when style.justifyContent is set (feature still works)', () => {
|
||||
const { html } = toHtml({ style: { justifyContent: 'center' } }, 'child');
|
||||
expect(html).toContain('display:flex');
|
||||
expect(html).toContain('flex-direction:column');
|
||||
expect(html).toContain('justify-content:center');
|
||||
});
|
||||
|
||||
test('style.minHeight flows into the emitted style attribute', () => {
|
||||
const { html } = toHtml({ style: { minHeight: '600px' } }, 'child');
|
||||
expect(html).toContain('min-height:600px');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Section.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||
test('margin/padding/border/box-shadow/opacity all flow into the emitted style attribute', () => {
|
||||
const { html } = toHtml(
|
||||
{
|
||||
style: {
|
||||
marginTop: '10px', marginRight: '10px', marginBottom: '10px', marginLeft: '10px',
|
||||
paddingTop: '5px',
|
||||
border: '2px solid #ff0000',
|
||||
boxShadow: '0 4px 8px rgba(0,0,0,0.12)',
|
||||
opacity: '0.8',
|
||||
},
|
||||
},
|
||||
'child',
|
||||
);
|
||||
expect(html).toContain('margin-top:10px');
|
||||
expect(html).toContain('padding-top:5px');
|
||||
expect(html).toContain('border:2px solid #ff0000');
|
||||
expect(html).toContain('box-shadow:0 4px 8px rgba(0,0,0,0.12)');
|
||||
expect(html).toContain('opacity:0.8');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Section.craft.props exposes the vertical-alignment/box-model/animation/visibility rollout', () => {
|
||||
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||
const props = (Section 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 vertical-alignment and box-model keys', () => {
|
||||
const style = (Section as any).craft.props.style;
|
||||
expect(style).toHaveProperty('justifyContent');
|
||||
expect(style).toHaveProperty('minHeight');
|
||||
expect(style).toHaveProperty('marginTop');
|
||||
expect(style).toHaveProperty('paddingTop');
|
||||
expect(style.border).toBe('none');
|
||||
expect(style.boxShadow).toBe('none');
|
||||
expect(style.opacity).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,6 +27,11 @@ interface SectionProps {
|
||||
bottomDividerColor?: string;
|
||||
bottomDividerHeight?: string;
|
||||
anchorId?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
}
|
||||
|
||||
/* ---------- Divider renderer ---------- */
|
||||
@@ -98,6 +103,13 @@ export const Section: UserComponent<SectionProps> = ({
|
||||
|
||||
const hasTopDivider = topDivider && topDivider !== 'none';
|
||||
const hasBottomDivider = bottomDivider && bottomDivider !== 'none';
|
||||
// Section's root only becomes a column flex container when the user has
|
||||
// actually set `style.justifyContent` (Vertical Alignment control, paired
|
||||
// with `style.minHeight`) -- see the matching note in Container.tsx for
|
||||
// why an unconditional conversion is a real regression (blockifies
|
||||
// deliberately inline-block children like ButtonLink/Icon) rather than a
|
||||
// no-op, so plain block flow is preserved unless vertical-align is set.
|
||||
const hasVerticalAlign = !!style.justifyContent;
|
||||
|
||||
return (
|
||||
<section
|
||||
@@ -107,6 +119,7 @@ export const Section: UserComponent<SectionProps> = ({
|
||||
width: '100%',
|
||||
position: (hasTopDivider || hasBottomDivider) ? 'relative' : undefined,
|
||||
...style,
|
||||
...(hasVerticalAlign ? { display: 'flex', flexDirection: 'column' } : {}),
|
||||
}}
|
||||
>
|
||||
{hasTopDivider && (
|
||||
@@ -143,7 +156,17 @@ export const Section: UserComponent<SectionProps> = ({
|
||||
Section.craft = {
|
||||
displayName: 'Section',
|
||||
props: {
|
||||
style: { padding: '40px 0', backgroundColor: '#ffffff' },
|
||||
style: {
|
||||
padding: '40px 0',
|
||||
backgroundColor: '#ffffff',
|
||||
minHeight: '',
|
||||
justifyContent: '',
|
||||
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||
border: 'none',
|
||||
boxShadow: 'none',
|
||||
opacity: '1',
|
||||
},
|
||||
innerMaxWidth: '1200px',
|
||||
topDivider: 'none',
|
||||
topDividerColor: '#ffffff',
|
||||
@@ -152,6 +175,11 @@ Section.craft = {
|
||||
bottomDividerColor: '#ffffff',
|
||||
bottomDividerHeight: '50px',
|
||||
anchorId: '',
|
||||
animation: '',
|
||||
animationDelay: '0',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: {
|
||||
canDrag: () => true,
|
||||
@@ -199,11 +227,13 @@ function buildDividerHtml(
|
||||
(Section as any).toHtml = (props: SectionProps, childrenHtml: string) => {
|
||||
const hasTopDivider = props.topDivider && props.topDivider !== 'none';
|
||||
const hasBottomDivider = props.bottomDivider && props.bottomDivider !== 'none';
|
||||
const hasVerticalAlign = !!props.style?.justifyContent;
|
||||
|
||||
const outerStyle = cssPropsToString({
|
||||
width: '100%',
|
||||
position: (hasTopDivider || hasBottomDivider) ? 'relative' : undefined,
|
||||
...props.style,
|
||||
...(hasVerticalAlign ? { display: 'flex', flexDirection: 'column' } : {}),
|
||||
});
|
||||
const innerStyle = cssPropsToString({
|
||||
maxWidth: props.innerMaxWidth || '1200px',
|
||||
|
||||
@@ -10,18 +10,40 @@ import {
|
||||
ColorSwatchGrid,
|
||||
GradientSwatchGrid,
|
||||
PresetButtonGrid,
|
||||
NumericUnitInput,
|
||||
labelStyle,
|
||||
inputStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
import { BoxModelSection, BorderEffectsSection, AnimVisSection } from './containerBoxModel';
|
||||
|
||||
/* ---------- CONTAINER / SECTION ---------- */
|
||||
// Vertical Alignment options shown to the user identically regardless of
|
||||
// which CSS property they end up mapped to (align-items for the Columns
|
||||
// flex ROW vs. justify-content for Container/Section's flex COLUMN root --
|
||||
// see the per-type branch below).
|
||||
const VERTICAL_ALIGN_OPTIONS: { label: string; value: string }[] = [
|
||||
{ label: 'Top', value: 'flex-start' },
|
||||
{ label: 'Center', value: 'center' },
|
||||
{ label: 'Bottom', value: 'flex-end' },
|
||||
{ label: 'Stretch', value: 'stretch' },
|
||||
];
|
||||
|
||||
/* ---------- CONTAINER / SECTION / COLUMNS ---------- */
|
||||
export const ContainerStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const style: CSSProperties = nodeProps.style || {};
|
||||
|
||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
// ColumnLayout only ever carries `columns`/`split` props -- Container and
|
||||
// Section never set them -- so checking either alone distinguishes the
|
||||
// flex-ROW case (align its columns via align-items, aligning uneven
|
||||
// column heights) from the flex-COLUMN case (Container/Section, which
|
||||
// vertically center/position their OWN content via justify-content,
|
||||
// paired with a Min Height control so centering is meaningful).
|
||||
const isColumns = nodeProps.columns !== undefined || nodeProps.split !== undefined;
|
||||
const vAlignKey = isColumns ? 'alignItems' : 'justifyContent';
|
||||
|
||||
return (
|
||||
<>
|
||||
{nodeProps.cssId !== undefined && (
|
||||
@@ -94,6 +116,30 @@ export const ContainerStylePanel: React.FC<StylePanelProps> = ({ selectedId, nod
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="guided-section">
|
||||
<SectionLabel>Vertical Alignment</SectionLabel>
|
||||
<PresetButtonGrid
|
||||
presets={VERTICAL_ALIGN_OPTIONS}
|
||||
activeValue={style[vAlignKey] as string}
|
||||
onSelect={(v) => setPropStyle(vAlignKey, v)}
|
||||
/>
|
||||
</div>
|
||||
{!isColumns && (
|
||||
<div className="guided-section">
|
||||
<SectionLabel>Min Height</SectionLabel>
|
||||
<NumericUnitInput
|
||||
value={(style.minHeight as string) || ''}
|
||||
onChange={(v) => setPropStyle('minHeight', v)}
|
||||
units={['px', 'vh', '%']}
|
||||
placeholder="auto"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Box model + border/effects + animation/visibility rollout */}
|
||||
<BoxModelSection style={style} setPropStyle={setPropStyle} />
|
||||
<BorderEffectsSection style={style} setPropStyle={setPropStyle} />
|
||||
<AnimVisSection nodeProps={nodeProps} setProp={setProp} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react';
|
||||
import React from 'react';
|
||||
import {
|
||||
TEXT_COLORS,
|
||||
BG_COLORS,
|
||||
@@ -17,85 +17,12 @@ 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', 'code']);
|
||||
const SKIP_PROPS = new Set(['style', 'children', 'cssId', 'cssClass']);
|
||||
|
||||
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 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,135 @@
|
||||
import React from 'react';
|
||||
import { SHADOW_PRESETS } from '../../../constants/presets';
|
||||
import {
|
||||
SectionLabel,
|
||||
PresetButtonGrid,
|
||||
CollapsibleSection,
|
||||
SpacingControl,
|
||||
SpacingSide,
|
||||
BorderControl,
|
||||
BorderValue,
|
||||
buildBorderShorthand,
|
||||
AnimationControl,
|
||||
VisibilityControl,
|
||||
sectionGap,
|
||||
labelStyle,
|
||||
} from './shared';
|
||||
|
||||
/* ==========================================================================
|
||||
Shared box-model / border+effects / animation+visibility sections for the
|
||||
CONTAINERS package's single shared panel (ContainerStylePanel, used for
|
||||
Container / Section / Columns). Kept local to this package (not in
|
||||
shared.tsx, which is foundation/import-only) since it's just DRY-ing the
|
||||
identical JSX block across those 3 components rather than a genuinely
|
||||
cross-package reusable control. Mirrors the equivalent helper in the
|
||||
media package (mediaBoxModel.tsx) -- same shape, independently duplicated
|
||||
per-package by design (packages are developed and merged in parallel).
|
||||
========================================================================== */
|
||||
|
||||
function capitalize(s: string): string {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
|
||||
/** Parses a `border` shorthand string (e.g. "2px solid #ff0000") back into
|
||||
* the {width,style,color} shape BorderControl edits. Only needs to
|
||||
* round-trip values this same panel produced via buildBorderShorthand --
|
||||
* not arbitrary author-supplied CSS. */
|
||||
export function parseBorderShorthand(v: string | undefined): BorderValue {
|
||||
if (!v || v === 'none') return { width: '', style: 'none', color: '#000000' };
|
||||
const m = String(v).trim().match(/^(\d+(?:\.\d+)?(?:px|em|rem)?)\s+(\w+)\s+(.+)$/);
|
||||
if (!m) return { width: '', style: 'none', color: '#000000' };
|
||||
return { width: m[1], style: m[2], color: m[3] };
|
||||
}
|
||||
|
||||
export interface BoxModelSectionProps {
|
||||
style: Record<string, any>;
|
||||
setPropStyle: (prop: string, value: string) => void;
|
||||
}
|
||||
|
||||
/** Margin + Padding, per-side, via the shared SpacingControl. */
|
||||
export const BoxModelSection: React.FC<BoxModelSectionProps> = ({ style, setPropStyle }) => {
|
||||
const sideSetter = (kind: 'margin' | 'padding') => (side: SpacingSide, value: string) =>
|
||||
setPropStyle(`${kind}${capitalize(side)}`, value);
|
||||
|
||||
return (
|
||||
<CollapsibleSection title="Spacing" defaultOpen={false}>
|
||||
<SpacingControl
|
||||
label="Margin"
|
||||
value={{ top: style.marginTop, right: style.marginRight, bottom: style.marginBottom, left: style.marginLeft }}
|
||||
onChange={sideSetter('margin')}
|
||||
/>
|
||||
<SpacingControl
|
||||
label="Padding"
|
||||
value={{ top: style.paddingTop, right: style.paddingRight, bottom: style.paddingBottom, left: style.paddingLeft }}
|
||||
onChange={sideSetter('padding')}
|
||||
/>
|
||||
</CollapsibleSection>
|
||||
);
|
||||
};
|
||||
|
||||
/** style.opacity is stored as a CSS-length-free numeric string ("0.8") or
|
||||
* may be blank/undefined (treated as fully opaque). Converts to a 0-100
|
||||
* integer for the range input / label. */
|
||||
function opacityPercent(v: unknown): number {
|
||||
if (v === undefined || v === null || v === '') return 100;
|
||||
const n = parseFloat(String(v));
|
||||
return Number.isFinite(n) ? Math.round(n * 100) : 100;
|
||||
}
|
||||
|
||||
export interface BorderEffectsSectionProps {
|
||||
style: Record<string, any>;
|
||||
setPropStyle: (prop: string, value: string) => void;
|
||||
}
|
||||
|
||||
/** Border (width/style/color) + box-shadow preset + opacity slider. */
|
||||
export const BorderEffectsSection: React.FC<BorderEffectsSectionProps> = ({ style, setPropStyle }) => (
|
||||
<CollapsibleSection title="Border & Effects" defaultOpen={false}>
|
||||
<BorderControl
|
||||
value={parseBorderShorthand(style.border)}
|
||||
onChange={(v) => setPropStyle('border', buildBorderShorthand(v))}
|
||||
/>
|
||||
<div className="guided-section">
|
||||
<SectionLabel>Shadow</SectionLabel>
|
||||
<PresetButtonGrid presets={SHADOW_PRESETS} activeValue={style.boxShadow} onSelect={(v) => setPropStyle('boxShadow', v)} />
|
||||
</div>
|
||||
<div style={sectionGap}>
|
||||
<label style={labelStyle}>Opacity: {opacityPercent(style.opacity)}%</label>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
value={opacityPercent(style.opacity)}
|
||||
onChange={(e) => setPropStyle('opacity', String(Number(e.target.value) / 100))}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleSection>
|
||||
);
|
||||
|
||||
export interface AnimVisSectionProps {
|
||||
nodeProps: Record<string, any>;
|
||||
setProp: (key: string, value: any) => void;
|
||||
}
|
||||
|
||||
/** Entrance animation + responsive hide toggles -- top-level props consumed
|
||||
* directly by html-export.ts's buildDataAttrs (no toHtml change needed). */
|
||||
export const AnimVisSection: React.FC<AnimVisSectionProps> = ({ nodeProps, setProp }) => (
|
||||
<CollapsibleSection title="Animation & Visibility" defaultOpen={false}>
|
||||
<AnimationControl
|
||||
value={{ animation: nodeProps.animation || 'none', animationDelay: nodeProps.animationDelay }}
|
||||
onChange={(v) => { setProp('animation', v.animation); setProp('animationDelay', v.animationDelay); }}
|
||||
/>
|
||||
<VisibilityControl
|
||||
value={{
|
||||
hideOnDesktop: nodeProps.hideOnDesktop,
|
||||
hideOnTablet: nodeProps.hideOnTablet,
|
||||
hideOnMobile: nodeProps.hideOnMobile,
|
||||
}}
|
||||
onChange={(v) => {
|
||||
setProp('hideOnDesktop', !!v.hideOnDesktop);
|
||||
setProp('hideOnTablet', !!v.hideOnTablet);
|
||||
setProp('hideOnMobile', !!v.hideOnMobile);
|
||||
}}
|
||||
/>
|
||||
</CollapsibleSection>
|
||||
);
|
||||
@@ -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 { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
import { Modal } from '../../ui/Modal';
|
||||
import { CodeEditor } from '../../ui/CodeEditor';
|
||||
|
||||
interface HeadCodeModalProps {
|
||||
open: boolean;
|
||||
@@ -56,15 +55,27 @@ 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>
|
||||
|
||||
<div style={{ flex: 1, minHeight: 300 }}>
|
||||
<CodeEditor
|
||||
value={design.headCode || ''}
|
||||
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>"}
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
value={design.headCode || ''}
|
||||
onChange={(e) => updateDesign({ headCode: e.target.value })}
|
||||
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>
|
||||
|
||||
{/* Footer */}
|
||||
|
||||
@@ -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