import { useStore } from '@nanostores/react'; import { memo, useCallback, useEffect, useRef, useState } from 'react'; import { IconButton } from '~/components/ui/IconButton'; import { workbenchStore } from '~/lib/stores/workbench'; import { PortDropdown } from './PortDropdown'; export const Preview = memo(() => { const iframeRef = useRef(null); const inputRef = useRef(null); const [activePreviewIndex, setActivePreviewIndex] = useState(0); const [isPortDropdownOpen, setIsPortDropdownOpen] = useState(false); const hasSelectedPreview = useRef(false); const previews = useStore(workbenchStore.previews); const activePreview = previews[activePreviewIndex]; const [url, setUrl] = useState(''); const [iframeUrl, setIframeUrl] = useState(); useEffect(() => { if (!activePreview) { setUrl(''); setIframeUrl(undefined); return; } const { baseUrl } = activePreview; setUrl(baseUrl); setIframeUrl(baseUrl); }, [activePreview, iframeUrl]); const validateUrl = useCallback( (value: string) => { if (!activePreview) { return false; } const { baseUrl } = activePreview; if (value === baseUrl) { return true; } else if (value.startsWith(baseUrl)) { return ['/', '?', '#'].includes(value.charAt(baseUrl.length)); } return false; }, [activePreview], ); const findMinPortIndex = useCallback( (minIndex: number, preview: { port: number }, index: number, array: { port: number }[]) => { return preview.port < array[minIndex].port ? index : minIndex; }, [], ); // when previews change, display the lowest port if user hasn't selected a preview useEffect(() => { if (previews.length > 1 && !hasSelectedPreview.current) { const minPortIndex = previews.reduce(findMinPortIndex, 0); setActivePreviewIndex(minPortIndex); } }, [previews]); const reloadPreview = () => { if (iframeRef.current) { iframeRef.current.src = iframeRef.current.src; } }; return (
{isPortDropdownOpen && (
setIsPortDropdownOpen(false)} /> )}
{ setUrl(event.target.value); }} onKeyDown={(event) => { if (event.key === 'Enter' && validateUrl(url)) { setIframeUrl(url); if (inputRef.current) { inputRef.current.blur(); } } }} />
{previews.length > 1 && ( (hasSelectedPreview.current = value)} setIsDropdownOpen={setIsPortDropdownOpen} previews={previews} /> )}
{activePreview ? (