Newer
Older
gnexus-ui-kit / src / vue / composables / useVueRouter.js
/**
 * Safe vue-router access without hard dependency.
 * Reads $router and $route from the component instance globalProperties.
 */
import { getCurrentInstance } from "vue";

export function tryUseRouter() {
	const instance = getCurrentInstance();
	return instance?.proxy?.$router || null;
}

export function tryUseRoute() {
	const instance = getCurrentInstance();
	return instance?.proxy?.$route || null;
}

/**
 * Check whether a route target matches the current route.
 *
 * @param {import("vue").Ref|Object} currentRoute
 * @param {string|Object} to
 * @param {string} strategy - 'exact' | 'prefix'
 * @returns {boolean}
 */
export function isRouteActive(currentRoute, to, strategy = "prefix") {
	if(!currentRoute) {
		return false;
	}

	const route = currentRoute.value || currentRoute;

	if(typeof to === "string") {
		if(strategy === "exact") {
			return route.path === to;
		}

		return route.path === to || route.path.startsWith(to + "/");
	}

	if(to.path) {
		if(strategy === "exact") {
			return route.path === to.path;
		}

		return route.path === to.path || route.path.startsWith(to.path + "/");
	}

	if(to.name) {
		return route.name === to.name;
	}

	return false;
}