AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

use-current-url.ts 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import type { InertiaLinkProps } from '@inertiajs/react';
  2. import { usePage } from '@inertiajs/react';
  3. import { toUrl } from '@/lib/utils';
  4. export type IsCurrentUrlFn = (
  5. urlToCheck: NonNullable<InertiaLinkProps['href']>,
  6. currentUrl?: string,
  7. startsWith?: boolean,
  8. ) => boolean;
  9. export type IsCurrentOrParentUrlFn = (
  10. urlToCheck: NonNullable<InertiaLinkProps['href']>,
  11. currentUrl?: string,
  12. ) => boolean;
  13. export type WhenCurrentUrlFn = <TIfTrue, TIfFalse = null>(
  14. urlToCheck: NonNullable<InertiaLinkProps['href']>,
  15. ifTrue: TIfTrue,
  16. ifFalse?: TIfFalse,
  17. ) => TIfTrue | TIfFalse;
  18. export type UseCurrentUrlReturn = {
  19. currentUrl: string;
  20. isCurrentUrl: IsCurrentUrlFn;
  21. isCurrentOrParentUrl: IsCurrentOrParentUrlFn;
  22. whenCurrentUrl: WhenCurrentUrlFn;
  23. };
  24. export function useCurrentUrl(): UseCurrentUrlReturn {
  25. const page = usePage();
  26. const currentUrlPath = new URL(
  27. page.url,
  28. typeof window !== 'undefined'
  29. ? window.location.origin
  30. : 'http://localhost',
  31. ).pathname;
  32. const isCurrentUrl: IsCurrentUrlFn = (
  33. urlToCheck: NonNullable<InertiaLinkProps['href']>,
  34. currentUrl?: string,
  35. startsWith: boolean = false,
  36. ) => {
  37. const urlToCompare = currentUrl ?? currentUrlPath;
  38. const urlString = toUrl(urlToCheck);
  39. const comparePath = (path: string): boolean =>
  40. startsWith ? urlToCompare.startsWith(path) : path === urlToCompare;
  41. if (!urlString.startsWith('http')) {
  42. return comparePath(urlString);
  43. }
  44. try {
  45. const absoluteUrl = new URL(urlString);
  46. return comparePath(absoluteUrl.pathname);
  47. } catch {
  48. return false;
  49. }
  50. };
  51. const isCurrentOrParentUrl: IsCurrentOrParentUrlFn = (
  52. urlToCheck: NonNullable<InertiaLinkProps['href']>,
  53. currentUrl?: string,
  54. ) => {
  55. return isCurrentUrl(urlToCheck, currentUrl, true);
  56. };
  57. const whenCurrentUrl: WhenCurrentUrlFn = <TIfTrue, TIfFalse = null>(
  58. urlToCheck: NonNullable<InertiaLinkProps['href']>,
  59. ifTrue: TIfTrue,
  60. ifFalse: TIfFalse = null as TIfFalse,
  61. ): TIfTrue | TIfFalse => {
  62. return isCurrentUrl(urlToCheck) ? ifTrue : ifFalse;
  63. };
  64. return {
  65. currentUrl: currentUrlPath,
  66. isCurrentUrl,
  67. isCurrentOrParentUrl,
  68. whenCurrentUrl,
  69. };
  70. }