|
| 1 | +import isUndef from 'licia/isUndef' |
| 2 | +import toBool from 'licia/toBool' |
| 3 | +import Protocol from 'devtools-protocol' |
| 4 | +import Input = Protocol.Input |
| 5 | + |
| 6 | +let isClick = false |
| 7 | + |
| 8 | +export function emulateTouchFromMouseEvent( |
| 9 | + params: Input.EmulateTouchFromMouseEventRequest |
| 10 | +) { |
| 11 | + const { type, x, y, deltaX, deltaY } = params |
| 12 | + |
| 13 | + const el = document.elementFromPoint(x, y) || document.documentElement |
| 14 | + |
| 15 | + switch (type) { |
| 16 | + case 'mousePressed': |
| 17 | + isClick = true |
| 18 | + triggerTouchEvent('touchstart', el, x, y) |
| 19 | + break |
| 20 | + case 'mouseMoved': |
| 21 | + isClick = false |
| 22 | + triggerTouchEvent('touchmove', el, x, y) |
| 23 | + break |
| 24 | + case 'mouseReleased': |
| 25 | + triggerTouchEvent('touchend', el, x, y) |
| 26 | + if (isClick) { |
| 27 | + el.dispatchEvent( |
| 28 | + new MouseEvent('click', { |
| 29 | + bubbles: true, |
| 30 | + cancelable: true, |
| 31 | + view: window, |
| 32 | + }) |
| 33 | + ) |
| 34 | + } |
| 35 | + isClick = false |
| 36 | + break |
| 37 | + case 'mouseWheel': |
| 38 | + if (!isUndef(deltaX) && !isUndef(deltaY)) { |
| 39 | + triggerScroll(el, deltaX, deltaY) |
| 40 | + } |
| 41 | + break |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +function triggerTouchEvent(type: string, el: Element, x: number, y: number) { |
| 46 | + const touch = new Touch({ |
| 47 | + identifier: 0, |
| 48 | + target: el, |
| 49 | + clientX: x, |
| 50 | + clientY: y, |
| 51 | + force: 1, |
| 52 | + }) |
| 53 | + |
| 54 | + el.dispatchEvent( |
| 55 | + new TouchEvent(type, { |
| 56 | + bubbles: true, |
| 57 | + touches: [touch], |
| 58 | + changedTouches: [touch], |
| 59 | + targetTouches: [touch], |
| 60 | + }) |
| 61 | + ) |
| 62 | +} |
| 63 | + |
| 64 | +function triggerScroll(el: Element, deltaX: number, deltaY: number) { |
| 65 | + el = findScrollableEl(el, deltaX, deltaY) |
| 66 | + el.scrollLeft -= deltaX |
| 67 | + el.scrollTop -= deltaY |
| 68 | +} |
| 69 | + |
| 70 | +function findScrollableEl(el: Element | null, deltaX: number, deltaY: number) { |
| 71 | + while (el) { |
| 72 | + if (toBool(deltaX) && isScrollable(el, 'x')) { |
| 73 | + return el |
| 74 | + } |
| 75 | + if (toBool(deltaY) && isScrollable(el, 'y')) { |
| 76 | + return el |
| 77 | + } |
| 78 | + |
| 79 | + el = el.parentElement |
| 80 | + } |
| 81 | + |
| 82 | + return el || document.documentElement |
| 83 | +} |
| 84 | + |
| 85 | +function isScrollable(el: Element, direction: 'x' | 'y') { |
| 86 | + const computedStyle = getComputedStyle(el) |
| 87 | + |
| 88 | + if (direction === 'x') { |
| 89 | + return ( |
| 90 | + el.scrollWidth > el.clientWidth && computedStyle.overflowX !== 'hidden' |
| 91 | + ) |
| 92 | + } |
| 93 | + |
| 94 | + return ( |
| 95 | + el.scrollHeight > el.clientHeight && computedStyle.overflowY !== 'hidden' |
| 96 | + ) |
| 97 | +} |
0 commit comments