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

preview.ts

345 lines11.1 KB

1/**
2 * Preview - Schemas for the in-app browser preview surface.
3 *
4 * The preview is desktop-only (Chromium <webview>); the server tracks per-thread
5 * tab metadata so it survives client reconnects and multi-window. The desktop
6 * renderer mediates: it owns the actual <webview> and reports navigation back to
7 * the server via these RPCs, the server fans events to all subscribers.
8 *
9 * @module Preview
10 */
11import { Schema } from "effect";
12import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
13​
14export const PREVIEW_URL_MAX_LENGTH = 2_048;
15export const CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS = 32;
16​
17const Url = TrimmedNonEmptyString.check(Schema.isMaxLength(PREVIEW_URL_MAX_LENGTH));
18​
19export const ConfiguredLocalServerUrls = Schema.Array(Url).check(
20 Schema.isMaxLength(CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS),
21);
22const Title = Schema.String.check(Schema.isMaxLength(512));
23​
24export const PreviewTabId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
25export type PreviewTabId = typeof PreviewTabId.Type;
26​
27export const PREVIEW_VIEWPORT_MIN_DIMENSION = 240;
28export const PREVIEW_VIEWPORT_MAX_DIMENSION = 3840;
29export const PREVIEW_VIEWPORT_MAX_AREA = 3840 * 2160;
30​
31const PreviewViewportDimension = Schema.Int.check(
32 Schema.isBetween({
33 minimum: PREVIEW_VIEWPORT_MIN_DIMENSION,
34 maximum: PREVIEW_VIEWPORT_MAX_DIMENSION,
35 }),
36);
37​
38const viewportAreaFilter = Schema.makeFilter(
39 ({ width, height }: { readonly width: number; readonly height: number }) =>
40 width * height <= PREVIEW_VIEWPORT_MAX_AREA ||
41 `Viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`,
42);
43​
44export const PreviewViewportSize = Schema.Struct({
45 width: PreviewViewportDimension,
46 height: PreviewViewportDimension,
47}).check(viewportAreaFilter);
48export type PreviewViewportSize = typeof PreviewViewportSize.Type;
49​
50/**
51 * The page's measured viewport can be smaller than the minimum selectable
52 * fixed size while fill mode follows a narrow panel. Keep measurement
53 * validation separate from the stricter user-selectable size constraints.
54 */
55export const PreviewRenderedViewportSize = Schema.Struct({
56 width: Schema.Int.check(Schema.isGreaterThan(0)),
57 height: Schema.Int.check(Schema.isGreaterThan(0)),
58});
59export type PreviewRenderedViewportSize = typeof PreviewRenderedViewportSize.Type;
60​
61export const PREVIEW_VIEWPORT_PRESET_IDS = [
62 "iphone-se",
63 "iphone-xr",
64 "iphone-12-pro",
65 "iphone-14-pro-max",
66 "pixel-7",
67 "samsung-galaxy-s8-plus",
68 "samsung-galaxy-s20-ultra",
69 "ipad-mini",
70 "ipad-air",
71 "ipad-pro",
72 "surface-pro-7",
73 "surface-duo",
74 "galaxy-z-fold-5",
75 "asus-zenbook-fold",
76 "samsung-galaxy-a51-71",
77 "nest-hub",
78 "nest-hub-max",
79] as const;
80​
81export const PreviewViewportPresetId = Schema.Literals(PREVIEW_VIEWPORT_PRESET_IDS);
82export type PreviewViewportPresetId = typeof PreviewViewportPresetId.Type;
83​
84/**
85 * Preset IDs shipped before the Chrome-compatible catalog. Existing sessions
86 * can still reconnect with these values, but new resize requests only expose
87 * PREVIEW_VIEWPORT_PRESET_IDS.
88 */
89const LEGACY_PREVIEW_VIEWPORT_PRESET_IDS = [
90 "desktop-1920x1080",
91 "desktop-1440x900",
92 "laptop-1366x768",
93 "laptop-1280x800",
94 "ipad-pro-11",
95 "iphone-15-pro",
96 "pixel-8",
97 "galaxy-s24",
98] as const;
99​
100const StoredPreviewViewportPresetId = Schema.Literals([
101 ...PREVIEW_VIEWPORT_PRESET_IDS,
102 ...LEGACY_PREVIEW_VIEWPORT_PRESET_IDS,
103]);
104​
105export const PreviewViewportSetting = Schema.Union([
106 Schema.TaggedStruct("fill", {}),
107 Schema.TaggedStruct("freeform", {
108 ...PreviewViewportSize.fields,
109 }).check(viewportAreaFilter),
110 Schema.TaggedStruct("preset", {
111 ...PreviewViewportSize.fields,
112 presetId: StoredPreviewViewportPresetId,
113 }).check(viewportAreaFilter),
114]);
115export type PreviewViewportSetting = typeof PreviewViewportSetting.Type;
116​
117export const FILL_PREVIEW_VIEWPORT = {
118 _tag: "fill",
119} as const satisfies PreviewViewportSetting;
120​
121/**
122 * Discrete zoom levels mirroring Chrome's preset ladder. Zoom is applied by the
123 * desktop main process to the Chromium guest, but the ladder lives here so the
124 * settings UI can offer exactly the steps the zoom controls step through.
125 */
126export const PREVIEW_ZOOM_LEVELS = [
127 0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0,
128] as const;
129​
130export const PreviewZoomFactor = Schema.Literals(PREVIEW_ZOOM_LEVELS);
131export type PreviewZoomFactor = typeof PreviewZoomFactor.Type;
132​
133export const DEFAULT_PREVIEW_ZOOM_FACTOR: PreviewZoomFactor = 1.0;
134​
135/**
136 * Preferred `prefers-color-scheme` for preview guests. `system` clears the
137 * emulation override so the guest follows the OS. Structurally identical to
138 * `DesktopPreviewColorScheme`, which is the IPC-layer spelling of the same set.
139 */
140export const PreviewAppearancePreference = Schema.Literals(["system", "light", "dark"]);
141export type PreviewAppearancePreference = typeof PreviewAppearancePreference.Type;
142​
143export const DEFAULT_PREVIEW_APPEARANCE: PreviewAppearancePreference = "system";
144​
145export const PreviewNavStatus = Schema.Union([
146 Schema.TaggedStruct("Idle", {}),
147 Schema.TaggedStruct("Loading", {
148 url: Url,
149 title: Title,
150 }),
151 Schema.TaggedStruct("Success", {
152 url: Url,
153 title: Title,
154 }),
155 Schema.TaggedStruct("LoadFailed", {
156 url: Url,
157 title: Title,
158 code: Schema.Int,
159 description: Schema.String,
160 }),
161]);
162export type PreviewNavStatus = typeof PreviewNavStatus.Type;
163​
164export const PreviewSessionSnapshot = Schema.Struct({
165 threadId: TrimmedNonEmptyString,
166 tabId: PreviewTabId,
167 navStatus: PreviewNavStatus,
168 canGoBack: Schema.Boolean,
169 canGoForward: Schema.Boolean,
170 /** Missing snapshots from older servers are treated as fill-panel mode. */
171 viewport: Schema.optional(PreviewViewportSetting),
172 updatedAt: Schema.String,
173});
174export type PreviewSessionSnapshot = typeof PreviewSessionSnapshot.Type;
175​
176export const PreviewOpenInput = Schema.Struct({
177 threadId: ThreadId,
178 /** Omit to create an empty (Idle) tab the user can type into. */
179 url: Schema.optional(Url),
180 /**
181 * Initial viewport for the new tab. Omitting it keeps the historical
182 * fill-panel behaviour; clients that have a configured default send it here
183 * so the session is born at the right size instead of being resized a frame
184 * later (which the user would see as a visible reflow).
185 */
186 viewport: Schema.optional(PreviewViewportSetting),
187});
188export type PreviewOpenInput = typeof PreviewOpenInput.Type;
189​
190export const PreviewNavigateInput = Schema.Struct({
191 threadId: ThreadId,
192 tabId: PreviewTabId,
193 url: Url,
194 resolvedTitle: Schema.optional(Title),
195});
196export type PreviewNavigateInput = typeof PreviewNavigateInput.Type;
197​
198export const PreviewReportStatusInput = Schema.Struct({
199 threadId: ThreadId,
200 tabId: PreviewTabId,
201 navStatus: PreviewNavStatus,
202 canGoBack: Schema.Boolean,
203 canGoForward: Schema.Boolean,
204});
205export type PreviewReportStatusInput = typeof PreviewReportStatusInput.Type;
206​
207export const PreviewRefreshInput = Schema.Struct({
208 threadId: ThreadId,
209 tabId: PreviewTabId,
210});
211export type PreviewRefreshInput = typeof PreviewRefreshInput.Type;
212​
213export const PreviewResizeInput = Schema.Struct({
214 threadId: ThreadId,
215 tabId: PreviewTabId,
216 viewport: PreviewViewportSetting,
217});
218export type PreviewResizeInput = typeof PreviewResizeInput.Type;
219​
220export const PreviewCloseInput = Schema.Struct({
221 threadId: ThreadId,
222 tabId: Schema.optional(PreviewTabId),
223});
224export type PreviewCloseInput = typeof PreviewCloseInput.Type;
225​
226export const PreviewListInput = Schema.Struct({
227 threadId: ThreadId,
228});
229export type PreviewListInput = typeof PreviewListInput.Type;
230​
231export const PreviewListResult = Schema.Struct({
232 sessions: Schema.Array(PreviewSessionSnapshot),
233 /** Identifies the current server process so revision resets are safe. */
234 serverEpoch: TrimmedNonEmptyString,
235 /** Monotonic server state revision used to reject stale list responses. */
236 revision: NonNegativeInt,
237});
238export type PreviewListResult = typeof PreviewListResult.Type;
239​
240const PreviewEventBaseSchema = Schema.Struct({
241 threadId: TrimmedNonEmptyString,
242 tabId: PreviewTabId,
243 createdAt: Schema.String,
244 /** Identifies the server process that emitted this event. */
245 serverEpoch: TrimmedNonEmptyString,
246 /** Monotonic server state revision shared with PreviewListResult. */
247 revision: PositiveInt,
248});
249​
250const PreviewOpenedEvent = Schema.Struct({
251 ...PreviewEventBaseSchema.fields,
252 type: Schema.Literal("opened"),
253 snapshot: PreviewSessionSnapshot,
254});
255​
256const PreviewNavigatedEvent = Schema.Struct({
257 ...PreviewEventBaseSchema.fields,
258 type: Schema.Literal("navigated"),
259 snapshot: PreviewSessionSnapshot,
260});
261​
262const PreviewResizedEvent = Schema.Struct({
263 ...PreviewEventBaseSchema.fields,
264 type: Schema.Literal("resized"),
265 snapshot: PreviewSessionSnapshot,
266});
267​
268const PreviewFailedEvent = Schema.Struct({
269 ...PreviewEventBaseSchema.fields,
270 type: Schema.Literal("failed"),
271 url: Url,
272 title: Title,
273 code: Schema.Int,
274 description: Schema.String,
275});
276​
277const PreviewClosedEvent = Schema.Struct({
278 ...PreviewEventBaseSchema.fields,
279 type: Schema.Literal("closed"),
280});
281​
282export const PreviewEvent = Schema.Union([
283 PreviewOpenedEvent,
284 PreviewNavigatedEvent,
285 PreviewResizedEvent,
286 PreviewFailedEvent,
287 PreviewClosedEvent,
288]);
289export type PreviewEvent = typeof PreviewEvent.Type;
290​
291/**
292 * A localhost server detected by the port scanner. Used to populate the
293 * "Local" recommendations in the empty-state of the preview panel.
294 */
295export const DiscoveredLocalServer = Schema.Struct({
296 host: TrimmedNonEmptyString,
297 port: Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536)),
298 url: Url,
299 processName: Schema.NullOr(TrimmedNonEmptyString),
300 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
301 terminal: Schema.NullOr(
302 Schema.Struct({
303 threadId: ThreadId,
304 terminalId: TrimmedNonEmptyString,
305 }),
306 ),
307});
308export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
309​
310export const DiscoveredLocalServerList = Schema.Struct({
311 servers: Schema.Array(DiscoveredLocalServer),
312 scannedAt: Schema.String,
313 configuredUrlProbing: Schema.optional(Schema.Literal(true)),
314});
315export type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;
316​
317export class PreviewSessionLookupError extends Schema.TaggedErrorClass<PreviewSessionLookupError>()(
318 "PreviewSessionLookupError",
319 {
320 threadId: Schema.String,
321 tabId: Schema.String,
322 },
323) {
324 override get message() {
325 return `Unknown preview session: thread=${this.threadId}, tab=${this.tabId}`;
326 }
328​
329export class PreviewInvalidUrlError extends Schema.TaggedErrorClass<PreviewInvalidUrlError>()(
330 "PreviewInvalidUrlError",
331 {
332 inputLength: Schema.Number,
333 reason: Schema.Literals(["empty", "parse", "unsupported-protocol", "unexpected"]),
334 protocol: Schema.optional(Schema.String),
335 cause: Schema.Defect(),
336 },
337) {
338 override get message() {
339 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
340 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;
341 }
343​
344export const PreviewError = Schema.Union([PreviewSessionLookupError, PreviewInvalidUrlError]);
345export type PreviewError = typeof PreviewError.Type;