Newer
Older
vmk-ui-kit / src / vue / composables / useToast.js
/**
 * useToast composable.
 *
 * Injects the toast API provided by <GnToastProvider>.
 * Returns no-op placeholders with a helpful error when called outside a provider.
 */

import { inject, getCurrentInstance } from "vue";
import { toastKey } from "./toast-context.js";

export function useToast() {
	const api = inject(toastKey, null);

	if (api) {
		return api;
	}

	// Fallback: look for the provider API on the app config globalProperties
	// (some consumers register the plugin globally and may not have the provider
	// in the exact ancestor chain due to createApp + inline templates).
	const instance = getCurrentInstance();
	const globalApi = instance?.appContext?.app?.config?.globalProperties?.$vmkToasts;
	if (globalApi) {
		return globalApi;
	}

	const missingProvider = () => {
		throw new Error("VMK UI Kit: useToast() requires <GnToastProvider> near the app root.");
	};

	return {
		show: missingProvider,
		info: missingProvider,
		success: missingProvider,
		warning: missingProvider,
		danger: missingProvider,
		error: missingProvider,
		close: missingProvider
	};
}

export default useToast;