UNPKG

@empathyco/x-components

Version:
78 lines (75 loc) 2.84 kB
import { Subscription } from 'rxjs'; import { inject, getCurrentInstance, onBeforeUnmount, isRef } from 'vue'; import { getRootXComponent, getXComponentXModuleName } from '../components/x-component.utils.js'; import { bus } from '../plugins/x-bus.js'; import { XPlugin } from '../plugins/x-plugin.js'; /** * Composable which injects the current location, returns the `on` and `emit` functions * using the bus and applying component metadata. Also unsubscribe from events when components is * unmounted. * * @remarks This composable tries to use the `XPlugin` bus and catches the exception thrown * by the `XPlugin` if it was not instantiated and uses the default `xBus` as fallback. * * @returns An object with the `on` and `emit` functions. * @public */ function useXBus() { const injectedLocation = inject('location', 'none'); const component = getCurrentInstance()?.proxy; const xComponent = getRootXComponent(component ?? null); if (component && xComponent) { component.xComponent = xComponent; } let bus$1; try { bus$1 = XPlugin.bus; // eslint-disable-next-line unused-imports/no-unused-vars } catch (_error) { bus$1 = bus; } const subscription = new Subscription(); onBeforeUnmount(() => { subscription.unsubscribe(); }); return { on: (event, withMetadata) => { const observable = bus$1.on(event, withMetadata); return { subscribe: (callback) => subscription.add(observable.subscribe(callback)), }; }, emit: async (event, payload, metadata = {}) => { const location = isRef(injectedLocation) ? injectedLocation.value : injectedLocation; xComponent?.$emit(event, payload); // TODO - Pending to deprecate return bus$1.emit(event, payload, createWireMetadata(metadata, component, location)); }, }; } /** * Creates a wire metadata object based on the component and the provided metadata. * * @param metadata - Additional metadata emitted by the component. * @param component - The component this metadata belongs to. * @param location - The location of the component. * * @returns A {@link WireMetadata} object. */ function createWireMetadata(metadata, component, location) { return Object.defineProperties({ replaceable: true, moduleName: component ? getXComponentXModuleName(component.xComponent) : null, location, ...metadata, }, { component: { value: component, /* TODO: defining component as a non-enumerable property to ease tests changes due to * cyclic dependencies in Vue component instances. */ enumerable: false, }, }); } export { useXBus }; //# sourceMappingURL=use-x-bus.js.map