65 lines
1.9 KiB
TypeScript
65 lines
1.9 KiB
TypeScript
import type { InertiaLinkProps } from '@inertiajs/vue3';
|
|
import { usePage } from '@inertiajs/vue3';
|
|
import type { ComputedRef, DeepReadonly } from 'vue';
|
|
import { computed, readonly } from 'vue';
|
|
import { toUrl } from '@/lib/utils';
|
|
import { matchesNavigationUrl } from '@/lib/navigation';
|
|
|
|
export type UseCurrentUrlReturn = {
|
|
currentUrl: DeepReadonly<ComputedRef<string>>;
|
|
isCurrentUrl: (
|
|
urlToCheck: NonNullable<InertiaLinkProps['href']>,
|
|
currentUrl?: string,
|
|
startsWith?: boolean,
|
|
) => boolean;
|
|
isCurrentOrParentUrl: (
|
|
urlToCheck: NonNullable<InertiaLinkProps['href']>,
|
|
currentUrl?: string,
|
|
) => boolean;
|
|
whenCurrentUrl: <T, F = null>(
|
|
urlToCheck: NonNullable<InertiaLinkProps['href']>,
|
|
ifTrue: T,
|
|
ifFalse?: F,
|
|
) => T | F;
|
|
};
|
|
|
|
export function useCurrentUrl(): UseCurrentUrlReturn {
|
|
const page = usePage();
|
|
const currentUrlReactive = computed(
|
|
() => new URL(page.url, 'http://localhost').pathname,
|
|
);
|
|
function isCurrentUrl(
|
|
urlToCheck: NonNullable<InertiaLinkProps['href']>,
|
|
currentUrl?: string,
|
|
startsWith: boolean = false,
|
|
) {
|
|
return matchesNavigationUrl(
|
|
toUrl(urlToCheck),
|
|
currentUrl ?? currentUrlReactive.value,
|
|
startsWith,
|
|
);
|
|
}
|
|
|
|
function isCurrentOrParentUrl(
|
|
urlToCheck: NonNullable<InertiaLinkProps['href']>,
|
|
currentUrl?: string,
|
|
) {
|
|
return isCurrentUrl(urlToCheck, currentUrl, true);
|
|
}
|
|
|
|
function whenCurrentUrl<T, F = null>(
|
|
urlToCheck: NonNullable<InertiaLinkProps['href']>,
|
|
ifTrue: T,
|
|
ifFalse: F = null as F,
|
|
): T | F {
|
|
return isCurrentUrl(urlToCheck) ? ifTrue : ifFalse;
|
|
}
|
|
|
|
return {
|
|
currentUrl: readonly(currentUrlReactive),
|
|
isCurrentUrl,
|
|
isCurrentOrParentUrl,
|
|
whenCurrentUrl,
|
|
};
|
|
}
|