'use client'; import { AlertTriangle, RotateCw, Terminal, Trash2 } from 'lucide-react'; import * as React from 'react'; import { Button } from '@/components/ui/button'; import { cn } from '@/lib/utils'; export type ExampleConsoleEntry = { detail?: string; id: number; label: string; time: string; }; type ExampleConsoleContextValue = { clear: () => void; entries: ExampleConsoleEntry[]; log: (label: string, detail?: string) => void; }; const MAX_CONSOLE_ENTRIES = 50; const ExampleConsoleContext = React.createContext(null); function formatTimestamp(date: Date) { return date.toLocaleTimeString('en-US', { hour: '2-digit', hour12: false, minute: '2-digit', second: '2-digit', }); } export function ExampleConsoleProvider({ children, }: { children: React.ReactNode; }) { const [entries, setEntries] = React.useState([]); const nextIdRef = React.useRef(1); const log = React.useCallback((label: string, detail?: string) => { const id = nextIdRef.current; nextIdRef.current += 1; const time = formatTimestamp(new Date()); setEntries((prev) => { const next = [...prev, { detail, id, label, time }]; return next.length > MAX_CONSOLE_ENTRIES ? next.slice(next.length - MAX_CONSOLE_ENTRIES) : next; }); }, []); const clear = React.useCallback(() => { setEntries([]); }, []); const value = React.useMemo( () => ({ clear, entries, log }), [clear, entries, log] ); return ( {children} ); } export function useExampleConsole() { return React.useContext(ExampleConsoleContext); } const TRACKED_SPECIAL_KEYS = new Set([ 'Backspace', 'Delete', 'Enter', 'Escape', 'Tab', ]); function formatKeyEvent(event: KeyboardEvent) { const parts: string[] = []; if (event.metaKey) parts.push('Cmd'); if (event.ctrlKey) parts.push('Ctrl'); if (event.altKey) parts.push('Alt'); if ( event.shiftKey && (parts.length > 0 || TRACKED_SPECIAL_KEYS.has(event.key)) ) { parts.push('Shift'); } const hasShortcutModifier = event.metaKey || event.ctrlKey || event.altKey; if (!hasShortcutModifier && !TRACKED_SPECIAL_KEYS.has(event.key)) { return null; } const keyLabel = event.key.length === 1 ? event.key.toUpperCase() : event.key; parts.push(keyLabel); return parts.join('+'); } export function usePreviewEventConsole( containerRef: React.RefObject, enabled: boolean ) { const consoleCtx = useExampleConsole(); React.useEffect(() => { if (!enabled || !consoleCtx) return undefined; const element = containerRef.current; if (!element) return undefined; const handleBeforeInput = (event: Event) => { const inputEvent = event as InputEvent; const data = inputEvent.data ? JSON.stringify(inputEvent.data.slice(0, 48)) : undefined; consoleCtx.log( 'beforeinput', data ? `${inputEvent.inputType} ${data}` : inputEvent.inputType ); }; const handleKeyDown = (event: KeyboardEvent) => { const formatted = formatKeyEvent(event); if (formatted) { consoleCtx.log('keydown', formatted); } }; const handlePaste = (event: ClipboardEvent) => { const types = [...(event.clipboardData?.types ?? [])]; consoleCtx.log( 'paste', types.length > 0 ? types.join(', ') : 'clipboard' ); }; element.addEventListener('beforeinput', handleBeforeInput, { passive: true, }); element.addEventListener('keydown', handleKeyDown, { passive: true }); element.addEventListener('paste', handlePaste, { passive: true }); return () => { element.removeEventListener('beforeinput', handleBeforeInput); element.removeEventListener('keydown', handleKeyDown); element.removeEventListener('paste', handlePaste); }; }, [consoleCtx, containerRef, enabled]); } export function ExampleConsole({ className, emptyLabel = 'Interact with the editor above to inspect live events.', }: { className?: string; emptyLabel?: string; }) { const consoleCtx = useExampleConsole(); const listRef = React.useRef(null); React.useEffect(() => { const list = listRef.current; if (list) { list.scrollTop = list.scrollHeight; } }, [consoleCtx?.entries.length]); if (!consoleCtx) return null; const { clear, entries } = consoleCtx; return (
Console {entries.length > 0 && ( {entries.length} )} {entries.length > 0 && ( )}
{entries.length === 0 ? (

{emptyLabel}

) : (
    {entries.map((entry) => (
  • {entry.time} {entry.label} {entry.detail && ( {entry.detail} )}
  • ))}
)}
); } type ExampleErrorBoundaryInnerProps = { children: React.ReactNode; name?: string; onRetry: () => void; }; type ExampleErrorBoundaryState = { error: Error | null; }; class ExampleErrorBoundaryInner extends React.Component< ExampleErrorBoundaryInnerProps, ExampleErrorBoundaryState > { state: ExampleErrorBoundaryState = { error: null }; static getDerivedStateFromError(error: Error): ExampleErrorBoundaryState { return { error }; } render() { if (this.state.error) { return (

{this.props.name ? `Preview "${this.props.name}" failed to render.` : 'Preview failed to render.'}

{this.state.error.message}

); } return this.props.children; } } export function ExampleErrorBoundary({ children, name, resetKey = 0, }: { children: React.ReactNode; name?: string; resetKey?: number; }) { const [retryCount, setRetryCount] = React.useState(0); const handleRetry = React.useCallback(() => { setRetryCount((count) => count + 1); }, []); return ( {children} ); } export function ExampleViewportGate({ children, className, eager = false, fallback, }: { children: React.ReactNode; className?: string; eager?: boolean; fallback: React.ReactNode; }) { const containerRef = React.useRef(null); const [activated, setActivated] = React.useState(eager); React.useEffect(() => { if (activated) return undefined; const element = containerRef.current; if (!element || typeof IntersectionObserver === 'undefined') { setActivated(true); return undefined; } const observer = new IntersectionObserver( (entries) => { if (entries.some((entry) => entry.isIntersecting)) { setActivated(true); observer.disconnect(); } }, { rootMargin: '100% 0px' } ); observer.observe(element); return () => { observer.disconnect(); }; }, [activated]); return (
{activated ? children : fallback}
); } export function DeferredCodeBlock({ active, children, }: { active: boolean; children: React.ReactNode; }) { const [idleReady, setIdleReady] = React.useState(false); const isReady = active || idleReady; React.useEffect(() => { if (isReady) return undefined; const win = window as Window & { cancelIdleCallback?: (id: number) => void; requestIdleCallback?: ( callback: () => void, options?: { timeout?: number } ) => number; }; if (typeof win.requestIdleCallback === 'function') { const id = win.requestIdleCallback( () => { setIdleReady(true); }, { timeout: 2000 } ); return () => { win.cancelIdleCallback?.(id); }; } const timer = setTimeout(() => { setIdleReady(true); }, 500); return () => { clearTimeout(timer); }; }, [isReady]); return isReady ? children : null; }