From 87ff81035fb9cf127939e8789b244e71facb0b06 Mon Sep 17 00:00:00 2001 From: Stijnus <72551117+Stijnus@users.noreply.github.com> Date: Fri, 17 Jan 2025 21:25:44 +0100 Subject: [PATCH] feat: added the "Open Preview in a New Tab" (#1101) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * added the "Open Preview in a New Tab" * enhancement [Open Preview] [▼] // Two buttons side by side | +-- [Mobile (375x667)] // Dropdown menu |-- [Tablet (768x1024)] |-- [Laptop (1366x768)] +-- [Desktop (1920x1080)] * Update Preview.tsx * Update Preview.tsx --- app/components/workbench/Preview.tsx | 120 ++++++++--- app/lib/stores/previews.ts | 260 ++++++++++++++++++++++++ app/routes/webcontainer.preview.$id.tsx | 92 +++++++++ 3 files changed, 445 insertions(+), 27 deletions(-) create mode 100644 app/routes/webcontainer.preview.$id.tsx diff --git a/app/components/workbench/Preview.tsx b/app/components/workbench/Preview.tsx index b2d97e31..68cc73e2 100644 --- a/app/components/workbench/Preview.tsx +++ b/app/components/workbench/Preview.tsx @@ -1,5 +1,5 @@ -import { useStore } from '@nanostores/react'; import { memo, useCallback, useEffect, useRef, useState } from 'react'; +import { useStore } from '@nanostores/react'; import { IconButton } from '~/components/ui/IconButton'; import { workbenchStore } from '~/lib/stores/workbench'; import { PortDropdown } from './PortDropdown'; @@ -7,6 +7,19 @@ import { ScreenshotSelector } from './ScreenshotSelector'; type ResizeSide = 'left' | 'right' | null; +interface WindowSize { + name: string; + width: number; + height: number; +} + +const WINDOW_SIZES: WindowSize[] = [ + { name: 'Mobile (375x667)', width: 375, height: 667 }, + { name: 'Tablet (768x1024)', width: 768, height: 1024 }, + { name: 'Laptop (1366x768)', width: 1366, height: 768 }, + { name: 'Desktop (1920x1080)', width: 1920, height: 1080 }, +]; + export const Preview = memo(() => { const iframeRef = useRef(null); const containerRef = useRef(null); @@ -15,6 +28,7 @@ export const Preview = memo(() => { const [activePreviewIndex, setActivePreviewIndex] = useState(0); const [isPortDropdownOpen, setIsPortDropdownOpen] = useState(false); const [isFullscreen, setIsFullscreen] = useState(false); + const [isPreviewOnly, setIsPreviewOnly] = useState(false); const hasSelectedPreview = useRef(false); const previews = useStore(workbenchStore.previews); const activePreview = previews[activePreviewIndex]; @@ -27,7 +41,7 @@ export const Preview = memo(() => { const [isDeviceModeOn, setIsDeviceModeOn] = useState(false); // Use percentage for width - const [widthPercent, setWidthPercent] = useState(37.5); // 375px assuming 1000px window width initially + const [widthPercent, setWidthPercent] = useState(37.5); const resizingState = useRef({ isResizing: false, @@ -37,8 +51,10 @@ export const Preview = memo(() => { windowWidth: window.innerWidth, }); - // Define the scaling factor - const SCALING_FACTOR = 2; // Adjust this value to increase/decrease sensitivity + const SCALING_FACTOR = 2; + + const [isWindowSizeDropdownOpen, setIsWindowSizeDropdownOpen] = useState(false); + const [selectedWindowSize, setSelectedWindowSize] = useState(WINDOW_SIZES[0]); useEffect(() => { if (!activePreview) { @@ -79,7 +95,6 @@ export const Preview = memo(() => { [], ); - // 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); @@ -122,7 +137,6 @@ export const Preview = memo(() => { return; } - // Prevent text selection document.body.style.userSelect = 'none'; resizingState.current.isResizing = true; @@ -134,7 +148,7 @@ export const Preview = memo(() => { document.addEventListener('mousemove', onMouseMove); document.addEventListener('mouseup', onMouseUp); - e.preventDefault(); // Prevent any text selection on mousedown + e.preventDefault(); }; const onMouseMove = (e: MouseEvent) => { @@ -145,7 +159,6 @@ export const Preview = memo(() => { const dx = e.clientX - resizingState.current.startX; const windowWidth = resizingState.current.windowWidth; - // Apply scaling factor to increase sensitivity const dxPercent = (dx / windowWidth) * 100 * SCALING_FACTOR; let newWidthPercent = resizingState.current.startWidthPercent; @@ -156,7 +169,6 @@ export const Preview = memo(() => { newWidthPercent = resizingState.current.startWidthPercent - dxPercent; } - // Clamp the width between 10% and 90% newWidthPercent = Math.max(10, Math.min(newWidthPercent, 90)); setWidthPercent(newWidthPercent); @@ -168,17 +180,12 @@ export const Preview = memo(() => { document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); - // Restore text selection document.body.style.userSelect = ''; }; - // Handle window resize to ensure widthPercent remains valid useEffect(() => { const handleWindowResize = () => { - /* - * Optional: Adjust widthPercent if necessary - * For now, since widthPercent is relative, no action is needed - */ + // Optional: Adjust widthPercent if necessary }; window.addEventListener('resize', handleWindowResize); @@ -188,7 +195,6 @@ export const Preview = memo(() => { }; }, []); - // A small helper component for the handle's "grip" icon const GripIcon = () => (
{
); + const openInNewWindow = (size: WindowSize) => { + if (activePreview?.baseUrl) { + const match = activePreview.baseUrl.match(/^https?:\/\/([^.]+)\.local-credentialless\.webcontainer-api\.io/); + + if (match) { + const previewId = match[1]; + const previewUrl = `/webcontainer/preview/${previewId}`; + const newWindow = window.open( + previewUrl, + '_blank', + `noopener,noreferrer,width=${size.width},height=${size.height},menubar=no,toolbar=no,location=no,status=no`, + ); + + if (newWindow) { + newWindow.focus(); + } + } else { + console.warn('[Preview] Invalid WebContainer URL:', activePreview.baseUrl); + } + } + }; + return ( -
+
{isPortDropdownOpen && (
setIsPortDropdownOpen(false)} /> )} @@ -225,10 +256,7 @@ export const Preview = memo(() => { onClick={() => setIsSelectionMode(!isSelectionMode)} className={isSelectionMode ? 'bg-bolt-elements-background-depth-3' : ''} /> -
+
{ /> )} - {/* Device mode toggle button */} - {/* Fullscreen toggle button */} + setIsPreviewOnly(!isPreviewOnly)} + title={isPreviewOnly ? 'Show Full Interface' : 'Show Preview Only'} + /> + + +
+ openInNewWindow(selectedWindowSize)} + title={`Open Preview in ${selectedWindowSize.name} Window`} + /> + setIsWindowSizeDropdownOpen(!isWindowSizeDropdownOpen)} + className="ml-1" + title="Select Window Size" + /> + + {isWindowSizeDropdownOpen && ( + <> +
setIsWindowSizeDropdownOpen(false)} /> +
+ {WINDOW_SIZES.map((size) => ( + + ))} +
+ + )} +
{ title="preview" className="border-none w-full h-full bg-white" src={iframeUrl} - allowFullScreen + sandbox="allow-scripts allow-forms allow-popups allow-modals allow-storage-access-by-user-activation allow-same-origin" + allow="cross-origin-isolated" /> { {isDeviceModeOn && ( <> - {/* Left handle */}
startResizing(e, 'left')} style={{ @@ -333,7 +400,6 @@ export const Preview = memo(() => {
- {/* Right handle */}
startResizing(e, 'right')} style={{ diff --git a/app/lib/stores/previews.ts b/app/lib/stores/previews.ts index 79480d1c..28954844 100644 --- a/app/lib/stores/previews.ts +++ b/app/lib/stores/previews.ts @@ -1,27 +1,192 @@ import type { WebContainer } from '@webcontainer/api'; import { atom } from 'nanostores'; +// Extend Window interface to include our custom property +declare global { + interface Window { + _tabId?: string; + } +} + export interface PreviewInfo { port: number; ready: boolean; baseUrl: string; } +// Create a broadcast channel for preview updates +const PREVIEW_CHANNEL = 'preview-updates'; + export class PreviewsStore { #availablePreviews = new Map(); #webcontainer: Promise; + #broadcastChannel: BroadcastChannel; + #lastUpdate = new Map(); + #watchedFiles = new Set(); + #refreshTimeouts = new Map(); + #REFRESH_DELAY = 300; + #storageChannel: BroadcastChannel; previews = atom([]); constructor(webcontainerPromise: Promise) { this.#webcontainer = webcontainerPromise; + this.#broadcastChannel = new BroadcastChannel(PREVIEW_CHANNEL); + this.#storageChannel = new BroadcastChannel('storage-sync-channel'); + + // Listen for preview updates from other tabs + this.#broadcastChannel.onmessage = (event) => { + const { type, previewId } = event.data; + + if (type === 'file-change') { + const timestamp = event.data.timestamp; + const lastUpdate = this.#lastUpdate.get(previewId) || 0; + + if (timestamp > lastUpdate) { + this.#lastUpdate.set(previewId, timestamp); + this.refreshPreview(previewId); + } + } + }; + + // Listen for storage sync messages + this.#storageChannel.onmessage = (event) => { + const { storage, source } = event.data; + + if (storage && source !== this._getTabId()) { + this._syncStorage(storage); + } + }; + + // Override localStorage setItem to catch all changes + if (typeof window !== 'undefined') { + const originalSetItem = localStorage.setItem; + + localStorage.setItem = (...args) => { + originalSetItem.apply(localStorage, args); + this._broadcastStorageSync(); + }; + } this.#init(); } + // Generate a unique ID for this tab + private _getTabId(): string { + if (typeof window !== 'undefined') { + if (!window._tabId) { + window._tabId = Math.random().toString(36).substring(2, 15); + } + + return window._tabId; + } + + return ''; + } + + // Sync storage data between tabs + private _syncStorage(storage: Record) { + if (typeof window !== 'undefined') { + Object.entries(storage).forEach(([key, value]) => { + try { + const originalSetItem = Object.getPrototypeOf(localStorage).setItem; + originalSetItem.call(localStorage, key, value); + } catch (error) { + console.error('[Preview] Error syncing storage:', error); + } + }); + + // Force a refresh after syncing storage + const previews = this.previews.get(); + previews.forEach((preview) => { + const previewId = this.getPreviewId(preview.baseUrl); + + if (previewId) { + this.refreshPreview(previewId); + } + }); + + // Reload the page content + if (typeof window !== 'undefined' && window.location) { + const iframe = document.querySelector('iframe'); + + if (iframe) { + iframe.src = iframe.src; + } + } + } + } + + // Broadcast storage state to other tabs + private _broadcastStorageSync() { + if (typeof window !== 'undefined') { + const storage: Record = {}; + + for (let i = 0; i < localStorage.length; i++) { + const key = localStorage.key(i); + + if (key) { + storage[key] = localStorage.getItem(key) || ''; + } + } + + this.#storageChannel.postMessage({ + type: 'storage-sync', + storage, + source: this._getTabId(), + timestamp: Date.now(), + }); + } + } + async #init() { const webcontainer = await this.#webcontainer; + // Listen for server ready events + webcontainer.on('server-ready', (port, url) => { + console.log('[Preview] Server ready on port:', port, url); + this.broadcastUpdate(url); + + // Initial storage sync when preview is ready + this._broadcastStorageSync(); + }); + + try { + // Watch for file changes + const watcher = await webcontainer.fs.watch('**/*', { persistent: true }); + + // Use the native watch events + (watcher as any).addEventListener('change', async () => { + const previews = this.previews.get(); + + for (const preview of previews) { + const previewId = this.getPreviewId(preview.baseUrl); + + if (previewId) { + this.broadcastFileChange(previewId); + } + } + }); + + // Watch for DOM changes that might affect storage + if (typeof window !== 'undefined') { + const observer = new MutationObserver((_mutations) => { + // Broadcast storage changes when DOM changes + this._broadcastStorageSync(); + }); + + observer.observe(document.body, { + childList: true, + subtree: true, + characterData: true, + attributes: true, + }); + } + } catch (error) { + console.error('[Preview] Error setting up watchers:', error); + } + + // Listen for port events webcontainer.on('port', (port, type, url) => { let previewInfo = this.#availablePreviews.get(port); @@ -44,6 +209,101 @@ export class PreviewsStore { previewInfo.baseUrl = url; this.previews.set([...previews]); + + if (type === 'open') { + this.broadcastUpdate(url); + } }); } + + // Helper to extract preview ID from URL + getPreviewId(url: string): string | null { + const match = url.match(/^https?:\/\/([^.]+)\.local-credentialless\.webcontainer-api\.io/); + return match ? match[1] : null; + } + + // Broadcast state change to all tabs + broadcastStateChange(previewId: string) { + const timestamp = Date.now(); + this.#lastUpdate.set(previewId, timestamp); + + this.#broadcastChannel.postMessage({ + type: 'state-change', + previewId, + timestamp, + }); + } + + // Broadcast file change to all tabs + broadcastFileChange(previewId: string) { + const timestamp = Date.now(); + this.#lastUpdate.set(previewId, timestamp); + + this.#broadcastChannel.postMessage({ + type: 'file-change', + previewId, + timestamp, + }); + } + + // Broadcast update to all tabs + broadcastUpdate(url: string) { + const previewId = this.getPreviewId(url); + + if (previewId) { + const timestamp = Date.now(); + this.#lastUpdate.set(previewId, timestamp); + + this.#broadcastChannel.postMessage({ + type: 'file-change', + previewId, + timestamp, + }); + } + } + + // Method to refresh a specific preview + refreshPreview(previewId: string) { + // Clear any pending refresh for this preview + const existingTimeout = this.#refreshTimeouts.get(previewId); + + if (existingTimeout) { + clearTimeout(existingTimeout); + } + + // Set a new timeout for this refresh + const timeout = setTimeout(() => { + const previews = this.previews.get(); + const preview = previews.find((p) => this.getPreviewId(p.baseUrl) === previewId); + + if (preview) { + preview.ready = false; + this.previews.set([...previews]); + + requestAnimationFrame(() => { + preview.ready = true; + this.previews.set([...previews]); + }); + } + + this.#refreshTimeouts.delete(previewId); + }, this.#REFRESH_DELAY); + + this.#refreshTimeouts.set(previewId, timeout); + } +} + +// Create a singleton instance +let previewsStore: PreviewsStore | null = null; + +export function usePreviewStore() { + if (!previewsStore) { + /* + * Initialize with a Promise that resolves to WebContainer + * This should match how you're initializing WebContainer elsewhere + */ + previewsStore = new PreviewsStore(Promise.resolve({} as WebContainer)); + } + + return previewsStore; } diff --git a/app/routes/webcontainer.preview.$id.tsx b/app/routes/webcontainer.preview.$id.tsx new file mode 100644 index 00000000..a52ccf92 --- /dev/null +++ b/app/routes/webcontainer.preview.$id.tsx @@ -0,0 +1,92 @@ +import { json, type LoaderFunctionArgs } from '@remix-run/cloudflare'; +import { useLoaderData } from '@remix-run/react'; +import { useCallback, useEffect, useRef, useState } from 'react'; + +const PREVIEW_CHANNEL = 'preview-updates'; + +export async function loader({ params }: LoaderFunctionArgs) { + const previewId = params.id; + + if (!previewId) { + throw new Response('Preview ID is required', { status: 400 }); + } + + return json({ previewId }); +} + +export default function WebContainerPreview() { + const { previewId } = useLoaderData(); + const iframeRef = useRef(null); + const broadcastChannelRef = useRef(); + const [previewUrl, setPreviewUrl] = useState(''); + + // Handle preview refresh + const handleRefresh = useCallback(() => { + if (iframeRef.current && previewUrl) { + // Force a clean reload + iframeRef.current.src = ''; + requestAnimationFrame(() => { + if (iframeRef.current) { + iframeRef.current.src = previewUrl; + } + }); + } + }, [previewUrl]); + + // Notify other tabs that this preview is ready + const notifyPreviewReady = useCallback(() => { + if (broadcastChannelRef.current && previewUrl) { + broadcastChannelRef.current.postMessage({ + type: 'preview-ready', + previewId, + url: previewUrl, + timestamp: Date.now(), + }); + } + }, [previewId, previewUrl]); + + useEffect(() => { + // Initialize broadcast channel + broadcastChannelRef.current = new BroadcastChannel(PREVIEW_CHANNEL); + + // Listen for preview updates + broadcastChannelRef.current.onmessage = (event) => { + if (event.data.previewId === previewId) { + if (event.data.type === 'refresh-preview' || event.data.type === 'file-change') { + handleRefresh(); + } + } + }; + + // Construct the WebContainer preview URL + const url = `https://${previewId}.local-credentialless.webcontainer-api.io`; + setPreviewUrl(url); + + // Set the iframe src + if (iframeRef.current) { + iframeRef.current.src = url; + } + + // Notify other tabs that this preview is ready + notifyPreviewReady(); + + // Cleanup + return () => { + broadcastChannelRef.current?.close(); + }; + }, [previewId, handleRefresh, notifyPreviewReady]); + + return ( +
+