UNPKG

@empathyco/x-components

Version:
55 lines (52 loc) 2.01 kB
import { useElementVisibility } from '@vueuse/core'; import { watch } from 'vue'; import { useXBus } from './use-x-bus.js'; /** * Composable that triggers a callback whenever the provided element appears in the viewport. * It can trigger the first time only or every time the element appears in the viewport. * * @param options - The options to customize the behavior of the composable. The element that * will be watched, the callback to trigger and if the callback should be triggered only once * or every time the element appears in the viewport, true by default. * @returns If the element is currently visible in the viewport or not and the watcher stop handle. * @public */ function useOnDisplay({ element, callback, triggerOnce = true, }) { const isElementVisible = useElementVisibility(element); const unwatchDisplay = watch(isElementVisible, newValue => { if (newValue) { callback(); if (triggerOnce) { unwatchDisplay(); } } }); return { isElementVisible, unwatchDisplay, }; } /** * Composable that emits a `TrackableElementDisplayed` event whenever the provided element * appears in the viewport for the first time. * * @param options - The options to customize the behavior of the composable. The element that * will be watched and the tagging request to emit. * @returns If the element is currently visible in the viewport or not and the watcher stop handle. * @public */ function useEmitDisplayEvent({ element, taggingRequest, eventMetadata = {}, }) { const bus = useXBus(); const { isElementVisible, unwatchDisplay } = useOnDisplay({ element, callback: () => { void bus.emit('TrackableElementDisplayed', { tagging: { display: taggingRequest } }, eventMetadata); }, }); return { isElementVisible, unwatchDisplay, }; } export { useEmitDisplayEvent, useOnDisplay }; //# sourceMappingURL=use-on-display.js.map