Open History to see the last commit
1import type { DevicePlatform, PreviewViewportSetting } from "@t3tools/contracts";
2
3import type { BrowserSurfaceContentPresentation } from "~/browser/browserSurfaceStore";
4import {
5 resolveFittedBrowserViewport,
6 type BrowserViewportResizeDirection,
7} from "~/browser/browserViewportLayout";
8import type { PreviewMiniPlayerPosition, PreviewMiniPlayerSize } from "~/previewMiniPlayerStore";
9
10import type { DeviceScreenSize } from "../device/deviceStream";
11
12export const PREVIEW_MINI_PLAYER_EDGE_GAP = 12;
13export const PREVIEW_MINI_PLAYER_CORNER_RADIUS = 12;
14// The mini-player shell straddles this webview at 47 and 49; dialogs begin at 50.
15export const PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX = 48;
16// A fresh player is the largest box at the source aspect ratio that fits here.
17const PREVIEW_MINI_PLAYER_DEFAULT_BOX = { width: 320, height: 320 } as const;
18const PREVIEW_MINI_PLAYER_MIN_SIZE = { width: 240, height: 150 } as const;
19
20export interface PreviewMiniPlayerFrame extends PreviewMiniPlayerPosition, PreviewMiniPlayerSize {}
21
22/**
23 * The rendered size of what the floating player mirrors: the device viewport
24 * when one is set, otherwise the size the webview had when it was floated
25 * (`fittedSourceContent`), which the hosted webview keeps as its CSS viewport.
26 */
27export function resolvePreviewMiniPlayerSourceSize(
28 viewport: PreviewViewportSetting,
29 fittedSourceContent: BrowserSurfaceContentPresentation | null,
30 zoomFactor: number,
31): PreviewMiniPlayerSize {
32 const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
33 const fitted = resolveFittedBrowserViewport(viewport, fittedSourceContent, normalizedZoomFactor);
34 return {
35 width: fitted.width * normalizedZoomFactor,
36 height: fitted.height * normalizedZoomFactor,
37 };
38}
39
40/**
41 * The device screen as the user sees it, so a rotated phone floats as a
42 * landscape box. Before the stream reports its size the platform's usual phone
43 * shape stands in, matching the stream view's own placeholder aspect; the
44 * nominal width only keeps the source cap above any sensible player width.
45 */
46export function resolveDeviceMiniPlayerSourceSize(
47 platform: DevicePlatform,
48 screen: DeviceScreenSize | null,
49): PreviewMiniPlayerSize {
50 if (!screen) {
51 const width = 1_000;
52 return { width, height: width / (platform === "ios" ? 9 / 19.5 : 9 / 20) };
53 }
54 const landscape =
55 screen.orientation === "landscape_left" || screen.orientation === "landscape_right";
56 const long = Math.max(screen.width, screen.height);
57 const short = Math.min(screen.width, screen.height);
58 return landscape ? { width: long, height: short } : { width: short, height: long };
59}
60
61/**
62 * The Android emulator composites the skin's rounded corners into its
63 * framebuffer as black wedges (measured at ~13% of the short side on a
64 * Pixel 9), so its player clips at a matching phone-like radius; the sliver
65 * lost under the curve is status-bar padding. iOS simulators stream an
66 * edge-to-edge rectangle and keep the frame radius, which matters for iPads
67 * whose real corners are far tighter than a phone's.
68 */
69export function resolveDeviceMiniPlayerCornerRadius(
70 platform: DevicePlatform,
71 player: PreviewMiniPlayerSize,
72): number {
73 if (platform !== "android") return PREVIEW_MINI_PLAYER_CORNER_RADIUS;
74 return Math.max(
75 PREVIEW_MINI_PLAYER_CORNER_RADIUS,
76 Math.round(Math.min(player.width, player.height) * 0.14),
77 );
78}
79
80interface HorizontalSpan {
81 readonly left: number;
82 readonly right: number;
83}
84
85/**
86 * What the player keeps clear of, in container coordinates. Both are docked
87 * to an edge, so each only reserves the columns it covers: the margins beside
88 * the composer and the column left of the details card stay open all the way.
89 */
90export interface PreviewMiniPlayerObstacles {
91 /** The composer stack docked to the bottom edge. */
92 readonly composer: (HorizontalSpan & { readonly height: number }) | null;
93 /** The inline thread-details card docked to the top-right corner. */
94 readonly detailsCard: (HorizontalSpan & { readonly bottom: number }) | null;
95}
96
97export const NO_PREVIEW_MINI_PLAYER_OBSTACLES: PreviewMiniPlayerObstacles = {
98 composer: null,
99 detailsCard: null,
100};
101
102const spanOf = (x: number, width: number): HorizontalSpan => ({ left: x, right: x + width });
103
104const spansOverlap = (a: HorizontalSpan, b: HorizontalSpan) => a.left < b.right && a.right > b.left;
105
106/** The lowest row (before the edge gap) open to a player covering these columns. */
107function floorFor(
108 span: HorizontalSpan,
109 container: PreviewMiniPlayerSize,
110 obstacles: PreviewMiniPlayerObstacles,
111): number {
112 const { composer } = obstacles;
113 return composer && spansOverlap(span, composer)
114 ? container.height - Math.max(0, composer.height)
115 : container.height;
116}
117
118/** The highest row (before the edge gap) open to a player covering these columns. */
119function ceilingFor(span: HorizontalSpan, obstacles: PreviewMiniPlayerObstacles): number {
120 const { detailsCard } = obstacles;
121 return detailsCard && spansOverlap(span, detailsCard) ? Math.max(0, detailsCard.bottom) : 0;
122}
123
124/**
125 * The box a stored size is fitted into. A player with a position keeps the
126 * rows its own columns have, so a tall frame parked beside the composer
127 * survives the next layout pass; without one it takes the rows above the
128 * composer, which every column has.
129 */
130const availableArea = (
131 container: PreviewMiniPlayerSize,
132 obstacles: PreviewMiniPlayerObstacles,
133 span: HorizontalSpan | null,
134): PreviewMiniPlayerSize => ({
135 width: container.width - PREVIEW_MINI_PLAYER_EDGE_GAP * 2,
136 height:
137 (span
138 ? floorFor(span, container, obstacles) - ceilingFor(span, obstacles)
139 : container.height - Math.max(0, obstacles.composer?.height ?? 0)) -
140 PREVIEW_MINI_PLAYER_EDGE_GAP * 2,
141});
142
143/**
144 * Width is the player's only free dimension; height always follows the source
145 * aspect ratio so the webview fills the box without letterboxing. The player
146 * never grows past the source's own size (the guest keeps its CSS viewport, so
147 * going bigger would only upscale), and a tight container wins over the minimum.
148 */
149function fitPreviewMiniPlayerWidth(
150 desiredWidth: number,
151 source: PreviewMiniPlayerSize,
152 max: PreviewMiniPlayerSize,
153): PreviewMiniPlayerSize {
154 const aspectRatio = source.width / source.height;
155 const width = Math.min(
156 Math.max(
157 desiredWidth,
158 PREVIEW_MINI_PLAYER_MIN_SIZE.width,
159 PREVIEW_MINI_PLAYER_MIN_SIZE.height * aspectRatio,
160 ),
161 source.width,
162 Math.max(1, max.width),
163 Math.max(1, max.height * aspectRatio),
164 );
165 return { width: Math.round(width), height: Math.round(width / aspectRatio) };
166}
167
168function defaultPreviewMiniPlayerWidth(source: PreviewMiniPlayerSize): number {
169 return Math.min(
170 PREVIEW_MINI_PLAYER_DEFAULT_BOX.width,
171 (PREVIEW_MINI_PLAYER_DEFAULT_BOX.height * source.width) / source.height,
172 );
173}
174
175const clampToContainer = (
176 position: PreviewMiniPlayerPosition,
177 container: PreviewMiniPlayerSize,
178 player: PreviewMiniPlayerSize,
179 bottom = container.height,
180): PreviewMiniPlayerPosition => ({
181 x: Math.min(
182 Math.max(position.x, PREVIEW_MINI_PLAYER_EDGE_GAP),
183 Math.max(
184 PREVIEW_MINI_PLAYER_EDGE_GAP,
185 container.width - player.width - PREVIEW_MINI_PLAYER_EDGE_GAP,
186 ),
187 ),
188 y: Math.min(
189 Math.max(position.y, PREVIEW_MINI_PLAYER_EDGE_GAP),
190 Math.max(PREVIEW_MINI_PLAYER_EDGE_GAP, bottom - player.height - PREVIEW_MINI_PLAYER_EDGE_GAP),
191 ),
192});
193
194const overlapsObstacle = (
195 position: PreviewMiniPlayerPosition,
196 player: PreviewMiniPlayerSize,
197 container: PreviewMiniPlayerSize,
198 obstacles: PreviewMiniPlayerObstacles,
199): boolean => {
200 const span = spanOf(position.x, player.width);
201 return (
202 position.y + player.height > floorFor(span, container, obstacles) ||
203 position.y < ceilingFor(span, obstacles)
204 );
205};
206
207/**
208 * Keeps the player inside the container and off the composer and details
209 * card. An overlapping player is moved the shortest distance that leaves it
210 * clear: vertically into the rows its own columns have open, or sideways to
211 * the space beside an obstacle, so a drag slides along the composer into a
212 * margin instead of stopping at its edge. When nothing leaves it clear it
213 * keeps its columns and sits below the card; the composer is where the user
214 * is typing, but a player under the card cannot be reached at all.
215 */
216export function clampPreviewMiniPlayerPosition(
217 position: PreviewMiniPlayerPosition,
218 container: PreviewMiniPlayerSize,
219 player: PreviewMiniPlayerSize,
220 obstacles: PreviewMiniPlayerObstacles = NO_PREVIEW_MINI_PLAYER_OBSTACLES,
221): PreviewMiniPlayerPosition {
222 const inside = clampToContainer(position, container, player);
223 if (!overlapsObstacle(inside, player, container, obstacles)) return inside;
224 const gap = PREVIEW_MINI_PLAYER_EDGE_GAP;
225 // The rows open to a player at this x, holding y as close to the drag as they allow.
226 const fitRows = (x: number): PreviewMiniPlayerPosition => {
227 const span = spanOf(x, player.width);
228 return {
229 x,
230 y: Math.min(
231 container.height - gap - player.height,
232 Math.max(
233 Math.min(inside.y, floorFor(span, container, obstacles) - gap - player.height),
234 ceilingFor(span, obstacles) + gap,
235 gap,
236 ),
237 ),
238 };
239 };
240 const fallback = fitRows(inside.x);
241 const { composer, detailsCard } = obstacles;
242 const span = spanOf(inside.x, player.width);
243 const beside = [composer, detailsCard]
244 .filter(
245 (obstacle): obstacle is NonNullable<typeof obstacle> =>
246 obstacle !== null && spansOverlap(span, obstacle),
247 )
248 .flatMap((obstacle) => [obstacle.left - gap - player.width, obstacle.right + gap]);
249 let best = fallback;
250 let bestDistance = overlapsObstacle(fallback, player, container, obstacles)
251 ? Number.POSITIVE_INFINITY
252 : Math.abs(fallback.y - inside.y);
253 for (const x of beside) {
254 const candidate = fitRows(x);
255 if (
256 clampToContainer(candidate, container, player).x !== x ||
257 overlapsObstacle(candidate, player, container, obstacles)
258 ) {
259 continue;
260 }
261 const distance = Math.abs(x - inside.x) + Math.abs(candidate.y - inside.y);
262 if (distance < bestDistance) {
263 best = candidate;
264 bestDistance = distance;
265 }
266 }
267 return best;
268}
269
270/**
271 * Resolves the on-screen frame from the stored width and position. Clamping
272 * happens here on every layout pass instead of being written back to the
273 * store, so a temporarily narrow container never destroys the user's chosen
274 * width. A player without a position sits in the top-right corner, or tucks
275 * under the details card with right edges aligned when the card owns it.
276 */
277export function resolvePreviewMiniPlayerFrame(input: {
278 readonly width: number | null;
279 readonly position: PreviewMiniPlayerPosition | null;
280 readonly source: PreviewMiniPlayerSize;
281 readonly container: PreviewMiniPlayerSize;
282 readonly obstacles?: PreviewMiniPlayerObstacles;
283}): PreviewMiniPlayerFrame {
284 const {
285 width,
286 position,
287 source,
288 container,
289 obstacles = NO_PREVIEW_MINI_PLAYER_OBSTACLES,
290 } = input;
291 const size = fitPreviewMiniPlayerWidth(
292 width ?? defaultPreviewMiniPlayerWidth(source),
293 source,
294 availableArea(
295 container,
296 // A stored player keeps its size under the details card — the card's
297 // ceiling is a placement concern, not a sizing one, and the clamp pass
298 // relocates the frame into columns the card leaves open.
299 position && width ? { composer: obstacles.composer, detailsCard: null } : obstacles,
300 position && width ? spanOf(position.x, width) : null,
301 ),
302 );
303 const { detailsCard } = obstacles;
304 const anchored =
305 position ??
306 (detailsCard
307 ? { x: detailsCard.right - size.width, y: detailsCard.bottom + PREVIEW_MINI_PLAYER_EDGE_GAP }
308 : {
309 x: container.width - PREVIEW_MINI_PLAYER_EDGE_GAP - size.width,
310 y: PREVIEW_MINI_PLAYER_EDGE_GAP,
311 });
312 return { ...clampPreviewMiniPlayerPosition(anchored, container, size, obstacles), ...size };
313}
314
315/**
316 * Resizes from any edge or corner while holding the aspect ratio. The edge
317 * opposite the dragged one stays anchored, so growth stops at the container
318 * on that axis and the pointer keeps tracking the grabbed edge. On a plain edge
319 * drag the perpendicular axis may use the whole container, and the player
320 * shifts as needed to stay inside.
321 */
322export function resizePreviewMiniPlayer(input: {
323 readonly start: PreviewMiniPlayerFrame;
324 readonly direction: BrowserViewportResizeDirection;
325 readonly delta: PreviewMiniPlayerPosition;
326 readonly source: PreviewMiniPlayerSize;
327 readonly container: PreviewMiniPlayerSize;
328 readonly obstacles?: PreviewMiniPlayerObstacles;
329}): PreviewMiniPlayerFrame {
330 const {
331 start,
332 direction,
333 delta,
334 source,
335 container,
336 obstacles = NO_PREVIEW_MINI_PLAYER_OBSTACLES,
337 } = input;
338 const east = direction.includes("east");
339 const west = direction.includes("west");
340 const north = direction.includes("north");
341 const south = direction.includes("south");
342 const right = start.x + start.width;
343 const bottom = start.y + start.height;
344 // Growth stops where the player's current columns meet an obstacle, and a
345 // plain edge drag lets the free axis use everything those columns have. A
346 // wider player may reach new columns; the clamp below slides it clear.
347 const span = spanOf(start.x, start.width);
348 const floor = floorFor(span, container, obstacles);
349 const ceiling = ceilingFor(span, obstacles);
350 const max = {
351 width: west
352 ? right - PREVIEW_MINI_PLAYER_EDGE_GAP
353 : east
354 ? container.width - PREVIEW_MINI_PLAYER_EDGE_GAP - start.x
355 : container.width - PREVIEW_MINI_PLAYER_EDGE_GAP * 2,
356 height: north
357 ? bottom - ceiling - PREVIEW_MINI_PLAYER_EDGE_GAP
358 : south
359 ? floor - PREVIEW_MINI_PLAYER_EDGE_GAP - start.y
360 : floor - ceiling - PREVIEW_MINI_PLAYER_EDGE_GAP * 2,
361 };
362 const desiredWidth = start.width + (east ? delta.x : west ? -delta.x : 0);
363 const desiredHeight = start.height + (south ? delta.y : north ? -delta.y : 0);
364 const horizontal = east || west;
365 const vertical = north || south;
366 const widthLeads =
367 horizontal && !vertical
368 ? true
369 : vertical && !horizontal
370 ? false
371 : Math.abs(desiredWidth - start.width) / start.width >=
372 Math.abs(desiredHeight - start.height) / start.height;
373 const size = fitPreviewMiniPlayerWidth(
374 widthLeads ? desiredWidth : (desiredHeight * source.width) / source.height,
375 source,
376 max,
377 );
378 const position = clampPreviewMiniPlayerPosition(
379 { x: west ? right - size.width : start.x, y: north ? bottom - size.height : start.y },
380 container,
381 size,
382 obstacles,
383 );
384 return { ...position, ...size };
385}