Files
element-plus/packages/hooks/use-same-target/index.ts
dopamine 8618a6bcd0 refactor: import shared utilities from @element-plus/utils (#18048)
chore: import shared utilities from `@element-plus/utils`
2024-08-29 09:04:03 +08:00

32 lines
963 B
TypeScript

import { NOOP } from '@element-plus/utils'
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 }
}