Skip to content

Commit

Permalink
fix(useScriptTriggerElement): reject promises on scope dispose
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Sep 3, 2024
1 parent af13a30 commit 7297783
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/runtime/composables/useScriptTriggerElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
useEventListener,
useIntersectionObserver,
} from '@vueuse/core'
import { tryOnScopeDispose } from '@vueuse/shared'
import type { ElementScriptTrigger } from '../types'

export interface ElementScriptTriggerOptions {
Expand All @@ -23,7 +24,7 @@ export interface ElementScriptTriggerOptions {

function useElementVisibilityPromise(element: MaybeComputedElementRef) {
let observer: UseIntersectionObserverReturn
return new Promise<void>((resolve) => {
return new Promise<void>((resolve, reject) => {
observer = useIntersectionObserver(
element,
(intersectionObserverEntries) => {
Expand All @@ -38,9 +39,14 @@ function useElementVisibilityPromise(element: MaybeComputedElementRef) {
threshold: 0,
},
)
}).finally(() => {
observer.stop()
tryOnScopeDispose(reject)
})
.catch(() => {
// it's okay
})
.finally(() => {
observer.stop()
})
}

/**
Expand All @@ -57,16 +63,19 @@ export function useScriptTriggerElement(options: ElementScriptTriggerOptions): P
return Promise.resolve()
if (!triggers.includes('immediate')) {
// TODO optimize this, only have 1 instance of intersection observer, stop on find
return new Promise<void>((resolve) => {
return new Promise<void>((resolve, reject) => {
const _ = useEventListener(
typeof el !== 'undefined' ? (el as EventTarget) : document.body,
triggers,
() => {
resolve()
_()
resolve()
},
{ once: true, passive: true },
)
tryOnScopeDispose(reject)
}).catch(() => {
// it's okay
})
}
return Promise.resolve()
Expand Down

0 comments on commit 7297783

Please sign in to comment.