import { FileBrowser } from '@components/admin/FileBrowser.js'; import { normalizeImageSrc } from '@components/common/page-builder/normalizeImageSrc.js'; import { LinkPicker } from '@components/common/page-builder/pickers/LinkPicker.js'; import { useScopedFieldName, useScopedFormContext } from '@components/common/page-builder/WidgetSettingsScope.js'; import { Button } from '@components/common/ui/Button.js'; import { Switch } from '@components/common/ui/Switch.js'; import { _ } from '@evershop/evershop/lib/locale/translate/_'; import { ChevronDown, ChevronUp, Eye, EyeOff, ImagePlus, Plus, Trash2 } from 'lucide-react'; import React, { useEffect, useMemo, useRef, useState } from 'react'; import { useFieldArray } from 'react-hook-form'; import { v4 as uuidv4 } from 'uuid'; import { resolveArrowsStyle, resolveDotsStyle, type ArrowsStyle, type DotsStyle } from './slideshowControls.js'; // --------------------------------------------------------------------------- // Compact form primitives (mirrors the design demo's vocabulary). // // Kept local because they are very specific to the page-builder drawer // (narrow column, dense vertical rhythm, label-on-top, 11-12px labels). The // shared `@components/common/form/*` Fields wrap their own label / hint / // validation surfaces designed for full-width admin forms — too tall here. // --------------------------------------------------------------------------- function Field({ label, hint, children }: { label?: string; hint?: string; children: React.ReactNode; }) { return (
{label && (
{label}
)}
{children}
{hint &&
{hint}
}
); } function Segmented({ value, onChange, options }: { value: T; onChange: (v: T) => void; options: ReadonlyArray<{ value: T; label: React.ReactNode; title?: string }>; }) { return (
{options.map((opt) => { const active = value === opt.value; return ( ); })}
); } // Drag-friendly slider. Uses an internal `display` state so the thumb // tracks the user's pointer smoothly during drag; the form is committed // only on release (mouseup / touchend / keyup). This avoids two problems: // - controlled-input rerender lag that made the previous version feel // "click-only" — each pointermove went `setValue -> form watch -> // re-render -> value prop update`, sometimes losing the drag thread. // - autosave thrashing: previously every pixel of drag triggered a save. function Slider({ value, onChange, min, max, step = 1, suffix }: { value: number; onChange: (v: number) => void; min: number; max: number; step?: number; suffix?: string; }) { const [display, setDisplay] = useState(value); const draggingRef = useRef(false); useEffect(() => { // Sync when the source value changes externally (slide switch, undo, // etc.) — but only when we're NOT in the middle of a drag, otherwise // the user's in-flight gesture would snap back. if (!draggingRef.current) setDisplay(value); }, [value]); const commit = (v: number) => { draggingRef.current = false; setDisplay(v); if (v !== value) onChange(v); }; return (
{ draggingRef.current = true; setDisplay(Number(e.target.value)); }} onMouseUp={(e) => commit(Number((e.target as HTMLInputElement).value))} onTouchEnd={(e) => commit(Number((e.target as HTMLInputElement).value))} onKeyUp={(e) => commit(Number((e.target as HTMLInputElement).value))} onBlur={(e) => { if (draggingRef.current) { commit(Number((e.target as HTMLInputElement).value)); } }} className="flex-1 accent-primary" /> {display} {suffix ?? ''}
); } // Switch-row toggle. Uses the shared `Switch` primitive (base-ui under the // shadcn-style wrapper) so the affordance matches the rest of the admin // UI — the previous custom-button version was inconsistent with sibling // dialogs and didn't pick up the global focus / disabled styling. function Toggle({ value, onChange, label, hint }: { value: boolean; onChange: (v: boolean) => void; label: string; hint?: string; }) { return (
{label} {hint && ( {hint} )}
onChange(Boolean(v))} />
); } // `ColorField` / `COLOR_SWATCHES` removed when slide CTAs moved to // `Button` variants (default / outline / secondary / ghost / link). Color // flows from the theme via the variant; no per-slide hex picker needed. function AnchorPicker({ value, onChange }: { value: ContentAnchor; onChange: (v: ContentAnchor) => void; }) { const cells: ContentAnchor[] = [ 'tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br' ]; return (
{cells.map((c) => { const active = value === c; return ( ); })}
); } function Section({ title, children, rightSlot }: { title: string; children: React.ReactNode; rightSlot?: React.ReactNode; }) { const [open, setOpen] = useState(true); return (
{open && (
{children}
)}
); } // --------------------------------------------------------------------------- // Types — mirrors `Slideshow.tsx`. // --------------------------------------------------------------------------- type ContentAnchor = | 'tl' | 'tc' | 'tr' | 'ml' | 'mc' | 'mr' | 'bl' | 'bc' | 'br'; type OverlayTint = 'none' | 'dark' | 'light' | 'gradient'; type AspectRatio = 'auto' | '16:9' | '21:9' | '4:3' | '1:1'; // Mirrors the shadcn Button variants. `filled` is the legacy value kept in // the union so already-saved slides type-check before the user touches them. type ButtonStyle = | 'default' | 'secondary' | 'outline' | 'ghost' | 'link' | 'filled'; interface SlideData { id: string; image: string; mobileImage?: string; mobileWidth?: number; mobileHeight?: number; width?: number; height?: number; eyebrow?: string; headline?: string; subText?: string; buttonText?: string; buttonLink?: string; buttonStyle?: ButtonStyle; button2Text?: string; button2Link?: string; button2Style?: ButtonStyle; contentPosition?: ContentAnchor; overlayTint?: OverlayTint; overlayOpacity?: number; wholeSlideLink?: boolean; hidden?: boolean; } interface SlideshowSettingProps { slideshowWidget?: { slides?: SlideData[]; autoplay?: boolean; autoplaySpeed?: number; arrows?: boolean; dots?: boolean; transition?: 'slide' | 'fade'; transitionSpeed?: number; pauseOnHover?: boolean; pauseOnInteraction?: boolean; arrowsStyle?: ArrowsStyle; dotsStyle?: DotsStyle; aspectRatio?: AspectRatio; defaultContentPosition?: ContentAnchor; defaultOverlayTint?: OverlayTint; defaultOverlayOpacity?: number; }; } // Maps to the shared shadcn `Button` variants — same vocabulary as every // other button in the admin. The legacy `filled` value is folded into // `default` when storefront resolves it, so old slides keep rendering. const BUTTON_STYLE_OPTIONS: ReadonlyArray<{ value: ButtonStyle; label: string; }> = [ { value: 'default', label: _('Primary') }, { value: 'secondary', label: _('Secondary') }, { value: 'outline', label: _('Outline') }, { value: 'ghost', label: _('Ghost') }, { value: 'link', label: _('Link') } ]; const OVERLAY_TINT_OPTIONS: ReadonlyArray<{ value: OverlayTint; label: string; }> = [ { value: 'none', label: _('None') }, { value: 'dark', label: _('Dark') }, { value: 'light', label: _('Light') }, { value: 'gradient', label: _('Gradient') } ]; const ASPECT_OPTIONS: ReadonlyArray<{ value: AspectRatio; label: string }> = [ { value: 'auto', label: _('Auto') }, { value: '16:9', label: '16:9' }, { value: '21:9', label: '21:9' }, { value: '4:3', label: '4:3' }, { value: '1:1', label: '1:1' } ]; const ARROWS_OPTIONS: ReadonlyArray<{ value: ArrowsStyle; label: string }> = [ { value: 'hidden', label: _('None') }, { value: 'sides', label: _('Sides') }, { value: 'bottom-right', label: _('Bottom') } ]; const DOTS_OPTIONS: ReadonlyArray<{ value: DotsStyle; label: string }> = [ { value: 'hidden', label: _('None') }, { value: 'dots', label: _('Dots') }, { value: 'bars', label: _('Bars') }, { value: 'numbers', label: '123' } ]; // --------------------------------------------------------------------------- // Setting drawer // --------------------------------------------------------------------------- export default function SlideshowSetting({ slideshowWidget }: SlideshowSettingProps) { const { slides = [], autoplay = true, autoplaySpeed = 3000, arrows = true, dots = true, transition = 'slide', transitionSpeed = 500, pauseOnHover = true, pauseOnInteraction = false, arrowsStyle, dotsStyle, aspectRatio = 'auto', defaultContentPosition = 'mc', defaultOverlayTint = 'none', defaultOverlayOpacity = 0.3 } = slideshowWidget || {}; const { control, setValue, watch, register } = useScopedFormContext(); // useFieldArray takes a literal form-root path; the scope helper resolves // it so the slides array is shared with the page-level form auto-save. const slidesArrayName = useScopedFieldName('settings.slides'); const { fields, append, remove, move } = useFieldArray({ control, name: slidesArrayName as 'settings.slides' }); const currentSlides = (watch('settings.slides', slides) ?? []) as SlideData[]; const currentAutoplay = Boolean(watch('settings.autoplay', autoplay)); const currentAutoplaySpeed = Number( watch('settings.autoplaySpeed', autoplaySpeed) ); const currentTransition = (watch('settings.transition', transition) ?? 'slide') as 'slide' | 'fade'; const currentTransitionSpeed = Number( watch('settings.transitionSpeed', transitionSpeed) ); const currentPauseOnHover = Boolean( watch('settings.pauseOnHover', pauseOnHover) ); const currentPauseOnInteraction = Boolean( watch('settings.pauseOnInteraction', pauseOnInteraction) ); // Resolved from BOTH fields, the way the storefront does (slideshowControls.ts), so what the // form shows is what the page renders. Choosing a style below writes both, so they stay in step. const currentArrowsStyle = resolveArrowsStyle( watch('settings.arrows', arrows) as boolean | null | undefined, watch('settings.arrowsStyle', arrowsStyle) as ArrowsStyle | null | undefined ); const currentDotsStyle = resolveDotsStyle( watch('settings.dots', dots) as boolean | null | undefined, watch('settings.dotsStyle', dotsStyle) as DotsStyle | null | undefined ); const currentAspectRatio = (watch('settings.aspectRatio', aspectRatio) as AspectRatio) || 'auto'; const currentDefaultPosition = (watch( 'settings.defaultContentPosition', defaultContentPosition ) as ContentAnchor) || 'mc'; const currentDefaultTint = (watch('settings.defaultOverlayTint', defaultOverlayTint) as OverlayTint) || 'none'; const currentDefaultOpacity = Number( watch('settings.defaultOverlayOpacity', defaultOverlayOpacity) ); // First-mount initializers — seed the form with the resolved defaults so // the auto-save doesn't have to wait for a user edit to capture them. // Uses an empty dep array intentionally; subsequent renders read live // values via watch(). useEffect(() => { setValue( 'settings.slides', currentSlides && currentSlides.length ? currentSlides : [] ); setValue('settings.autoplay', currentAutoplay); setValue( 'settings.autoplaySpeed', Number.isFinite(currentAutoplaySpeed) ? currentAutoplaySpeed : 3000 ); setValue('settings.transition', currentTransition); setValue( 'settings.transitionSpeed', Number.isFinite(currentTransitionSpeed) ? currentTransitionSpeed : 500 ); setValue('settings.pauseOnHover', currentPauseOnHover); setValue('settings.pauseOnInteraction', currentPauseOnInteraction); setValue('settings.arrowsStyle', currentArrowsStyle); setValue('settings.dotsStyle', currentDotsStyle); // Back-compat: keep the legacy booleans in sync so third-party // storefront code that still reads arrows/dots boolean keys keeps // working. setValue('settings.arrows', currentArrowsStyle !== 'hidden'); setValue('settings.dots', currentDotsStyle !== 'hidden'); setValue('settings.aspectRatio', currentAspectRatio); setValue('settings.defaultContentPosition', currentDefaultPosition); setValue('settings.defaultOverlayTint', currentDefaultTint); setValue( 'settings.defaultOverlayOpacity', Number.isFinite(currentDefaultOpacity) ? currentDefaultOpacity : 0.3 ); // Auto-detect dimensions for slides missing width/height. The storefront // needs them for the SSR layout (avoids CLS). currentSlides.forEach((slide, idx) => { if (slide.image && (!slide.width || !slide.height)) { loadImageDimensions(slide.image, idx); } if (slide.mobileImage && (!slide.mobileWidth || !slide.mobileHeight)) { loadImageDimensions(slide.mobileImage, idx, 'mobile'); } }); }, []); const [activeSlideIndex, setActiveSlideIndex] = useState( fields.length > 0 ? 0 : null ); const [imagePickerTarget, setImagePickerTarget] = useState<{ kind: 'desktop' | 'mobile'; slideIndex: number; } | null>(null); const loadImageDimensions = ( imageUrl: string, slideIndex: number, target: 'desktop' | 'mobile' = 'desktop' ) => { if (!imageUrl) return; const img = new Image(); const [widthKey, heightKey] = target === 'mobile' ? ['mobileWidth', 'mobileHeight'] : ['width', 'height']; img.onload = () => { // Path-level setValue (rather than rebuilding the slides array) so // text inputs registered in the same slide row don't get remounted // and steal focus when the image's natural size arrives. setValue( `settings.slides.${slideIndex}.${widthKey}` as any, img.naturalWidth ); setValue( `settings.slides.${slideIndex}.${heightKey}` as any, img.naturalHeight ); }; img.src = imageUrl; }; // Update a single field on a slide WITHOUT rewriting the whole slides // array. Calling `setValue('settings.slides', newArray)` on every // keystroke makes `useFieldArray` regenerate its internal field ids, // which remounts every `` in the slide list and drops focus // after the first character (issue 4 in the merchandiser bug round). // Path-level setValue keeps the array structure stable. const updateSlide = (idx: number, patch: Partial) => { Object.entries(patch).forEach(([key, value]) => { setValue(`settings.slides.${idx}.${key}` as any, value); }); }; const handleImagePick = (filePath: string) => { if (!imagePickerTarget) return; const { kind, slideIndex } = imagePickerTarget; const normalized = normalizeImageSrc(filePath); if (kind === 'desktop') { updateSlide(slideIndex, { image: normalized, width: 0, height: 0 }); loadImageDimensions(normalized, slideIndex); } else { updateSlide(slideIndex, { mobileImage: normalized, mobileWidth: 0, mobileHeight: 0 }); loadImageDimensions(normalized, slideIndex, 'mobile'); } setImagePickerTarget(null); }; const addSlide = () => { const newSlide: SlideData = { id: uuidv4(), image: '', mobileImage: '', mobileWidth: 0, mobileHeight: 0, width: 0, height: 0, eyebrow: '', headline: '', subText: '', buttonText: '', buttonLink: '', buttonStyle: 'default', button2Text: '', button2Link: '', button2Style: 'outline', contentPosition: undefined, overlayTint: undefined, overlayOpacity: undefined, wholeSlideLink: false, hidden: false }; append(newSlide); // append → fields length will be n+1 after RHF flushes; activate it next // frame so the inline editor opens. setTimeout(() => setActiveSlideIndex(fields.length), 0); }; const moveUp = (idx: number) => { if (idx > 0) { move(idx, idx - 1); if (activeSlideIndex === idx) setActiveSlideIndex(idx - 1); else if (activeSlideIndex === idx - 1) setActiveSlideIndex(idx); } }; const moveDown = (idx: number) => { if (idx < fields.length - 1) { move(idx, idx + 1); if (activeSlideIndex === idx) setActiveSlideIndex(idx + 1); else if (activeSlideIndex === idx + 1) setActiveSlideIndex(idx); } }; const removeSlide = (idx: number) => { remove(idx); if (activeSlideIndex === idx) setActiveSlideIndex(null); else if (activeSlideIndex !== null && activeSlideIndex > idx) { setActiveSlideIndex(activeSlideIndex - 1); } }; const toggleHidden = (idx: number) => { updateSlide(idx, { hidden: !currentSlides[idx]?.hidden }); }; const slideCount = fields.length; // Inline-expanded body for the active slide — rendered as part of the // slide row's tile so it stays in visual context. Pulled into a memo so // typing in one field doesn't tear down the others' inputs. const renderActiveBody = useMemo(() => { return (idx: number) => { const slide = currentSlides[idx]; if (!slide) return null; const slidePos = (slide.contentPosition || currentDefaultPosition) as ContentAnchor; const slideTint = (slide.overlayTint || currentDefaultTint) as OverlayTint; const slideOpacity = typeof slide.overlayOpacity === 'number' ? slide.overlayOpacity : currentDefaultOpacity; const hasSecondary = !!slide.button2Text || !!slide.button2Link; return (
{/* Image picker */}
{slide.image ? ( ) : ( )}
{slide.mobileImage ? ( ) : ( )}
{slide.mobileImage && ( )}
{slide.image && slide.width ? (
{slide.width} × {slide.height} px {slide.mobileImage && slide.mobileWidth ? ( <> {' · '} {_('mobile')} {slide.mobileWidth} × {slide.mobileHeight} px ) : null}
) : null}
{/* Text inputs — bound via `register()` so RHF manages the value internally and the input element stays mounted across each keystroke (controlled `value` + onChange of the whole slides array remounted these and dropped focus after one letter). */}