-
-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathpinch-zoom-logic.ts
More file actions
304 lines (253 loc) · 9.87 KB
/
pinch-zoom-logic.ts
File metadata and controls
304 lines (253 loc) · 9.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import type { ViewportCapability } from '@embedpdf/plugin-viewport';
import type { ZoomCapability } from '@embedpdf/plugin-zoom';
export interface ZoomGestureOptions {
/** Enable pinch-to-zoom gesture (default: true) */
enablePinch?: boolean;
/** Enable wheel zoom with ctrl/cmd key (default: true) */
enableWheel?: boolean;
/** Override wheel zoom step; 0.1 = 10% (default: 0.1) */
zoomStep?: number;
}
export interface ZoomGestureDeps {
element: HTMLDivElement;
/** Optional viewport container element for attaching events (from context) */
container?: HTMLElement;
documentId: string;
viewportProvides: ViewportCapability;
zoomProvides: ZoomCapability;
options?: ZoomGestureOptions;
}
function getTouchDistance(touches: TouchList): number {
const [t1, t2] = [touches[0], touches[1]];
const dx = t2.clientX - t1.clientX;
const dy = t2.clientY - t1.clientY;
return Math.hypot(dx, dy);
}
function getTouchCenter(touches: TouchList): { x: number; y: number } {
const [t1, t2] = [touches[0], touches[1]];
return {
x: (t1.clientX + t2.clientX) / 2,
y: (t1.clientY + t2.clientY) / 2,
};
}
export function setupZoomGestures({
element,
container,
documentId,
viewportProvides,
zoomProvides,
options = {},
}: ZoomGestureDeps) {
const { enablePinch = true, enableWheel = true, zoomStep = 0.1 } = options;
if (typeof window === 'undefined') {
return () => {};
}
// Use provided container (from context) or fall back to element
// When container is provided, events work anywhere in the viewport
const eventContainer = container || element;
const viewportScope = viewportProvides.forDocument(documentId);
const zoomScope = zoomProvides.forDocument(documentId);
const getState = () => zoomScope.getState();
// Shared state
let initialZoom = 0;
let currentScale = 1;
let isPinching = false;
let initialDistance = 0;
// Wheel state
let wheelZoomTimeout: ReturnType<typeof setTimeout> | null = null;
let accumulatedWheelScale = 1;
// Gesture state
let initialElementWidth = 0;
let initialElementHeight = 0;
let initialElementLeft = 0;
let initialElementTop = 0;
// Container Dimensions (Bounding Box)
let containerRectWidth = 0;
let containerRectHeight = 0;
// Layout Dimensions (Client Box from Metrics)
let layoutWidth = 0;
let layoutCenterX = 0;
let pointerLocalY = 0;
let pointerContainerX = 0;
let pointerContainerY = 0;
let currentGap = 0;
let pivotLocalX = 0;
const clamp = (val: number, min: number, max: number) => Math.min(Math.max(val, min), max);
// --- Margin calculation (no scroll plugin needed!) ---
const updateMargin = () => {
const metrics = viewportScope.getMetrics();
const vpGap = viewportProvides.getViewportGap() || 0;
const availableWidth = metrics.clientWidth - 2 * vpGap;
// Use element's actual rendered width - no need for scroll plugin!
const elementWidth = element.offsetWidth;
const newMargin = elementWidth < availableWidth ? (availableWidth - elementWidth) / 2 : 0;
element.style.marginLeft = `${newMargin}px`;
};
const calculateTransform = (scale: number) => {
const finalWidth = initialElementWidth * scale;
const finalHeight = initialElementHeight * scale;
let ty = pointerLocalY * (1 - scale);
const targetX = layoutCenterX - finalWidth / 2;
const txCenter = targetX - initialElementLeft;
const txMouse = pointerContainerX - pivotLocalX * scale - initialElementLeft;
const overflow = Math.max(0, finalWidth - layoutWidth);
const blendRange = layoutWidth * 0.3;
const blend = Math.min(1, overflow / blendRange);
let tx = txCenter + (txMouse - txCenter) * blend;
const safeHeight = containerRectHeight - currentGap * 2;
if (finalHeight > safeHeight) {
const currentTop = initialElementTop + ty;
const maxTop = currentGap;
const minTop = containerRectHeight - currentGap - finalHeight;
const constrainedTop = clamp(currentTop, minTop, maxTop);
ty = constrainedTop - initialElementTop;
}
const safeWidth = containerRectWidth - currentGap * 2;
if (finalWidth > safeWidth) {
const currentLeft = initialElementLeft + tx;
const maxLeft = currentGap;
const minLeft = containerRectWidth - currentGap - finalWidth;
const constrainedLeft = clamp(currentLeft, minLeft, maxLeft);
tx = constrainedLeft - initialElementLeft;
}
return { tx, ty, blend, finalWidth };
};
const updateTransform = (scale: number) => {
currentScale = scale;
const { tx, ty } = calculateTransform(scale);
element.style.transformOrigin = '0 0';
element.style.transform = `translate(${tx}px, ${ty}px) scale(${scale})`;
};
const resetTransform = () => {
element.style.transform = 'none';
element.style.transformOrigin = '0 0';
currentScale = 1;
};
const commitZoom = () => {
const { tx, finalWidth } = calculateTransform(currentScale);
const delta = (currentScale - 1) * initialZoom;
let anchorX: number;
let anchorY: number = pointerContainerY;
if (finalWidth <= layoutWidth) {
anchorX = layoutCenterX;
} else {
const scaleDiff = 1 - currentScale;
anchorX =
Math.abs(scaleDiff) > 0.001 ? initialElementLeft + tx / scaleDiff : pointerContainerX;
}
zoomScope.requestZoomBy(delta, { vx: anchorX, vy: anchorY });
resetTransform();
initialZoom = 0;
};
const initializeGestureState = (clientX: number, clientY: number) => {
// Get container rect directly from DOM element (no plugin dependency for DOM access)
const containerRect = eventContainer.getBoundingClientRect();
const contRect = {
origin: { x: containerRect.left, y: containerRect.top },
size: { width: containerRect.width, height: containerRect.height },
};
const innerRect = element.getBoundingClientRect();
const metrics = viewportScope.getMetrics();
currentGap = viewportProvides.getViewportGap() || 0;
initialElementWidth = innerRect.width;
initialElementHeight = innerRect.height;
initialElementLeft = innerRect.left - contRect.origin.x;
initialElementTop = innerRect.top - contRect.origin.y;
containerRectWidth = contRect.size.width;
containerRectHeight = contRect.size.height;
const clientLeft = metrics.clientLeft;
layoutWidth = metrics.clientWidth;
layoutCenterX = clientLeft + layoutWidth / 2;
const rawPointerLocalX = clientX - innerRect.left;
pointerLocalY = clientY - innerRect.top;
pointerContainerX = clientX - contRect.origin.x;
pointerContainerY = clientY - contRect.origin.y;
if (initialElementWidth < layoutWidth) {
pivotLocalX = (pointerContainerX * initialElementWidth) / layoutWidth;
} else {
pivotLocalX = rawPointerLocalX;
}
};
// --- Handlers ---
const handleTouchStart = (e: TouchEvent) => {
if (e.touches.length !== 2) return;
isPinching = true;
initialZoom = getState().currentZoomLevel;
initialDistance = getTouchDistance(e.touches);
const center = getTouchCenter(e.touches);
initializeGestureState(center.x, center.y);
e.preventDefault();
};
const handleTouchMove = (e: TouchEvent) => {
if (!isPinching || e.touches.length !== 2) return;
const currentDistance = getTouchDistance(e.touches);
const scale = currentDistance / initialDistance;
updateTransform(scale);
e.preventDefault();
};
const handleTouchEnd = (e: TouchEvent) => {
if (!isPinching) return;
if (e.touches.length >= 2) return;
isPinching = false;
commitZoom();
};
const handleWheel = (e: WheelEvent) => {
if (!e.ctrlKey && !e.metaKey) return;
e.preventDefault();
if (wheelZoomTimeout === null) {
initialZoom = getState().currentZoomLevel;
accumulatedWheelScale = 1;
initializeGestureState(e.clientX, e.clientY);
} else {
clearTimeout(wheelZoomTimeout);
}
// Utilizing deltaY sign instead of raw value to eliminate discrepancies between browsers
const zoomFactor = 1 - Math.sign(e.deltaY) * zoomStep; // Should this use zoomStep configured by the plugin config?
accumulatedWheelScale *= zoomFactor;
accumulatedWheelScale = clamp(accumulatedWheelScale, 0.1, 10);
updateTransform(accumulatedWheelScale);
wheelZoomTimeout = setTimeout(() => {
wheelZoomTimeout = null;
commitZoom();
accumulatedWheelScale = 1;
}, 150);
};
// Subscribe to zoom changes to update margin
const unsubZoom = zoomScope.onStateChange(() => updateMargin());
const unsubViewport = viewportScope.onViewportChange(() => updateMargin());
// Use ResizeObserver to update margin when element size changes
const resizeObserver = new ResizeObserver(() => updateMargin());
resizeObserver.observe(element);
// Initial margin calculation
updateMargin();
// Attach events to the viewport container for better UX
// (gestures work anywhere in viewport, not just on the PDF)
if (enablePinch) {
eventContainer.addEventListener('touchstart', handleTouchStart, { passive: false });
eventContainer.addEventListener('touchmove', handleTouchMove, { passive: false });
eventContainer.addEventListener('touchend', handleTouchEnd);
eventContainer.addEventListener('touchcancel', handleTouchEnd);
}
if (enableWheel) {
eventContainer.addEventListener('wheel', handleWheel, { passive: false });
}
return () => {
if (enablePinch) {
eventContainer.removeEventListener('touchstart', handleTouchStart);
eventContainer.removeEventListener('touchmove', handleTouchMove);
eventContainer.removeEventListener('touchend', handleTouchEnd);
eventContainer.removeEventListener('touchcancel', handleTouchEnd);
}
if (enableWheel) {
eventContainer.removeEventListener('wheel', handleWheel);
}
if (wheelZoomTimeout) {
clearTimeout(wheelZoomTimeout);
}
unsubZoom();
unsubViewport();
resizeObserver.disconnect();
resetTransform();
element.style.marginLeft = '';
};
}