-
Notifications
You must be signed in to change notification settings - Fork 0
/
gesture-frame.ts
497 lines (459 loc) · 17.4 KB
/
gesture-frame.ts
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
const clamp = (x: number, min: number, max: number) => (x < min ? min : x > max ? max : x);
const clampZero = (x: number) => (x < 0 ? 0 : x);
const preventDefault = (event: Event) => event.preventDefault();
const throttle = (callback: () => void): [() => void, () => void] => {
let handle: number | undefined;
const wrappedCallback = () => ((handle = undefined), callback());
return [
() => (handle ??= requestAnimationFrame(wrappedCallback)),
() => handle !== undefined && (cancelAnimationFrame(handle), (handle = undefined)),
];
};
const computedStyleCache = new WeakMap<Element, CSSStyleDeclaration>();
const cachedComputedStyle = (element: Element) => {
let computedStyle = computedStyleCache.get(element);
if (!computedStyle) {
computedStyle = getComputedStyle(element);
computedStyleCache.set(element, computedStyle);
}
return computedStyle;
};
const accumulateInverseCssZoom = CSS.supports('zoom', '1')
? (element: Element) => {
let zoom = 1;
// @ts-ignore
for (; element; element = element.parentElement) zoom *= cachedComputedStyle(element).zoom;
return 1 / zoom;
}
: () => 1;
class ScrollableFrame extends HTMLElement {
static readonly observedAttributes: readonly string[] = ['scale', 'min-scale', 'max-scale', 'offset-x', 'offset-y'];
#scale = 1;
get scale() {
return this.#scale;
}
set scale(scale) {
scale = clamp(scale, this.#minScale, this.#maxScale);
if (this.#scale !== scale) {
this.#setAttribute('scale', (this.#scale = scale));
this.#content.style.transform = `scale(${scale})`;
}
}
#minScale = 0.1;
get minScale() {
return this.#minScale;
}
set minScale(minScale) {
if (this.#minScale !== minScale && minScale > 0) {
this.#setAttribute('min-scale', (this.#minScale = minScale));
this.#scale < minScale && (this.scale = minScale);
}
}
#maxScale = 100;
get maxScale() {
return this.#maxScale;
}
set maxScale(maxScale) {
if (this.#maxScale !== maxScale && maxScale > 0) {
this.#setAttribute('max-scale', (this.#maxScale = maxScale));
this.#scale > maxScale && (this.scale = maxScale);
}
}
#offsetX = 0;
get offsetX() {
return this.#offsetX;
}
set offsetX(offsetX) {
this.setOffset(offsetX, this.#offsetY);
}
#offsetY = 0;
get offsetY() {
return this.#offsetY;
}
set offsetY(offsetY) {
this.setOffset(this.#offsetX, offsetY);
}
#marginX = 0;
#marginY = 0;
readonly #container;
readonly #topLeft;
readonly #content;
readonly #disableScrollEventTemporarily;
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = '<div part=container><div part=top-left></div><slot part=content></slot></div>';
this.#container = shadowRoot.firstElementChild as HTMLDivElement;
this.#topLeft = this.#container.firstElementChild as HTMLDivElement;
this.#content = this.#topLeft.nextElementSibling as HTMLSlotElement;
{
let isScrollEventEnabled = 1;
const [reserveListeningScrollEvent] = throttle(() => (isScrollEventEnabled = 1));
this.#disableScrollEventTemporarily = () => {
reserveListeningScrollEvent();
isScrollEventEnabled = 0;
};
this.addEventListener('scroll', () => {
if (isScrollEventEnabled) {
const offset = this.#getCTMs()[0].transformPoint({ x: this.#marginX - this.scrollLeft, y: this.#marginY - this.scrollTop });
this.#setAttribute('offset-x', (this.#offsetX = offset.x));
this.#setAttribute('offset-y', (this.#offsetY = offset.y));
}
});
}
}
#isAttributeChangedCallbackEnabled = 1;
#setAttribute(name: string, value: string | number) {
this.#isAttributeChangedCallbackEnabled = 0;
this.setAttribute(name, value as string & number);
this.#isAttributeChangedCallbackEnabled = 1;
}
connectedCallback() {
this.#setAttribute('scale', this.#scale);
this.#setAttribute('min-scale', this.#minScale);
this.#setAttribute('max-scale', this.#maxScale);
}
attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null) {
if (this.#isAttributeChangedCallbackEnabled && oldValue !== newValue && newValue !== null) {
if (name === 'offset-x') {
this.offsetX = +newValue;
} else if (name === 'offset-y') {
this.offsetY = +newValue;
} else if (name === 'scale') {
this.scale = +newValue;
} else if (name === 'min-scale') {
this.minScale = +newValue;
} else if (name === 'max-scale') {
this.maxScale = +newValue;
}
}
}
#memoizedCTMString = '';
#memoizedCTMs: readonly [DOMMatrixReadOnly, DOMMatrixReadOnly] = [new DOMMatrixReadOnly(), new DOMMatrixReadOnly()];
#getCTMs() {
let ctmString = '';
for (let element: Element | null = this; element; element = element.parentElement) {
const transform = cachedComputedStyle(element).transform;
transform && transform !== 'none' && (ctmString = `${transform} ${ctmString}`);
}
if (this.#memoizedCTMString !== ctmString) {
const ctm = new DOMMatrix(ctmString);
ctm.e = ctm.f = 0;
this.#memoizedCTMString = ctmString;
this.#memoizedCTMs = [ctm, ctm.inverse()];
}
return this.#memoizedCTMs;
}
setOffset(offsetX: number, offsetY: number) {
if (this.#offsetX === offsetX && this.#offsetY === offsetY) {
return;
}
this.#setAttribute('offset-x', (this.#offsetX = offsetX));
this.#setAttribute('offset-y', (this.#offsetY = offsetY));
const { x, y } = this.#getCTMs()[1].transformPoint({ x: offsetX, y: offsetY });
const containerStyle = this.#container.style;
containerStyle.margin = `${(this.#marginY = clampZero(y))}px 0 0 ${(this.#marginX = clampZero(x))}px`;
containerStyle.width = `${x < 0 ? this.clientWidth - x : 0}px`;
containerStyle.height = `${y < 0 ? this.clientHeight - y : 0}px`;
this.#disableScrollEventTemporarily();
this.scrollTo(clampZero(-x), clampZero(-y));
}
_zoom(scaleRatio: number, originClientX: number, originClientY: number) {
const previousScale = this.#scale;
const scale = clamp(previousScale * scaleRatio, this.#minScale, this.#maxScale);
if (scale !== previousScale) {
const offsetScale = scale / previousScale - 1;
const topLeft = this.#topLeft.getBoundingClientRect();
this.scale = scale;
this.setOffset(this.#offsetX + offsetScale * (topLeft.x - originClientX), this.#offsetY + offsetScale * (topLeft.y - originClientY));
}
}
/**
* Zoom keeping the apparent position of `(origin.x, origin.y)`. Zoom in when `scaleRatio > 1` and zoom out when `scaleRatio < 1`. `origin.x` and `origin.y` can be specified as a `number` (px) or a `` `${number}%` ``. The default value for both is `"50%"` (center).
*/
zoom(scaleRatio: number, origin?: { readonly x?: number | `${number}%`; readonly y?: number | `${number}%` }) {
if (scaleRatio === 1) {
return;
}
const rect = this.getBoundingClientRect();
const originX = origin?.x ?? rect.width / 2;
const originY = origin?.y ?? rect.height / 2;
this._zoom(
scaleRatio,
rect.x + (typeof originX === 'number' ? originX : rect.width * parseFloat(originX) * 0.01),
rect.y + (typeof originY === 'number' ? originY : rect.height * parseFloat(originY) * 0.01),
);
}
/**
* Adjust the scale and offset to display the entire content.
*/
fit(options?: { readonly marginX?: number; readonly marginY?: number }) {
const { offsetWidth: width, offsetHeight: height } = this;
const { offsetWidth: contentWidth, offsetHeight: contentHeight } = this.#content;
const marginX = options?.marginX ?? 0;
const marginY = options?.marginY ?? 0;
const widthBasedScale = (width - marginX - marginX) / contentWidth;
const heightBasedScale = (height - marginY - marginY) / contentHeight;
if (widthBasedScale < heightBasedScale) {
this.scale = widthBasedScale;
this.setOffset(marginX, Math.floor(height - contentHeight * widthBasedScale) / 2);
} else {
this.scale = heightBasedScale;
this.setOffset(Math.floor(width - contentWidth * heightBasedScale) / 2, marginY);
}
}
/**
* Adjust the scale and offset-x to fit the width.
*/
fitX(options?: { readonly margin?: number }) {
const margin = options?.margin ?? 0;
this.scale = (this.offsetWidth - margin - margin) / this.#content.offsetWidth;
this.offsetX = margin;
}
/**
* Adjust the scale and offset-y to fit the height.
*/
fitY(options?: { readonly margin?: number }) {
const margin = options?.margin ?? 0;
this.scale = (this.offsetHeight - margin - margin) / this.#content.offsetHeight;
this.offsetY = margin;
}
}
export class GestureFrame extends ScrollableFrame {
static override readonly observedAttributes: readonly string[] = [
...super.observedAttributes,
'pan-x',
'pan-y',
'pan-button',
'pinch-zoom',
'anchor-left',
'anchor-right',
'anchor-top',
'anchor-bottom',
];
#setBooleanAttribute(name: string, oldValue: boolean, newValue: boolean, setValue: (value: boolean) => void) {
newValue = !!newValue;
if (oldValue !== newValue) {
setValue(newValue);
newValue ? this.setAttribute(name, '') : this.removeAttribute(name);
}
}
#panX = false;
get panX() {
return this.#panX;
}
set panX(panX) {
this.#setBooleanAttribute('pan-x', this.#panX, panX, (panX) => (this.#panX = panX));
}
#panY = false;
get panY() {
return this.#panY;
}
set panY(panY) {
this.#setBooleanAttribute('pan-y', this.#panY, panY, (panY) => (this.#panY = panY));
}
#panButton = 0;
get panButton() {
return this.#panButton;
}
set panButton(panButton) {
if (this.#panButton !== panButton) {
this.setAttribute('pan-button', (this.#panButton = panButton) as string & number);
if (panButton === 2) {
this.addEventListener('contextmenu', preventDefault);
} else {
this.removeEventListener('contextmenu', preventDefault);
}
}
}
#pinchZoom = false;
get pinchZoom() {
return this.#pinchZoom;
}
set pinchZoom(pinchZoom) {
this.#setBooleanAttribute('pinch-zoom', this.#pinchZoom, pinchZoom, (pinchZoom) => (this.#pinchZoom = pinchZoom));
}
#anchorLeft = false;
get anchorLeft() {
return this.#anchorLeft;
}
set anchorLeft(anchorLeft) {
this.#setBooleanAttribute('anchor-left', this.#anchorLeft, anchorLeft, (anchorLeft) => (this.#anchorLeft = anchorLeft));
}
#anchorRight = false;
get anchorRight() {
return this.#anchorRight;
}
set anchorRight(anchorRight) {
this.#setBooleanAttribute('anchor-right', this.#anchorRight, anchorRight, (anchorRight) => (this.#anchorRight = anchorRight));
}
#anchorTop = false;
get anchorTop() {
return this.#anchorTop;
}
set anchorTop(anchorTop) {
this.#setBooleanAttribute('anchor-top', this.#anchorTop, anchorTop, (anchorTop) => (this.#anchorTop = anchorTop));
}
#anchorBottom = false;
get anchorBottom() {
return this.#anchorBottom;
}
set anchorBottom(anchorBottom) {
this.#setBooleanAttribute('anchor-bottom', this.#anchorBottom, anchorBottom, (anchorBottom) => (this.#anchorBottom = anchorBottom));
}
#w0!: number;
#h0!: number;
readonly #resizeObserver = new ResizeObserver(() => {
const { offsetWidth: w, offsetHeight: h, anchorLeft, anchorRight, anchorTop, anchorBottom } = this;
const w0 = this.#w0;
const h0 = this.#h0;
const anchorCenterX = anchorLeft === anchorRight;
const anchorCenterY = anchorTop === anchorBottom;
this.setOffset(
this.offsetX + (anchorCenterX ? (w - w0) / 2 : anchorLeft ? 0 : w - w0),
this.offsetY + (anchorCenterY ? (h - h0) / 2 : anchorTop ? 0 : h - h0),
);
if (anchorLeft && anchorRight) {
this.zoom(
w / w0,
anchorCenterY
? undefined
: { y: this.offsetY + (anchorTop ? 0 : ((this.firstElementChild as HTMLElement)?.offsetHeight ?? 0) * this.scale) },
);
} else if (anchorTop && anchorBottom) {
this.zoom(
h / h0,
anchorCenterX
? undefined
: { x: this.offsetX + (anchorLeft ? 0 : ((this.firstElementChild as HTMLElement)?.offsetWidth ?? 0) * this.scale) },
);
}
this.#w0 = w;
this.#h0 = h;
});
override connectedCallback(): void {
this.#resizeObserver.observe(this, { box: 'border-box' });
this.#w0 = this.offsetWidth;
this.#h0 = this.offsetHeight;
}
disconnectedCallback(): void {
this.#resizeObserver.disconnect();
}
override attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null) {
if (name === 'pan-x') {
this.panX = newValue !== null;
} else if (name === 'pan-y') {
this.panY = newValue !== null;
} else if (name === 'pan-button') {
this.panButton = +newValue! || 0;
} else if (name === 'pinch-zoom') {
this.pinchZoom = newValue !== null;
} else if (name === 'anchor-left') {
this.anchorLeft = newValue !== null;
} else if (name === 'anchor-right') {
this.anchorRight = newValue !== null;
} else if (name === 'anchor-top') {
this.anchorTop = newValue !== null;
} else if (name === 'anchor-bottom') {
this.anchorBottom = newValue !== null;
} else {
super.attributeChangedCallback(name, oldValue, newValue);
}
}
constructor() {
super();
{
let scaleRatio = 1;
let clientX: number;
let clientY: number;
const [reserveZooming] = throttle(() => {
const inverseCssZoom = accumulateInverseCssZoom(this);
this._zoom(scaleRatio, clientX * inverseCssZoom, clientY * inverseCssZoom);
scaleRatio = 1;
});
this.addEventListener(
'wheel',
(event: WheelEvent) => {
if (this.#pinchZoom && event.ctrlKey) {
event.preventDefault();
scaleRatio *= 0.99 ** event.deltaY;
({ clientX, clientY } = event);
reserveZooming();
}
},
{ passive: false },
);
}
{
// do not use movementX/Y, that do not aware page zoom
let pointers: {
readonly id: PointerEvent['pointerId'];
readonly b: PointerEvent['button'];
cx: number;
cy: number;
px: number;
py: number;
}[] = [];
let inverseCssZoom = 1;
const [requestPanZoom] = throttle(() => {
const [p1, p2] = pointers;
if (p1 && p2 && this.#pinchZoom) {
const x = (p1.cx + p2.cx) / 2;
const y = (p1.cy + p2.cy) / 2;
const cd = Math.hypot(p1.cx - p2.cx, p1.cy - p2.cy);
const pd = Math.hypot(p1.px - p2.px, p1.py - p2.py);
cd && pd && this._zoom(cd / pd, x, y);
this.setOffset(this.offsetX + x - (p1.px + p2.px) / 2, this.offsetY + y - (p1.py + p2.py) / 2);
} else if (p1 && (this.#panX || this.#panY) && p1.b === this.#panButton) {
this.setOffset(
this.#panX ? this.offsetX + p1.cx - p1.px : this.offsetX,
this.#panY ? this.offsetY + p1.cy - p1.py : this.offsetY,
);
}
pointers.forEach((pointer) => {
pointer.px = pointer.cx;
pointer.py = pointer.cy;
});
});
const onPointerMove = (event: PointerEvent) => {
// switching tab while dragging prevents handling of pointerup events.
if (event.buttons === 0) {
pointers = [];
removeEventListeners();
return;
}
const pointer = pointers.find((p) => p.id === event.pointerId);
if (pointer) {
(this.#panX || this.#panY || (this.#pinchZoom && pointers.length >= 2)) && event.preventDefault();
pointer.cx = event.clientX * inverseCssZoom;
pointer.cy = event.clientY * inverseCssZoom;
requestPanZoom();
}
};
const onPointerUp = (event: PointerEvent) => {
const index = pointers.findIndex((p) => p.id === event.pointerId);
if (index !== -1) {
pointers.splice(index, 1);
pointers.length || removeEventListeners();
}
};
const removeEventListeners = () => {
removeEventListener('pointermove', onPointerMove);
removeEventListener('pointerup', onPointerUp, true);
removeEventListener('pointercancel', onPointerUp, true);
};
this.addEventListener('pointerdown', (event) => {
if (((this.#panX || this.#panY) && event.button === this.#panButton) || (this.#pinchZoom && event.button === 0)) {
pointers.length === 0 && (inverseCssZoom = accumulateInverseCssZoom(this));
const cx = event.clientX * inverseCssZoom;
const cy = event.clientY * inverseCssZoom;
pointers.push({ id: event.pointerId, b: event.button, cx, cy, px: cx, py: cy });
addEventListener('pointermove', onPointerMove);
addEventListener('pointerup', onPointerUp, true);
addEventListener('pointercancel', onPointerUp, true);
}
});
}
}
}
customElements.define('gesture-frame', GestureFrame);