-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathPreviewPanel.tsx
More file actions
460 lines (418 loc) · 15.4 KB
/
Copy pathPreviewPanel.tsx
File metadata and controls
460 lines (418 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import type { PreviewTabsState, PreviewTabState, ThreadId } from "@okcode/contracts";
import { type FormEvent, useEffect, useLayoutEffect, useRef, useState } from "react";
import {
ChevronLeftIcon,
ChevronRightIcon,
ExternalLinkIcon,
GlobeIcon,
LoaderCircleIcon,
PlusIcon,
RefreshCwIcon,
StarIcon,
WrenchIcon,
XIcon,
} from "lucide-react";
import { validateHttpPreviewUrl } from "@okcode/shared/preview";
import { readDesktopPreviewBridge } from "~/desktopPreview";
import { cn } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
import { usePreviewStateStore } from "~/previewStateStore";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
const EMPTY_TABS_STATE: PreviewTabsState = {
tabs: [],
activeTabId: null,
visible: false,
};
const HIDDEN_PREVIEW_BOUNDS = {
x: 0,
y: 0,
width: 0,
height: 0,
visible: false,
viewportWidth: 0,
viewportHeight: 0,
} as const;
/**
* Selector that matches any popup positioner element portaled to the body.
* When any of these are present, the native BrowserView overlay should be
* hidden so it doesn't render on top of dropdown menus / popovers.
*/
const POPUP_POSITIONER_SELECTOR = [
'[data-slot="menu-positioner"]',
'[data-slot="popover-positioner"]',
'[data-slot="select-positioner"]',
'[data-slot="combobox-positioner"]',
'[data-slot="autocomplete-positioner"]',
].join(",");
function getActiveTab(state: PreviewTabsState): PreviewTabState | null {
if (!state.activeTabId) return null;
return state.tabs.find((t) => t.tabId === state.activeTabId) ?? null;
}
function tabDisplayTitle(tab: PreviewTabState): string {
if (tab.title) return tab.title;
if (tab.url) {
try {
const u = new URL(tab.url);
return u.hostname + (u.pathname !== "/" ? u.pathname : "");
} catch {
return tab.url;
}
}
return "New Tab";
}
interface PreviewPanelProps {
threadId: ThreadId;
onClose: () => void;
}
export function PreviewPanel({ threadId, onClose }: PreviewPanelProps) {
const previewBridge = readDesktopPreviewBridge();
const setGlobalOpen = usePreviewStateStore((state) => state.setGlobalOpen);
const favoriteUrls = usePreviewStateStore((state) => state.favoriteUrls);
const toggleFavoriteUrl = usePreviewStateStore((state) => state.toggleFavoriteUrl);
const [tabsState, setTabsState] = useState<PreviewTabsState>(EMPTY_TABS_STATE);
const [inputUrl, setInputUrl] = useState("");
const [inputError, setInputError] = useState<string | null>(null);
const surfaceRef = useRef<HTMLDivElement | null>(null);
const activeTab = getActiveTab(tabsState);
const showEmbeddedSurface =
activeTab !== null && (activeTab.status === "loading" || activeTab.status === "ready");
// Sync URL input when active tab changes
useEffect(() => {
if (activeTab?.url) {
setInputUrl(activeTab.url);
}
}, [activeTab?.tabId, activeTab?.url]);
// Subscribe to state changes
useEffect(() => {
if (!previewBridge) {
setTabsState(EMPTY_TABS_STATE);
return;
}
const unsubscribe = previewBridge.onState((state) => {
setTabsState(state);
});
void previewBridge.getState().then((state) => {
setTabsState(state);
});
return () => {
unsubscribe();
};
}, [previewBridge]);
// Bounds sync
useLayoutEffect(() => {
if (!previewBridge) return;
let frameId = 0;
let destroyed = false;
let lastBoundsKey = "";
let resizeObserver: ResizeObserver | null = null;
const computeBounds = () => {
const element = surfaceRef.current;
if (!element) return HIDDEN_PREVIEW_BOUNDS;
const rect = element.getBoundingClientRect();
// Hide the native BrowserView when any popup/dropdown is open so it
// doesn't render on top of menus (native overlays ignore CSS z-index).
const hasOpenPopup = document.querySelector(POPUP_POSITIONER_SELECTOR) !== null;
const visible =
tabsState.tabs.length > 0 &&
document.visibilityState === "visible" &&
rect.width > 0 &&
rect.height > 0 &&
!hasOpenPopup;
return {
x: rect.left,
y: rect.top,
width: rect.width,
height: rect.height,
visible,
viewportWidth: window.innerWidth,
viewportHeight: window.innerHeight,
};
};
const syncBounds = () => {
if (destroyed) return;
const nextBounds = computeBounds();
const nextKey = `${Math.round(nextBounds.x)}:${Math.round(nextBounds.y)}:${Math.round(nextBounds.width)}:${Math.round(nextBounds.height)}:${nextBounds.visible ? 1 : 0}`;
if (nextKey !== lastBoundsKey) {
lastBoundsKey = nextKey;
void previewBridge.setBounds(nextBounds);
}
frameId = window.requestAnimationFrame(syncBounds);
};
const scheduleImmediateSync = () => {
if (destroyed || frameId !== 0) return;
frameId = window.requestAnimationFrame(syncBounds);
};
const element = surfaceRef.current;
if (typeof ResizeObserver !== "undefined" && element) {
resizeObserver = new ResizeObserver(() => {
lastBoundsKey = "";
});
resizeObserver.observe(element);
}
const visualViewport = window.visualViewport;
const invalidateBounds = () => {
lastBoundsKey = "";
};
// Watch for popup positioners being added/removed from the DOM so we
// can immediately hide/show the native BrowserView overlay.
const popupObserver = new MutationObserver(invalidateBounds);
popupObserver.observe(document.body, { childList: true, subtree: false });
window.addEventListener("resize", invalidateBounds);
window.addEventListener("scroll", invalidateBounds, true);
document.addEventListener("visibilitychange", invalidateBounds);
visualViewport?.addEventListener("resize", invalidateBounds);
visualViewport?.addEventListener("scroll", invalidateBounds);
scheduleImmediateSync();
return () => {
destroyed = true;
if (frameId !== 0) window.cancelAnimationFrame(frameId);
resizeObserver?.disconnect();
popupObserver.disconnect();
window.removeEventListener("resize", invalidateBounds);
window.removeEventListener("scroll", invalidateBounds, true);
document.removeEventListener("visibilitychange", invalidateBounds);
visualViewport?.removeEventListener("resize", invalidateBounds);
visualViewport?.removeEventListener("scroll", invalidateBounds);
void previewBridge.setBounds(HIDDEN_PREVIEW_BOUNDS);
};
}, [previewBridge, tabsState.tabs.length, threadId]);
// Cleanup on unmount
useEffect(() => {
return () => {
void previewBridge?.setBounds(HIDDEN_PREVIEW_BOUNDS);
};
}, [previewBridge]);
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const validatedUrl = validateHttpPreviewUrl(inputUrl);
if (!validatedUrl.ok) {
setInputError(validatedUrl.error.message);
return;
}
setInputError(null);
if (activeTab) {
// Navigate existing active tab
void previewBridge?.navigate({ url: validatedUrl.url });
} else {
// Create a new tab
void previewBridge?.createTab({ url: validatedUrl.url });
}
};
const onNewTab = () => {
const url = inputUrl.trim();
if (url.length > 0) {
const validatedUrl = validateHttpPreviewUrl(url);
if (validatedUrl.ok) {
void previewBridge?.createTab({ url: validatedUrl.url });
return;
}
}
// Create tab with a default page
void previewBridge?.createTab({ url: "https://www.google.com" });
};
const onClosePreview = () => {
setGlobalOpen(false);
void previewBridge?.closeAll();
onClose();
};
const onOpenExternal = () => {
const targetUrl = activeTab?.url;
if (!targetUrl) return;
const api = readNativeApi();
void api?.shell.openExternal(targetUrl);
};
const currentPageUrl = activeTab?.url ?? null;
const isFavorite = currentPageUrl !== null && favoriteUrls.includes(currentPageUrl);
return (
<div className="flex h-full min-w-0 flex-col bg-background">
{/* Toolbar */}
<div className="flex items-center gap-2 border-b border-border/60 px-3 py-2">
<div className="flex min-w-0 flex-1 items-center gap-2">
<Button
type="button"
size="icon-xs"
variant="ghost"
className="text-muted-foreground/55 hover:bg-transparent hover:text-foreground"
aria-label="Back"
onClick={() => void previewBridge?.goBack()}
disabled={!previewBridge || !activeTab?.canGoBack}
>
<ChevronLeftIcon className="size-3.5" />
</Button>
<Button
type="button"
size="icon-xs"
variant="ghost"
className="text-muted-foreground/55 hover:bg-transparent hover:text-foreground"
aria-label="Forward"
onClick={() => void previewBridge?.goForward()}
disabled={!previewBridge || !activeTab?.canGoForward}
>
<ChevronRightIcon className="size-3.5" />
</Button>
<Button
type="button"
size="icon-xs"
variant="ghost"
className="text-muted-foreground/55 hover:bg-transparent hover:text-foreground"
aria-label="Reload"
onClick={() => {
setInputError(null);
void previewBridge?.reload();
}}
disabled={!showEmbeddedSurface}
>
<RefreshCwIcon className="size-3.5" />
</Button>
<GlobeIcon className="size-3.5 shrink-0 text-muted-foreground/65" />
<form className="min-w-0 flex-1" onSubmit={onSubmit}>
<Input
value={inputUrl}
onChange={(event) => {
setInputUrl(event.target.value);
if (inputError) setInputError(null);
}}
placeholder="https://example.com"
aria-label="URL"
autoCapitalize="off"
autoCorrect="off"
spellCheck={false}
className="h-7 text-xs"
/>
</form>
</div>
<div className="flex items-center gap-1">
<Button
type="button"
size="icon-xs"
variant="ghost"
className={cn(
"text-muted-foreground/55 hover:bg-transparent hover:text-foreground",
activeTab?.devToolsOpen ? "text-blue-500 hover:text-blue-500" : undefined,
)}
aria-label="Toggle DevTools"
aria-pressed={activeTab?.devToolsOpen ?? false}
onClick={() => void previewBridge?.toggleDevTools()}
disabled={!previewBridge || !activeTab}
>
<WrenchIcon className="size-3.5" />
</Button>
<Button
type="button"
size="icon-xs"
variant="ghost"
className={cn(
"text-muted-foreground/55 hover:bg-transparent hover:text-foreground",
isFavorite ? "text-amber-500 hover:text-amber-500" : undefined,
)}
aria-label={isFavorite ? "Remove favorite" : "Favorite current page"}
aria-pressed={isFavorite}
onClick={() => {
if (currentPageUrl) toggleFavoriteUrl(currentPageUrl);
}}
disabled={!previewBridge || currentPageUrl === null}
>
<StarIcon className={cn("size-3.5", isFavorite ? "fill-current" : "")} />
</Button>
<Button
type="button"
size="icon-xs"
variant="ghost"
className="text-muted-foreground/55 hover:bg-transparent hover:text-foreground"
aria-label="Open externally"
onClick={onOpenExternal}
disabled={!activeTab?.url}
>
<ExternalLinkIcon className="size-3.5" />
</Button>
<Button
type="button"
size="icon-xs"
variant="ghost"
className="text-muted-foreground/55 hover:bg-transparent hover:text-foreground"
aria-label="Close browser"
onClick={onClosePreview}
>
<XIcon className="size-3.5" />
</Button>
</div>
</div>
{/* Tab bar */}
<div className="flex items-center gap-0.5 overflow-x-auto border-b border-border/40 bg-muted/30 px-2 py-1">
{tabsState.tabs.map((tab) => (
<button
key={tab.tabId}
type="button"
className={cn(
"group flex max-w-[180px] items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] transition-colors",
tab.tabId === tabsState.activeTabId
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:bg-background/50 hover:text-foreground",
)}
onClick={() => void previewBridge?.activateTab({ tabId: tab.tabId })}
title={tab.url ?? tabDisplayTitle(tab)}
>
{tab.status === "loading" ? (
<LoaderCircleIcon className="size-3 shrink-0 animate-spin" />
) : (
<GlobeIcon className="size-3 shrink-0 opacity-50" />
)}
<span className="truncate">{tabDisplayTitle(tab)}</span>
<button
type="button"
className="ml-auto shrink-0 rounded p-0.5 opacity-0 transition-opacity hover:bg-muted group-hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
void previewBridge?.closeTab({ tabId: tab.tabId });
}}
aria-label={`Close ${tabDisplayTitle(tab)}`}
>
<XIcon className="size-2.5" />
</button>
</button>
))}
<button
type="button"
className="flex items-center justify-center rounded-md p-1 text-muted-foreground/60 transition-colors hover:bg-background/50 hover:text-foreground"
onClick={onNewTab}
aria-label="New tab"
>
<PlusIcon className="size-3.5" />
</button>
</div>
{/* Status bar */}
{(inputError || (activeTab && activeTab.status !== "ready")) && (
<div className="flex items-start gap-2 border-b border-border/40 px-3 py-1.5 text-xs">
{activeTab?.status === "loading" ? (
<LoaderCircleIcon className="mt-0.5 size-3.5 shrink-0 animate-spin text-muted-foreground/70" />
) : null}
<p
className={
activeTab?.error || inputError ? "text-amber-700" : "text-muted-foreground/70"
}
>
{inputError ??
activeTab?.error?.message ??
(activeTab?.status === "loading" ? `Loading ${activeTab.url ?? ""}...` : null)}
</p>
</div>
)}
{/* Content area */}
<div className="flex min-h-0 flex-1 flex-col p-3">
<div
ref={surfaceRef}
className="relative min-h-0 flex-1 overflow-hidden rounded-lg border border-border/70 bg-card/20"
>
{!showEmbeddedSurface ? (
<div className="flex h-full items-center justify-center px-6 text-center text-sm text-muted-foreground/70">
{tabsState.tabs.length === 0
? "Enter a URL or click + to open a new tab."
: (activeTab?.error?.message ?? "Preview closed.")}
</div>
) : null}
</div>
</div>
</div>
);
}