| 1 | import type { Ref } from 'vue' |
| 2 | import { useEventListener } from '@vueuse/core' |
| 3 | import { computed, onScopeDispose, watch } from 'vue' |
| 4 | import { hideCursorIdle } from '../state' |
| 5 | |
| 6 | const TIMEOUT = 2000 |
| 7 | |
| 8 | export function useHideCursorIdle( |
| 9 | enabled: Ref<boolean>, |
| 10 | ) { |
| 11 | const shouldHide = computed(() => enabled.value && hideCursorIdle.value) |
| 12 | |
| 13 | function hide() { |
| 14 | document.body.style.cursor = 'none' |
| 15 | } |
| 16 | function show() { |
| 17 | document.body.style.cursor = '' |
| 18 | } |
| 19 | |
| 20 | let timer: ReturnType<typeof setTimeout> | null = null |
| 21 | |
| 22 | // If disabled, immediately show the cursor and stop the timer |
| 23 | watch( |
| 24 | shouldHide, |
| 25 | (value) => { |
| 26 | if (!value) { |
| 27 | show() |
| 28 | if (timer) { |
| 29 | clearTimeout(timer) |
| 30 | } |
| 31 | timer = null |
| 32 | } |
| 33 | }, |
| 34 | ) |
| 35 | |
| 36 | onScopeDispose(() => { |
| 37 | show() |
| 38 | if (timer) { |
| 39 | clearTimeout(timer) |
| 40 | } |
| 41 | timer = null |
| 42 | }) |
| 43 | |
| 44 | useEventListener( |
| 45 | document.body, |
| 46 | ['pointermove', 'pointerdown'], |
| 47 | () => { |
| 48 | show() |
| 49 | if (timer) |
| 50 | clearTimeout(timer) |
| 51 | if (shouldHide.value) { |
| 52 | timer = setTimeout(hide, TIMEOUT) |
| 53 | } |
| 54 | else { |
| 55 | timer = null |
| 56 | } |
| 57 | }, |
| 58 | { passive: true }, |
| 59 | ) |
| 60 | } |
| 61 |