feat(builder): media package -- image crop/perf, video size+picker, gallery cols/lightbox, box-model+anim/vis rollout

- ImageBlock/ImageStylePanel: SizeControl width(absorbs old maxWidth
  presets)/height, AspectRatioControl + OBJECT_FIT grid + FocalPointGrid for
  CSS framing crop (aspect-ratio/object-fit/object-position on the <img>).
  Exported <img> always gets loading="lazy" decoding="async", plus width/
  height attrs when the style has a plain px length (pxAttr helper).
- VideoBlock/MediaStylePanel: Video URL text input replaced with
  AssetPicker(mediaType="video") writing videoUrl (paste-URL still handles
  YouTube/Vimeo, upload/browse handle files). Added SizeControl(width) +
  AspectRatioControl so the video frame honors real size/aspect instead of
  a hardcoded 16:9 (padding-bottom hack replaced with CSS aspect-ratio).
  New optional `poster` prop (image AssetPicker) + preload="metadata" on
  file-type <video>.
- Gallery: surfaced the existing-but-unexposed `columns` and `lightbox`
  props with panel controls.
- All 5 owned components (ImageBlock, VideoBlock, Gallery, ContentSlider,
  MapEmbed): added margin/padding (per-side)/border/box-shadow/opacity style
  defaults + AnimationControl/VisibilityControl-backed animation/
  animationDelay/hideOnDesktop/hideOnTablet/hideOnMobile props. New shared
  mediaBoxModel.tsx (package-local, not shared.tsx) DRYs the box-model +
  border/effects + animation/visibility panel sections across
  ImageStylePanel and MediaStylePanel.
- Tests: extended *.toHtml.test.ts for all 5 components (crop/perf attrs,
  video size/aspect/poster/preload, gallery columns/lightbox, box-model
  style emission, craft.props presence) + new MediaStylePanel.video.test.tsx
  verifying the AssetPicker wiring writes videoUrl/poster and the video-only
  size controls are gated on videoUrl. 694 tests green, tsc + vite build
  clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-14 06:30:50 -07:00
parent 1d9460c173
commit 0419291259
14 changed files with 851 additions and 44 deletions
@@ -2,30 +2,28 @@ import React, { CSSProperties } from 'react';
import { useEditor } from '@craftjs/core';
import {
IMAGE_RADIUS_PRESETS,
OBJECT_FIT,
} from '../../../constants/presets';
import {
StylePanelProps,
SectionLabel,
PresetButtonGrid,
TextInputField,
SizeControl,
AspectRatioControl,
FocalPointGrid,
useNodeProp,
} from './shared';
import { AssetPicker } from '../../../ui/AssetPicker';
import { PLACEHOLDER_SRC } from '../../../components/media/ImageBlock';
import { BoxModelSection, BorderEffectsSection, AnimVisSection } from './mediaBoxModel';
/* ---------- IMAGE (with upload/browse/drop) ---------- */
export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const style: CSSProperties = nodeProps.style || {};
const { setPropStyle } = useNodeProp(selectedId);
const maxWidthPresets = [
{ label: '25%', value: '25%' },
{ label: '50%', value: '50%' },
{ label: '75%', value: '75%' },
{ label: '100%', value: '100%' },
];
const { setProp, setPropStyle } = useNodeProp(selectedId);
return (
<>
@@ -49,6 +47,39 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
}}
/>
{/* Size -- Width absorbs the historical maxWidth presets (25/50/75/100%
are a subset of SizeControl's default preset row), Height is new. */}
<SizeControl
label="Width"
value={(style.maxWidth as string) || ''}
onChange={(v) => setPropStyle('maxWidth', v)}
/>
<SizeControl
label="Height"
value={(style.height as string) || ''}
onChange={(v) => setPropStyle('height', v)}
/>
{/* Crop & Framing -- aspect-ratio + object-fit + object-position on the
<img> itself is a CSS framing crop (no server-side image processing
needed). */}
<AspectRatioControl
value={(style.aspectRatio as string) || ''}
onChange={(v) => setPropStyle('aspectRatio', v)}
/>
<div className="guided-section">
<SectionLabel>Object Fit</SectionLabel>
<PresetButtonGrid
presets={OBJECT_FIT}
activeValue={(style.objectFit as string) || ''}
onSelect={(v) => setPropStyle('objectFit', v)}
/>
</div>
<FocalPointGrid
value={(style.objectPosition as string) || ''}
onChange={(v) => setPropStyle('objectPosition', v)}
/>
{/* Border Radius */}
<div className="guided-section">
<SectionLabel>Border Radius</SectionLabel>
@@ -59,15 +90,10 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
/>
</div>
{/* Max Width */}
<div className="guided-section">
<SectionLabel>Max Width</SectionLabel>
<PresetButtonGrid
presets={maxWidthPresets}
activeValue={style.maxWidth as string}
onSelect={(v) => setPropStyle('maxWidth', v)}
/>
</div>
{/* Box model + animation/visibility rollout */}
<BoxModelSection style={style} setPropStyle={setPropStyle} />
<BorderEffectsSection style={style} setPropStyle={setPropStyle} />
<AnimVisSection nodeProps={nodeProps} setProp={setProp} />
</>
);
};
@@ -2,7 +2,6 @@ import React from 'react';
import { useEditor } from '@craftjs/core';
import {
BG_COLORS,
SPACING_PRESETS,
RADIUS_PRESETS,
} from '../../../constants/presets';
import {
@@ -13,6 +12,8 @@ import {
CollapsibleSection,
ColorPickerField,
ArrayPropEditor,
SizeControl,
AspectRatioControl,
labelStyle,
inputStyle,
smallInputStyle,
@@ -20,6 +21,14 @@ import {
useNodeProp,
} from './shared';
import { AssetPicker } from '../../../ui/AssetPicker';
import { BoxModelSection, BorderEffectsSection, AnimVisSection } from './mediaBoxModel';
const GALLERY_COLUMN_PRESETS = [
{ label: '2', value: '2' },
{ label: '3', value: '3' },
{ label: '4', value: '4' },
{ label: '5', value: '5' },
];
/* ---------- MEDIA (Video / Gallery / Map / Slider) ---------- */
export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
@@ -30,11 +39,48 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
return (
<>
{/* Video URL */}
{/* Video source -- upload/browse/paste-URL (paste-URL still handles
YouTube/Vimeo; upload/browse handle files via detectVideoType's
serve_asset resolution). */}
{nodeProps.videoUrl !== undefined && (
<div style={sectionGap}>
<label style={labelStyle}>Video URL</label>
<input type="text" value={nodeProps.videoUrl || ''} onChange={(e) => setProp('videoUrl', e.target.value)} placeholder="YouTube, Vimeo, or .mp4 URL" style={inputStyle} />
<div className="guided-section">
<SectionLabel>Video Source</SectionLabel>
<AssetPicker
mediaType="video"
value={nodeProps.videoUrl || ''}
onChange={(url) => setProp('videoUrl', url)}
variant="full"
placeholder="Or paste a YouTube/Vimeo/.mp4 URL..."
/>
</div>
)}
{/* Video size -- width + aspect ratio for the video frame. */}
{nodeProps.videoUrl !== undefined && (
<>
<SizeControl
label="Width"
value={(style.width as string) || ''}
onChange={(v) => setPropStyle('width', v)}
/>
<AspectRatioControl
value={(style.aspectRatio as string) || ''}
onChange={(v) => setPropStyle('aspectRatio', v)}
/>
</>
)}
{/* Poster image (optional, file-type videos only in practice but
harmless to offer whenever the component has a poster prop). */}
{nodeProps.poster !== undefined && (
<div className="guided-section">
<SectionLabel>Poster Image (optional)</SectionLabel>
<AssetPicker
mediaType="image"
value={nodeProps.poster || ''}
onChange={(url) => setProp('poster', url)}
variant="full"
/>
</div>
)}
@@ -80,6 +126,26 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
</div>
)}
{/* Gallery layout -- columns + lightbox (existing-but-previously-unexposed props). */}
{nodeProps.images !== undefined && Array.isArray(nodeProps.images) && (
<>
<div className="guided-section">
<SectionLabel>Columns</SectionLabel>
<PresetButtonGrid
presets={GALLERY_COLUMN_PRESETS}
activeValue={String(nodeProps.columns ?? 3)}
onSelect={(v) => setProp('columns', Number(v))}
/>
</div>
<div style={sectionGap}>
<label style={{ ...labelStyle, display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
<input type="checkbox" checked={!!nodeProps.lightbox} onChange={(e) => setProp('lightbox', e.target.checked)} />
Enable Lightbox
</label>
</div>
</>
)}
{/* Gallery items */}
{nodeProps.images !== undefined && Array.isArray(nodeProps.images) && (
<CollapsibleSection title="Images">
@@ -178,21 +244,23 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
</CollapsibleSection>
)}
{/* Background & padding */}
{/* Background & radius */}
<CollapsibleSection title="Style" defaultOpen={false}>
<div className="guided-section">
<SectionLabel>Background</SectionLabel>
<ColorSwatchGrid colors={BG_COLORS} activeValue={style.backgroundColor} onSelect={(v: string) => setPropStyle('backgroundColor', v)} />
</div>
<div className="guided-section">
<SectionLabel>Padding</SectionLabel>
<PresetButtonGrid presets={SPACING_PRESETS} activeValue={style.padding as string} onSelect={(v) => setPropStyle('padding', v)} />
</div>
<div className="guided-section">
<SectionLabel>Border Radius</SectionLabel>
<PresetButtonGrid presets={RADIUS_PRESETS} activeValue={style.borderRadius as string} onSelect={(v) => setPropStyle('borderRadius', v)} />
</div>
</CollapsibleSection>
{/* Box model + animation/visibility rollout (Video/Gallery/Map/Slider
all carry these props now, so it's safe to render unconditionally). */}
<BoxModelSection style={style} setPropStyle={setPropStyle} />
<BorderEffectsSection style={style} setPropStyle={setPropStyle} />
<AnimVisSection nodeProps={nodeProps} setProp={setProp} />
</>
);
};
@@ -0,0 +1,149 @@
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
/* Same DOM-harness pattern as MediaStylePanel.slides.test.tsx -- mock
@craftjs/core's useEditor so setProp calls can be observed without
mounting a real <Editor> tree, and mock utils/assets so AssetPicker
doesn't hit the network. */
const setPropSpy = vi.fn((_id: string, updater: (p: any) => void) => {
updater(lastProps);
});
let lastProps: any;
vi.mock('@craftjs/core', () => ({
useEditor: () => ({ actions: { setProp: setPropSpy } }),
}));
vi.mock('../../../utils/assets', () => ({
uploadAsset: vi.fn(),
listAssets: vi.fn(),
}));
import { MediaStylePanel } from './MediaStylePanel';
let container: HTMLDivElement;
let root: Root;
function render(ui: React.ReactElement) {
container = document.createElement('div');
document.body.appendChild(container);
act(() => {
root = createRoot(container);
root.render(ui);
});
}
function unmount() {
act(() => { root.unmount(); });
container.remove();
}
function q<T extends Element = Element>(testId: string): T | null {
return container.querySelector(`[data-testid="${testId}"]`);
}
function qAll<T extends Element = Element>(testId: string): T[] {
return Array.from(container.querySelectorAll(`[data-testid="${testId}"]`));
}
function setValue(input: HTMLInputElement, value: string) {
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')!.set!;
setter.call(input, value);
input.dispatchEvent(new Event('input', { bubbles: true }));
}
beforeEach(() => {
setPropSpy.mockClear();
});
afterEach(() => {
if (container) unmount();
});
describe('MediaStylePanel Video source uses AssetPicker (upload/browse/paste-URL), not a plain text input', () => {
test('renders a full-variant AssetPicker (not the old plain input) for videoUrl', () => {
lastProps = { videoUrl: '', poster: '', style: {} };
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
expect(q('asset-picker-full')).not.toBeNull();
});
test('applying a pasted URL via the AssetPicker writes videoUrl (not some other key)', () => {
lastProps = { videoUrl: '', poster: '', style: {} };
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
// The Video Source AssetPicker is the first url-input on the page (the
// Poster picker is a second, separate AssetPicker instance below it).
const urlInput = qAll<HTMLInputElement>('asset-picker-url-input')[0];
expect(urlInput).toBeTruthy();
setValue(urlInput, 'https://example.com/clip.mp4');
const applyBtn = qAll<HTMLButtonElement>('asset-picker-apply')[0];
act(() => {
applyBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
expect(setPropSpy).toHaveBeenCalled();
expect(lastProps.videoUrl).toBe('https://example.com/clip.mp4');
});
test('a video-shaped selection also renders a Poster AssetPicker (image) that writes `poster`', () => {
lastProps = { videoUrl: 'https://example.com/clip.mp4', poster: '', style: {} };
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
const pickers = qAll('asset-picker-full');
expect(pickers.length).toBe(2); // Video Source + Poster Image
const urlInputs = qAll<HTMLInputElement>('asset-picker-url-input');
const posterInput = urlInputs[1];
setValue(posterInput, 'https://example.com/poster.jpg');
const applyBtns = qAll<HTMLButtonElement>('asset-picker-apply');
act(() => {
applyBtns[1].dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
expect(lastProps.poster).toBe('https://example.com/poster.jpg');
});
});
describe('MediaStylePanel Video size controls (Width + Aspect Ratio) are gated on videoUrl', () => {
test('a video-shaped selection renders SizeControl + AspectRatioControl', () => {
lastProps = { videoUrl: '', poster: '', style: {} };
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
expect(q('size-control')).not.toBeNull();
expect(q('aspect-ratio-control')).not.toBeNull();
});
test('a Map-shaped selection (no videoUrl) does NOT render the video size controls', () => {
lastProps = { address: 'New York, NY', zoom: 14, height: '400px', style: {} };
render(<MediaStylePanel selectedId="map-1" nodeProps={lastProps} />);
expect(q('size-control')).toBeNull();
expect(q('aspect-ratio-control')).toBeNull();
});
});
function openCollapsibleByTitle(title: string) {
const btn = Array.from(container.querySelectorAll('button')).find((b) => b.textContent?.includes(title));
expect(btn).toBeTruthy();
act(() => {
btn!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
}
describe('MediaStylePanel box-model + animation/visibility rollout renders for every media type', () => {
test('a Map-shaped selection still gets Spacing / Border & Effects / Animation & Visibility sections (collapsed by default, open on click)', () => {
lastProps = { address: 'New York, NY', zoom: 14, height: '400px', style: {}, animation: '', hideOnDesktop: false };
render(<MediaStylePanel selectedId="map-1" nodeProps={lastProps} />);
openCollapsibleByTitle('Spacing');
expect(q('spacing-control')).not.toBeNull();
openCollapsibleByTitle('Border & Effects');
expect(q('border-control')).not.toBeNull();
openCollapsibleByTitle('Animation & Visibility');
expect(q('animation-control')).not.toBeNull();
expect(q('visibility-control')).not.toBeNull();
});
});
@@ -0,0 +1,133 @@
import React from 'react';
import { SHADOW_PRESETS } from '../../../constants/presets';
import {
SectionLabel,
PresetButtonGrid,
CollapsibleSection,
SpacingControl,
SpacingSide,
BorderControl,
BorderValue,
buildBorderShorthand,
AnimationControl,
VisibilityControl,
sectionGap,
labelStyle,
} from './shared';
/* ==========================================================================
Shared box-model / border+effects / animation+visibility sections for the
MEDIA package's panels (ImageStylePanel + MediaStylePanel). Kept local to
this package (not in shared.tsx, which is foundation/import-only) since
it's just DRY-ing the identical JSX block across ImageBlock/VideoBlock/
Gallery/ContentSlider/MapEmbed rather than a genuinely cross-package
reusable control.
========================================================================== */
function capitalize(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1);
}
/** Parses a `border` shorthand string (e.g. "2px solid #ff0000") back into
* the {width,style,color} shape BorderControl edits. Only needs to
* round-trip values this same panel produced via buildBorderShorthand --
* not arbitrary author-supplied CSS. */
export function parseBorderShorthand(v: string | undefined): BorderValue {
if (!v || v === 'none') return { width: '', style: 'none', color: '#000000' };
const m = String(v).trim().match(/^(\d+(?:\.\d+)?(?:px|em|rem)?)\s+(\w+)\s+(.+)$/);
if (!m) return { width: '', style: 'none', color: '#000000' };
return { width: m[1], style: m[2], color: m[3] };
}
export interface BoxModelSectionProps {
style: Record<string, any>;
setPropStyle: (prop: string, value: string) => void;
}
/** Margin + Padding, per-side, via the shared SpacingControl. */
export const BoxModelSection: React.FC<BoxModelSectionProps> = ({ style, setPropStyle }) => {
const sideSetter = (kind: 'margin' | 'padding') => (side: SpacingSide, value: string) =>
setPropStyle(`${kind}${capitalize(side)}`, value);
return (
<CollapsibleSection title="Spacing" defaultOpen={false}>
<SpacingControl
label="Margin"
value={{ top: style.marginTop, right: style.marginRight, bottom: style.marginBottom, left: style.marginLeft }}
onChange={sideSetter('margin')}
/>
<SpacingControl
label="Padding"
value={{ top: style.paddingTop, right: style.paddingRight, bottom: style.paddingBottom, left: style.paddingLeft }}
onChange={sideSetter('padding')}
/>
</CollapsibleSection>
);
};
/** style.opacity is stored as a CSS-length-free numeric string ("0.8") or
* may be blank/undefined (treated as fully opaque). Converts to a 0-100
* integer for the range input / label. */
function opacityPercent(v: unknown): number {
if (v === undefined || v === null || v === '') return 100;
const n = parseFloat(String(v));
return Number.isFinite(n) ? Math.round(n * 100) : 100;
}
export interface BorderEffectsSectionProps {
style: Record<string, any>;
setPropStyle: (prop: string, value: string) => void;
}
/** Border (width/style/color) + box-shadow preset + opacity slider. */
export const BorderEffectsSection: React.FC<BorderEffectsSectionProps> = ({ style, setPropStyle }) => (
<CollapsibleSection title="Border & Effects" defaultOpen={false}>
<BorderControl
value={parseBorderShorthand(style.border)}
onChange={(v) => setPropStyle('border', buildBorderShorthand(v))}
/>
<div className="guided-section">
<SectionLabel>Shadow</SectionLabel>
<PresetButtonGrid presets={SHADOW_PRESETS} activeValue={style.boxShadow} onSelect={(v) => setPropStyle('boxShadow', v)} />
</div>
<div style={sectionGap}>
<label style={labelStyle}>Opacity: {opacityPercent(style.opacity)}%</label>
<input
type="range"
min={0}
max={100}
value={opacityPercent(style.opacity)}
onChange={(e) => setPropStyle('opacity', String(Number(e.target.value) / 100))}
style={{ width: '100%' }}
/>
</div>
</CollapsibleSection>
);
export interface AnimVisSectionProps {
nodeProps: Record<string, any>;
setProp: (key: string, value: any) => void;
}
/** Entrance animation + responsive hide toggles -- top-level props consumed
* directly by html-export.ts's buildDataAttrs (no toHtml change needed). */
export const AnimVisSection: React.FC<AnimVisSectionProps> = ({ nodeProps, setProp }) => (
<CollapsibleSection title="Animation & Visibility" defaultOpen={false}>
<AnimationControl
value={{ animation: nodeProps.animation || 'none', animationDelay: nodeProps.animationDelay }}
onChange={(v) => { setProp('animation', v.animation); setProp('animationDelay', v.animationDelay); }}
/>
<VisibilityControl
value={{
hideOnDesktop: nodeProps.hideOnDesktop,
hideOnTablet: nodeProps.hideOnTablet,
hideOnMobile: nodeProps.hideOnMobile,
}}
onChange={(v) => {
setProp('hideOnDesktop', !!v.hideOnDesktop);
setProp('hideOnTablet', !!v.hideOnTablet);
setProp('hideOnMobile', !!v.hideOnMobile);
}}
/>
</CollapsibleSection>
);