Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use @vueuse/core useEventListener composable in order to remove listeners easier #1201

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions packages/radix-vue/src/DismissableLayer/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isClient } from '@vueuse/shared'
import { useEventListener } from '@vueuse/core'
import { handleAndDispatchCustomEvent } from '@/shared'
import { type Ref, nextTick, ref, watchEffect } from 'vue'

Expand Down Expand Up @@ -30,12 +31,11 @@ function isLayerExist(layerElement: HTMLElement, targetElement: HTMLElement) {
(targetLayer
&& mainLayer === targetLayer)
|| nodeList.indexOf(mainLayer) < nodeList.indexOf(targetLayer)
) {
)
return true
}
else {

else
return false
}
}

/**
Expand All @@ -53,6 +53,9 @@ export function usePointerDownOutside(
const isPointerInsideDOMTree = ref(false)
const handleClickRef = ref(() => {})

let ownerDocumentClickCleanup: ReturnType<typeof useEventListener>
let ownerDocumentPointerdownCleanup: ReturnType<typeof useEventListener>

watchEffect((cleanupFn) => {
if (!isClient)
return
Expand Down Expand Up @@ -93,7 +96,7 @@ export function usePointerDownOutside(
if (event.pointerType === 'touch') {
ownerDocument.removeEventListener('click', handleClickRef.value)
handleClickRef.value = handleAndDispatchPointerDownOutsideEvent
ownerDocument.addEventListener('click', handleClickRef.value, {
ownerDocumentClickCleanup = useEventListener(ownerDocument, 'click', handleClickRef.value, {
once: true,
})
}
Expand All @@ -104,7 +107,7 @@ export function usePointerDownOutside(
else {
// We need to remove the event listener in case the outside click has been canceled.
// See: https://github.com/radix-ui/primitives/issues/2171
ownerDocument.removeEventListener('click', handleClickRef.value)
ownerDocumentClickCleanup && ownerDocumentClickCleanup()
}
isPointerInsideDOMTree.value = false
}
Expand All @@ -122,13 +125,12 @@ export function usePointerDownOutside(
* });
*/
const timerId = window.setTimeout(() => {
ownerDocument.addEventListener('pointerdown', handlePointerDown)
ownerDocumentPointerdownCleanup = useEventListener(ownerDocument, 'pointerdown', handlePointerDown)
}, 0)

cleanupFn(() => {
window.clearTimeout(timerId)
ownerDocument.removeEventListener('pointerdown', handlePointerDown)
ownerDocument.removeEventListener('click', handleClickRef.value)
ownerDocumentPointerdownCleanup && ownerDocumentPointerdownCleanup()
})
})

Expand All @@ -148,6 +150,8 @@ export function useFocusOutside(
const ownerDocument: Document
= element?.value?.ownerDocument ?? globalThis?.document

let ownerDocumentFocusinCleanup: ReturnType<typeof useEventListener>

const isFocusInsideDOMTree = ref(false)
watchEffect((cleanupFn) => {
if (!isClient)
Expand All @@ -170,9 +174,9 @@ export function useFocusOutside(
}
}

ownerDocument.addEventListener('focusin', handleFocus)
ownerDocumentFocusinCleanup = useEventListener(ownerDocument, 'focusin', handleFocus)

cleanupFn(() => ownerDocument.removeEventListener('focusin', handleFocus))
cleanupFn(() => ownerDocumentFocusinCleanup())
})

return {
Expand Down
24 changes: 14 additions & 10 deletions packages/radix-vue/src/FocusScope/FocusScope.vue
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export interface FocusScopeProps extends PrimitiveProps {

<script setup lang="ts">
import { nextTick, reactive, ref, watchEffect } from 'vue'
import { useEventListener } from '@vueuse/core'
import { isClient } from '@vueuse/shared'
import {
AUTOFOCUS_ON_MOUNT,
Expand Down Expand Up @@ -68,7 +69,7 @@ const focusScope = reactive({
},
})

watchEffect((cleanupFn) => {
watchEffect((onCleanup) => {
if (!isClient)
return
const container = currentElement.value
Expand Down Expand Up @@ -122,20 +123,21 @@ watchEffect((cleanupFn) => {
focus(container)
}

document.addEventListener('focusin', handleFocusIn)
document.addEventListener('focusout', handleFocusOut)
const documentFocusInCleanup = useEventListener(document, 'focusin', handleFocusIn)
const documentFocusOutCleanup = useEventListener(document, 'focusout', handleFocusOut)

const mutationObserver = new MutationObserver(handleMutations)
if (container)
mutationObserver.observe(container, { childList: true, subtree: true })

cleanupFn(() => {
document.removeEventListener('focusin', handleFocusIn)
document.removeEventListener('focusout', handleFocusOut)
onCleanup(() => {
documentFocusInCleanup()
documentFocusOutCleanup()
mutationObserver.disconnect()
})
})

watchEffect(async (cleanupFn) => {
watchEffect(async (onCleanup) => {
const container = currentElement.value

await nextTick()
Expand All @@ -160,23 +162,25 @@ watchEffect(async (cleanupFn) => {
}
}

cleanupFn(() => {
onCleanup(() => {
container.removeEventListener(AUTOFOCUS_ON_MOUNT, (ev: Event) =>
emits('mountAutoFocus', ev))

const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS)
const unmountEventHandler = (ev: Event) => {
emits('unmountAutoFocus', ev)
}
container.addEventListener(AUTOFOCUS_ON_UNMOUNT, unmountEventHandler)

const stop = useEventListener(container, AUTOFOCUS_ON_UNMOUNT, unmountEventHandler)

container.dispatchEvent(unmountEvent)

setTimeout(() => {
if (!unmountEvent.defaultPrevented)
focus(previouslyFocusedElement ?? document.body, { select: true })

// we need to remove the listener after we `dispatchEvent`
container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, unmountEventHandler)
stop()

focusScopesStack.remove(focusScope)
}, 0)
Expand Down
4 changes: 2 additions & 2 deletions packages/radix-vue/src/HoverCard/HoverCardContentImpl.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface HoverCardContentImplProps extends PopperContentProps {}

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, watchEffect } from 'vue'
import { useEventListener } from '@vueuse/core'
import { injectHoverCardRootContext } from './HoverCardRoot.vue'
import { PopperContent } from '@/Popper'
import { DismissableLayer } from '@/DismissableLayer'
Expand Down Expand Up @@ -63,15 +64,14 @@ function handlePointerUp() {
}
onMounted(() => {
if (contentElement.value) {
document.addEventListener('pointerup', handlePointerUp)
useEventListener(document, 'pointerup', handlePointerUp)

const tabbables = getTabbableNodes(contentElement.value)
tabbables.forEach(tabbable => tabbable.setAttribute('tabindex', '-1'))
}
})

onUnmounted(() => {
document.removeEventListener('pointerup', handlePointerUp)
rootContext.hasSelectionRef.value = false
rootContext.isPointerDownOnContentRef.value = false
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface NavigationMenuContentImplProps extends DismissableLayerProps {}

<script setup lang="ts">
import { computed, ref, watchEffect } from 'vue'
import { useEventListener } from '@vueuse/core'
import { injectNavigationMenuContext } from './NavigationMenuRoot.vue'
import {
EVENT_ROOT_CONTENT_DISMISS,
Expand Down Expand Up @@ -107,7 +108,7 @@ function handlePointerDownOutside(ev: PointerDownOutsideEvent) {
}
}

watchEffect((cleanupFn) => {
watchEffect((onCleanup) => {
const content = currentElement.value
if (menuContext.isRootMenu && content) {
// Bubble dismiss to the root content node and focus its trigger
Expand All @@ -117,11 +118,12 @@ watchEffect((cleanupFn) => {
if (content.contains(document.activeElement))
itemContext.triggerRef.value?.focus()
}
content.addEventListener(EVENT_ROOT_CONTENT_DISMISS, handleClose)

cleanupFn(() =>
content.removeEventListener(EVENT_ROOT_CONTENT_DISMISS, handleClose),
)
const documentDismissCleanup = useEventListener(document, EVENT_ROOT_CONTENT_DISMISS, handleClose)

onCleanup(() => {
documentDismissCleanup()
})
}
})

Expand Down
10 changes: 4 additions & 6 deletions packages/radix-vue/src/ScrollArea/ScrollAreaScrollbarHover.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export interface ScrollAreaScrollbarHoverProps extends ScrollAreaScrollbarAutoPr

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { useEventListener } from '@vueuse/core'
import { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'
import ScrollAreaScrollbarAuto from './ScrollAreaScrollbarAuto.vue'
import { Presence } from '@/Presence'
Expand Down Expand Up @@ -38,18 +39,15 @@ onMounted(() => {
const scrollArea = rootContext.scrollArea.value

if (scrollArea) {
scrollArea.addEventListener('pointerenter', handlePointerEnter)
scrollArea.addEventListener('pointerleave', handlePointerLeave)
useEventListener(scrollArea, 'pointerenter', handlePointerEnter)
useEventListener(scrollArea, 'pointerleave', handlePointerLeave)
}
})

onUnmounted(() => {
const scrollArea = rootContext.scrollArea.value
if (scrollArea) {
if (scrollArea)
window.clearTimeout(timeout)
scrollArea.removeEventListener('pointerenter', handlePointerEnter)
scrollArea.removeEventListener('pointerleave', handlePointerLeave)
}
})
</script>

Expand Down
9 changes: 3 additions & 6 deletions packages/radix-vue/src/ScrollArea/ScrollAreaScrollbarImpl.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ export interface ScrollAreaScrollbarImplProps {
</script>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { useResizeObserver } from '@vueuse/core'
import { onMounted, ref } from 'vue'
import { useEventListener, useResizeObserver } from '@vueuse/core'
import { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'
import { injectScrollAreaScrollbarVisibleContext } from './ScrollAreaScrollbarVisible.vue'
import { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'
Expand Down Expand Up @@ -83,10 +83,7 @@ function handleWheel(event: WheelEvent) {
}

onMounted(() => {
document.addEventListener('wheel', handleWheel, { passive: false })
})
onUnmounted(() => {
document.removeEventListener('wheel', handleWheel)
useEventListener(document, 'wheel', handleWheel, { passive: false })
})

function handleSizeChange() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export interface ScrollAreaScrollbarScrollProps {

<script setup lang="ts">
import { watchEffect } from 'vue'
import { useDebounceFn } from '@vueuse/core'
import { useDebounceFn, useEventListener } from '@vueuse/core'
import { useStateMachine } from '../shared/useStateMachine'
import { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'
import { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'
Expand Down Expand Up @@ -72,10 +72,11 @@ watchEffect((onCleanup) => {
}
prevScrollPos = scrollPos
}
viewport.addEventListener('scroll', handleScroll)

const viewportScrollCleanup = useEventListener(viewport, 'scroll', handleScroll)

onCleanup(() => {
viewport.removeEventListener('scroll', handleScroll)
viewportScrollCleanup()
})
}
})
Expand Down
6 changes: 3 additions & 3 deletions packages/radix-vue/src/ScrollArea/ScrollAreaThumb.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export interface ScrollAreaThumbProps extends PrimitiveProps {}

<script setup lang="ts">
import { computed, onUnmounted, ref } from 'vue'
import { watchOnce } from '@vueuse/core'
import { useEventListener, watchOnce } from '@vueuse/core'
import { Primitive } from '@/Primitive'
import { addUnlinkedScrollListener } from './utils'
import { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'
Expand Down Expand Up @@ -58,12 +58,12 @@ watchOnce(sizes, () => {
* https://developer.mozilla.org/en-US/docs/Mozilla/Performance/Scroll-linked_effects
*/
scrollbarContextVisible.onThumbPositionChange()
viewport.value.addEventListener('scroll', handleScroll)

useEventListener(viewport, 'scroll', handleScroll)
}
})

onUnmounted(() => {
viewport.value!.removeEventListener('scroll', handleScroll)
rootContext.viewport.value?.removeEventListener('scroll', handleScroll)
})
</script>
Expand Down
15 changes: 9 additions & 6 deletions packages/radix-vue/src/Select/SelectContentImpl.vue
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ import {
watch,
watchEffect,
} from 'vue'
import { unrefElement } from '@vueuse/core'
import { unrefElement, useEventListener } from '@vueuse/core'
import { injectSelectRootContext } from './SelectRoot.vue'
import SelectItemAlignedPosition from './SelectItemAlignedPosition.vue'
import SelectPopperPosition from './SelectPopperPosition.vue'
Expand Down Expand Up @@ -130,7 +130,10 @@ watch(isPositioned, () => {
// prevent selecting items on `pointerup` in some cases after opening from `pointerdown`
// and close on `pointerup` outside.
const { onOpenChange, triggerPointerDownPosRef } = rootContext
watchEffect((cleanupFn) => {

let documentPointermoveCleanup: ReturnType<typeof useEventListener>

watchEffect((onCleanup) => {
if (!content.value)
return
let pointerMoveDelta = { x: 0, y: 0 }
Expand Down Expand Up @@ -160,20 +163,20 @@ watchEffect((cleanupFn) => {
if (!content.value?.contains(event.target as HTMLElement))
onOpenChange(false)
}
document.removeEventListener('pointermove', handlePointerMove)
documentPointermoveCleanup = useEventListener(document, 'pointermove', handlePointerMove)
triggerPointerDownPosRef.value = null
}

if (triggerPointerDownPosRef.value !== null) {
document.addEventListener('pointermove', handlePointerMove)
documentPointermoveCleanup = useEventListener(document, 'pointermove', handlePointerMove)
document.addEventListener('pointerup', handlePointerUp, {
capture: true,
once: true,
})
}

cleanupFn(() => {
document.removeEventListener('pointermove', handlePointerMove)
onCleanup(() => {
documentPointermoveCleanup && documentPointermoveCleanup()
document.removeEventListener('pointerup', handlePointerUp, {
capture: true,
})
Expand Down
10 changes: 7 additions & 3 deletions packages/radix-vue/src/Select/SelectScrollDownButton.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface SelectScrollDownButtonProps extends PrimitiveProps {}

<script setup lang="ts">
import { ref, watch, watchEffect } from 'vue'
import { useEventListener } from '@vueuse/core'
import { SelectContentDefaultContextValue, injectSelectContentContext } from './SelectContentImpl.vue'
import SelectScrollButtonImpl from './SelectScrollButtonImpl.vue'
import { injectSelectItemAlignedPositionContext } from './SelectItemAlignedPosition.vue'
Expand All @@ -23,7 +24,7 @@ const { forwardRef, currentElement } = useForwardExpose()

const canScrollDown = ref(false)

watchEffect((cleanupFn) => {
watchEffect((onCleanup) => {
if (contentContext.viewport?.value && contentContext.isPositioned?.value) {
const viewport = contentContext.viewport.value

Expand All @@ -34,9 +35,12 @@ watchEffect((cleanupFn) => {
canScrollDown.value = Math.ceil(viewport.scrollTop) < maxScroll
}
handleScroll()
viewport.addEventListener('scroll', handleScroll)

cleanupFn(() => viewport.removeEventListener('scroll', handleScroll))
const viewportScrollCleanup = useEventListener(viewport, 'scroll', handleScroll)

onCleanup(() => {
viewportScrollCleanup()
})
}
})

Expand Down
Loading
Loading