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

useBrowserViewportResize.ts

260 lines9.0 KB

1"use client";
2​
3import type { PreviewViewportSetting, PreviewViewportSize } from "@t3tools/contracts";
4import {
5 useCallback,
6 useEffect,
7 useRef,
8 useState,
9 type KeyboardEvent as ReactKeyboardEvent,
10 type PointerEvent as ReactPointerEvent,
11} from "react";
12​
13import { commitBrowserViewportChange } from "./browserViewportActions";
14import {
15 browserViewportSettingKey,
16 resizeBrowserViewportFromRail,
17 resizeFreeformViewport,
18 resolveBrowserDeviceViewportArea,
19 resolveBrowserDeviceViewportLayout,
20 resolveBrowserViewportLayout,
21 type BrowserViewportResizeDirection,
22} from "./browserViewportLayout";
23​
24interface ViewportDrag extends PreviewViewportSize {
25 readonly sourceKey: string;
26 readonly direction: BrowserViewportResizeDirection;
28​
29const KEYBOARD_RESIZE_COMMIT_DELAY_MS = 150;
30​
31export function useBrowserViewportResize(options: {
32 readonly tabId: string;
33 readonly viewport: PreviewViewportSetting;
34 readonly zoomFactor: number;
35 readonly containerSize: PreviewViewportSize;
36 readonly deviceToolbarVisible: boolean;
37 readonly aspectRatio: number | null;
38}) {
39 const { tabId, viewport, zoomFactor, containerSize, deviceToolbarVisible, aspectRatio } = options;
40 const dragCleanupRef = useRef<(() => void) | null>(null);
41 const dragVersionRef = useRef(0);
42 const keyboardCommitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
43 const keyboardViewportRef = useRef<ViewportDrag | null>(null);
44 const [dragViewport, setDragViewport] = useState<ViewportDrag | null>(null);
45 const sourceViewportKey = browserViewportSettingKey(viewport);
46 const sourceViewportKeyRef = useRef(sourceViewportKey);
47 sourceViewportKeyRef.current = sourceViewportKey;
48 const activeDrag = dragViewport?.sourceKey === sourceViewportKey ? dragViewport : null;
49 const effectiveViewport = activeDrag
50 ? ({
51 _tag: "freeform",
52 width: activeDrag.width,
53 height: activeDrag.height,
54 } as const satisfies PreviewViewportSetting)
55 : viewport;
56 const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
57 const viewportContainerSize = deviceToolbarVisible
58 ? resolveBrowserDeviceViewportArea(containerSize)
59 : containerSize;
60 const layout =
61 deviceToolbarVisible && effectiveViewport._tag !== "fill"
62 ? resolveBrowserDeviceViewportLayout(containerSize, effectiveViewport, zoomFactor)
63 : resolveBrowserViewportLayout(containerSize, effectiveViewport, zoomFactor);
64​
65 useEffect(
66 () => () => {
67 dragVersionRef.current += 1;
68 dragCleanupRef.current?.();
69 if (keyboardCommitTimerRef.current !== null) {
70 clearTimeout(keyboardCommitTimerRef.current);
71 }
72 keyboardCommitTimerRef.current = null;
73 keyboardViewportRef.current = null;
74 },
75 [],
76 );
77​
78 useEffect(() => {
79 const pending = keyboardViewportRef.current;
80 if (!pending || pending.sourceKey === sourceViewportKey) return;
81 if (keyboardCommitTimerRef.current !== null) {
82 clearTimeout(keyboardCommitTimerRef.current);
83 keyboardCommitTimerRef.current = null;
84 }
85 keyboardViewportRef.current = null;
86 }, [sourceViewportKey]);
87​
88 const commitViewportChange = useCallback(
89 (next: PreviewViewportSetting) => {
90 dragVersionRef.current += 1;
91 dragCleanupRef.current?.();
92 if (keyboardCommitTimerRef.current !== null) {
93 clearTimeout(keyboardCommitTimerRef.current);
94 keyboardCommitTimerRef.current = null;
95 }
96 keyboardViewportRef.current = null;
97 setDragViewport(null);
98 return commitBrowserViewportChange(tabId, next);
99 },
100 [tabId],
101 );
102​
103 const clearDrag = () => setDragViewport(null);
104 const commitDrag = (next: PreviewViewportSetting) => {
105 const version = ++dragVersionRef.current;
106 const clearIfCurrent = () => {
107 if (dragVersionRef.current === version) clearDrag();
108 };
109 void commitBrowserViewportChange(tabId, next).then(clearIfCurrent, clearIfCurrent);
110 };
111​
112 const handleResizeKeyDown = (
113 direction: BrowserViewportResizeDirection,
114 event: ReactKeyboardEvent<HTMLButtonElement>,
115 ) => {
116 if (effectiveViewport._tag === "fill") return;
117 const controlsWidth = direction.includes("east") || direction.includes("west");
118 const controlsHeight = direction.includes("north") || direction.includes("south");
119 const step = (event.shiftKey ? 50 : 10) * normalizedZoomFactor;
120 const delta =
121 event.key === "ArrowLeft" && controlsWidth
122 ? { x: -step, y: 0 }
123 : event.key === "ArrowRight" && controlsWidth
124 ? { x: step, y: 0 }
125 : event.key === "ArrowUp" && controlsHeight
126 ? { x: 0, y: -step }
127 : event.key === "ArrowDown" && controlsHeight
128 ? { x: 0, y: step }
129 : null;
130 if (!delta) return;
131 event.preventDefault();
132 event.stopPropagation();
133 const pending = keyboardViewportRef.current;
134 const base = pending?.sourceKey === sourceViewportKey ? pending : effectiveViewport;
135 const next = resizeFreeformViewport(
136 base,
137 delta,
138 zoomFactor,
139 direction,
140 aspectRatio ?? undefined,
141 );
142 if (next.width === base.width && next.height === base.height) return;
143 const keyboardViewport = { sourceKey: sourceViewportKey, ...next, direction };
144 keyboardViewportRef.current = keyboardViewport;
145 setDragViewport(keyboardViewport);
146 if (keyboardCommitTimerRef.current !== null) {
147 clearTimeout(keyboardCommitTimerRef.current);
148 }
149 keyboardCommitTimerRef.current = setTimeout(() => {
150 keyboardCommitTimerRef.current = null;
151 const latest = keyboardViewportRef.current;
152 if (!latest || latest.sourceKey !== sourceViewportKeyRef.current) return;
153 keyboardViewportRef.current = null;
154 commitDrag({ _tag: "freeform", width: latest.width, height: latest.height });
155 }, KEYBOARD_RESIZE_COMMIT_DELAY_MS);
156 };
157​
158 const handleResizePointerDown = (
159 direction: BrowserViewportResizeDirection,
160 event: ReactPointerEvent<HTMLButtonElement>,
161 ) => {
162 if (effectiveViewport._tag === "fill") return;
163 event.preventDefault();
164 event.stopPropagation();
165 if (keyboardCommitTimerRef.current !== null) {
166 clearTimeout(keyboardCommitTimerRef.current);
167 keyboardCommitTimerRef.current = null;
168 }
169 keyboardViewportRef.current = null;
170 dragCleanupRef.current?.();
171 dragVersionRef.current += 1;
172 const pointerId = event.pointerId;
173 const target = event.currentTarget;
174 const startX = event.clientX;
175 const startY = event.clientY;
176 const startWidth = effectiveViewport.width;
177 const startHeight = effectiveViewport.height;
178 const dragZoomFactor = normalizedZoomFactor * layout.viewportScale;
179 let latest = { width: startWidth, height: startHeight };
180 setDragViewport({
181 sourceKey: sourceViewportKey,
182 width: startWidth,
183 height: startHeight,
184 direction,
185 });
186 try {
187 target.setPointerCapture(pointerId);
188 } catch {
189 // Window listeners below keep the drag functional when capture is unavailable.
190 }
191​
192 const sourceChanged = () => sourceViewportKeyRef.current !== sourceViewportKey;
193 const move = (moveEvent: PointerEvent) => {
194 if (moveEvent.pointerId !== pointerId) return;
195 if (sourceChanged()) {
196 cleanup();
197 dragVersionRef.current += 1;
198 clearDrag();
199 return;
200 }
201 moveEvent.preventDefault();
202 const { width, height } = resizeBrowserViewportFromRail(
203 { width: startWidth, height: startHeight },
204 {
205 x: moveEvent.clientX - startX,
206 y: moveEvent.clientY - startY,
207 },
208 viewportContainerSize,
209 dragZoomFactor,
210 direction,
211 aspectRatio ?? undefined,
212 );
213 latest = { width, height };
214 setDragViewport({ sourceKey: sourceViewportKey, width, height, direction });
215 };
216 function cleanup() {
217 window.removeEventListener("pointermove", move);
218 window.removeEventListener("pointerup", finish);
219 window.removeEventListener("pointercancel", cancel);
220 dragCleanupRef.current = null;
221 try {
222 target.releasePointerCapture(pointerId);
223 } catch {
224 // The browser may already have released capture on pointerup.
225 }
226 }
227 function finish(upEvent: PointerEvent) {
228 if (upEvent.pointerId !== pointerId) return;
229 cleanup();
230 if (sourceChanged() || (latest.width === startWidth && latest.height === startHeight)) {
231 clearDrag();
232 return;
233 }
234 commitDrag({
235 _tag: "freeform",
236 width: latest.width,
237 height: latest.height,
238 });
239 }
240 function cancel(cancelEvent: PointerEvent) {
241 if (cancelEvent.pointerId !== pointerId) return;
242 cleanup();
243 dragVersionRef.current += 1;
244 clearDrag();
245 }
246 dragCleanupRef.current = cleanup;
247 window.addEventListener("pointermove", move, { passive: false });
248 window.addEventListener("pointerup", finish);
249 window.addEventListener("pointercancel", cancel);
250 };
251​
252 return {
253 activeDrag,
254 commitViewportChange,
255 effectiveViewport,
256 handleResizeKeyDown,
257 handleResizePointerDown,
258 layout,
259 };