element-plus/packages/hooks/use-same-target/index.ts
Aex 78ab1b2f8e
feat(hooks): add same target support (#3473)
* feat(hooks): add same target support

* fix: dialog test

* fix: remove unused code

* improvement: custom-mask-event attr
2021-09-18 10:04:25 +08:00

32 lines
955 B
TypeScript

import { NOOP } from '@vue/shared'
export const useSameTarget = (handleClick?: (e: MouseEvent) => void) => {
if (!handleClick) {
return { onClick: NOOP, onMousedown: NOOP, onMouseup: NOOP }
}
let mousedownTarget = false
let mouseupTarget = false
// refer to this https://javascript.info/mouse-events-basics
// events fired in the order: mousedown -> mouseup -> click
// we need to set the mousedown handle to false after click fired.
const onClick = (e: MouseEvent) => {
// if and only if
if (mousedownTarget && mouseupTarget) {
handleClick(e)
}
mousedownTarget = mouseupTarget = false
}
const onMousedown = (e: MouseEvent) => {
// marking current mousedown target.
mousedownTarget = e.target === e.currentTarget
}
const onMouseup = (e: MouseEvent) => {
// marking current mouseup target.
mouseupTarget = e.target === e.currentTarget
}
return { onClick, onMousedown, onMouseup }
}