Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

preview.ts

471 lines17.4 KB

1import {
2 DesktopPreviewAnnotationSendEnabledInputSchema,
3 DesktopPreviewAnnotationThemeInputSchema,
4 DesktopPreviewArtifactInputSchema,
5 DesktopPreviewConfigInputSchema,
6 DesktopPreviewNavigateInputSchema,
7 DesktopPreviewRecordingArtifactSchema,
8 DesktopPreviewRecordingSaveInputSchema,
9 DesktopPreviewRegisterWebviewInputSchema,
10 DesktopPreviewScreenshotArtifactSchema,
11 DesktopPreviewSetAudioMutedInputSchema,
12 DesktopPreviewSetColorSchemeInputSchema,
13 DesktopPreviewSetZoomFactorInputSchema,
14 BrowserImportResult,
15 BrowserImportSource,
16 DesktopPreviewClearDataInputSchema,
17 DesktopPreviewImportCookiesInputSchema,
18 DesktopPreviewCreateTabInputSchema,
19 DesktopPreviewTabInputSchema,
20 DesktopPreviewWebviewConfigSchema,
21 PreviewAnnotationSubmissionResultSchema,
22 PreviewCaptureFailure,
23 DEFAULT_BROWSER_PROFILE_ID,
24 INCOGNITO_BROWSER_PROFILE_ID,
25 PreviewForwardedShortcut,
26 MAX_KEYBINDINGS_COUNT,
27} from "@t3tools/contracts";
28import * as Effect from "effect/Effect";
29import * as Schema from "effect/Schema";
30import * as Option from "effect/Option";
31import * as NodeURL from "node:url";
32​
33import * as ElectronWindow from "../../electron/ElectronWindow.ts";
34import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts";
35import * as PreviewManager from "../../preview/Manager.ts";
36import { normalizeCaptureFailure } from "../../preview/captureErrors.ts";
37import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
38import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
39import * as IpcChannels from "../channels.ts";
40import * as DesktopIpc from "../DesktopIpc.ts";
41​
42export const installPreviewEventForwarding = Effect.fn(
43 "desktop.ipc.preview.installEventForwarding",
44)(function* () {
45 const electronWindow = yield* ElectronWindow.ElectronWindow;
46 const manager = yield* PreviewManager.PreviewManager;
47 yield* manager.subscribeStateChanges((tabId, state) =>
48 electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
49 );
50 yield* manager.subscribeRecordingFrames((frame) =>
51 electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
52 );
53 yield* manager.subscribeRecordingInputs((event) =>
54 electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL, event),
55 );
56 yield* manager.subscribePointerEvents((event) =>
57 electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
58 );
59 yield* manager.subscribeOpenLinks((event) =>
60 electronWindow.sendAll(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, event),
61 );
62});
63​
64const setForwardedShortcuts = DesktopIpc.makeIpcMethod({
65 channel: IpcChannels.PREVIEW_SET_FORWARDED_SHORTCUTS_CHANNEL,
66 payload: Schema.Array(PreviewForwardedShortcut).check(Schema.isMaxLength(MAX_KEYBINDINGS_COUNT)),
67 result: Schema.Void,
68 handler: Effect.fn("desktop.ipc.preview.setForwardedShortcuts")(function* (shortcuts) {
69 const manager = yield* PreviewManager.PreviewManager;
70 yield* manager.setForwardedShortcuts(shortcuts);
71 }),
72});
73​
74const createTab = DesktopIpc.makeIpcMethod({
75 channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
76 payload: DesktopPreviewCreateTabInputSchema,
77 result: Schema.Void,
78 handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({
79 tabId,
80 zoomFactor,
81 colorScheme,
82 serverTab,
83 }) {
84 const manager = yield* PreviewManager.PreviewManager;
85 yield* manager.createTab(tabId, { zoomFactor, colorScheme, serverTab });
86 }),
87});
88​
89const closeTab = DesktopIpc.makeIpcMethod({
90 channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
91 payload: DesktopPreviewTabInputSchema,
92 result: Schema.Void,
93 handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) {
94 const manager = yield* PreviewManager.PreviewManager;
95 yield* manager.closeTab(tabId);
96 }),
97});
98​
99const registerWebview = DesktopIpc.makeIpcMethod({
100 channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
101 payload: DesktopPreviewRegisterWebviewInputSchema,
102 result: Schema.Void,
103 handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) {
104 const manager = yield* PreviewManager.PreviewManager;
105 yield* manager.registerWebview(tabId, webContentsId);
106 }),
107});
108​
109const navigate = DesktopIpc.makeIpcMethod({
110 channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
111 payload: DesktopPreviewNavigateInputSchema,
112 result: Schema.Void,
113 handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) {
114 const manager = yield* PreviewManager.PreviewManager;
115 yield* manager.navigate(tabId, url);
116 }),
117});
118​
119const tabMethod = (
120 channel: string,
121 name: string,
122 invoke: (
123 manager: PreviewManager.PreviewManager["Service"],
124 tabId: string,
125 ) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
126) =>
127 DesktopIpc.makeIpcMethod({
128 channel,
129 payload: DesktopPreviewTabInputSchema,
130 result: Schema.Void,
131 handler: Effect.fn(name)(function* ({ tabId }) {
132 const manager = yield* PreviewManager.PreviewManager;
133 yield* invoke(manager, tabId);
134 }),
135 });
136​
137const goBack = tabMethod(
138 IpcChannels.PREVIEW_GO_BACK_CHANNEL,
139 "desktop.ipc.preview.goBack",
140 (manager, tabId) => manager.goBack(tabId),
141);
142const goForward = tabMethod(
143 IpcChannels.PREVIEW_GO_FORWARD_CHANNEL,
144 "desktop.ipc.preview.goForward",
145 (manager, tabId) => manager.goForward(tabId),
146);
147const refresh = tabMethod(
148 IpcChannels.PREVIEW_REFRESH_CHANNEL,
149 "desktop.ipc.preview.refresh",
150 (manager, tabId) => manager.refresh(tabId),
151);
152const zoomIn = tabMethod(
153 IpcChannels.PREVIEW_ZOOM_IN_CHANNEL,
154 "desktop.ipc.preview.zoomIn",
155 (manager, tabId) => manager.zoomIn(tabId),
156);
157const zoomOut = tabMethod(
158 IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL,
159 "desktop.ipc.preview.zoomOut",
160 (manager, tabId) => manager.zoomOut(tabId),
161);
162const resetZoom = tabMethod(
163 IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL,
164 "desktop.ipc.preview.resetZoom",
165 (manager, tabId) => manager.resetZoom(tabId),
166);
167const hardReload = tabMethod(
168 IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL,
169 "desktop.ipc.preview.hardReload",
170 (manager, tabId) => manager.hardReload(tabId),
171);
172const setZoomFactor = DesktopIpc.makeIpcMethod({
173 channel: IpcChannels.PREVIEW_SET_ZOOM_FACTOR_CHANNEL,
174 payload: DesktopPreviewSetZoomFactorInputSchema,
175 result: Schema.Void,
176 handler: Effect.fn("desktop.ipc.preview.setZoomFactor")(function* ({ tabId, zoomFactor }) {
177 const manager = yield* PreviewManager.PreviewManager;
178 yield* manager.setZoomFactor(tabId, zoomFactor);
179 }),
180});
181const setColorScheme = DesktopIpc.makeIpcMethod({
182 channel: IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL,
183 payload: DesktopPreviewSetColorSchemeInputSchema,
184 result: Schema.Void,
185 handler: Effect.fn("desktop.ipc.preview.setColorScheme")(function* ({ tabId, colorScheme }) {
186 const manager = yield* PreviewManager.PreviewManager;
187 yield* manager.setColorScheme(tabId, colorScheme);
188 }),
189});
190const setAudioMuted = DesktopIpc.makeIpcMethod({
191 channel: IpcChannels.PREVIEW_SET_AUDIO_MUTED_CHANNEL,
192 payload: DesktopPreviewSetAudioMutedInputSchema,
193 result: Schema.Void,
194 handler: Effect.fn("desktop.ipc.preview.setAudioMuted")(function* ({ tabId, audioMuted }) {
195 const manager = yield* PreviewManager.PreviewManager;
196 yield* manager.setAudioMuted(tabId, audioMuted);
197 }),
198});
199const openDevTools = tabMethod(
200 IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
201 "desktop.ipc.preview.openDevTools",
202 (manager, tabId) => manager.openDevTools(tabId),
203);
204const cancelPickElement = tabMethod(
205 IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL,
206 "desktop.ipc.preview.cancelPickElement",
207 (manager, tabId) => manager.cancelPickElement(tabId),
208);
209export const startRecording = DesktopIpc.makeIpcMethod({
210 channel: IpcChannels.PREVIEW_RECORDING_START_CHANNEL,
211 payload: DesktopPreviewTabInputSchema,
212 // Void encodes any value as undefined, so the tagged failure must be tried first.
213 result: Schema.Union([PreviewCaptureFailure, Schema.Void]),
214 handler: Effect.fn("desktop.ipc.preview.startRecording")(function* ({ tabId }) {
215 const manager = yield* PreviewManager.PreviewManager;
216 const store = yield* DesktopClientSettings.DesktopClientSettings;
217 const settings = yield* store.get;
218 const options = Option.map(settings, (value) => ({
219 showKeyPresses: value.browserRecordingShowKeyPresses,
220 showMousePresses: value.browserRecordingShowMousePresses,
221 }));
222 return yield* manager
223 .startRecording(tabId, Option.getOrUndefined(options))
224 .pipe(
225 Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "recording-start"))),
226 );
227 }),
228});
229const stopRecording = tabMethod(
230 IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,
231 "desktop.ipc.preview.stopRecording",
232 (manager, tabId) => manager.stopRecording(tabId),
233);
234const openPictureInPicture = tabMethod(
235 IpcChannels.PREVIEW_PICTURE_IN_PICTURE_OPEN_CHANNEL,
236 "desktop.ipc.preview.openPictureInPicture",
237 (manager, tabId) => manager.openPictureInPicture(tabId),
238);
239const closePictureInPicture = tabMethod(
240 IpcChannels.PREVIEW_PICTURE_IN_PICTURE_CLOSE_CHANNEL,
241 "desktop.ipc.preview.closePictureInPicture",
242 (manager, tabId) => manager.closePictureInPicture(tabId),
243);
244​
245const clearCookies = DesktopIpc.makeIpcMethod({
246 channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
247 payload: DesktopPreviewClearDataInputSchema,
248 result: Schema.Void,
249 handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* ({ environmentId, profileId }) {
250 const manager = yield* PreviewManager.PreviewManager;
251 yield* manager.clearCookies(yield* resolveClearPartitions(manager, environmentId, profileId));
252 }),
253});
254​
255const clearCache = DesktopIpc.makeIpcMethod({
256 channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
257 payload: DesktopPreviewClearDataInputSchema,
258 result: Schema.Void,
259 handler: Effect.fn("desktop.ipc.preview.clearCache")(function* ({ environmentId, profileId }) {
260 const manager = yield* PreviewManager.PreviewManager;
261 yield* manager.clearCache(yield* resolveClearPartitions(manager, environmentId, profileId));
262 }),
263});
264​
265/**
266 * The default profile keeps the bare environment id it used before profiles
267 * existed, so upgrading does not strand anyone's existing logins in an orphaned
268 * partition.
269 */
270export function resolvePartitionScope(
271 environmentId: string,
272 profileId: string | undefined,
273): {
274 readonly scope: string;
275 readonly persistent: boolean;
276 readonly namespace?: "profile";
277} {
278 if (profileId === undefined || profileId === DEFAULT_BROWSER_PROFILE_ID) {
279 return { scope: environmentId, persistent: true };
280 }
281 // JSON's tuple framing is injective for strings, including lone UTF-16
282 // surrogates (which it escapes). URI encoding throws on those supported ids,
283 // while replacing them with U+FFFD would collapse distinct identities.
284 return {
285 scope: JSON.stringify([environmentId, profileId]),
286 persistent: profileId !== INCOGNITO_BROWSER_PROFILE_ID,
287 namespace: "profile" as const,
288 };
290​
291/**
292 * Clearing without a profile keeps the historical "everything" behaviour for
293 * an explicit all-profiles action; naming a profile confines it to that
294 * profile's partition so one profile's sign-out cannot reach the others.
295 */
296const resolveClearPartitions = Effect.fn("desktop.ipc.preview.resolveClearPartitions")(function* (
297 manager: PreviewManager.PreviewManager["Service"],
298 environmentId: string,
299 profileId: string | undefined,
300) {
301 if (profileId === undefined) return undefined;
302 const { scope, persistent, namespace } = resolvePartitionScope(environmentId, profileId);
303 // Loading the session is what puts the partition in the map the clear walks.
304 // Deriving the partition string alone leaves nothing to match, so clearing a
305 // profile with no tab open this run — after a restart, or when deleting a
306 // profile — would report success and delete nothing.
307 yield* manager.getBrowserSession(scope, persistent, namespace);
308 return [yield* manager.getBrowserPartition(scope, persistent, namespace)];
309});
310​
311const getPreviewConfig = DesktopIpc.makeIpcMethod({
312 channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
313 payload: DesktopPreviewConfigInputSchema,
314 result: DesktopPreviewWebviewConfigSchema,
315 handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId, profileId }) {
316 const manager = yield* PreviewManager.PreviewManager;
317 const { scope, persistent, namespace } = resolvePartitionScope(environmentId, profileId);
318 // Creating the session first is what installs the UA rewrite and permission
319 // handlers; a guest that attached to an untouched partition would run with
320 // Electron's default UA and Chromium's default permission behaviour.
321 yield* manager.getBrowserSession(scope, persistent, namespace);
322 return {
323 partition: yield* manager.getBrowserPartition(scope, persistent, namespace),
324 webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
325 preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
326 };
327 }),
328});
329​
330export const listBrowserImportSources = DesktopIpc.makeIpcMethod({
331 channel: IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL,
332 payload: Schema.Void,
333 result: Schema.Array(BrowserImportSource),
334 handler: Effect.fn("desktop.ipc.preview.listBrowserImportSources")(function* () {
335 const browserImport = yield* BrowserImport.BrowserImport;
336 return yield* browserImport.listSources;
337 }),
338});
339​
340export const importBrowserCookies = DesktopIpc.makeIpcMethod({
341 channel: IpcChannels.PREVIEW_IMPORT_COOKIES_CHANNEL,
342 payload: DesktopPreviewImportCookiesInputSchema,
343 result: BrowserImportResult,
344 handler: Effect.fn("desktop.ipc.preview.importBrowserCookies")(function* ({
345 environmentId,
346 ...importInput
347 }) {
348 const browserImport = yield* BrowserImport.BrowserImport;
349 // Derived in main from the same helper the webview config uses, so cookies
350 // land in exactly the partition the profile's tabs attach to.
351 const { scope, persistent, namespace } = resolvePartitionScope(
352 environmentId,
353 importInput.targetProfileId,
354 );
355 return yield* browserImport.importCookies({
356 input: importInput,
357 scope,
358 persistent,
359 ...(namespace === undefined ? {} : { namespace }),
360 });
361 }),
362});
363​
364const setAnnotationTheme = DesktopIpc.makeIpcMethod({
365 channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
366 payload: DesktopPreviewAnnotationThemeInputSchema,
367 result: Schema.Void,
368 handler: Effect.fn("desktop.ipc.preview.setAnnotationTheme")(function* ({ theme }) {
369 const manager = yield* PreviewManager.PreviewManager;
370 yield* manager.setAnnotationTheme(theme);
371 }),
372});
373​
374const pickElement = DesktopIpc.makeIpcMethod({
375 channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
376 payload: DesktopPreviewTabInputSchema,
377 result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
378 handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
379 const manager = yield* PreviewManager.PreviewManager;
380 return yield* manager.pickElement(tabId);
381 }),
382});
383​
384const setAnnotationSendEnabled = DesktopIpc.makeIpcMethod({
385 channel: IpcChannels.PREVIEW_SET_ANNOTATION_SEND_ENABLED_CHANNEL,
386 payload: DesktopPreviewAnnotationSendEnabledInputSchema,
387 result: Schema.Void,
388 handler: Effect.fn("desktop.ipc.preview.setAnnotationSendEnabled")(function* ({
389 tabId,
390 enabled,
391 }) {
392 const manager = yield* PreviewManager.PreviewManager;
393 yield* manager.setAnnotationSendEnabled(tabId, enabled);
394 }),
395});
396​
397export const captureScreenshot = DesktopIpc.makeIpcMethod({
398 channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
399 payload: DesktopPreviewTabInputSchema,
400 result: Schema.Union([DesktopPreviewScreenshotArtifactSchema, PreviewCaptureFailure]),
401 handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) {
402 const manager = yield* PreviewManager.PreviewManager;
403 return yield* manager
404 .captureScreenshot(tabId)
405 .pipe(Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "screenshot"))));
406 }),
407});
408​
409const revealArtifact = DesktopIpc.makeIpcMethod({
410 channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
411 payload: DesktopPreviewArtifactInputSchema,
412 result: Schema.Void,
413 handler: Effect.fn("desktop.ipc.preview.revealArtifact")(function* ({ path }) {
414 const manager = yield* PreviewManager.PreviewManager;
415 yield* manager.revealArtifact(path);
416 }),
417});
418​
419const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
420 channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
421 payload: DesktopPreviewArtifactInputSchema,
422 result: Schema.Void,
423 handler: Effect.fn("desktop.ipc.preview.copyArtifactToClipboard")(function* ({ path }) {
424 const manager = yield* PreviewManager.PreviewManager;
425 yield* manager.copyArtifactToClipboard(path);
426 }),
427});
428​
429const saveRecording = DesktopIpc.makeIpcMethod({
430 channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
431 payload: DesktopPreviewRecordingSaveInputSchema,
432 result: DesktopPreviewRecordingArtifactSchema,
433 handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) {
434 const manager = yield* PreviewManager.PreviewManager;
435 return yield* manager.saveRecording(tabId, mimeType, data);
436 }),
437});
438​
439export const methods = [
440 setForwardedShortcuts,
441 createTab,
442 closeTab,
443 registerWebview,
444 navigate,
445 goBack,
446 goForward,
447 refresh,
448 zoomIn,
449 zoomOut,
450 resetZoom,
451 hardReload,
452 setColorScheme,
453 setZoomFactor,
454 setAudioMuted,
455 openDevTools,
456 clearCookies,
457 clearCache,
458 getPreviewConfig,
459 setAnnotationTheme,
460 setAnnotationSendEnabled,
461 pickElement,
462 cancelPickElement,
463 captureScreenshot,
464 revealArtifact,
465 copyArtifactToClipboard,
466 openPictureInPicture,
467 closePictureInPicture,
468 startRecording,
469 stopRecording,
470 saveRecording,
471] as const;