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

browserViewportLayout.ts

366 lines12.7 KB

1import {
2 PREVIEW_VIEWPORT_MAX_AREA,
3 PREVIEW_VIEWPORT_MAX_DIMENSION,
4 PREVIEW_VIEWPORT_MIN_DIMENSION,
5 type PreviewViewportSetting,
6 type PreviewViewportSize,
7} from "@t3tools/contracts";
8​
9export interface BrowserViewportLayout {
10 readonly canvasWidth: number;
11 readonly canvasHeight: number;
12 readonly viewportX: number;
13 readonly viewportY: number;
14 readonly viewportWidth: number;
15 readonly viewportHeight: number;
16 readonly viewportScale: number;
17 readonly fillsPanel: boolean;
19​
20export const BROWSER_DEVICE_TOOLBAR_HEIGHT = 38;
21export const BROWSER_VIEWPORT_RESIZE_RAIL_SIZE = 10;
22​
23export type BrowserViewportResizeDirection =
24 | "north"
25 | "northeast"
26 | "east"
27 | "southeast"
28 | "south"
29 | "southwest"
30 | "west"
31 | "northwest";
32​
33export const browserViewportSettingKey = (setting: PreviewViewportSetting): string =>
34 setting._tag === "fill"
35 ? "fill"
36 : `${setting._tag}:${setting.width}:${setting.height}:${setting._tag === "preset" ? setting.presetId : ""}`;
37​
38const normalizeZoomFactor = (zoomFactor: number): number =>
39 Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
40​
41// Convert guest CSS pixels to host CSS pixels without changing the guest's page zoom.
42export const resolveBrowserLayoutZoomFactor = (
43 previewZoomFactor: number,
44 windowZoomFactor: number,
45): number => normalizeZoomFactor(previewZoomFactor) / normalizeZoomFactor(windowZoomFactor);
46​
47export function resolveFittedBrowserViewport(
48 setting: PreviewViewportSetting,
49 sourceContent: {
50 readonly width: number;
51 readonly height: number;
52 readonly scale: number;
53 } | null,
54 zoomFactor = 1,
55): Exclude<PreviewViewportSetting, { readonly _tag: "fill" }> {
56 if (setting._tag !== "fill") return setting;
57 const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
58 if (sourceContent) {
59 return {
60 _tag: "freeform",
61 width: Math.max(
62 1,
63 Math.round(sourceContent.width / sourceContent.scale / normalizedZoomFactor),
64 ),
65 height: Math.max(
66 1,
67 Math.round(sourceContent.height / sourceContent.scale / normalizedZoomFactor),
68 ),
69 };
70 }
71 return { _tag: "freeform", width: 1280, height: 800 };
73​
74export function resolveHiddenBrowserViewportSize(input: {
75 readonly setting: PreviewViewportSetting;
76 readonly zoomFactor: number;
77 readonly content: {
78 readonly width: number;
79 readonly height: number;
80 readonly scale: number;
81 } | null;
82 readonly lastRect: { readonly width: number; readonly height: number } | null;
83 readonly windowSize: { readonly width: number; readonly height: number };
84}): { readonly width: number; readonly height: number } {
85 const { content, lastRect, setting, windowSize, zoomFactor } = input;
86 if (setting._tag !== "fill") {
87 // Chromium paints a guest only near the window, so a capture of a larger one loses its far edge.
88 return {
89 width: Math.min(windowSize.width, setting.width * zoomFactor),
90 height: Math.min(windowSize.height, setting.height * zoomFactor),
91 };
92 }
93 if (content)
94 return { width: content.width / content.scale, height: content.height / content.scale };
95 return { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 };
97​
98export function resolveHiddenBrowserViewportFitScale(
99 hiddenSize: { readonly width: number; readonly height: number },
100 windowSize: { readonly width: number; readonly height: number },
101): number {
102 // A minimized window can report a zero viewport; scale(0) would stop the guest compositing.
103 if (windowSize.width <= 0 || windowSize.height <= 0) return 1;
104 return Math.min(1, windowSize.width / hiddenSize.width, windowSize.height / hiddenSize.height);
106​
107export function resolveBrowserDeviceViewportArea(container: {
108 readonly width: number;
109 readonly height: number;
110}): PreviewViewportSize {
111 return {
112 width: Math.max(1, container.width - BROWSER_VIEWPORT_RESIZE_RAIL_SIZE * 2),
113 height: Math.max(
114 1,
115 container.height - BROWSER_DEVICE_TOOLBAR_HEIGHT - BROWSER_VIEWPORT_RESIZE_RAIL_SIZE,
116 ),
117 };
119​
120export function resolveBrowserViewportLayout(
121 container: { readonly width: number; readonly height: number },
122 setting: PreviewViewportSetting,
123 zoomFactor = 1,
124): BrowserViewportLayout {
125 const containerWidth = Math.max(1, Math.round(container.width));
126 const containerHeight = Math.max(1, Math.round(container.height));
127 if (setting._tag === "fill") {
128 return {
129 canvasWidth: containerWidth,
130 canvasHeight: containerHeight,
131 viewportX: 0,
132 viewportY: 0,
133 viewportWidth: containerWidth,
134 viewportHeight: containerHeight,
135 viewportScale: 1,
136 fillsPanel: true,
137 };
138 }
139 const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
140 const renderedWidth = setting.width * normalizedZoomFactor;
141 const renderedHeight = setting.height * normalizedZoomFactor;
142 const viewportScale = Math.min(
143 1,
144 containerWidth / renderedWidth,
145 containerHeight / renderedHeight,
146 );
147 const viewportWidth = renderedWidth * viewportScale;
148 const viewportHeight = renderedHeight * viewportScale;
149 return {
150 canvasWidth: containerWidth,
151 canvasHeight: containerHeight,
152 viewportX: Math.max(0, Math.round((containerWidth - viewportWidth) / 2)),
153 viewportY: Math.max(0, Math.round((containerHeight - viewportHeight) / 2)),
154 viewportWidth,
155 viewportHeight,
156 viewportScale,
157 fillsPanel: false,
158 };
160​
161/**
162 * Chromium rasters a CSS-scaled guest at its on-screen scale, so captures of it lose detail.
163 * Its raster scale also counts x/y-to-z terms, which a `preserve-3d` parent keeps and the
164 * screen drops, so `fullDetail` draws like `scale()` but keeps full-resolution frames.
165 */
166export function resolveBrowserViewportTransform(
167 scale: number,
168 fullDetail: boolean,
169): string | undefined {
170 if (scale >= 1) return undefined;
171 if (!fullDetail) return `scale(${scale})`;
172 // Positive depth keeps the guest in front of its parent for hit testing.
173 const depth = Math.sqrt(1 - scale * scale);
174 return `matrix3d(${scale}, 0, ${depth}, 0, 0, ${scale}, ${depth}, 0, 0, 0, 1, 0, 0, 0, 0, 1)`;
176​
177export function resolveBrowserDeviceViewportLayout(
178 container: { readonly width: number; readonly height: number },
179 setting: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>,
180 zoomFactor = 1,
181): BrowserViewportLayout {
182 const layout = resolveBrowserViewportLayout(
183 resolveBrowserDeviceViewportArea(container),
184 setting,
185 zoomFactor,
186 );
187 return {
188 ...layout,
189 canvasWidth: Math.max(1, Math.round(container.width)),
190 canvasHeight: Math.max(1, Math.round(container.height)),
191 viewportX: layout.viewportX + BROWSER_VIEWPORT_RESIZE_RAIL_SIZE,
192 viewportY: layout.viewportY + BROWSER_DEVICE_TOOLBAR_HEIGHT,
193 };
195​
196const clampViewportDimension = (value: number): number =>
197 Math.min(PREVIEW_VIEWPORT_MAX_DIMENSION, Math.max(PREVIEW_VIEWPORT_MIN_DIMENSION, value));
198​
199const validAspectRatio = (aspectRatio: number | undefined): aspectRatio is number =>
200 aspectRatio !== undefined && Number.isFinite(aspectRatio) && aspectRatio > 0;
201​
202function resizeAtAspectRatio(
203 desired: number,
204 aspectRatio: number,
205 primaryAxis: "width" | "height",
206): PreviewViewportSize {
207 if (primaryAxis === "width") {
208 const minimum = Math.ceil(
209 Math.max(PREVIEW_VIEWPORT_MIN_DIMENSION, PREVIEW_VIEWPORT_MIN_DIMENSION * aspectRatio),
210 );
211 const maximum = Math.floor(
212 Math.min(
213 PREVIEW_VIEWPORT_MAX_DIMENSION,
214 PREVIEW_VIEWPORT_MAX_DIMENSION * aspectRatio,
215 Math.sqrt(PREVIEW_VIEWPORT_MAX_AREA * aspectRatio),
216 ),
217 );
218 let width = Math.min(maximum, Math.max(minimum, Math.round(desired)));
219 let height = Math.round(width / aspectRatio);
220 while (width * height > PREVIEW_VIEWPORT_MAX_AREA && width > minimum) {
221 width -= 1;
222 height = Math.round(width / aspectRatio);
223 }
224 return { width, height };
225 }
226​
227 const minimum = Math.ceil(
228 Math.max(PREVIEW_VIEWPORT_MIN_DIMENSION, PREVIEW_VIEWPORT_MIN_DIMENSION / aspectRatio),
229 );
230 const maximum = Math.floor(
231 Math.min(
232 PREVIEW_VIEWPORT_MAX_DIMENSION,
233 PREVIEW_VIEWPORT_MAX_DIMENSION / aspectRatio,
234 Math.sqrt(PREVIEW_VIEWPORT_MAX_AREA / aspectRatio),
235 ),
236 );
237 let height = Math.min(maximum, Math.max(minimum, Math.round(desired)));
238 let width = Math.round(height * aspectRatio);
239 while (width * height > PREVIEW_VIEWPORT_MAX_AREA && height > minimum) {
240 height -= 1;
241 width = Math.round(height * aspectRatio);
242 }
243 return { width, height };
245​
246export function resizeFreeformViewport(
247 start: PreviewViewportSize,
248 delta: { readonly x: number; readonly y: number },
249 zoomFactor = 1,
250 direction: BrowserViewportResizeDirection = "southeast",
251 aspectRatio?: number,
252): PreviewViewportSize {
253 const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
254 const horizontalDelta = direction.includes("east")
255 ? delta.x
256 : direction.includes("west")
257 ? -delta.x
258 : 0;
259 const verticalDelta = direction.includes("south")
260 ? delta.y
261 : direction.includes("north")
262 ? -delta.y
263 : 0;
264 const desiredWidth = start.width + horizontalDelta / normalizedZoomFactor;
265 const desiredHeight = start.height + verticalDelta / normalizedZoomFactor;
266 if (validAspectRatio(aspectRatio)) {
267 const controlsWidth = horizontalDelta !== 0 || direction === "east" || direction === "west";
268 const controlsHeight = verticalDelta !== 0 || direction === "north" || direction === "south";
269 const primaryAxis =
270 controlsWidth && !controlsHeight
271 ? "width"
272 : controlsHeight && !controlsWidth
273 ? "height"
274 : Math.abs(desiredWidth - start.width) / start.width >=
275 Math.abs(desiredHeight - start.height) / start.height
276 ? "width"
277 : "height";
278 return resizeAtAspectRatio(
279 primaryAxis === "width" ? desiredWidth : desiredHeight,
280 aspectRatio,
281 primaryAxis,
282 );
283 }
284 let width = clampViewportDimension(Math.round(desiredWidth));
285 let height = clampViewportDimension(Math.round(desiredHeight));
286 if (width * height <= PREVIEW_VIEWPORT_MAX_AREA) return { width, height };
287 if (Math.abs(horizontalDelta) >= Math.abs(verticalDelta)) {
288 width = Math.max(
289 PREVIEW_VIEWPORT_MIN_DIMENSION,
290 Math.floor(PREVIEW_VIEWPORT_MAX_AREA / height),
291 );
292 } else {
293 height = Math.max(
294 PREVIEW_VIEWPORT_MIN_DIMENSION,
295 Math.floor(PREVIEW_VIEWPORT_MAX_AREA / width),
296 );
297 }
298 return { width, height };
300​
301const resizeFromEndRail = (start: number, pointerDelta: number, available: number): number => {
302 const startEdge = start < available ? (available + start) / 2 : start;
303 const targetEdge = startEdge + pointerDelta;
304 return targetEdge <= available ? targetEdge * 2 - available : targetEdge;
305};
306​
307const resizeFromStartRail = (start: number, pointerDelta: number, available: number): number => {
308 if (start > available) {
309 const distanceToFit = start - available;
310 return pointerDelta <= distanceToFit
311 ? start - pointerDelta
312 : available - (pointerDelta - distanceToFit) * 2;
313 }
314 const targetEdge = (available - start) / 2 + pointerDelta;
315 return targetEdge >= 0 ? available - targetEdge * 2 : available - targetEdge;
316};
317​
318export function resizeBrowserViewportFromRail(
319 start: PreviewViewportSize,
320 pointerDelta: { readonly x: number; readonly y: number },
321 available: PreviewViewportSize,
322 zoomFactor = 1,
323 direction: BrowserViewportResizeDirection = "southeast",
324 aspectRatio?: number,
325): PreviewViewportSize {
326 const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
327 const startWidth = start.width * normalizedZoomFactor;
328 const startHeight = start.height * normalizedZoomFactor;
329 const desiredWidth = direction.includes("east")
330 ? resizeFromEndRail(startWidth, pointerDelta.x, available.width)
331 : direction.includes("west")
332 ? resizeFromStartRail(startWidth, pointerDelta.x, available.width)
333 : startWidth;
334 const desiredHeight = direction.includes("south")
335 ? resizeFromEndRail(startHeight, pointerDelta.y, available.height)
336 : direction.includes("north")
337 ? resizeFromStartRail(startHeight, pointerDelta.y, available.height)
338 : startHeight;
339 const widthDelta = desiredWidth - startWidth;
340 const heightDelta = desiredHeight - startHeight;
341 return resizeFreeformViewport(
342 start,
343 {
344 x: direction.includes("west") ? -widthDelta : widthDelta,
345 y: direction.includes("north") ? -heightDelta : heightDelta,
346 },
347 normalizedZoomFactor,
348 direction,
349 aspectRatio,
350 );
352​
353export function resolveResponsiveBrowserViewportSize(
354 container: { readonly width: number; readonly height: number },
355 zoomFactor = 1,
356): PreviewViewportSize {
357 const area = resolveBrowserDeviceViewportArea(container);
358 const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
359 return resizeFreeformViewport(
360 {
361 width: area.width / normalizedZoomFactor,
362 height: area.height / normalizedZoomFactor,
363 },
364 { x: 0, y: 0 },
365 );