import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types' import { ExternalLink, Globe, Loader2, Monitor, RefreshCw, Smartphone, Tablet, X } from 'lucide-react' import { createPreviewSession, usePreviewPorts } from '@/api/preview' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { useMobile } from '@/hooks/useMobile' import { useUrlParams } from '@/hooks/useUrlParams' import { buildPreviewStartUrl, getPreviewOrigin, isSameOriginAsManager } from '@/lib/preview-url' import { cn } from '@/lib/utils' interface PreviewPanelProps { isOpen: boolean onClose: () => void directory: string | undefined } type ViewportPreset = 'mobile' | 'tablet' | 'full' const VIEWPORT_WIDTHS: Record = { mobile: 390, tablet: 820, full: null, } const VIEWPORT_PRESETS: Array<{ preset: ViewportPreset; label: string; icon: typeof Monitor }> = [ { preset: 'mobile', label: 'Mobile viewport', icon: Smartphone }, { preset: 'tablet', label: 'Tablet viewport', icon: Tablet }, { preset: 'full', label: 'Full width viewport', icon: Monitor }, ] const PORT_WAIT_TIMEOUT_MS = 60_000 interface ActiveSession { targetPort: number path: string renderKey: number data: CreatePreviewSessionResponse } function isInsideDirectory(cwd: string | null, directory: string | undefined): boolean { if (!cwd || !directory) return false if (cwd === directory) return true const prefix = directory.endsWith('/') ? directory : `${directory}/` return cwd.startsWith(prefix) } function errorMessage(error: unknown, fallback: string): string { return error instanceof Error ? error.message : fallback } export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) { const isMobile = useMobile() const { searchParams, updateParams } = useUrlParams() const requestedPort = useMemo(() => { const raw = searchParams.get('previewPort') if (!raw) return undefined const port = Number(raw) return Number.isInteger(port) && port > 0 && port <= 65535 ? port : undefined }, [searchParams]) const requestedPath = searchParams.get('previewPath') || '/' const [pathDraft, setPathDraft] = useState(requestedPath) const [viewport, setViewport] = useState('full') const [session, setSession] = useState(null) const [sessionError, setSessionError] = useState(null) const [waitExpired, setWaitExpired] = useState(false) const [retryNonce, setRetryNonce] = useState(0) const sessionPortRef = useRef(null) const activePathRef = useRef(null) const requestIdRef = useRef(0) const portsQuery = usePreviewPorts(directory, { enabled: isOpen, refetchInterval: isOpen ? 2000 : false, }) const ports = useMemo(() => portsQuery.data?.ports ?? [], [portsQuery.data]) const enabled = portsQuery.data?.enabled ?? true const portListed = requestedPort !== undefined && ports.some((entry) => entry.port === requestedPort) useEffect(() => { setPathDraft(requestedPath) }, [requestedPath]) useEffect(() => { if (!isOpen) { requestIdRef.current += 1 sessionPortRef.current = null activePathRef.current = null setSession(null) setSessionError(null) } }, [isOpen]) useEffect(() => { if (portListed) return requestIdRef.current += 1 sessionPortRef.current = null activePathRef.current = null setSession(null) }, [portListed]) useEffect(() => { if (!isOpen || !requestedPort || !enabled || portListed) { setWaitExpired(false) return } setWaitExpired(false) const timer = setTimeout(() => setWaitExpired(true), PORT_WAIT_TIMEOUT_MS) return () => clearTimeout(timer) }, [isOpen, requestedPort, enabled, portListed, retryNonce]) const startSession = useCallback((port: number, path: string) => { const requestId = requestIdRef.current + 1 requestIdRef.current = requestId sessionPortRef.current = port activePathRef.current = path setSessionError(null) setSession(null) return createPreviewSession(port) .then((data) => { if (requestIdRef.current !== requestId) return setSession({ targetPort: port, path, renderKey: requestId, data }) }) .catch((error: unknown) => { if (requestIdRef.current !== requestId) return sessionPortRef.current = null activePathRef.current = null setSessionError(errorMessage(error, 'Failed to start preview')) }) }, []) useEffect(() => { if (!isOpen || !requestedPort || !enabled || !portListed) return if (sessionPortRef.current === requestedPort && activePathRef.current === requestedPath) return void startSession(requestedPort, requestedPath) }, [isOpen, requestedPort, requestedPath, enabled, portListed, startSession]) const selectPort = useCallback((port: number) => { updateParams((params) => { params.set('previewPort', String(port)) params.delete('previewPath') }, 'replace') }, [updateParams]) const reload = useCallback(() => { if (!requestedPort) return void startSession(requestedPort, requestedPath) }, [requestedPort, requestedPath, startSession]) const handleGo = useCallback(() => { const nextPath = pathDraft.trim() || '/' updateParams((params) => { params.set('previewPath', nextPath) }, 'replace') if (requestedPort) { void startSession(requestedPort, nextPath) } }, [pathDraft, requestedPort, updateParams, startSession]) const handleOpenInNewTab = useCallback(() => { if (!requestedPort) return createPreviewSession(requestedPort) .then((data) => { window.open(buildPreviewStartUrl(data, requestedPath), '_blank', 'noopener,noreferrer') }) .catch((error: unknown) => { setSessionError(errorMessage(error, 'Failed to open preview')) }) }, [requestedPort, requestedPath]) const retry = useCallback(() => { if (portListed && requestedPort) { void startSession(requestedPort, requestedPath) return } setWaitExpired(false) setRetryNonce((nonce) => nonce + 1) void portsQuery.refetch() }, [portListed, requestedPort, requestedPath, startSession, portsQuery]) const activeSession = session && session.targetPort === requestedPort ? session : null const previewOrigin = activeSession ? getPreviewOrigin(activeSession.data) : null const sameOrigin = previewOrigin ? isSameOriginAsManager(previewOrigin) : false const viewportWidth = VIEWPORT_WIDTHS[viewport] const renderMessage = (message: ReactNode, options: { retry?: boolean; alert?: boolean } = {}) => (
{message}
{options.retry && ( )}
) const body = () => { if (!enabled) { return renderMessage('Preview is disabled (PREVIEW_PORT=0)') } if (!requestedPort) { return renderMessage('Select a port to preview') } if (!portListed) { if (waitExpired) { return renderMessage(`Port ${requestedPort} is not listening`, { retry: true, alert: true }) } return renderMessage( <> Waiting for port {requestedPort}… , ) } if (sessionError) { return renderMessage(sessionError, { retry: true, alert: true }) } if (activeSession) { if (sameOrigin) { return renderMessage('Preview must run on a different origin than OpenCode Manager.', { alert: true }) } return (