-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathcreateInsideZoom.ts
More file actions
396 lines (319 loc) · 12.9 KB
/
createInsideZoom.ts
File metadata and controls
396 lines (319 loc) · 12.9 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import type { EventManager, ChartGPUEventPayload } from "./createEventManager";
import type { ZoomState } from "./createZoomState";
export type InsideZoom = Readonly<{
enable(): void;
disable(): void;
dispose(): void;
}>;
const clamp = (v: number, lo: number, hi: number): number =>
Math.min(hi, Math.max(lo, v));
const normalizeWheelDelta = (e: WheelEvent, basisCssPx: number): number => {
const raw = e.deltaY;
if (!Number.isFinite(raw) || raw === 0) return 0;
// Normalize to CSS pixels-ish so sensitivity is stable across deltaMode.
switch (e.deltaMode) {
case WheelEvent.DOM_DELTA_PIXEL:
return raw;
case WheelEvent.DOM_DELTA_LINE:
return raw * 16;
case WheelEvent.DOM_DELTA_PAGE:
return (
raw * (Number.isFinite(basisCssPx) && basisCssPx > 0 ? basisCssPx : 800)
);
default:
return raw;
}
};
const normalizeWheelDeltaX = (e: WheelEvent, basisCssPx: number): number => {
const raw = e.deltaX;
if (!Number.isFinite(raw) || raw === 0) return 0;
// Normalize to CSS pixels-ish so sensitivity is stable across deltaMode.
switch (e.deltaMode) {
case WheelEvent.DOM_DELTA_PIXEL:
return raw;
case WheelEvent.DOM_DELTA_LINE:
return raw * 16;
case WheelEvent.DOM_DELTA_PAGE:
return (
raw * (Number.isFinite(basisCssPx) && basisCssPx > 0 ? basisCssPx : 800)
);
default:
return raw;
}
};
const wheelDeltaToZoomFactor = (deltaCssPx: number): number => {
// Positive delta = scroll down = zoom out; negative = zoom in.
const abs = Math.abs(deltaCssPx);
if (!Number.isFinite(abs) || abs === 0) return 1;
// Cap extreme deltas (some devices can emit huge values).
const capped = Math.min(abs, 200);
const sensitivity = 0.002;
return Math.exp(capped * sensitivity);
};
const isMiddleButtonDrag = (e: PointerEvent): boolean =>
e.pointerType === "mouse" && (e.buttons & 4) !== 0;
const isShiftLeftDrag = (e: PointerEvent): boolean =>
e.pointerType === "mouse" && e.shiftKey && (e.buttons & 1) !== 0;
/**
* Internal “inside” zoom interaction:
* - wheel zoom centered at cursor-x (only when inside grid)
* - shift+left drag OR middle-mouse drag pans left/right (only when inside grid)
* - single-finger touch drag pans left/right (only when inside grid)
* - two-finger pinch-to-zoom centered at finger midpoint (only when inside grid)
*/
export function createInsideZoom(
eventManager: EventManager,
zoomState: ZoomState,
): InsideZoom {
let disposed = false;
let enabled = false;
let lastPointer: ChartGPUEventPayload | null = null;
let isPanning = false;
let lastPanGridX = 0;
// --- Touch state ---
const isTouchDevice =
typeof navigator !== "undefined" && navigator.maxTouchPoints > 0;
const activePointers = new Map<number, { x: number; y: number }>();
let previousPinchDist = 0;
let savedTouchAction = "";
const resetPinchState = (): void => {
previousPinchDist = 0;
};
const clearPan = (): void => {
isPanning = false;
lastPanGridX = 0;
};
// --- Mouse event handlers (from EventManager) ---
const onMouseMove = (payload: ChartGPUEventPayload): void => {
lastPointer = payload;
if (!enabled) return;
// Pan only for mouse drags, only when inside grid.
const e = payload.originalEvent;
const shouldPan =
payload.isInGrid && (isShiftLeftDrag(e) || isMiddleButtonDrag(e));
if (!shouldPan) {
clearPan();
return;
}
const plotWidthCss = payload.plotWidthCss;
if (!(plotWidthCss > 0) || !Number.isFinite(plotWidthCss)) {
clearPan();
return;
}
if (!isPanning) {
isPanning = true;
lastPanGridX = payload.gridX;
return;
}
const dxCss = payload.gridX - lastPanGridX;
lastPanGridX = payload.gridX;
if (!Number.isFinite(dxCss) || dxCss === 0) return;
const { start, end } = zoomState.getRange();
const span = end - start;
if (!Number.isFinite(span) || span === 0) return;
// Convert grid-local px to percent points *within the current window*.
// “Grab to pan” behavior: dragging right should move the window left (show earlier data).
const deltaPct = -(dxCss / plotWidthCss) * span;
if (!Number.isFinite(deltaPct) || deltaPct === 0) return;
zoomState.pan(deltaPct);
};
const onMouseLeave = (_payload: ChartGPUEventPayload): void => {
lastPointer = null;
clearPan();
};
// --- Wheel handler ---
const onWheel = (e: WheelEvent): void => {
if (!enabled || disposed) return;
const p = lastPointer;
if (!p || !p.isInGrid) return;
const plotWidthCss = p.plotWidthCss;
const plotHeightCss = p.plotHeightCss;
if (!(plotWidthCss > 0) || !(plotHeightCss > 0)) return;
const deltaYCss = normalizeWheelDelta(e, plotHeightCss);
const deltaXCss = normalizeWheelDeltaX(e, plotWidthCss);
// Check if horizontal scroll is dominant (pan operation).
if (Math.abs(deltaXCss) > Math.abs(deltaYCss) && deltaXCss !== 0) {
const { start, end } = zoomState.getRange();
const span = end - start;
if (!Number.isFinite(span) || span === 0) return;
// Convert horizontal scroll delta to percent pan.
// Positive deltaX = scroll right = pan right (show earlier data).
const deltaPct = (deltaXCss / plotWidthCss) * span;
if (!Number.isFinite(deltaPct) || deltaPct === 0) return;
e.preventDefault();
zoomState.pan(deltaPct);
return;
}
// Otherwise, proceed with vertical scroll zoom logic.
if (deltaYCss === 0) return;
const factor = wheelDeltaToZoomFactor(deltaYCss);
if (!(factor > 1)) return;
const { start, end } = zoomState.getRange();
const span = end - start;
if (!Number.isFinite(span) || span === 0) return;
const r = clamp(p.gridX / plotWidthCss, 0, 1);
const centerPct = clamp(start + r * span, 0, 100);
// Only prevent default when we are actually consuming the wheel to zoom.
e.preventDefault();
if (deltaYCss < 0) zoomState.zoomIn(centerPct, factor);
else zoomState.zoomOut(centerPct, factor);
};
// --- Touch pointer handlers (on canvas) ---
/** Fallback grid check when lastPointer isn't available yet (e.g. touch-only device). */
const isPointInGrid = (
e: PointerEvent,
canvas: HTMLCanvasElement,
): boolean => {
const rect = canvas.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return false;
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
return x >= 0 && x <= rect.width && y >= 0 && y <= rect.height;
};
const onTouchPointerDown = (e: PointerEvent): void => {
if (!enabled || disposed) return;
if (e.pointerType !== "touch") return;
// Prevent default to suppress browser scroll/zoom on touch.
e.preventDefault();
// Only start tracking if the pointer is inside the grid.
// Use lastPointer when available (precise grid margins); fall back to canvas bounds
// so touch-only devices (where mousemove may never fire) are not locked out.
const inGrid = lastPointer
? lastPointer.isInGrid
: isPointInGrid(e, eventManager.canvas);
if (!inGrid) return;
// Reject 3+ simultaneous pointers to prevent corrupting pinch state.
if (activePointers.size >= 2) return;
activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
// Capture pointer so up/cancel events route here even if the finger slides off canvas.
eventManager.canvas.setPointerCapture(e.pointerId);
// Reset pinch state when pointer count changes (transition between pan/pinch).
resetPinchState();
};
const onTouchPointerMove = (e: PointerEvent): void => {
if (!enabled || disposed) return;
if (e.pointerType !== "touch") return;
if (!activePointers.has(e.pointerId)) return;
const pointerCount = activePointers.size;
if (pointerCount === 1) {
// --- Single-finger pan ---
const prev = activePointers.get(e.pointerId);
if (!prev) return;
const dxCss = e.clientX - prev.x;
activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (!Number.isFinite(dxCss) || dxCss === 0) return;
const plotWidthCss = lastPointer?.plotWidthCss ?? 0;
if (!(plotWidthCss > 0)) return;
const { start, end } = zoomState.getRange();
const span = end - start;
if (!Number.isFinite(span) || span === 0) return;
const deltaPct = -(dxCss / plotWidthCss) * span;
if (!Number.isFinite(deltaPct) || deltaPct === 0) return;
zoomState.pan(deltaPct);
} else if (pointerCount === 2) {
// --- Pinch-to-zoom ---
// Update the moved pointer position first.
activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
const iter = activePointers.values();
const p1 = iter.next().value!;
const p2 = iter.next().value!;
const currentDist = Math.hypot(p1.x - p2.x, p1.y - p2.y);
const currentMidX = (p1.x + p2.x) / 2;
if (!Number.isFinite(currentDist) || currentDist === 0) return;
if (previousPinchDist > 0 && Number.isFinite(previousPinchDist)) {
const ratio = previousPinchDist / currentDist;
// Compute zoom center in percent space from the midpoint.
const canvas = eventManager.canvas;
const rect = canvas.getBoundingClientRect();
const plotWidthCss = lastPointer?.plotWidthCss ?? 0;
if (!(plotWidthCss > 0) || rect.width === 0) {
previousPinchDist = currentDist;
return;
}
// Estimate grid-left offset from lastPointer (gridX is relative to plot area).
// plotLeftCss = lastPointer.x - lastPointer.gridX gives the plot area's left edge
// in canvas CSS coordinates. The midpoint in canvas CSS is (currentMidX - rect.left).
const plotLeftCss = lastPointer ? lastPointer.x - lastPointer.gridX : 0;
const midGridX = currentMidX - rect.left - plotLeftCss;
const r = clamp(midGridX / plotWidthCss, 0, 1);
const { start, end } = zoomState.getRange();
const span = end - start;
if (!Number.isFinite(span) || span === 0) {
previousPinchDist = currentDist;
return;
}
const centerPct = clamp(start + r * span, 0, 100);
// Apply zoom based on pinch direction.
// ratio > 1 means fingers got closer => zoom out (pass ratio directly as factor).
// ratio < 1 means fingers spread apart => zoom in (invert to get factor > 1).
if (ratio > 1) {
zoomState.zoomOut(centerPct, ratio);
} else if (ratio > 0 && ratio < 1) {
zoomState.zoomIn(centerPct, 1 / ratio);
}
}
previousPinchDist = currentDist;
}
};
const onTouchPointerUp = (e: PointerEvent): void => {
if (!enabled || disposed) return;
if (e.pointerType !== "touch") return;
activePointers.delete(e.pointerId);
resetPinchState();
};
const onTouchPointerCancel = (e: PointerEvent): void => {
if (!enabled || disposed) return;
if (e.pointerType !== "touch") return;
activePointers.delete(e.pointerId);
resetPinchState();
};
// --- Enable / disable / dispose ---
const enable: InsideZoom["enable"] = () => {
if (disposed || enabled) return;
enabled = true;
eventManager.on("mousemove", onMouseMove);
eventManager.on("mouseleave", onMouseLeave);
eventManager.canvas.addEventListener("wheel", onWheel, { passive: false });
// Touch gesture listeners on canvas (only on touch-capable devices to avoid
// registering passive-false pointermove on desktop where it degrades scroll perf).
if (isTouchDevice) {
const canvas = eventManager.canvas;
savedTouchAction = canvas.style.touchAction;
canvas.style.touchAction = "none";
canvas.addEventListener("pointerdown", onTouchPointerDown, {
passive: false,
});
canvas.addEventListener("pointermove", onTouchPointerMove, {
passive: false,
});
canvas.addEventListener("pointerup", onTouchPointerUp);
canvas.addEventListener("pointercancel", onTouchPointerCancel);
}
};
const disable: InsideZoom["disable"] = () => {
if (disposed || !enabled) return;
enabled = false;
eventManager.off("mousemove", onMouseMove);
eventManager.off("mouseleave", onMouseLeave);
eventManager.canvas.removeEventListener("wheel", onWheel);
// Remove touch gesture listeners.
if (isTouchDevice) {
const canvas = eventManager.canvas;
canvas.style.touchAction = savedTouchAction;
canvas.removeEventListener("pointerdown", onTouchPointerDown);
canvas.removeEventListener("pointermove", onTouchPointerMove);
canvas.removeEventListener("pointerup", onTouchPointerUp);
canvas.removeEventListener("pointercancel", onTouchPointerCancel);
}
activePointers.clear();
resetPinchState();
lastPointer = null;
clearPan();
};
const dispose: InsideZoom["dispose"] = () => {
if (disposed) return;
disable();
disposed = true;
};
return { enable, disable, dispose };
}