UNPKG

@empathyco/x-components

Version:
122 lines (119 loc) 3.75 kB
import { defineComponent, ref, computed, watch } from 'vue'; import { use$x } from '../../../composables/use-_x.js'; import { useState } from '../../../composables/use-state.js'; import { searchXModule } from '../x-module.js'; /** * A redirection is a component that sends the user to a link in the website. It is helpful when * there are queries like `help`, `shipping costs`, `my account`, where a link to a section in the * website will be more helpful than the set of results returned. * * @public */ var _sfc_main = defineComponent({ name: 'Redirection', xModule: searchXModule.name, props: { /** * The redirection mode. Auto for auto redirection and manual for an user interaction. * * @public */ mode: { type: String, default: 'auto', }, /** * The waiting time in seconds until the redirection is made. * * @remarks this delay only works in auto mode. * * @public */ delayInSeconds: { type: Number, default: 0, }, }, setup(props, { slots }) { const $x = use$x(); const { redirections } = useState('search'); /** * List of events to stop the animation. */ const eventsToStopAnimation = [ 'UserAcceptedAQuery', 'UserClearedQuery', 'UserSelectedARelatedTag', ]; /** * The timeout id, used to cancel the redirection. * * @internal */ const timeoutId = ref(0); /** * Boolean flag which indicates if the redirection is running. * * @public */ const isRedirecting = ref(true); /** * Computed property which returns the first recommendation of the state, if any returns null. * * @returns The first redirection of the state. * * @internal */ const redirection = computed(() => redirections?.value[0] ?? null); /** * Stops the animation if the user search another query. * * @internal */ const cancelRedirect = () => { clearTimeout(timeoutId.value); isRedirecting.value = false; }; eventsToStopAnimation.forEach(event => $x.on(event, false).subscribe(cancelRedirect)); /** * Dispatches the redirection, updating the url. * * @public */ const redirect = () => { clearTimeout(timeoutId.value); $x.emit('UserClickedARedirection', redirection.value); window.location.replace(redirection.value.url); }; /** * Stops the redirection, emitting `UserClickedAbortARedirection` event. * * @public */ const abortRedirect = () => { cancelRedirect(); $x.emit('UserClickedAbortARedirection'); }; /** * Watcher function which adds a setTimeout to the redirect method is the component * is in auto mode and there are redirections. * * @internal */ watch(redirections, () => { isRedirecting.value = true; if (props.mode === 'auto' && redirection.value) { timeoutId.value = window.setTimeout(redirect, props.delayInSeconds * 1000); } }, { immediate: true }); return { redirection, redirect, abortRedirect, isRedirecting, slots, }; }, }); export { _sfc_main as default }; //# sourceMappingURL=redirection.vue2.js.map