Stijnus
commited on
feat: added the "Open Preview in a New Tab" (#1101)
Browse files* 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
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
-
import { useStore } from '@nanostores/react';
|
2 |
import { memo, useCallback, useEffect, useRef, useState } from 'react';
|
|
|
3 |
import { IconButton } from '~/components/ui/IconButton';
|
4 |
import { workbenchStore } from '~/lib/stores/workbench';
|
5 |
import { PortDropdown } from './PortDropdown';
|
@@ -7,6 +7,19 @@ import { ScreenshotSelector } from './ScreenshotSelector';
|
|
7 |
|
8 |
type ResizeSide = 'left' | 'right' | null;
|
9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
export const Preview = memo(() => {
|
11 |
const iframeRef = useRef<HTMLIFrameElement>(null);
|
12 |
const containerRef = useRef<HTMLDivElement>(null);
|
@@ -15,6 +28,7 @@ export const Preview = memo(() => {
|
|
15 |
const [activePreviewIndex, setActivePreviewIndex] = useState(0);
|
16 |
const [isPortDropdownOpen, setIsPortDropdownOpen] = useState(false);
|
17 |
const [isFullscreen, setIsFullscreen] = useState(false);
|
|
|
18 |
const hasSelectedPreview = useRef(false);
|
19 |
const previews = useStore(workbenchStore.previews);
|
20 |
const activePreview = previews[activePreviewIndex];
|
@@ -27,7 +41,7 @@ export const Preview = memo(() => {
|
|
27 |
const [isDeviceModeOn, setIsDeviceModeOn] = useState(false);
|
28 |
|
29 |
// Use percentage for width
|
30 |
-
const [widthPercent, setWidthPercent] = useState<number>(37.5);
|
31 |
|
32 |
const resizingState = useRef({
|
33 |
isResizing: false,
|
@@ -37,8 +51,10 @@ export const Preview = memo(() => {
|
|
37 |
windowWidth: window.innerWidth,
|
38 |
});
|
39 |
|
40 |
-
|
41 |
-
|
|
|
|
|
42 |
|
43 |
useEffect(() => {
|
44 |
if (!activePreview) {
|
@@ -79,7 +95,6 @@ export const Preview = memo(() => {
|
|
79 |
[],
|
80 |
);
|
81 |
|
82 |
-
// When previews change, display the lowest port if user hasn't selected a preview
|
83 |
useEffect(() => {
|
84 |
if (previews.length > 1 && !hasSelectedPreview.current) {
|
85 |
const minPortIndex = previews.reduce(findMinPortIndex, 0);
|
@@ -122,7 +137,6 @@ export const Preview = memo(() => {
|
|
122 |
return;
|
123 |
}
|
124 |
|
125 |
-
// Prevent text selection
|
126 |
document.body.style.userSelect = 'none';
|
127 |
|
128 |
resizingState.current.isResizing = true;
|
@@ -134,7 +148,7 @@ export const Preview = memo(() => {
|
|
134 |
document.addEventListener('mousemove', onMouseMove);
|
135 |
document.addEventListener('mouseup', onMouseUp);
|
136 |
|
137 |
-
e.preventDefault();
|
138 |
};
|
139 |
|
140 |
const onMouseMove = (e: MouseEvent) => {
|
@@ -145,7 +159,6 @@ export const Preview = memo(() => {
|
|
145 |
const dx = e.clientX - resizingState.current.startX;
|
146 |
const windowWidth = resizingState.current.windowWidth;
|
147 |
|
148 |
-
// Apply scaling factor to increase sensitivity
|
149 |
const dxPercent = (dx / windowWidth) * 100 * SCALING_FACTOR;
|
150 |
|
151 |
let newWidthPercent = resizingState.current.startWidthPercent;
|
@@ -156,7 +169,6 @@ export const Preview = memo(() => {
|
|
156 |
newWidthPercent = resizingState.current.startWidthPercent - dxPercent;
|
157 |
}
|
158 |
|
159 |
-
// Clamp the width between 10% and 90%
|
160 |
newWidthPercent = Math.max(10, Math.min(newWidthPercent, 90));
|
161 |
|
162 |
setWidthPercent(newWidthPercent);
|
@@ -168,17 +180,12 @@ export const Preview = memo(() => {
|
|
168 |
document.removeEventListener('mousemove', onMouseMove);
|
169 |
document.removeEventListener('mouseup', onMouseUp);
|
170 |
|
171 |
-
// Restore text selection
|
172 |
document.body.style.userSelect = '';
|
173 |
};
|
174 |
|
175 |
-
// Handle window resize to ensure widthPercent remains valid
|
176 |
useEffect(() => {
|
177 |
const handleWindowResize = () => {
|
178 |
-
|
179 |
-
* Optional: Adjust widthPercent if necessary
|
180 |
-
* For now, since widthPercent is relative, no action is needed
|
181 |
-
*/
|
182 |
};
|
183 |
|
184 |
window.addEventListener('resize', handleWindowResize);
|
@@ -188,7 +195,6 @@ export const Preview = memo(() => {
|
|
188 |
};
|
189 |
}, []);
|
190 |
|
191 |
-
// A small helper component for the handle's "grip" icon
|
192 |
const GripIcon = () => (
|
193 |
<div
|
194 |
style={{
|
@@ -213,8 +219,33 @@ export const Preview = memo(() => {
|
|
213 |
</div>
|
214 |
);
|
215 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
216 |
return (
|
217 |
-
<div
|
|
|
|
|
|
|
218 |
{isPortDropdownOpen && (
|
219 |
<div className="z-iframe-overlay w-full h-full absolute" onClick={() => setIsPortDropdownOpen(false)} />
|
220 |
)}
|
@@ -225,10 +256,7 @@ export const Preview = memo(() => {
|
|
225 |
onClick={() => setIsSelectionMode(!isSelectionMode)}
|
226 |
className={isSelectionMode ? 'bg-bolt-elements-background-depth-3' : ''}
|
227 |
/>
|
228 |
-
<div
|
229 |
-
className="flex items-center gap-1 flex-grow bg-bolt-elements-preview-addressBar-background border border-bolt-elements-borderColor text-bolt-elements-preview-addressBar-text rounded-full px-3 py-1 text-sm hover:bg-bolt-elements-preview-addressBar-backgroundHover hover:focus-within:bg-bolt-elements-preview-addressBar-backgroundActive focus-within:bg-bolt-elements-preview-addressBar-backgroundActive
|
230 |
-
focus-within-border-bolt-elements-borderColorActive focus-within:text-bolt-elements-preview-addressBar-textActive"
|
231 |
-
>
|
232 |
<input
|
233 |
title="URL"
|
234 |
ref={inputRef}
|
@@ -261,26 +289,65 @@ export const Preview = memo(() => {
|
|
261 |
/>
|
262 |
)}
|
263 |
|
264 |
-
{/* Device mode toggle button */}
|
265 |
<IconButton
|
266 |
icon="i-ph:devices"
|
267 |
onClick={toggleDeviceMode}
|
268 |
title={isDeviceModeOn ? 'Switch to Responsive Mode' : 'Switch to Device Mode'}
|
269 |
/>
|
270 |
|
271 |
-
|
|
|
|
|
|
|
|
|
|
|
272 |
<IconButton
|
273 |
icon={isFullscreen ? 'i-ph:arrows-in' : 'i-ph:arrows-out'}
|
274 |
onClick={toggleFullscreen}
|
275 |
title={isFullscreen ? 'Exit Full Screen' : 'Full Screen'}
|
276 |
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
277 |
</div>
|
278 |
|
279 |
<div className="flex-1 border-t border-bolt-elements-borderColor flex justify-center items-center overflow-auto">
|
280 |
<div
|
281 |
style={{
|
282 |
width: isDeviceModeOn ? `${widthPercent}%` : '100%',
|
283 |
-
height: '100%',
|
284 |
overflow: 'visible',
|
285 |
background: '#fff',
|
286 |
position: 'relative',
|
@@ -294,7 +361,8 @@ export const Preview = memo(() => {
|
|
294 |
title="preview"
|
295 |
className="border-none w-full h-full bg-white"
|
296 |
src={iframeUrl}
|
297 |
-
|
|
|
298 |
/>
|
299 |
<ScreenshotSelector
|
300 |
isSelectionMode={isSelectionMode}
|
@@ -308,7 +376,6 @@ export const Preview = memo(() => {
|
|
308 |
|
309 |
{isDeviceModeOn && (
|
310 |
<>
|
311 |
-
{/* Left handle */}
|
312 |
<div
|
313 |
onMouseDown={(e) => startResizing(e, 'left')}
|
314 |
style={{
|
@@ -333,7 +400,6 @@ export const Preview = memo(() => {
|
|
333 |
<GripIcon />
|
334 |
</div>
|
335 |
|
336 |
-
{/* Right handle */}
|
337 |
<div
|
338 |
onMouseDown={(e) => startResizing(e, 'right')}
|
339 |
style={{
|
|
|
|
|
1 |
import { memo, useCallback, useEffect, useRef, useState } from 'react';
|
2 |
+
import { useStore } from '@nanostores/react';
|
3 |
import { IconButton } from '~/components/ui/IconButton';
|
4 |
import { workbenchStore } from '~/lib/stores/workbench';
|
5 |
import { PortDropdown } from './PortDropdown';
|
|
|
7 |
|
8 |
type ResizeSide = 'left' | 'right' | null;
|
9 |
|
10 |
+
interface WindowSize {
|
11 |
+
name: string;
|
12 |
+
width: number;
|
13 |
+
height: number;
|
14 |
+
}
|
15 |
+
|
16 |
+
const WINDOW_SIZES: WindowSize[] = [
|
17 |
+
{ name: 'Mobile (375x667)', width: 375, height: 667 },
|
18 |
+
{ name: 'Tablet (768x1024)', width: 768, height: 1024 },
|
19 |
+
{ name: 'Laptop (1366x768)', width: 1366, height: 768 },
|
20 |
+
{ name: 'Desktop (1920x1080)', width: 1920, height: 1080 },
|
21 |
+
];
|
22 |
+
|
23 |
export const Preview = memo(() => {
|
24 |
const iframeRef = useRef<HTMLIFrameElement>(null);
|
25 |
const containerRef = useRef<HTMLDivElement>(null);
|
|
|
28 |
const [activePreviewIndex, setActivePreviewIndex] = useState(0);
|
29 |
const [isPortDropdownOpen, setIsPortDropdownOpen] = useState(false);
|
30 |
const [isFullscreen, setIsFullscreen] = useState(false);
|
31 |
+
const [isPreviewOnly, setIsPreviewOnly] = useState(false);
|
32 |
const hasSelectedPreview = useRef(false);
|
33 |
const previews = useStore(workbenchStore.previews);
|
34 |
const activePreview = previews[activePreviewIndex];
|
|
|
41 |
const [isDeviceModeOn, setIsDeviceModeOn] = useState(false);
|
42 |
|
43 |
// Use percentage for width
|
44 |
+
const [widthPercent, setWidthPercent] = useState<number>(37.5);
|
45 |
|
46 |
const resizingState = useRef({
|
47 |
isResizing: false,
|
|
|
51 |
windowWidth: window.innerWidth,
|
52 |
});
|
53 |
|
54 |
+
const SCALING_FACTOR = 2;
|
55 |
+
|
56 |
+
const [isWindowSizeDropdownOpen, setIsWindowSizeDropdownOpen] = useState(false);
|
57 |
+
const [selectedWindowSize, setSelectedWindowSize] = useState<WindowSize>(WINDOW_SIZES[0]);
|
58 |
|
59 |
useEffect(() => {
|
60 |
if (!activePreview) {
|
|
|
95 |
[],
|
96 |
);
|
97 |
|
|
|
98 |
useEffect(() => {
|
99 |
if (previews.length > 1 && !hasSelectedPreview.current) {
|
100 |
const minPortIndex = previews.reduce(findMinPortIndex, 0);
|
|
|
137 |
return;
|
138 |
}
|
139 |
|
|
|
140 |
document.body.style.userSelect = 'none';
|
141 |
|
142 |
resizingState.current.isResizing = true;
|
|
|
148 |
document.addEventListener('mousemove', onMouseMove);
|
149 |
document.addEventListener('mouseup', onMouseUp);
|
150 |
|
151 |
+
e.preventDefault();
|
152 |
};
|
153 |
|
154 |
const onMouseMove = (e: MouseEvent) => {
|
|
|
159 |
const dx = e.clientX - resizingState.current.startX;
|
160 |
const windowWidth = resizingState.current.windowWidth;
|
161 |
|
|
|
162 |
const dxPercent = (dx / windowWidth) * 100 * SCALING_FACTOR;
|
163 |
|
164 |
let newWidthPercent = resizingState.current.startWidthPercent;
|
|
|
169 |
newWidthPercent = resizingState.current.startWidthPercent - dxPercent;
|
170 |
}
|
171 |
|
|
|
172 |
newWidthPercent = Math.max(10, Math.min(newWidthPercent, 90));
|
173 |
|
174 |
setWidthPercent(newWidthPercent);
|
|
|
180 |
document.removeEventListener('mousemove', onMouseMove);
|
181 |
document.removeEventListener('mouseup', onMouseUp);
|
182 |
|
|
|
183 |
document.body.style.userSelect = '';
|
184 |
};
|
185 |
|
|
|
186 |
useEffect(() => {
|
187 |
const handleWindowResize = () => {
|
188 |
+
// Optional: Adjust widthPercent if necessary
|
|
|
|
|
|
|
189 |
};
|
190 |
|
191 |
window.addEventListener('resize', handleWindowResize);
|
|
|
195 |
};
|
196 |
}, []);
|
197 |
|
|
|
198 |
const GripIcon = () => (
|
199 |
<div
|
200 |
style={{
|
|
|
219 |
</div>
|
220 |
);
|
221 |
|
222 |
+
const openInNewWindow = (size: WindowSize) => {
|
223 |
+
if (activePreview?.baseUrl) {
|
224 |
+
const match = activePreview.baseUrl.match(/^https?:\/\/([^.]+)\.local-credentialless\.webcontainer-api\.io/);
|
225 |
+
|
226 |
+
if (match) {
|
227 |
+
const previewId = match[1];
|
228 |
+
const previewUrl = `/webcontainer/preview/${previewId}`;
|
229 |
+
const newWindow = window.open(
|
230 |
+
previewUrl,
|
231 |
+
'_blank',
|
232 |
+
`noopener,noreferrer,width=${size.width},height=${size.height},menubar=no,toolbar=no,location=no,status=no`,
|
233 |
+
);
|
234 |
+
|
235 |
+
if (newWindow) {
|
236 |
+
newWindow.focus();
|
237 |
+
}
|
238 |
+
} else {
|
239 |
+
console.warn('[Preview] Invalid WebContainer URL:', activePreview.baseUrl);
|
240 |
+
}
|
241 |
+
}
|
242 |
+
};
|
243 |
+
|
244 |
return (
|
245 |
+
<div
|
246 |
+
ref={containerRef}
|
247 |
+
className={`w-full h-full flex flex-col relative ${isPreviewOnly ? 'fixed inset-0 z-50 bg-white' : ''}`}
|
248 |
+
>
|
249 |
{isPortDropdownOpen && (
|
250 |
<div className="z-iframe-overlay w-full h-full absolute" onClick={() => setIsPortDropdownOpen(false)} />
|
251 |
)}
|
|
|
256 |
onClick={() => setIsSelectionMode(!isSelectionMode)}
|
257 |
className={isSelectionMode ? 'bg-bolt-elements-background-depth-3' : ''}
|
258 |
/>
|
259 |
+
<div className="flex items-center gap-1 flex-grow bg-bolt-elements-preview-addressBar-background border border-bolt-elements-borderColor text-bolt-elements-preview-addressBar-text rounded-full px-3 py-1 text-sm hover:bg-bolt-elements-preview-addressBar-backgroundHover hover:focus-within:bg-bolt-elements-preview-addressBar-backgroundActive focus-within:bg-bolt-elements-preview-addressBar-backgroundActive focus-within-border-bolt-elements-borderColorActive focus-within:text-bolt-elements-preview-addressBar-textActive">
|
|
|
|
|
|
|
260 |
<input
|
261 |
title="URL"
|
262 |
ref={inputRef}
|
|
|
289 |
/>
|
290 |
)}
|
291 |
|
|
|
292 |
<IconButton
|
293 |
icon="i-ph:devices"
|
294 |
onClick={toggleDeviceMode}
|
295 |
title={isDeviceModeOn ? 'Switch to Responsive Mode' : 'Switch to Device Mode'}
|
296 |
/>
|
297 |
|
298 |
+
<IconButton
|
299 |
+
icon="i-ph:layout-light"
|
300 |
+
onClick={() => setIsPreviewOnly(!isPreviewOnly)}
|
301 |
+
title={isPreviewOnly ? 'Show Full Interface' : 'Show Preview Only'}
|
302 |
+
/>
|
303 |
+
|
304 |
<IconButton
|
305 |
icon={isFullscreen ? 'i-ph:arrows-in' : 'i-ph:arrows-out'}
|
306 |
onClick={toggleFullscreen}
|
307 |
title={isFullscreen ? 'Exit Full Screen' : 'Full Screen'}
|
308 |
/>
|
309 |
+
|
310 |
+
<div className="relative">
|
311 |
+
<IconButton
|
312 |
+
icon="i-ph:arrow-square-out"
|
313 |
+
onClick={() => openInNewWindow(selectedWindowSize)}
|
314 |
+
title={`Open Preview in ${selectedWindowSize.name} Window`}
|
315 |
+
/>
|
316 |
+
<IconButton
|
317 |
+
icon="i-ph:caret-down"
|
318 |
+
onClick={() => setIsWindowSizeDropdownOpen(!isWindowSizeDropdownOpen)}
|
319 |
+
className="ml-1"
|
320 |
+
title="Select Window Size"
|
321 |
+
/>
|
322 |
+
|
323 |
+
{isWindowSizeDropdownOpen && (
|
324 |
+
<>
|
325 |
+
<div className="fixed inset-0 z-50" onClick={() => setIsWindowSizeDropdownOpen(false)} />
|
326 |
+
<div className="absolute right-0 top-full mt-1 z-50 bg-bolt-elements-background-depth-2 rounded-lg shadow-lg border border-bolt-elements-borderColor overflow-hidden">
|
327 |
+
{WINDOW_SIZES.map((size) => (
|
328 |
+
<button
|
329 |
+
key={size.name}
|
330 |
+
className="w-full px-4 py-2 text-left hover:bg-bolt-elements-background-depth-3 text-sm whitespace-nowrap"
|
331 |
+
onClick={() => {
|
332 |
+
setSelectedWindowSize(size);
|
333 |
+
setIsWindowSizeDropdownOpen(false);
|
334 |
+
openInNewWindow(size);
|
335 |
+
}}
|
336 |
+
>
|
337 |
+
{size.name}
|
338 |
+
</button>
|
339 |
+
))}
|
340 |
+
</div>
|
341 |
+
</>
|
342 |
+
)}
|
343 |
+
</div>
|
344 |
</div>
|
345 |
|
346 |
<div className="flex-1 border-t border-bolt-elements-borderColor flex justify-center items-center overflow-auto">
|
347 |
<div
|
348 |
style={{
|
349 |
width: isDeviceModeOn ? `${widthPercent}%` : '100%',
|
350 |
+
height: '100%',
|
351 |
overflow: 'visible',
|
352 |
background: '#fff',
|
353 |
position: 'relative',
|
|
|
361 |
title="preview"
|
362 |
className="border-none w-full h-full bg-white"
|
363 |
src={iframeUrl}
|
364 |
+
sandbox="allow-scripts allow-forms allow-popups allow-modals allow-storage-access-by-user-activation allow-same-origin"
|
365 |
+
allow="cross-origin-isolated"
|
366 |
/>
|
367 |
<ScreenshotSelector
|
368 |
isSelectionMode={isSelectionMode}
|
|
|
376 |
|
377 |
{isDeviceModeOn && (
|
378 |
<>
|
|
|
379 |
<div
|
380 |
onMouseDown={(e) => startResizing(e, 'left')}
|
381 |
style={{
|
|
|
400 |
<GripIcon />
|
401 |
</div>
|
402 |
|
|
|
403 |
<div
|
404 |
onMouseDown={(e) => startResizing(e, 'right')}
|
405 |
style={{
|
app/lib/stores/previews.ts
CHANGED
@@ -1,27 +1,192 @@
|
|
1 |
import type { WebContainer } from '@webcontainer/api';
|
2 |
import { atom } from 'nanostores';
|
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
export interface PreviewInfo {
|
5 |
port: number;
|
6 |
ready: boolean;
|
7 |
baseUrl: string;
|
8 |
}
|
9 |
|
|
|
|
|
|
|
10 |
export class PreviewsStore {
|
11 |
#availablePreviews = new Map<number, PreviewInfo>();
|
12 |
#webcontainer: Promise<WebContainer>;
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
previews = atom<PreviewInfo[]>([]);
|
15 |
|
16 |
constructor(webcontainerPromise: Promise<WebContainer>) {
|
17 |
this.#webcontainer = webcontainerPromise;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
this.#init();
|
20 |
}
|
21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
async #init() {
|
23 |
const webcontainer = await this.#webcontainer;
|
24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
webcontainer.on('port', (port, type, url) => {
|
26 |
let previewInfo = this.#availablePreviews.get(port);
|
27 |
|
@@ -44,6 +209,101 @@ export class PreviewsStore {
|
|
44 |
previewInfo.baseUrl = url;
|
45 |
|
46 |
this.previews.set([...previews]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
});
|
48 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
}
|
|
|
1 |
import type { WebContainer } from '@webcontainer/api';
|
2 |
import { atom } from 'nanostores';
|
3 |
|
4 |
+
// Extend Window interface to include our custom property
|
5 |
+
declare global {
|
6 |
+
interface Window {
|
7 |
+
_tabId?: string;
|
8 |
+
}
|
9 |
+
}
|
10 |
+
|
11 |
export interface PreviewInfo {
|
12 |
port: number;
|
13 |
ready: boolean;
|
14 |
baseUrl: string;
|
15 |
}
|
16 |
|
17 |
+
// Create a broadcast channel for preview updates
|
18 |
+
const PREVIEW_CHANNEL = 'preview-updates';
|
19 |
+
|
20 |
export class PreviewsStore {
|
21 |
#availablePreviews = new Map<number, PreviewInfo>();
|
22 |
#webcontainer: Promise<WebContainer>;
|
23 |
+
#broadcastChannel: BroadcastChannel;
|
24 |
+
#lastUpdate = new Map<string, number>();
|
25 |
+
#watchedFiles = new Set<string>();
|
26 |
+
#refreshTimeouts = new Map<string, NodeJS.Timeout>();
|
27 |
+
#REFRESH_DELAY = 300;
|
28 |
+
#storageChannel: BroadcastChannel;
|
29 |
|
30 |
previews = atom<PreviewInfo[]>([]);
|
31 |
|
32 |
constructor(webcontainerPromise: Promise<WebContainer>) {
|
33 |
this.#webcontainer = webcontainerPromise;
|
34 |
+
this.#broadcastChannel = new BroadcastChannel(PREVIEW_CHANNEL);
|
35 |
+
this.#storageChannel = new BroadcastChannel('storage-sync-channel');
|
36 |
+
|
37 |
+
// Listen for preview updates from other tabs
|
38 |
+
this.#broadcastChannel.onmessage = (event) => {
|
39 |
+
const { type, previewId } = event.data;
|
40 |
+
|
41 |
+
if (type === 'file-change') {
|
42 |
+
const timestamp = event.data.timestamp;
|
43 |
+
const lastUpdate = this.#lastUpdate.get(previewId) || 0;
|
44 |
+
|
45 |
+
if (timestamp > lastUpdate) {
|
46 |
+
this.#lastUpdate.set(previewId, timestamp);
|
47 |
+
this.refreshPreview(previewId);
|
48 |
+
}
|
49 |
+
}
|
50 |
+
};
|
51 |
+
|
52 |
+
// Listen for storage sync messages
|
53 |
+
this.#storageChannel.onmessage = (event) => {
|
54 |
+
const { storage, source } = event.data;
|
55 |
+
|
56 |
+
if (storage && source !== this._getTabId()) {
|
57 |
+
this._syncStorage(storage);
|
58 |
+
}
|
59 |
+
};
|
60 |
+
|
61 |
+
// Override localStorage setItem to catch all changes
|
62 |
+
if (typeof window !== 'undefined') {
|
63 |
+
const originalSetItem = localStorage.setItem;
|
64 |
+
|
65 |
+
localStorage.setItem = (...args) => {
|
66 |
+
originalSetItem.apply(localStorage, args);
|
67 |
+
this._broadcastStorageSync();
|
68 |
+
};
|
69 |
+
}
|
70 |
|
71 |
this.#init();
|
72 |
}
|
73 |
|
74 |
+
// Generate a unique ID for this tab
|
75 |
+
private _getTabId(): string {
|
76 |
+
if (typeof window !== 'undefined') {
|
77 |
+
if (!window._tabId) {
|
78 |
+
window._tabId = Math.random().toString(36).substring(2, 15);
|
79 |
+
}
|
80 |
+
|
81 |
+
return window._tabId;
|
82 |
+
}
|
83 |
+
|
84 |
+
return '';
|
85 |
+
}
|
86 |
+
|
87 |
+
// Sync storage data between tabs
|
88 |
+
private _syncStorage(storage: Record<string, string>) {
|
89 |
+
if (typeof window !== 'undefined') {
|
90 |
+
Object.entries(storage).forEach(([key, value]) => {
|
91 |
+
try {
|
92 |
+
const originalSetItem = Object.getPrototypeOf(localStorage).setItem;
|
93 |
+
originalSetItem.call(localStorage, key, value);
|
94 |
+
} catch (error) {
|
95 |
+
console.error('[Preview] Error syncing storage:', error);
|
96 |
+
}
|
97 |
+
});
|
98 |
+
|
99 |
+
// Force a refresh after syncing storage
|
100 |
+
const previews = this.previews.get();
|
101 |
+
previews.forEach((preview) => {
|
102 |
+
const previewId = this.getPreviewId(preview.baseUrl);
|
103 |
+
|
104 |
+
if (previewId) {
|
105 |
+
this.refreshPreview(previewId);
|
106 |
+
}
|
107 |
+
});
|
108 |
+
|
109 |
+
// Reload the page content
|
110 |
+
if (typeof window !== 'undefined' && window.location) {
|
111 |
+
const iframe = document.querySelector('iframe');
|
112 |
+
|
113 |
+
if (iframe) {
|
114 |
+
iframe.src = iframe.src;
|
115 |
+
}
|
116 |
+
}
|
117 |
+
}
|
118 |
+
}
|
119 |
+
|
120 |
+
// Broadcast storage state to other tabs
|
121 |
+
private _broadcastStorageSync() {
|
122 |
+
if (typeof window !== 'undefined') {
|
123 |
+
const storage: Record<string, string> = {};
|
124 |
+
|
125 |
+
for (let i = 0; i < localStorage.length; i++) {
|
126 |
+
const key = localStorage.key(i);
|
127 |
+
|
128 |
+
if (key) {
|
129 |
+
storage[key] = localStorage.getItem(key) || '';
|
130 |
+
}
|
131 |
+
}
|
132 |
+
|
133 |
+
this.#storageChannel.postMessage({
|
134 |
+
type: 'storage-sync',
|
135 |
+
storage,
|
136 |
+
source: this._getTabId(),
|
137 |
+
timestamp: Date.now(),
|
138 |
+
});
|
139 |
+
}
|
140 |
+
}
|
141 |
+
|
142 |
async #init() {
|
143 |
const webcontainer = await this.#webcontainer;
|
144 |
|
145 |
+
// Listen for server ready events
|
146 |
+
webcontainer.on('server-ready', (port, url) => {
|
147 |
+
console.log('[Preview] Server ready on port:', port, url);
|
148 |
+
this.broadcastUpdate(url);
|
149 |
+
|
150 |
+
// Initial storage sync when preview is ready
|
151 |
+
this._broadcastStorageSync();
|
152 |
+
});
|
153 |
+
|
154 |
+
try {
|
155 |
+
// Watch for file changes
|
156 |
+
const watcher = await webcontainer.fs.watch('**/*', { persistent: true });
|
157 |
+
|
158 |
+
// Use the native watch events
|
159 |
+
(watcher as any).addEventListener('change', async () => {
|
160 |
+
const previews = this.previews.get();
|
161 |
+
|
162 |
+
for (const preview of previews) {
|
163 |
+
const previewId = this.getPreviewId(preview.baseUrl);
|
164 |
+
|
165 |
+
if (previewId) {
|
166 |
+
this.broadcastFileChange(previewId);
|
167 |
+
}
|
168 |
+
}
|
169 |
+
});
|
170 |
+
|
171 |
+
// Watch for DOM changes that might affect storage
|
172 |
+
if (typeof window !== 'undefined') {
|
173 |
+
const observer = new MutationObserver((_mutations) => {
|
174 |
+
// Broadcast storage changes when DOM changes
|
175 |
+
this._broadcastStorageSync();
|
176 |
+
});
|
177 |
+
|
178 |
+
observer.observe(document.body, {
|
179 |
+
childList: true,
|
180 |
+
subtree: true,
|
181 |
+
characterData: true,
|
182 |
+
attributes: true,
|
183 |
+
});
|
184 |
+
}
|
185 |
+
} catch (error) {
|
186 |
+
console.error('[Preview] Error setting up watchers:', error);
|
187 |
+
}
|
188 |
+
|
189 |
+
// Listen for port events
|
190 |
webcontainer.on('port', (port, type, url) => {
|
191 |
let previewInfo = this.#availablePreviews.get(port);
|
192 |
|
|
|
209 |
previewInfo.baseUrl = url;
|
210 |
|
211 |
this.previews.set([...previews]);
|
212 |
+
|
213 |
+
if (type === 'open') {
|
214 |
+
this.broadcastUpdate(url);
|
215 |
+
}
|
216 |
+
});
|
217 |
+
}
|
218 |
+
|
219 |
+
// Helper to extract preview ID from URL
|
220 |
+
getPreviewId(url: string): string | null {
|
221 |
+
const match = url.match(/^https?:\/\/([^.]+)\.local-credentialless\.webcontainer-api\.io/);
|
222 |
+
return match ? match[1] : null;
|
223 |
+
}
|
224 |
+
|
225 |
+
// Broadcast state change to all tabs
|
226 |
+
broadcastStateChange(previewId: string) {
|
227 |
+
const timestamp = Date.now();
|
228 |
+
this.#lastUpdate.set(previewId, timestamp);
|
229 |
+
|
230 |
+
this.#broadcastChannel.postMessage({
|
231 |
+
type: 'state-change',
|
232 |
+
previewId,
|
233 |
+
timestamp,
|
234 |
});
|
235 |
}
|
236 |
+
|
237 |
+
// Broadcast file change to all tabs
|
238 |
+
broadcastFileChange(previewId: string) {
|
239 |
+
const timestamp = Date.now();
|
240 |
+
this.#lastUpdate.set(previewId, timestamp);
|
241 |
+
|
242 |
+
this.#broadcastChannel.postMessage({
|
243 |
+
type: 'file-change',
|
244 |
+
previewId,
|
245 |
+
timestamp,
|
246 |
+
});
|
247 |
+
}
|
248 |
+
|
249 |
+
// Broadcast update to all tabs
|
250 |
+
broadcastUpdate(url: string) {
|
251 |
+
const previewId = this.getPreviewId(url);
|
252 |
+
|
253 |
+
if (previewId) {
|
254 |
+
const timestamp = Date.now();
|
255 |
+
this.#lastUpdate.set(previewId, timestamp);
|
256 |
+
|
257 |
+
this.#broadcastChannel.postMessage({
|
258 |
+
type: 'file-change',
|
259 |
+
previewId,
|
260 |
+
timestamp,
|
261 |
+
});
|
262 |
+
}
|
263 |
+
}
|
264 |
+
|
265 |
+
// Method to refresh a specific preview
|
266 |
+
refreshPreview(previewId: string) {
|
267 |
+
// Clear any pending refresh for this preview
|
268 |
+
const existingTimeout = this.#refreshTimeouts.get(previewId);
|
269 |
+
|
270 |
+
if (existingTimeout) {
|
271 |
+
clearTimeout(existingTimeout);
|
272 |
+
}
|
273 |
+
|
274 |
+
// Set a new timeout for this refresh
|
275 |
+
const timeout = setTimeout(() => {
|
276 |
+
const previews = this.previews.get();
|
277 |
+
const preview = previews.find((p) => this.getPreviewId(p.baseUrl) === previewId);
|
278 |
+
|
279 |
+
if (preview) {
|
280 |
+
preview.ready = false;
|
281 |
+
this.previews.set([...previews]);
|
282 |
+
|
283 |
+
requestAnimationFrame(() => {
|
284 |
+
preview.ready = true;
|
285 |
+
this.previews.set([...previews]);
|
286 |
+
});
|
287 |
+
}
|
288 |
+
|
289 |
+
this.#refreshTimeouts.delete(previewId);
|
290 |
+
}, this.#REFRESH_DELAY);
|
291 |
+
|
292 |
+
this.#refreshTimeouts.set(previewId, timeout);
|
293 |
+
}
|
294 |
+
}
|
295 |
+
|
296 |
+
// Create a singleton instance
|
297 |
+
let previewsStore: PreviewsStore | null = null;
|
298 |
+
|
299 |
+
export function usePreviewStore() {
|
300 |
+
if (!previewsStore) {
|
301 |
+
/*
|
302 |
+
* Initialize with a Promise that resolves to WebContainer
|
303 |
+
* This should match how you're initializing WebContainer elsewhere
|
304 |
+
*/
|
305 |
+
previewsStore = new PreviewsStore(Promise.resolve({} as WebContainer));
|
306 |
+
}
|
307 |
+
|
308 |
+
return previewsStore;
|
309 |
}
|
app/routes/webcontainer.preview.$id.tsx
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import { json, type LoaderFunctionArgs } from '@remix-run/cloudflare';
|
2 |
+
import { useLoaderData } from '@remix-run/react';
|
3 |
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
4 |
+
|
5 |
+
const PREVIEW_CHANNEL = 'preview-updates';
|
6 |
+
|
7 |
+
export async function loader({ params }: LoaderFunctionArgs) {
|
8 |
+
const previewId = params.id;
|
9 |
+
|
10 |
+
if (!previewId) {
|
11 |
+
throw new Response('Preview ID is required', { status: 400 });
|
12 |
+
}
|
13 |
+
|
14 |
+
return json({ previewId });
|
15 |
+
}
|
16 |
+
|
17 |
+
export default function WebContainerPreview() {
|
18 |
+
const { previewId } = useLoaderData<typeof loader>();
|
19 |
+
const iframeRef = useRef<HTMLIFrameElement>(null);
|
20 |
+
const broadcastChannelRef = useRef<BroadcastChannel>();
|
21 |
+
const [previewUrl, setPreviewUrl] = useState('');
|
22 |
+
|
23 |
+
// Handle preview refresh
|
24 |
+
const handleRefresh = useCallback(() => {
|
25 |
+
if (iframeRef.current && previewUrl) {
|
26 |
+
// Force a clean reload
|
27 |
+
iframeRef.current.src = '';
|
28 |
+
requestAnimationFrame(() => {
|
29 |
+
if (iframeRef.current) {
|
30 |
+
iframeRef.current.src = previewUrl;
|
31 |
+
}
|
32 |
+
});
|
33 |
+
}
|
34 |
+
}, [previewUrl]);
|
35 |
+
|
36 |
+
// Notify other tabs that this preview is ready
|
37 |
+
const notifyPreviewReady = useCallback(() => {
|
38 |
+
if (broadcastChannelRef.current && previewUrl) {
|
39 |
+
broadcastChannelRef.current.postMessage({
|
40 |
+
type: 'preview-ready',
|
41 |
+
previewId,
|
42 |
+
url: previewUrl,
|
43 |
+
timestamp: Date.now(),
|
44 |
+
});
|
45 |
+
}
|
46 |
+
}, [previewId, previewUrl]);
|
47 |
+
|
48 |
+
useEffect(() => {
|
49 |
+
// Initialize broadcast channel
|
50 |
+
broadcastChannelRef.current = new BroadcastChannel(PREVIEW_CHANNEL);
|
51 |
+
|
52 |
+
// Listen for preview updates
|
53 |
+
broadcastChannelRef.current.onmessage = (event) => {
|
54 |
+
if (event.data.previewId === previewId) {
|
55 |
+
if (event.data.type === 'refresh-preview' || event.data.type === 'file-change') {
|
56 |
+
handleRefresh();
|
57 |
+
}
|
58 |
+
}
|
59 |
+
};
|
60 |
+
|
61 |
+
// Construct the WebContainer preview URL
|
62 |
+
const url = `https://${previewId}.local-credentialless.webcontainer-api.io`;
|
63 |
+
setPreviewUrl(url);
|
64 |
+
|
65 |
+
// Set the iframe src
|
66 |
+
if (iframeRef.current) {
|
67 |
+
iframeRef.current.src = url;
|
68 |
+
}
|
69 |
+
|
70 |
+
// Notify other tabs that this preview is ready
|
71 |
+
notifyPreviewReady();
|
72 |
+
|
73 |
+
// Cleanup
|
74 |
+
return () => {
|
75 |
+
broadcastChannelRef.current?.close();
|
76 |
+
};
|
77 |
+
}, [previewId, handleRefresh, notifyPreviewReady]);
|
78 |
+
|
79 |
+
return (
|
80 |
+
<div className="w-full h-full">
|
81 |
+
<iframe
|
82 |
+
ref={iframeRef}
|
83 |
+
title="WebContainer Preview"
|
84 |
+
className="w-full h-full border-none"
|
85 |
+
sandbox="allow-scripts allow-forms allow-popups allow-modals allow-storage-access-by-user-activation allow-same-origin"
|
86 |
+
allow="cross-origin-isolated"
|
87 |
+
loading="eager"
|
88 |
+
onLoad={notifyPreviewReady}
|
89 |
+
/>
|
90 |
+
</div>
|
91 |
+
);
|
92 |
+
}
|