index.ts 955 B

12345678910111213141516171819202122232425262728293031
  1. import { NOOP } from '@vue/shared'
  2. export const useSameTarget = (handleClick?: (e: MouseEvent) => void) => {
  3. if (!handleClick) {
  4. return { onClick: NOOP, onMousedown: NOOP, onMouseup: NOOP }
  5. }
  6. let mousedownTarget = false
  7. let mouseupTarget = false
  8. // refer to this https://javascript.info/mouse-events-basics
  9. // events fired in the order: mousedown -> mouseup -> click
  10. // we need to set the mousedown handle to false after click fired.
  11. const onClick = (e: MouseEvent) => {
  12. // if and only if
  13. if (mousedownTarget && mouseupTarget) {
  14. handleClick(e)
  15. }
  16. mousedownTarget = mouseupTarget = false
  17. }
  18. const onMousedown = (e: MouseEvent) => {
  19. // marking current mousedown target.
  20. mousedownTarget = e.target === e.currentTarget
  21. }
  22. const onMouseup = (e: MouseEvent) => {
  23. // marking current mouseup target.
  24. mouseupTarget = e.target === e.currentTarget
  25. }
  26. return { onClick, onMousedown, onMouseup }
  27. }