| 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 |
17x
17x
17x
17x
4697x
2x
4695x
4695x
17x
97x
97x
97x
97x
97x
97x
97x
97x
97x
97x
97x
97x
97x
97x
97x
17x
87x
87x
17x
91x
3x
3x
91x
91x
17x
158x
158x
158x
158x
17x
75x
75x
17x
93x
93x
1x
92x
92x
92x
92x
17x
169x
85x
85x
83x
169x
17x
2725x
17x
10x
10x
10x
10x
10x
10x
17x
77x
77x
77x
77x
6x
71x
71x
71x
71x
71x
71x
71x
71x
71x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
4679x
204x
204x
4x
4x
200x
131x
131x
131x
4x
127x
4675x
4675x
7298x
4675x
2073x
2073x
2073x
4675x
4675x
2041x
2041x
2041x
4675x
17x
52x
52x
52x
52x
52x
52x
52x
52x
52x
52x
85x
85x
124x
85x
208x
85x
69x
69x
237x
237x
321x
237x
553x
237x
237x
17x
4723x
4723x
17x
4675x
91x
91x
91x
91x
91x
91x
91x
91x
91x
91x
124x
91x
124x
161x
161x
161x
161x
155x
155x
203x
155x
203x
161x
161x
97x
1x
1x
1x
97x
3x
1x
1x
3x
97x
17x
| /*
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
/* eslint-disable @typescript-eslint/no-empty-function */
import {
$,
isCssPropsFromAxes,
setCssProps,
revertCssProps,
useDirection,
getDirection,
} from "../utils";
import {
IS_IOS_SAFARI,
IOS_EDGE_THRESHOLD,
DIRECTION_NONE,
DIRECTION_VERTICAL,
DIRECTION_HORIZONTAL,
MOUSE_LEFT,
ANY,
} from "../const";
import { ActiveEvent, ElementType, InputEventType } from "../types";
import {
convertInputType,
getAddEventOptions,
InputType,
InputTypeObserver,
toAxis,
} from "./InputType";
export interface PanInputOption {
inputType?: string[];
inputKey?: string[];
inputButton?: string[];
scale?: number[];
thresholdAngle?: number;
threshold?: number;
preventClickOnDrag?: boolean;
preventDefaultOnDrag?: boolean;
iOSEdgeSwipeThreshold?: number;
releaseOnScroll?: boolean;
touchAction?: string;
}
// get user's direction
export const getDirectionByAngle = (
angle: number,
thresholdAngle: number
): number => {
if (thresholdAngle < 0 || thresholdAngle > 90) {
return DIRECTION_NONE;
}
const toAngle = Math.abs(angle);
return toAngle > thresholdAngle && toAngle < 180 - thresholdAngle
? DIRECTION_VERTICAL
: DIRECTION_HORIZONTAL;
};
/**
* @typedef {Object} PanInputOption The option object of the eg.Axes.PanInput module.
* @ko eg.Axes.PanInput 모듈의 옵션 객체
* @param {String[]} [inputType=["touch", "mouse", "pointer"]] Types of input devices
* - touch: Touch screen
* - mouse: Mouse
* - pointer: Mouse and touch <ko>입력 장치 종류
* - touch: 터치 입력 장치
* - mouse: 마우스
* - pointer: 마우스 및 터치</ko>
* @param {String[]} [inputKey=["any"]] List of key combinations to allow input
* - any: any key
* - shift: shift key
* - ctrl: ctrl key and pinch gesture on the trackpad
* - alt: alt key
* - meta: meta key
* - none: none of these keys are pressed <ko>입력을 허용할 키 조합 목록
* - any: 아무 키
* - shift: shift 키
* - ctrl: ctrl 키 및 트랙패드의 pinch 제스쳐
* - alt: alt 키
* - meta: meta 키
* - none: 아무 키도 눌리지 않은 상태 </ko>
* @param {String[]} [inputButton=["left"]] List of buttons to allow input
* - left: Left mouse button and normal touch
* - middle: Mouse wheel press
* - right: Right mouse button <ko>입력을 허용할 버튼 목록
* - left: 마우스 왼쪽 버튼
* - middle: 마우스 휠 눌림
* - right: 마우스 오른쪽 버튼 </ko>
* @param {Number[]} [scale] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko>
* @param {Number} [scale[0]=1] horizontal axis scale <ko>수평축 배율</ko>
* @param {Number} [scale[1]=1] vertical axis scale <ko>수직축 배율</ko>
* @param {Number} [thresholdAngle=45] The threshold value that determines whether user action is horizontal or vertical (0~90) <ko>사용자의 동작이 가로 방향인지 세로 방향인지 판단하는 기준 각도(0~90)</ko>
* @param {Number} [threshold=0] Minimal pan distance required before recognizing <ko>사용자의 Pan 동작을 인식하기 위해산 최소한의 거리</ko>
* @param {Boolean} [preventClickOnDrag=false] Whether to cancel the {@link https://developer.mozilla.org/en/docs/Web/API/Element/click_event click} event when the user finishes dragging more than 1 pixel <ko>사용자가 1픽셀 이상 드래그를 마쳤을 때 {@link https://developer.mozilla.org/ko/docs/Web/API/Element/click_event click} 이벤트 취소 여부</ko>
* @param {Boolean} [preventDefaultOnDrag=false] Whether to use the {@link https://developer.mozilla.org/ko/docs/Web/API/Event/preventDefault preventDefault} when the user starts dragging <ko>사용자가 드래그를 시작할 때 {@link https://developer.mozilla.org/ko/docs/Web/API/Event/preventDefault preventDefault} 실행 여부</ko>
* @param {Number} [iOSEdgeSwipeThreshold=30] Area (px) that can go to the next page when swiping the right edge in iOS safari <ko>iOS Safari에서 오른쪽 엣지를 스와이프 하는 경우 다음 페이지로 넘어갈 수 있는 영역(px)</ko>
* @param {String} [touchAction=null] Value that overrides the element's "touch-action" css property. If set to null, it is automatically set to prevent scrolling in the direction of the connected axis. <ko>엘리먼트의 "touch-action" CSS 속성을 덮어쓰는 값. 만약 null로 설정된 경우, 연결된 축 방향으로의 스크롤을 방지하게끔 자동으로 설정된다.</ko>
**/
/**
* A module that passes the amount of change to eg.Axes when the mouse or touchscreen is down and moved. use less than two axes.
* @ko 마우스나 터치 스크린을 누르고 움직일때의 변화량을 eg.Axes에 전달하는 모듈. 두개 이하의 축을 사용한다.
*
* @example
* ```js
* const pan = new eg.Axes.PanInput("#area", {
* inputType: ["touch"],
* scale: [1, 1.3],
* });
*
* // Connect the 'something2' axis to the mouse or touchscreen x position when the mouse or touchscreen is down and moved.
* // Connect the 'somethingN' axis to the mouse or touchscreen y position when the mouse or touchscreen is down and moved.
* axes.connect(["something2", "somethingN"], pan); // or axes.connect("something2 somethingN", pan);
*
* // Connect only one 'something1' axis to the mouse or touchscreen x position when the mouse or touchscreen is down and moved.
* axes.connect(["something1"], pan); // or axes.connect("something1", pan);
*
* // Connect only one 'something2' axis to the mouse or touchscreen y position when the mouse or touchscreen is down and moved.
* axes.connect(["", "something2"], pan); // or axes.connect(" something2", pan);
* ```
* @param {String|HTMLElement|Ref<HTMLElement>|jQuery} element An element to use the eg.Axes.PanInput module <ko>eg.Axes.PanInput 모듈을 사용할 엘리먼트</ko>
* @param {PanInputOption} [options={}] The option object of the eg.Axes.PanInput module<ko>eg.Axes.PanInput 모듈의 옵션 객체</ko>
*/
export class PanInput implements InputType {
public options: PanInputOption;
public axes: string[] = [];
public element: HTMLElement = null;
protected _observer: InputTypeObserver;
protected _direction: number;
protected _enabled = false;
protected _activeEvent: ActiveEvent = null;
private _originalCssProps: { [key: string]: string };
private _atRightEdge = false;
private _rightEdgeTimer = 0;
private _dragged = false;
private _isOverThreshold = false;
private _startTarget: Node | null = null;
/**
*
*/
public constructor(el: ElementType, options?: PanInputOption) {
this.element = $(el);
this.options = {
inputType: ["touch", "mouse", "pointer"],
inputKey: [ANY],
inputButton: [MOUSE_LEFT],
scale: [1, 1],
thresholdAngle: 45,
threshold: 0,
preventClickOnDrag: false,
preventDefaultOnDrag: false,
iOSEdgeSwipeThreshold: IOS_EDGE_THRESHOLD,
releaseOnScroll: false,
touchAction: null,
...options,
};
this._onPanstart = this._onPanstart.bind(this);
this._onPanmove = this._onPanmove.bind(this);
this._onPanend = this._onPanend.bind(this);
}
public mapAxes(axes: string[]) {
this._direction = getDirection(!!axes[0], !!axes[1]);
this.axes = axes;
}
public connect(observer: InputTypeObserver): InputType {
if (this._activeEvent) {
this._detachElementEvent();
this._detachWindowEvent(this._activeEvent);
}
this._attachElementEvent(observer);
return this;
}
public disconnect() {
this._detachElementEvent();
this._detachWindowEvent(this._activeEvent);
this._direction = DIRECTION_NONE;
return this;
}
/**
* Destroys elements, properties, and events used in a module.
* @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다.
*/
public destroy() {
this.disconnect();
this.element = null;
}
/**
* Enables input devices
* @ko 입력 장치를 사용할 수 있게 한다
* @return {PanInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
public enable() {
const activeEvent = convertInputType(this.options.inputType);
if (!activeEvent) {
throw new Error("PanInput cannot be enabled if there is no available input event.");
} else Eif (!this._enabled) {
this._enabled = true;
this._originalCssProps = setCssProps(
this.element,
this.options,
this._direction
);
}
return this;
}
/**
* Disables input devices
* @ko 입력 장치를 사용할 수 없게 한다.
* @return {PanInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
public disable() {
if (this._enabled) {
this._enabled = false;
if (!isCssPropsFromAxes(this._originalCssProps)) {
revertCssProps(this.element, this._originalCssProps);
}
}
return this;
}
/**
* Returns whether to use an input device
* @ko 입력 장치 사용 여부를 반환한다.
* @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko>
*/
public isEnabled() {
return this._enabled;
}
/**
* Releases current user input.
* @ko 사용자의 입력을 강제로 중단시킨다.
* @return {PanInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
public release() {
const activeEvent = this._activeEvent;
const prevEvent = activeEvent.prevEvent;
activeEvent.onRelease();
this._observer.release(this, prevEvent, [0, 0]);
this._detachWindowEvent(activeEvent);
return this;
}
protected _onPanstart(event: InputEventType) {
const { inputKey, inputButton, preventDefaultOnDrag } = this.options;
const activeEvent = this._activeEvent;
const panEvent = activeEvent.onEventStart(event, inputKey, inputButton);
if (
!panEvent ||
!this._enabled ||
activeEvent.getTouches(event, inputButton) > 1
) {
return;
}
Eif (panEvent.srcEvent.cancelable !== false) {
const edgeThreshold = this.options.iOSEdgeSwipeThreshold;
this._dragged = false;
this._isOverThreshold = false;
this._observer.hold(this, panEvent);
this._atRightEdge =
IS_IOS_SAFARI && panEvent.center.x > window.innerWidth - edgeThreshold;
this._attachWindowEvent(activeEvent, event);
(preventDefaultOnDrag && panEvent.srcEvent.type !== "touchstart") && panEvent.srcEvent.preventDefault();
activeEvent.prevEvent = panEvent;
}
}
protected _onPanmove(event: InputEventType) {
const {
iOSEdgeSwipeThreshold,
preventClickOnDrag,
releaseOnScroll,
inputKey,
inputButton,
threshold,
thresholdAngle,
} = this.options;
const activeEvent = this._activeEvent;
const panEvent = activeEvent.onEventMove(event, inputKey, inputButton);
const touches = activeEvent.getTouches(event, inputButton);
Iif (
touches === 0 ||
(releaseOnScroll && panEvent && !panEvent.srcEvent.cancelable)
) {
this._onPanend(event);
return;
}
Iif (!panEvent || !this._enabled || touches > 1) {
return;
}
const userDirection = getDirectionByAngle(panEvent.angle, thresholdAngle);
const useHorizontal = useDirection(
DIRECTION_HORIZONTAL,
this._direction,
userDirection
);
const useVertical = useDirection(
DIRECTION_VERTICAL,
this._direction,
userDirection
);
if (activeEvent.prevEvent && IS_IOS_SAFARI) {
const swipeLeftToRight = panEvent.center.x < 0;
if (swipeLeftToRight) {
// iOS swipe left => right
this.release();
return;
} else if (this._atRightEdge) {
clearTimeout(this._rightEdgeTimer);
// - is right to left
const swipeRightToLeft = panEvent.deltaX < -iOSEdgeSwipeThreshold;
if (swipeRightToLeft) {
this._atRightEdge = false;
} else {
// iOS swipe right => left
this._rightEdgeTimer = window.setTimeout(() => this.release(), 100);
}
}
}
const distance = this._getDistance(
[panEvent.deltaX, panEvent.deltaY],
[useHorizontal, useVertical]
);
const offset = this._getOffset(
[panEvent.offsetX, panEvent.offsetY],
[useHorizontal, useVertical]
);
const prevent = offset.some((v) => v !== 0);
if (prevent) {
Eif (panEvent.srcEvent.cancelable !== false) {
panEvent.srcEvent.preventDefault();
}
panEvent.srcEvent.stopPropagation();
}
panEvent.preventSystemEvent = prevent;
if (prevent && (this._isOverThreshold || distance >= threshold)) {
this._dragged = preventClickOnDrag;
this._isOverThreshold = true;
this._observer.change(this, panEvent, toAxis(this.axes, offset));
}
activeEvent.prevEvent = panEvent;
}
protected _onPanend(event: InputEventType) {
const inputButton = this.options.inputButton;
const activeEvent = this._activeEvent;
activeEvent.onEventEnd(event);
Iif (!this._enabled || activeEvent.getTouches(event, inputButton) !== 0) {
return;
}
this._detachWindowEvent(activeEvent);
clearTimeout(this._rightEdgeTimer);
const prevEvent = activeEvent.prevEvent;
const velocity = this._isOverThreshold ? this._getOffset(
[
Math.abs(prevEvent.velocityX) * prevEvent.directionX,
Math.abs(prevEvent.velocityY) * prevEvent.directionY,
],
[
useDirection(DIRECTION_HORIZONTAL, this._direction),
useDirection(DIRECTION_VERTICAL, this._direction),
]
) : [0, 0];
activeEvent.onRelease();
this._observer.release(this, prevEvent, velocity);
}
protected _attachWindowEvent(activeEvent: ActiveEvent, startEvent?: InputEventType) {
activeEvent?.move.forEach((event) => {
window.addEventListener(event, this._onPanmove, getAddEventOptions(event));
});
activeEvent?.end.forEach((event) => {
window.addEventListener(event, this._onPanend, getAddEventOptions(event));
});
// Touch events are no longer fired when the target of the touchstart is removed from the DOM,
// while mouse/pointer events keep being delivered to window.
// The browser releases the implicit pointer capture of the touch and fires "lostpointercapture" at the document,
// so listen to it to release the input instead of being stuck in the hold state.
if (startEvent?.type === "touchstart") {
this._startTarget = startEvent.target as Node;
window.addEventListener("lostpointercapture", this._onLostPointerCapture, true);
}
}
protected _detachWindowEvent(activeEvent: ActiveEvent) {
activeEvent?.move.forEach((event) => {
window.removeEventListener(event, this._onPanmove);
});
activeEvent?.end.forEach((event) => {
window.removeEventListener(event, this._onPanend);
});
window.removeEventListener("lostpointercapture", this._onLostPointerCapture, true);
this._startTarget = null;
}
protected _getOffset(properties: number[], direction: boolean[]): number[] {
const scale = this.options.scale;
return [
direction[0] ? properties[0] * scale[0] : 0,
direction[1] ? properties[1] * scale[1] : 0,
];
}
private _getDistance(delta: number[], direction: boolean[]): number {
return Math.sqrt(
Number(direction[0]) * Math.pow(delta[0], 2) +
Number(direction[1]) * Math.pow(delta[1], 2)
);
}
private _attachElementEvent(observer: InputTypeObserver) {
const activeEvent = convertInputType(this.options.inputType);
const element = this.element;
Iif (!activeEvent) {
return;
}
Iif (!element) {
throw new Error("Element to connect input does not exist.");
}
this._observer = observer;
this.enable();
this._activeEvent = activeEvent;
element.addEventListener("click", this._preventClickWhenDragged, true);
activeEvent.start.forEach((event) => {
element.addEventListener(event, this._onPanstart);
});
// adding event listener to element prevents invalid behavior in iOS Safari
activeEvent.move.forEach((event) => {
element.addEventListener(event, this._voidFunction);
});
}
private _detachElementEvent() {
const activeEvent = this._activeEvent;
const element = this.element;
if (element) {
element.removeEventListener("click", this._preventClickWhenDragged, true);
activeEvent?.start.forEach((event) => {
element.removeEventListener(event, this._onPanstart);
});
activeEvent?.move.forEach((event) => {
element.removeEventListener(event, this._voidFunction);
});
}
this.disable();
this._observer = null;
}
// "lostpointercapture" is also fired on a normal pointerup, so release only when the target is actually detached.
private _onLostPointerCapture = () => {
const target = this._startTarget;
Eif (target && !target.isConnected) {
this.release();
}
};
private _preventClickWhenDragged = (e: PointerEvent | MouseEvent) => {
if (this._dragged) {
e.preventDefault();
e.stopPropagation();
}
this._dragged = false;
};
private _voidFunction = () => {};
}
|