@tanstack/react-router 1.127.8 → 1.128.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/Matches.cjs +1 -1
- package/dist/cjs/Matches.cjs.map +1 -1
- package/dist/cjs/Transitioner.cjs +7 -9
- package/dist/cjs/Transitioner.cjs.map +1 -1
- package/dist/cjs/link.cjs +98 -67
- package/dist/cjs/link.cjs.map +1 -1
- package/dist/cjs/utils.cjs +4 -10
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +1 -1
- package/dist/esm/Matches.js +1 -1
- package/dist/esm/Matches.js.map +1 -1
- package/dist/esm/Transitioner.js +7 -9
- package/dist/esm/Transitioner.js.map +1 -1
- package/dist/esm/link.js +99 -68
- package/dist/esm/link.js.map +1 -1
- package/dist/esm/utils.d.ts +1 -1
- package/dist/esm/utils.js +4 -10
- package/dist/esm/utils.js.map +1 -1
- package/dist/llms/rules/guide.d.ts +1 -1
- package/dist/llms/rules/guide.js +469 -0
- package/dist/llms/rules/routing.d.ts +1 -1
- package/dist/llms/rules/routing.js +34 -0
- package/package.json +3 -3
- package/src/Matches.tsx +1 -1
- package/src/Transitioner.tsx +6 -8
- package/src/link.tsx +124 -88
- package/src/utils.ts +6 -14
package/dist/cjs/Matches.cjs
CHANGED
|
@@ -32,7 +32,7 @@ function Matches() {
|
|
|
32
32
|
const pendingElement = router.options.defaultPendingComponent ? /* @__PURE__ */ jsxRuntime.jsx(router.options.defaultPendingComponent, {}) : null;
|
|
33
33
|
const ResolvedSuspense = router.isServer || typeof document !== "undefined" && router.ssr ? SafeFragment.SafeFragment : React__namespace.Suspense;
|
|
34
34
|
const inner = /* @__PURE__ */ jsxRuntime.jsxs(ResolvedSuspense, { fallback: pendingElement, children: [
|
|
35
|
-
/* @__PURE__ */ jsxRuntime.jsx(Transitioner.Transitioner, {}),
|
|
35
|
+
!router.isServer && /* @__PURE__ */ jsxRuntime.jsx(Transitioner.Transitioner, {}),
|
|
36
36
|
/* @__PURE__ */ jsxRuntime.jsx(MatchesInner, {})
|
|
37
37
|
] });
|
|
38
38
|
return router.options.InnerWrap ? /* @__PURE__ */ jsxRuntime.jsx(router.options.InnerWrap, { children: inner }) : inner;
|
package/dist/cjs/Matches.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Matches.cjs","sources":["../../src/Matches.tsx"],"sourcesContent":["import * as React from 'react'\nimport warning from 'tiny-warning'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { Transitioner } from './Transitioner'\nimport { matchContext } from './matchContext'\nimport { Match } from './Match'\nimport { SafeFragment } from './SafeFragment'\nimport type {\n StructuralSharingOption,\n ValidateSelected,\n} from './structuralSharing'\nimport type {\n AnyRouter,\n DeepPartial,\n Expand,\n MakeOptionalPathParams,\n MakeOptionalSearchParams,\n MakeRouteMatchUnion,\n MaskOptions,\n MatchRouteOptions,\n NoInfer,\n RegisteredRouter,\n ResolveRelativePath,\n ResolveRoute,\n RouteByPath,\n RouterState,\n ToSubOptionsProps,\n} from '@tanstack/router-core'\n\ndeclare module '@tanstack/router-core' {\n export interface RouteMatchExtensions {\n meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>\n links?: Array<React.JSX.IntrinsicElements['link'] | undefined>\n scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n styles?: Array<React.JSX.IntrinsicElements['style'] | undefined>\n headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n }\n}\n\nexport function Matches() {\n const router = useRouter()\n\n const pendingElement = router.options.defaultPendingComponent ? (\n <router.options.defaultPendingComponent />\n ) : null\n\n // Do not render a root Suspense during SSR or hydrating from SSR\n const ResolvedSuspense =\n router.isServer || (typeof document !== 'undefined' && router.ssr)\n ? SafeFragment\n : React.Suspense\n\n const inner = (\n <ResolvedSuspense fallback={pendingElement}>\n <Transitioner />\n <MatchesInner />\n </ResolvedSuspense>\n )\n\n return router.options.InnerWrap ? (\n <router.options.InnerWrap>{inner}</router.options.InnerWrap>\n ) : (\n inner\n )\n}\n\nfunction MatchesInner() {\n const matchId = useRouterState({\n select: (s) => {\n return s.matches[0]?.id\n },\n })\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n return (\n <matchContext.Provider value={matchId}>\n <CatchBoundary\n getResetKey={() => resetKey}\n errorComponent={ErrorComponent}\n onCatch={(error) => {\n warning(\n false,\n `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,\n )\n warning(false, error.message || error.toString())\n }}\n >\n {matchId ? <Match matchId={matchId} /> : null}\n </CatchBoundary>\n </matchContext.Provider>\n )\n}\n\nexport type UseMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = ToSubOptionsProps<TRouter, TFrom, TTo> &\n DeepPartial<MakeOptionalSearchParams<TRouter, TFrom, TTo>> &\n DeepPartial<MakeOptionalPathParams<TRouter, TFrom, TTo>> &\n MaskOptions<TRouter, TMaskFrom, TMaskTo> &\n MatchRouteOptions\n\nexport function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {\n const router = useRouter()\n\n useRouterState({\n select: (s) => [s.location.href, s.resolvedLocation?.href, s.status],\n structuralSharing: true as any,\n })\n\n return React.useCallback(\n <\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n >(\n opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n ):\n | false\n | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> => {\n const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts\n\n return router.matchRoute(rest as any, {\n pending,\n caseSensitive,\n fuzzy,\n includeSearch,\n })\n },\n [router],\n )\n}\n\nexport type MakeMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | ((\n params?: RouteByPath<\n TRouter['routeTree'],\n ResolveRelativePath<TFrom, NoInfer<TTo>>\n >['types']['allParams'],\n ) => React.ReactNode)\n | React.ReactNode\n}\n\nexport function MatchRoute<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {\n const matchRoute = useMatchRoute()\n const params = matchRoute(props as any) as boolean\n\n if (typeof props.children === 'function') {\n return (props.children as any)(params)\n }\n\n return params ? props.children : null\n}\n\nexport interface UseMatchesBaseOptions<\n TRouter extends AnyRouter,\n TSelected,\n TStructuralSharing,\n> {\n select?: (\n matches: Array<MakeRouteMatchUnion<TRouter>>,\n ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>\n}\n\nexport type UseMatchesResult<\n TRouter extends AnyRouter,\n TSelected,\n> = unknown extends TSelected ? Array<MakeRouteMatchUnion<TRouter>> : TSelected\n\nexport function useMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n return useRouterState({\n select: (state: RouterState<TRouter['routeTree']>) => {\n const matches = state.matches\n return opts?.select\n ? opts.select(matches as Array<MakeRouteMatchUnion<TRouter>>)\n : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any) as UseMatchesResult<TRouter, TSelected>\n}\n\nexport function useParentMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n 0,\n matches.findIndex((d) => d.id === contextMatchId),\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n\nexport function useChildMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n matches.findIndex((d) => d.id === contextMatchId) + 1,\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n"],"names":["useRouter","SafeFragment","React","jsxs","jsx","Transitioner","useRouterState","matchContext","CatchBoundary","ErrorComponent","Match"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCO,SAAS,UAAU;AACxB,QAAM,SAASA,UAAAA,UAAU;AAEnB,QAAA,iBAAiB,OAAO,QAAQ,yDACnC,OAAO,QAAQ,yBAAf,CAAuC,CAAA,IACtC;AAGE,QAAA,mBACJ,OAAO,YAAa,OAAO,aAAa,eAAe,OAAO,MAC1DC,4BACAC,iBAAM;AAEZ,QAAM,QACJC,2BAAAA,KAAC,kBAAiB,EAAA,UAAU,gBAC1B,UAAA;AAAA,IAAAC,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ACH;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AACF;AAoBO,SAAS,WAMd,OAA4E;AAC5E,QAAM,aAAa,cAAc;AAC3B,QAAA,SAAS,WAAW,KAAY;AAElC,MAAA,OAAO,MAAM,aAAa,YAAY;AAChC,WAAA,MAAM,SAAiB,MAAM;AAAA,EAAA;AAGhC,SAAA,SAAS,MAAM,WAAW;AACnC;AAiBO,SAAS,WAKd,MAEsC;AACtC,SAAOI,8BAAe;AAAA,IACpB,QAAQ,CAAC,UAA6C;AACpD,YAAM,UAAU,MAAM;AACtB,cAAO,6BAAM,UACT,KAAK,OAAO,OAA8C,IAC1D;AAAA,IACN;AAAA,IACA,mBAAmB,6BAAM;AAAA,EAAA,CACnB;AACV;AAEO,SAAS,iBAKd,MAEsC;AAChC,QAAA,iBAAiBJ,iBAAM,WAAWK,yBAAY;AAEpD,SAAO,WAAW;AAAA,IAChB,QAAQ,CAAC,YAAiD;AACxD,gBAAU,QAAQ;AAAA,QAChB;AAAA,QACA,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc;AAAA,MAClD;AACA,cAAO,6BAAM,UAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,6BAAM;AAAA,EAAA,CACnB;AACV;AAEO,SAAS,gBAKd,MAEsC;AAChC,QAAA,iBAAiBL,iBAAM,WAAWK,yBAAY;AAEpD,SAAO,WAAW;AAAA,IAChB,QAAQ,CAAC,YAAiD;AACxD,gBAAU,QAAQ;AAAA,QAChB,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc,IAAI;AAAA,MACtD;AACA,cAAO,6BAAM,UAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,6BAAM;AAAA,EAAA,CACnB;AACV;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"Matches.cjs","sources":["../../src/Matches.tsx"],"sourcesContent":["import * as React from 'react'\nimport warning from 'tiny-warning'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { Transitioner } from './Transitioner'\nimport { matchContext } from './matchContext'\nimport { Match } from './Match'\nimport { SafeFragment } from './SafeFragment'\nimport type {\n StructuralSharingOption,\n ValidateSelected,\n} from './structuralSharing'\nimport type {\n AnyRouter,\n DeepPartial,\n Expand,\n MakeOptionalPathParams,\n MakeOptionalSearchParams,\n MakeRouteMatchUnion,\n MaskOptions,\n MatchRouteOptions,\n NoInfer,\n RegisteredRouter,\n ResolveRelativePath,\n ResolveRoute,\n RouteByPath,\n RouterState,\n ToSubOptionsProps,\n} from '@tanstack/router-core'\n\ndeclare module '@tanstack/router-core' {\n export interface RouteMatchExtensions {\n meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>\n links?: Array<React.JSX.IntrinsicElements['link'] | undefined>\n scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n styles?: Array<React.JSX.IntrinsicElements['style'] | undefined>\n headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n }\n}\n\nexport function Matches() {\n const router = useRouter()\n\n const pendingElement = router.options.defaultPendingComponent ? (\n <router.options.defaultPendingComponent />\n ) : null\n\n // Do not render a root Suspense during SSR or hydrating from SSR\n const ResolvedSuspense =\n router.isServer || (typeof document !== 'undefined' && router.ssr)\n ? SafeFragment\n : React.Suspense\n\n const inner = (\n <ResolvedSuspense fallback={pendingElement}>\n {!router.isServer && <Transitioner />}\n <MatchesInner />\n </ResolvedSuspense>\n )\n\n return router.options.InnerWrap ? (\n <router.options.InnerWrap>{inner}</router.options.InnerWrap>\n ) : (\n inner\n )\n}\n\nfunction MatchesInner() {\n const matchId = useRouterState({\n select: (s) => {\n return s.matches[0]?.id\n },\n })\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n return (\n <matchContext.Provider value={matchId}>\n <CatchBoundary\n getResetKey={() => resetKey}\n errorComponent={ErrorComponent}\n onCatch={(error) => {\n warning(\n false,\n `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,\n )\n warning(false, error.message || error.toString())\n }}\n >\n {matchId ? <Match matchId={matchId} /> : null}\n </CatchBoundary>\n </matchContext.Provider>\n )\n}\n\nexport type UseMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = ToSubOptionsProps<TRouter, TFrom, TTo> &\n DeepPartial<MakeOptionalSearchParams<TRouter, TFrom, TTo>> &\n DeepPartial<MakeOptionalPathParams<TRouter, TFrom, TTo>> &\n MaskOptions<TRouter, TMaskFrom, TMaskTo> &\n MatchRouteOptions\n\nexport function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {\n const router = useRouter()\n\n useRouterState({\n select: (s) => [s.location.href, s.resolvedLocation?.href, s.status],\n structuralSharing: true as any,\n })\n\n return React.useCallback(\n <\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n >(\n opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n ):\n | false\n | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> => {\n const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts\n\n return router.matchRoute(rest as any, {\n pending,\n caseSensitive,\n fuzzy,\n includeSearch,\n })\n },\n [router],\n )\n}\n\nexport type MakeMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | ((\n params?: RouteByPath<\n TRouter['routeTree'],\n ResolveRelativePath<TFrom, NoInfer<TTo>>\n >['types']['allParams'],\n ) => React.ReactNode)\n | React.ReactNode\n}\n\nexport function MatchRoute<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {\n const matchRoute = useMatchRoute()\n const params = matchRoute(props as any) as boolean\n\n if (typeof props.children === 'function') {\n return (props.children as any)(params)\n }\n\n return params ? props.children : null\n}\n\nexport interface UseMatchesBaseOptions<\n TRouter extends AnyRouter,\n TSelected,\n TStructuralSharing,\n> {\n select?: (\n matches: Array<MakeRouteMatchUnion<TRouter>>,\n ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>\n}\n\nexport type UseMatchesResult<\n TRouter extends AnyRouter,\n TSelected,\n> = unknown extends TSelected ? Array<MakeRouteMatchUnion<TRouter>> : TSelected\n\nexport function useMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n return useRouterState({\n select: (state: RouterState<TRouter['routeTree']>) => {\n const matches = state.matches\n return opts?.select\n ? opts.select(matches as Array<MakeRouteMatchUnion<TRouter>>)\n : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any) as UseMatchesResult<TRouter, TSelected>\n}\n\nexport function useParentMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n 0,\n matches.findIndex((d) => d.id === contextMatchId),\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n\nexport function useChildMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n matches.findIndex((d) => d.id === contextMatchId) + 1,\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n"],"names":["useRouter","SafeFragment","React","jsxs","jsx","Transitioner","useRouterState","matchContext","CatchBoundary","ErrorComponent","Match"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCO,SAAS,UAAU;AACxB,QAAM,SAASA,UAAAA,UAAU;AAEnB,QAAA,iBAAiB,OAAO,QAAQ,yDACnC,OAAO,QAAQ,yBAAf,CAAuC,CAAA,IACtC;AAGE,QAAA,mBACJ,OAAO,YAAa,OAAO,aAAa,eAAe,OAAO,MAC1DC,4BACAC,iBAAM;AAEZ,QAAM,QACJC,2BAAAA,KAAC,kBAAiB,EAAA,UAAU,gBACzB,UAAA;AAAA,IAAC,CAAA,OAAO,YAAYC,+BAACC,aAAAA,cAAa,CAAA,CAAA;AAAA,mCAClC,cAAa,CAAA,CAAA;AAAA,EAAA,GAChB;AAGK,SAAA,OAAO,QAAQ,YACpBD,2BAAA,IAAC,OAAO,QAAQ,WAAf,EAA0B,UAAA,MAAA,CAAM,IAEjC;AAEJ;AAEA,SAAS,eAAe;AACtB,QAAM,UAAUE,eAAAA,eAAe;AAAA,IAC7B,QAAQ,CAAC,MAAM;;AACN,cAAA,OAAE,QAAQ,C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,IACpB,QAAQ,CAAC,UAA6C;AACpD,YAAM,UAAU,MAAM;AACtB,cAAO,6BAAM,UACT,KAAK,OAAO,OAA8C,IAC1D;AAAA,IACN;AAAA,IACA,mBAAmB,6BAAM;AAAA,EAAA,CACnB;AACV;AAEO,SAAS,iBAKd,MAEsC;AAChC,QAAA,iBAAiBJ,iBAAM,WAAWK,yBAAY;AAEpD,SAAO,WAAW;AAAA,IAChB,QAAQ,CAAC,YAAiD;AACxD,gBAAU,QAAQ;AAAA,QAChB;AAAA,QACA,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc;AAAA,MAClD;AACA,cAAO,6BAAM,UAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,6BAAM;AAAA,EAAA,CACnB;AACV;AAEO,SAAS,gBAKd,MAEsC;AAChC,QAAA,iBAAiBL,iBAAM,WAAWK,yBAAY;AAEpD,SAAO,WAAW;AAAA,IAChB,QAAQ,CAAC,YAAiD;AACxD,gBAAU,QAAQ;AAAA,QAChB,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc,IAAI;AAAA,MACtD;AACA,cAAO,6BAAM,UAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,6BAAM;AAAA,EAAA,CACnB;AACV;;;;;;;"}
|
|
@@ -38,15 +38,13 @@ function Transitioner() {
|
|
|
38
38
|
const previousIsAnyPending = utils.usePrevious(isAnyPending);
|
|
39
39
|
const isPagePending = isLoading || hasPendingMatches;
|
|
40
40
|
const previousIsPagePending = utils.usePrevious(isPagePending);
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
};
|
|
49
|
-
}
|
|
41
|
+
router.startTransition = (fn) => {
|
|
42
|
+
setIsTransitioning(true);
|
|
43
|
+
React__namespace.startTransition(() => {
|
|
44
|
+
fn();
|
|
45
|
+
setIsTransitioning(false);
|
|
46
|
+
});
|
|
47
|
+
};
|
|
50
48
|
React__namespace.useEffect(() => {
|
|
51
49
|
const unsub = router.history.subscribe(router.load);
|
|
52
50
|
const nextLocation = router.buildLocation({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Transitioner.cjs","sources":["../../src/Transitioner.tsx"],"sourcesContent":["import * as React from 'react'\nimport {\n getLocationChangeInfo,\n handleHashScroll,\n trimPathRight,\n} from '@tanstack/router-core'\nimport { useLayoutEffect, usePrevious } from './utils'\nimport { useRouter } from './useRouter'\nimport { useRouterState } from './useRouterState'\n\nexport function Transitioner() {\n const router = useRouter()\n const mountLoadForRouter = React.useRef({ router, mounted: false })\n\n const [isTransitioning, setIsTransitioning] = React.useState(false)\n // Track pending state changes\n const { hasPendingMatches, isLoading } = useRouterState({\n select: (s) => ({\n isLoading: s.isLoading,\n hasPendingMatches: s.matches.some((d) => d.status === 'pending'),\n }),\n structuralSharing: true,\n })\n\n const previousIsLoading = usePrevious(isLoading)\n\n const isAnyPending = isLoading || isTransitioning || hasPendingMatches\n const previousIsAnyPending = usePrevious(isAnyPending)\n\n const isPagePending = isLoading || hasPendingMatches\n const previousIsPagePending = usePrevious(isPagePending)\n\n
|
|
1
|
+
{"version":3,"file":"Transitioner.cjs","sources":["../../src/Transitioner.tsx"],"sourcesContent":["import * as React from 'react'\nimport {\n getLocationChangeInfo,\n handleHashScroll,\n trimPathRight,\n} from '@tanstack/router-core'\nimport { useLayoutEffect, usePrevious } from './utils'\nimport { useRouter } from './useRouter'\nimport { useRouterState } from './useRouterState'\n\nexport function Transitioner() {\n const router = useRouter()\n const mountLoadForRouter = React.useRef({ router, mounted: false })\n\n const [isTransitioning, setIsTransitioning] = React.useState(false)\n // Track pending state changes\n const { hasPendingMatches, isLoading } = useRouterState({\n select: (s) => ({\n isLoading: s.isLoading,\n hasPendingMatches: s.matches.some((d) => d.status === 'pending'),\n }),\n structuralSharing: true,\n })\n\n const previousIsLoading = usePrevious(isLoading)\n\n const isAnyPending = isLoading || isTransitioning || hasPendingMatches\n const previousIsAnyPending = usePrevious(isAnyPending)\n\n const isPagePending = isLoading || hasPendingMatches\n const previousIsPagePending = usePrevious(isPagePending)\n\n router.startTransition = (fn: () => void) => {\n setIsTransitioning(true)\n React.startTransition(() => {\n fn()\n setIsTransitioning(false)\n })\n }\n\n // Subscribe to location changes\n // and try to load the new location\n React.useEffect(() => {\n const unsub = router.history.subscribe(router.load)\n\n const nextLocation = router.buildLocation({\n to: router.latestLocation.pathname,\n search: true,\n params: true,\n hash: true,\n state: true,\n _includeValidateSearch: true,\n })\n\n if (\n trimPathRight(router.latestLocation.href) !==\n trimPathRight(nextLocation.href)\n ) {\n router.commitLocation({ ...nextLocation, replace: true })\n }\n\n return () => {\n unsub()\n }\n }, [router, router.history])\n\n // Try to load the initial location\n useLayoutEffect(() => {\n if (\n // if we are hydrating from SSR, loading is triggered in ssr-client\n (typeof window !== 'undefined' && router.ssr) ||\n (mountLoadForRouter.current.router === router &&\n mountLoadForRouter.current.mounted)\n ) {\n return\n }\n mountLoadForRouter.current = { router, mounted: true }\n\n const tryLoad = async () => {\n try {\n await router.load()\n } catch (err) {\n console.error(err)\n }\n }\n\n tryLoad()\n }, [router])\n\n useLayoutEffect(() => {\n // The router was loading and now it's not\n if (previousIsLoading && !isLoading) {\n router.emit({\n type: 'onLoad', // When the new URL has committed, when the new matches have been loaded into state.matches\n ...getLocationChangeInfo(router.state),\n })\n }\n }, [previousIsLoading, router, isLoading])\n\n useLayoutEffect(() => {\n // emit onBeforeRouteMount\n if (previousIsPagePending && !isPagePending) {\n router.emit({\n type: 'onBeforeRouteMount',\n ...getLocationChangeInfo(router.state),\n })\n }\n }, [isPagePending, previousIsPagePending, router])\n\n useLayoutEffect(() => {\n // The router was pending and now it's not\n if (previousIsAnyPending && !isAnyPending) {\n router.emit({\n type: 'onResolved',\n ...getLocationChangeInfo(router.state),\n })\n\n router.__store.setState((s) => ({\n ...s,\n status: 'idle',\n resolvedLocation: s.location,\n }))\n\n handleHashScroll(router)\n }\n }, [isAnyPending, previousIsAnyPending, router])\n\n return null\n}\n"],"names":["useRouter","React","useRouterState","usePrevious","trimPathRight","useLayoutEffect","getLocationChangeInfo","handleHashScroll"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAUO,SAAS,eAAe;AAC7B,QAAM,SAASA,UAAAA,UAAU;AACzB,QAAM,qBAAqBC,iBAAM,OAAO,EAAE,QAAQ,SAAS,OAAO;AAElE,QAAM,CAAC,iBAAiB,kBAAkB,IAAIA,iBAAM,SAAS,KAAK;AAElE,QAAM,EAAE,mBAAmB,UAAU,IAAIC,8BAAe;AAAA,IACtD,QAAQ,CAAC,OAAO;AAAA,MACd,WAAW,EAAE;AAAA,MACb,mBAAmB,EAAE,QAAQ,KAAK,CAAC,MAAM,EAAE,WAAW,SAAS;AAAA,IAAA;AAAA,IAEjE,mBAAmB;AAAA,EAAA,CACpB;AAEK,QAAA,oBAAoBC,kBAAY,SAAS;AAEzC,QAAA,eAAe,aAAa,mBAAmB;AAC/C,QAAA,uBAAuBA,kBAAY,YAAY;AAErD,QAAM,gBAAgB,aAAa;AAC7B,QAAA,wBAAwBA,kBAAY,aAAa;AAEhD,SAAA,kBAAkB,CAAC,OAAmB;AAC3C,uBAAmB,IAAI;AACvBF,qBAAM,gBAAgB,MAAM;AACvB,SAAA;AACH,yBAAmB,KAAK;AAAA,IAAA,CACzB;AAAA,EACH;AAIAA,mBAAM,UAAU,MAAM;AACpB,UAAM,QAAQ,OAAO,QAAQ,UAAU,OAAO,IAAI;AAE5C,UAAA,eAAe,OAAO,cAAc;AAAA,MACxC,IAAI,OAAO,eAAe;AAAA,MAC1B,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,OAAO;AAAA,MACP,wBAAwB;AAAA,IAAA,CACzB;AAGC,QAAAG,WAAA,cAAc,OAAO,eAAe,IAAI,MACxCA,yBAAc,aAAa,IAAI,GAC/B;AACA,aAAO,eAAe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AA,MAAA,EACpB;AAEFC,iBAAAA,iBAAiB,MAAM;AAAA,IAAA;AAAA,EAExB,GAAA,CAAC,cAAc,sBAAsB,MAAM,CAAC;AAExC,SAAA;AACT;;"}
|
package/dist/cjs/link.cjs
CHANGED
|
@@ -32,8 +32,8 @@ function useLinkProps(options, forwardedRef) {
|
|
|
32
32
|
const innerRef = utils.useForwardedRef(forwardedRef);
|
|
33
33
|
const {
|
|
34
34
|
// custom props
|
|
35
|
-
activeProps
|
|
36
|
-
inactiveProps
|
|
35
|
+
activeProps,
|
|
36
|
+
inactiveProps,
|
|
37
37
|
activeOptions,
|
|
38
38
|
to,
|
|
39
39
|
preload: userPreload,
|
|
@@ -55,9 +55,6 @@ function useLinkProps(options, forwardedRef) {
|
|
|
55
55
|
onMouseLeave,
|
|
56
56
|
onTouchStart,
|
|
57
57
|
ignoreBlocker,
|
|
58
|
-
...rest
|
|
59
|
-
} = options;
|
|
60
|
-
const {
|
|
61
58
|
// prevent these from being returned
|
|
62
59
|
params: _params,
|
|
63
60
|
search: _search,
|
|
@@ -66,11 +63,13 @@ function useLinkProps(options, forwardedRef) {
|
|
|
66
63
|
mask: _mask,
|
|
67
64
|
reloadDocument: _reloadDocument,
|
|
68
65
|
unsafeRelative: _unsafeRelative,
|
|
66
|
+
from: _from,
|
|
67
|
+
_fromLocation,
|
|
69
68
|
...propsSafeToSpread
|
|
70
|
-
} =
|
|
69
|
+
} = options;
|
|
71
70
|
const type = React__namespace.useMemo(() => {
|
|
72
71
|
try {
|
|
73
|
-
new URL(
|
|
72
|
+
new URL(to);
|
|
74
73
|
return "external";
|
|
75
74
|
} catch {
|
|
76
75
|
}
|
|
@@ -80,26 +79,33 @@ function useLinkProps(options, forwardedRef) {
|
|
|
80
79
|
select: (s) => s.location.search,
|
|
81
80
|
structuralSharing: true
|
|
82
81
|
});
|
|
83
|
-
const
|
|
82
|
+
const from = useMatch.useMatch({
|
|
84
83
|
strict: false,
|
|
85
|
-
select: (match) => match.fullPath
|
|
84
|
+
select: (match) => options.from ?? match.fullPath
|
|
86
85
|
});
|
|
87
|
-
const from = options.from ?? nearestFrom;
|
|
88
|
-
options = { ...options, from };
|
|
89
86
|
const next = React__namespace.useMemo(
|
|
90
|
-
() => router.buildLocation(options),
|
|
87
|
+
() => router.buildLocation({ ...options, from }),
|
|
91
88
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
92
|
-
[
|
|
89
|
+
[
|
|
90
|
+
router,
|
|
91
|
+
currentSearch,
|
|
92
|
+
options._fromLocation,
|
|
93
|
+
from,
|
|
94
|
+
options.hash,
|
|
95
|
+
options.to,
|
|
96
|
+
options.search,
|
|
97
|
+
options.params,
|
|
98
|
+
options.state,
|
|
99
|
+
options.mask,
|
|
100
|
+
options.unsafeRelative
|
|
101
|
+
]
|
|
93
102
|
);
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
return false;
|
|
97
|
-
}
|
|
98
|
-
return userPreload ?? router.options.defaultPreload;
|
|
99
|
-
}, [router.options.defaultPreload, userPreload, options.reloadDocument]);
|
|
103
|
+
const isExternal = type === "external";
|
|
104
|
+
const preload = options.reloadDocument || isExternal ? false : userPreload ?? router.options.defaultPreload;
|
|
100
105
|
const preloadDelay = userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0;
|
|
101
106
|
const isActive = useRouterState.useRouterState({
|
|
102
107
|
select: (s) => {
|
|
108
|
+
if (isExternal) return false;
|
|
103
109
|
if (activeOptions == null ? void 0 : activeOptions.exact) {
|
|
104
110
|
const testExact = routerCore.exactPathTest(
|
|
105
111
|
s.location.pathname,
|
|
@@ -113,14 +119,12 @@ function useLinkProps(options, forwardedRef) {
|
|
|
113
119
|
const currentPathSplit = routerCore.removeTrailingSlash(
|
|
114
120
|
s.location.pathname,
|
|
115
121
|
router.basepath
|
|
116
|
-
)
|
|
122
|
+
);
|
|
117
123
|
const nextPathSplit = routerCore.removeTrailingSlash(
|
|
118
124
|
next.pathname,
|
|
119
125
|
router.basepath
|
|
120
|
-
).split("/");
|
|
121
|
-
const pathIsFuzzyEqual = nextPathSplit.every(
|
|
122
|
-
(d, i) => d === currentPathSplit[i]
|
|
123
126
|
);
|
|
127
|
+
const pathIsFuzzyEqual = currentPathSplit.startsWith(nextPathSplit) && (currentPathSplit.length === nextPathSplit.length || currentPathSplit[nextPathSplit.length] === "/");
|
|
124
128
|
if (!pathIsFuzzyEqual) {
|
|
125
129
|
return false;
|
|
126
130
|
}
|
|
@@ -140,12 +144,34 @@ function useLinkProps(options, forwardedRef) {
|
|
|
140
144
|
return true;
|
|
141
145
|
}
|
|
142
146
|
});
|
|
143
|
-
const doPreload = React__namespace.useCallback(
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
147
|
+
const doPreload = React__namespace.useCallback(
|
|
148
|
+
() => {
|
|
149
|
+
router.preloadRoute({ ...options, from }).catch((err) => {
|
|
150
|
+
console.warn(err);
|
|
151
|
+
console.warn(routerCore.preloadWarning);
|
|
152
|
+
});
|
|
153
|
+
},
|
|
154
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
155
|
+
[
|
|
156
|
+
router,
|
|
157
|
+
options.to,
|
|
158
|
+
options._fromLocation,
|
|
159
|
+
from,
|
|
160
|
+
options.search,
|
|
161
|
+
options.hash,
|
|
162
|
+
options.params,
|
|
163
|
+
options.state,
|
|
164
|
+
options.mask,
|
|
165
|
+
options.unsafeRelative,
|
|
166
|
+
options.hashScrollIntoView,
|
|
167
|
+
options.href,
|
|
168
|
+
options.ignoreBlocker,
|
|
169
|
+
options.reloadDocument,
|
|
170
|
+
options.replace,
|
|
171
|
+
options.resetScroll,
|
|
172
|
+
options.viewTransition
|
|
173
|
+
]
|
|
174
|
+
);
|
|
149
175
|
const preloadViewportIoCallback = React__namespace.useCallback(
|
|
150
176
|
(entry) => {
|
|
151
177
|
if (entry == null ? void 0 : entry.isIntersecting) {
|
|
@@ -157,10 +183,10 @@ function useLinkProps(options, forwardedRef) {
|
|
|
157
183
|
utils.useIntersectionObserver(
|
|
158
184
|
innerRef,
|
|
159
185
|
preloadViewportIoCallback,
|
|
160
|
-
|
|
186
|
+
intersectionObserverOptions,
|
|
161
187
|
{ disabled: !!disabled || !(preload === "viewport") }
|
|
162
188
|
);
|
|
163
|
-
|
|
189
|
+
React__namespace.useEffect(() => {
|
|
164
190
|
if (hasRenderFetched.current) {
|
|
165
191
|
return;
|
|
166
192
|
}
|
|
@@ -169,7 +195,7 @@ function useLinkProps(options, forwardedRef) {
|
|
|
169
195
|
hasRenderFetched.current = true;
|
|
170
196
|
}
|
|
171
197
|
}, [disabled, doPreload, preload]);
|
|
172
|
-
if (
|
|
198
|
+
if (isExternal) {
|
|
173
199
|
return {
|
|
174
200
|
...propsSafeToSpread,
|
|
175
201
|
ref: innerRef,
|
|
@@ -199,6 +225,7 @@ function useLinkProps(options, forwardedRef) {
|
|
|
199
225
|
});
|
|
200
226
|
return router.navigate({
|
|
201
227
|
...options,
|
|
228
|
+
from,
|
|
202
229
|
replace,
|
|
203
230
|
resetScroll,
|
|
204
231
|
hashScrollIntoView,
|
|
@@ -216,46 +243,38 @@ function useLinkProps(options, forwardedRef) {
|
|
|
216
243
|
};
|
|
217
244
|
const handleTouchStart = handleFocus;
|
|
218
245
|
const handleEnter = (e) => {
|
|
219
|
-
if (disabled) return;
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
246
|
+
if (disabled || !preload) return;
|
|
247
|
+
if (!preloadDelay) {
|
|
248
|
+
doPreload();
|
|
249
|
+
} else {
|
|
250
|
+
const eventTarget = e.target;
|
|
251
|
+
if (timeoutMap.has(eventTarget)) {
|
|
223
252
|
return;
|
|
224
253
|
}
|
|
225
|
-
|
|
254
|
+
const id = setTimeout(() => {
|
|
255
|
+
timeoutMap.delete(eventTarget);
|
|
226
256
|
doPreload();
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
eventTarget.preloadTimeout = null;
|
|
230
|
-
doPreload();
|
|
231
|
-
}, preloadDelay);
|
|
232
|
-
}
|
|
257
|
+
}, preloadDelay);
|
|
258
|
+
timeoutMap.set(eventTarget, id);
|
|
233
259
|
}
|
|
234
260
|
};
|
|
235
261
|
const handleLeave = (e) => {
|
|
236
|
-
if (disabled) return;
|
|
237
|
-
const eventTarget = e.target
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
262
|
+
if (disabled || !preload || !preloadDelay) return;
|
|
263
|
+
const eventTarget = e.target;
|
|
264
|
+
const id = timeoutMap.get(eventTarget);
|
|
265
|
+
if (id) {
|
|
266
|
+
clearTimeout(id);
|
|
267
|
+
timeoutMap.delete(eventTarget);
|
|
241
268
|
}
|
|
242
269
|
};
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
(_a = e.persist) == null ? void 0 : _a.call(e);
|
|
246
|
-
handlers.filter(Boolean).forEach((handler) => {
|
|
247
|
-
if (e.defaultPrevented) return;
|
|
248
|
-
handler(e);
|
|
249
|
-
});
|
|
250
|
-
};
|
|
251
|
-
const resolvedActiveProps = isActive ? routerCore.functionalUpdate(activeProps, {}) ?? {} : {};
|
|
252
|
-
const resolvedInactiveProps = isActive ? {} : routerCore.functionalUpdate(inactiveProps, {});
|
|
270
|
+
const resolvedActiveProps = isActive ? routerCore.functionalUpdate(activeProps, {}) ?? STATIC_ACTIVE_OBJECT : STATIC_EMPTY_OBJECT;
|
|
271
|
+
const resolvedInactiveProps = isActive ? STATIC_EMPTY_OBJECT : routerCore.functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT;
|
|
253
272
|
const resolvedClassName = [
|
|
254
273
|
className,
|
|
255
274
|
resolvedActiveProps.className,
|
|
256
275
|
resolvedInactiveProps.className
|
|
257
276
|
].filter(Boolean).join(" ");
|
|
258
|
-
const resolvedStyle = {
|
|
277
|
+
const resolvedStyle = (style || resolvedActiveProps.style || resolvedInactiveProps.style) && {
|
|
259
278
|
...style,
|
|
260
279
|
...resolvedActiveProps.style,
|
|
261
280
|
...resolvedInactiveProps.style
|
|
@@ -273,16 +292,28 @@ function useLinkProps(options, forwardedRef) {
|
|
|
273
292
|
onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),
|
|
274
293
|
disabled: !!disabled,
|
|
275
294
|
target,
|
|
276
|
-
...
|
|
295
|
+
...resolvedStyle && { style: resolvedStyle },
|
|
277
296
|
...resolvedClassName && { className: resolvedClassName },
|
|
278
|
-
...disabled &&
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
},
|
|
282
|
-
...isActive && { "data-status": "active", "aria-current": "page" },
|
|
283
|
-
...isTransitioning && { "data-transitioning": "transitioning" }
|
|
297
|
+
...disabled && STATIC_DISABLED_PROPS,
|
|
298
|
+
...isActive && STATIC_ACTIVE_PROPS,
|
|
299
|
+
...isTransitioning && STATIC_TRANSITIONING_PROPS
|
|
284
300
|
};
|
|
285
301
|
}
|
|
302
|
+
const STATIC_EMPTY_OBJECT = {};
|
|
303
|
+
const STATIC_ACTIVE_OBJECT = { className: "active" };
|
|
304
|
+
const STATIC_DISABLED_PROPS = { role: "link", "aria-disabled": true };
|
|
305
|
+
const STATIC_ACTIVE_PROPS = { "data-status": "active", "aria-current": "page" };
|
|
306
|
+
const STATIC_TRANSITIONING_PROPS = { "data-transitioning": "transitioning" };
|
|
307
|
+
const timeoutMap = /* @__PURE__ */ new WeakMap();
|
|
308
|
+
const intersectionObserverOptions = {
|
|
309
|
+
rootMargin: "100px"
|
|
310
|
+
};
|
|
311
|
+
const composeHandlers = (handlers) => (e) => {
|
|
312
|
+
handlers.filter(Boolean).forEach((handler) => {
|
|
313
|
+
if (e.defaultPrevented) return;
|
|
314
|
+
handler(e);
|
|
315
|
+
});
|
|
316
|
+
};
|
|
286
317
|
function createLink(Comp) {
|
|
287
318
|
return React__namespace.forwardRef(function CreatedLink(props, ref) {
|
|
288
319
|
return /* @__PURE__ */ jsxRuntime.jsx(Link, { ...props, _asChild: Comp, ref });
|
|
@@ -299,7 +330,7 @@ const Link = React__namespace.forwardRef(
|
|
|
299
330
|
const children = typeof rest.children === "function" ? rest.children({
|
|
300
331
|
isActive: linkProps["data-status"] === "active"
|
|
301
332
|
}) : rest.children;
|
|
302
|
-
if (
|
|
333
|
+
if (_asChild === void 0) {
|
|
303
334
|
delete linkProps.disabled;
|
|
304
335
|
}
|
|
305
336
|
return React__namespace.createElement(
|
package/dist/cjs/link.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link.cjs","sources":["../../src/link.tsx"],"sourcesContent":["import * as React from 'react'\nimport { flushSync } from 'react-dom'\nimport {\n deepEqual,\n exactPathTest,\n functionalUpdate,\n preloadWarning,\n removeTrailingSlash,\n} from '@tanstack/router-core'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\n\nimport {\n useForwardedRef,\n useIntersectionObserver,\n useLayoutEffect,\n} from './utils'\n\nimport { useMatch } from './useMatch'\nimport type {\n AnyRouter,\n Constrain,\n LinkCurrentTargetElement,\n LinkOptions,\n RegisteredRouter,\n RoutePaths,\n} from '@tanstack/router-core'\nimport type { ReactNode } from 'react'\nimport type {\n ValidateLinkOptions,\n ValidateLinkOptionsArray,\n} from './typePrimitives'\n\nexport function useLinkProps<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n forwardedRef?: React.ForwardedRef<Element>,\n): React.ComponentPropsWithRef<'a'> {\n const router = useRouter()\n const [isTransitioning, setIsTransitioning] = React.useState(false)\n const hasRenderFetched = React.useRef(false)\n const innerRef = useForwardedRef(forwardedRef)\n\n const {\n // custom props\n activeProps = () => ({ className: 'active' }),\n inactiveProps = () => ({}),\n activeOptions,\n to,\n preload: userPreload,\n preloadDelay: userPreloadDelay,\n hashScrollIntoView,\n replace,\n startTransition,\n resetScroll,\n viewTransition,\n // element props\n children,\n target,\n disabled,\n style,\n className,\n onClick,\n onFocus,\n onMouseEnter,\n onMouseLeave,\n onTouchStart,\n ignoreBlocker,\n ...rest\n } = options\n\n const {\n // prevent these from being returned\n params: _params,\n search: _search,\n hash: _hash,\n state: _state,\n mask: _mask,\n reloadDocument: _reloadDocument,\n unsafeRelative: _unsafeRelative,\n ...propsSafeToSpread\n } = rest\n\n // If this link simply reloads the current route,\n // make sure it has a new key so it will trigger a data refresh\n\n // If this `to` is a valid external URL, return\n // null for LinkUtils\n\n const type: 'internal' | 'external' = React.useMemo(() => {\n try {\n new URL(`${to}`)\n return 'external'\n } catch {}\n return 'internal'\n }, [to])\n\n // subscribe to search params to re-build location if it changes\n const currentSearch = useRouterState({\n select: (s) => s.location.search,\n structuralSharing: true as any,\n })\n\n const nearestFrom = useMatch({\n strict: false,\n select: (match) => match.fullPath,\n })\n\n const from = options.from ?? nearestFrom\n\n // Use it as the default `from` location\n options = { ...options, from }\n\n const next = React.useMemo(\n () => router.buildLocation(options as any),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [router, options, currentSearch],\n )\n\n const preload = React.useMemo(() => {\n if (options.reloadDocument) {\n return false\n }\n return userPreload ?? router.options.defaultPreload\n }, [router.options.defaultPreload, userPreload, options.reloadDocument])\n const preloadDelay =\n userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0\n\n const isActive = useRouterState({\n select: (s) => {\n if (activeOptions?.exact) {\n const testExact = exactPathTest(\n s.location.pathname,\n next.pathname,\n router.basepath,\n )\n if (!testExact) {\n return false\n }\n } else {\n const currentPathSplit = removeTrailingSlash(\n s.location.pathname,\n router.basepath,\n ).split('/')\n const nextPathSplit = removeTrailingSlash(\n next.pathname,\n router.basepath,\n ).split('/')\n\n const pathIsFuzzyEqual = nextPathSplit.every(\n (d, i) => d === currentPathSplit[i],\n )\n if (!pathIsFuzzyEqual) {\n return false\n }\n }\n\n if (activeOptions?.includeSearch ?? true) {\n const searchTest = deepEqual(s.location.search, next.search, {\n partial: !activeOptions?.exact,\n ignoreUndefined: !activeOptions?.explicitUndefined,\n })\n if (!searchTest) {\n return false\n }\n }\n\n if (activeOptions?.includeHash) {\n return s.location.hash === next.hash\n }\n return true\n },\n })\n\n const doPreload = React.useCallback(() => {\n router.preloadRoute(options as any).catch((err) => {\n console.warn(err)\n console.warn(preloadWarning)\n })\n }, [options, router])\n\n const preloadViewportIoCallback = React.useCallback(\n (entry: IntersectionObserverEntry | undefined) => {\n if (entry?.isIntersecting) {\n doPreload()\n }\n },\n [doPreload],\n )\n\n useIntersectionObserver(\n innerRef,\n preloadViewportIoCallback,\n { rootMargin: '100px' },\n { disabled: !!disabled || !(preload === 'viewport') },\n )\n\n useLayoutEffect(() => {\n if (hasRenderFetched.current) {\n return\n }\n if (!disabled && preload === 'render') {\n doPreload()\n hasRenderFetched.current = true\n }\n }, [disabled, doPreload, preload])\n\n if (type === 'external') {\n return {\n ...propsSafeToSpread,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n type,\n href: to,\n ...(children && { children }),\n ...(target && { target }),\n ...(disabled && { disabled }),\n ...(style && { style }),\n ...(className && { className }),\n ...(onClick && { onClick }),\n ...(onFocus && { onFocus }),\n ...(onMouseEnter && { onMouseEnter }),\n ...(onMouseLeave && { onMouseLeave }),\n ...(onTouchStart && { onTouchStart }),\n }\n }\n\n // The click handler\n const handleClick = (e: MouseEvent) => {\n if (\n !disabled &&\n !isCtrlEvent(e) &&\n !e.defaultPrevented &&\n (!target || target === '_self') &&\n e.button === 0\n ) {\n e.preventDefault()\n\n flushSync(() => {\n setIsTransitioning(true)\n })\n\n const unsub = router.subscribe('onResolved', () => {\n unsub()\n setIsTransitioning(false)\n })\n\n // All is well? Navigate!\n // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing\n return router.navigate({\n ...options,\n replace,\n resetScroll,\n hashScrollIntoView,\n startTransition,\n viewTransition,\n ignoreBlocker,\n })\n }\n }\n\n // The click handler\n const handleFocus = (_: MouseEvent) => {\n if (disabled) return\n if (preload) {\n doPreload()\n }\n }\n\n const handleTouchStart = handleFocus\n\n const handleEnter = (e: MouseEvent) => {\n if (disabled) return\n const eventTarget = (e.target || {}) as LinkCurrentTargetElement\n\n if (preload) {\n if (eventTarget.preloadTimeout) {\n return\n }\n\n if (!preloadDelay) {\n doPreload()\n } else {\n eventTarget.preloadTimeout = setTimeout(() => {\n eventTarget.preloadTimeout = null\n doPreload()\n }, preloadDelay)\n }\n }\n }\n\n const handleLeave = (e: MouseEvent) => {\n if (disabled) return\n const eventTarget = (e.target || {}) as LinkCurrentTargetElement\n\n if (eventTarget.preloadTimeout) {\n clearTimeout(eventTarget.preloadTimeout)\n eventTarget.preloadTimeout = null\n }\n }\n\n const composeHandlers =\n (handlers: Array<undefined | ((e: any) => void)>) =>\n (e: { persist?: () => void; defaultPrevented: boolean }) => {\n e.persist?.()\n handlers.filter(Boolean).forEach((handler) => {\n if (e.defaultPrevented) return\n handler!(e)\n })\n }\n\n // Get the active props\n const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = isActive\n ? (functionalUpdate(activeProps as any, {}) ?? {})\n : {}\n\n // Get the inactive props\n const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> =\n isActive ? {} : functionalUpdate(inactiveProps, {})\n\n const resolvedClassName = [\n className,\n resolvedActiveProps.className,\n resolvedInactiveProps.className,\n ]\n .filter(Boolean)\n .join(' ')\n\n const resolvedStyle = {\n ...style,\n ...resolvedActiveProps.style,\n ...resolvedInactiveProps.style,\n }\n\n return {\n ...propsSafeToSpread,\n ...resolvedActiveProps,\n ...resolvedInactiveProps,\n href: disabled\n ? undefined\n : next.maskedLocation\n ? router.history.createHref(next.maskedLocation.href)\n : router.history.createHref(next.href),\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n onClick: composeHandlers([onClick, handleClick]),\n onFocus: composeHandlers([onFocus, handleFocus]),\n onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),\n onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),\n onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),\n disabled: !!disabled,\n target,\n ...(Object.keys(resolvedStyle).length && { style: resolvedStyle }),\n ...(resolvedClassName && { className: resolvedClassName }),\n ...(disabled && {\n role: 'link',\n 'aria-disabled': true,\n }),\n ...(isActive && { 'data-status': 'active', 'aria-current': 'page' }),\n ...(isTransitioning && { 'data-transitioning': 'transitioning' }),\n }\n}\n\ntype UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements\n ? React.JSX.IntrinsicElements[TComp]\n : React.PropsWithoutRef<\n TComp extends React.ComponentType<infer TProps> ? TProps : never\n > &\n React.RefAttributes<\n TComp extends\n | React.FC<{ ref: React.Ref<infer TRef> }>\n | React.Component<{ ref: React.Ref<infer TRef> }>\n ? TRef\n : never\n >\n\nexport type UseLinkPropsOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> | string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n UseLinkReactProps<'a'>\n\nexport type ActiveLinkOptions<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n ActiveLinkOptionProps<TComp>\n\ntype ActiveLinkProps<TComp> = Partial<\n LinkComponentReactProps<TComp> & {\n [key: `data-${string}`]: unknown\n }\n>\n\nexport interface ActiveLinkOptionProps<TComp = 'a'> {\n /**\n * A function that returns additional props for the `active` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n /**\n * A function that returns additional props for the `inactive` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n}\n\nexport type LinkProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n LinkPropsChildren\n\nexport interface LinkPropsChildren {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | React.ReactNode\n | ((state: {\n isActive: boolean\n isTransitioning: boolean\n }) => React.ReactNode)\n}\n\ntype LinkComponentReactProps<TComp> = Omit<\n UseLinkReactProps<TComp>,\n keyof CreateLinkProps\n>\n\nexport type LinkComponentProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkComponentReactProps<TComp> &\n LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\nexport type CreateLinkProps = LinkProps<\n any,\n any,\n string,\n string,\n string,\n string\n>\n\nexport type LinkComponent<\n in out TComp,\n in out TDefaultFrom extends string = string,\n> = <\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = TDefaultFrom,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n) => React.ReactElement\n\nexport interface LinkComponentRoute<\n in out TDefaultFrom extends string = string,\n> {\n defaultFrom: TDefaultFrom\n <\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = undefined,\n const TMaskTo extends string = '',\n >(\n props: LinkComponentProps<\n 'a',\n TRouter,\n this['defaultFrom'],\n TTo,\n this['defaultFrom'],\n TMaskTo\n >,\n ): React.ReactElement\n}\n\nexport function createLink<const TComp>(\n Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>,\n): LinkComponent<TComp> {\n return React.forwardRef(function CreatedLink(props, ref) {\n return <Link {...(props as any)} _asChild={Comp} ref={ref} />\n }) as any\n}\n\nexport const Link: LinkComponent<'a'> = React.forwardRef<Element, any>(\n (props, ref) => {\n const { _asChild, ...rest } = props\n const {\n type: _type,\n ref: innerRef,\n ...linkProps\n } = useLinkProps(rest as any, ref)\n\n const children =\n typeof rest.children === 'function'\n ? rest.children({\n isActive: (linkProps as any)['data-status'] === 'active',\n })\n : rest.children\n\n if (typeof _asChild === 'undefined') {\n // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop\n // @ts-expect-error\n delete linkProps.disabled\n }\n\n return React.createElement(\n _asChild ? _asChild : 'a',\n {\n ...linkProps,\n ref: innerRef,\n },\n children,\n )\n },\n) as any\n\nfunction isCtrlEvent(e: MouseEvent) {\n return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)\n}\n\nexport type LinkOptionsFnOptions<\n TOptions,\n TComp,\n TRouter extends AnyRouter = RegisteredRouter,\n> =\n TOptions extends ReadonlyArray<any>\n ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>\n : ValidateLinkOptions<TRouter, TOptions, string, TComp>\n\nexport type LinkOptionsFn<TComp> = <\n const TOptions,\n TRouter extends AnyRouter = RegisteredRouter,\n>(\n options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,\n) => TOptions\n\nexport const linkOptions: LinkOptionsFn<'a'> = (options) => {\n return options as any\n}\n"],"names":["useRouter","React","useForwardedRef","useRouterState","useMatch","exactPathTest","removeTrailingSlash","deepEqual","preloadWarning","useIntersectionObserver","useLayoutEffect","flushSync","functionalUpdate"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCgB,SAAA,aAOd,SACA,cACkC;AAClC,QAAM,SAASA,UAAAA,UAAU;AAC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ACvD,0CAAQ,MAAM,EAAA,GAAI,OAAe,UAAU,MAAM,KAAU;AAAA,EAAA,CAC5D;AACH;AAEO,MAAM,OAA2BA,iBAAM;AAAA,EAC5C,CAAC,OAAO,QAAQ;AACd,UAAM,EAAE,UAAU,GAAG,KAAA,IAAS;AACxB,UAAA;AAAA,MACJ,MAAM;AAAA,MACN,KAAK;AAAA,MACL,GAAG;AAAA,IAAA,IACD,aAAa,MAAa,GAAG;AAEjC,UAAM,WACJ,OAAO,KAAK,aAAa,aACrB,KAAK,SAAS;AAAA,MACZ,UAAW,UAAkB,aAAa,MAAM;AAAA,IAAA,CACjD,IACD,KAAK;AAEP,QAAA,OAAO,aAAa,aAAa;AAGnC,aAAO,UAAU;AAAA,IAAA;AAGnB,WAAOA,iBAAM;AAAA,MACX,WAAW,WAAW;AAAA,MACtB;AAAA,QACE,GAAG;AAAA,QACH,KAAK;AAAA,MACP;AAAA,MACA;AAAA,IACF;AAAA,EAAA;AAEJ;AAEA,SAAS,YAAY,GAAe;AAC3B,SAAA,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE;AACpD;AAkBa,MAAA,cAAkC,CAAC,YAAY;AACnD,SAAA;AACT;;;;;"}
|
|
1
|
+
{"version":3,"file":"link.cjs","sources":["../../src/link.tsx"],"sourcesContent":["import * as React from 'react'\nimport { flushSync } from 'react-dom'\nimport {\n deepEqual,\n exactPathTest,\n functionalUpdate,\n preloadWarning,\n removeTrailingSlash,\n} from '@tanstack/router-core'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\n\nimport { useForwardedRef, useIntersectionObserver } from './utils'\n\nimport { useMatch } from './useMatch'\nimport type {\n AnyRouter,\n Constrain,\n LinkOptions,\n RegisteredRouter,\n RoutePaths,\n} from '@tanstack/router-core'\nimport type { ReactNode } from 'react'\nimport type {\n ValidateLinkOptions,\n ValidateLinkOptionsArray,\n} from './typePrimitives'\n\nexport function useLinkProps<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n forwardedRef?: React.ForwardedRef<Element>,\n): React.ComponentPropsWithRef<'a'> {\n const router = useRouter()\n const [isTransitioning, setIsTransitioning] = React.useState(false)\n const hasRenderFetched = React.useRef(false)\n const innerRef = useForwardedRef(forwardedRef)\n\n const {\n // custom props\n activeProps,\n inactiveProps,\n activeOptions,\n to,\n preload: userPreload,\n preloadDelay: userPreloadDelay,\n hashScrollIntoView,\n replace,\n startTransition,\n resetScroll,\n viewTransition,\n // element props\n children,\n target,\n disabled,\n style,\n className,\n onClick,\n onFocus,\n onMouseEnter,\n onMouseLeave,\n onTouchStart,\n ignoreBlocker,\n // prevent these from being returned\n params: _params,\n search: _search,\n hash: _hash,\n state: _state,\n mask: _mask,\n reloadDocument: _reloadDocument,\n unsafeRelative: _unsafeRelative,\n from: _from,\n _fromLocation,\n ...propsSafeToSpread\n } = options\n\n // If this link simply reloads the current route,\n // make sure it has a new key so it will trigger a data refresh\n\n // If this `to` is a valid external URL, return\n // null for LinkUtils\n\n const type: 'internal' | 'external' = React.useMemo(() => {\n try {\n new URL(to as any)\n return 'external'\n } catch {}\n return 'internal'\n }, [to])\n\n // subscribe to search params to re-build location if it changes\n const currentSearch = useRouterState({\n select: (s) => s.location.search,\n structuralSharing: true as any,\n })\n\n const from = useMatch({\n strict: false,\n select: (match) => options.from ?? match.fullPath,\n })\n\n const next = React.useMemo(\n () => router.buildLocation({ ...options, from } as any),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n router,\n currentSearch,\n options._fromLocation,\n from,\n options.hash,\n options.to,\n options.search,\n options.params,\n options.state,\n options.mask,\n options.unsafeRelative,\n ],\n )\n\n const isExternal = type === 'external'\n\n const preload =\n options.reloadDocument || isExternal\n ? false\n : (userPreload ?? router.options.defaultPreload)\n const preloadDelay =\n userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0\n\n const isActive = useRouterState({\n select: (s) => {\n if (isExternal) return false\n if (activeOptions?.exact) {\n const testExact = exactPathTest(\n s.location.pathname,\n next.pathname,\n router.basepath,\n )\n if (!testExact) {\n return false\n }\n } else {\n const currentPathSplit = removeTrailingSlash(\n s.location.pathname,\n router.basepath,\n )\n const nextPathSplit = removeTrailingSlash(\n next.pathname,\n router.basepath,\n )\n\n const pathIsFuzzyEqual =\n currentPathSplit.startsWith(nextPathSplit) &&\n (currentPathSplit.length === nextPathSplit.length ||\n currentPathSplit[nextPathSplit.length] === '/')\n\n if (!pathIsFuzzyEqual) {\n return false\n }\n }\n\n if (activeOptions?.includeSearch ?? true) {\n const searchTest = deepEqual(s.location.search, next.search, {\n partial: !activeOptions?.exact,\n ignoreUndefined: !activeOptions?.explicitUndefined,\n })\n if (!searchTest) {\n return false\n }\n }\n\n if (activeOptions?.includeHash) {\n return s.location.hash === next.hash\n }\n return true\n },\n })\n\n const doPreload = React.useCallback(\n () => {\n router.preloadRoute({ ...options, from } as any).catch((err) => {\n console.warn(err)\n console.warn(preloadWarning)\n })\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n router,\n options.to,\n options._fromLocation,\n from,\n options.search,\n options.hash,\n options.params,\n options.state,\n options.mask,\n options.unsafeRelative,\n options.hashScrollIntoView,\n options.href,\n options.ignoreBlocker,\n options.reloadDocument,\n options.replace,\n options.resetScroll,\n options.viewTransition,\n ],\n )\n\n const preloadViewportIoCallback = React.useCallback(\n (entry: IntersectionObserverEntry | undefined) => {\n if (entry?.isIntersecting) {\n doPreload()\n }\n },\n [doPreload],\n )\n\n useIntersectionObserver(\n innerRef,\n preloadViewportIoCallback,\n intersectionObserverOptions,\n { disabled: !!disabled || !(preload === 'viewport') },\n )\n\n React.useEffect(() => {\n if (hasRenderFetched.current) {\n return\n }\n if (!disabled && preload === 'render') {\n doPreload()\n hasRenderFetched.current = true\n }\n }, [disabled, doPreload, preload])\n\n if (isExternal) {\n return {\n ...propsSafeToSpread,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n type,\n href: to,\n ...(children && { children }),\n ...(target && { target }),\n ...(disabled && { disabled }),\n ...(style && { style }),\n ...(className && { className }),\n ...(onClick && { onClick }),\n ...(onFocus && { onFocus }),\n ...(onMouseEnter && { onMouseEnter }),\n ...(onMouseLeave && { onMouseLeave }),\n ...(onTouchStart && { onTouchStart }),\n }\n }\n\n // The click handler\n const handleClick = (e: React.MouseEvent) => {\n if (\n !disabled &&\n !isCtrlEvent(e) &&\n !e.defaultPrevented &&\n (!target || target === '_self') &&\n e.button === 0\n ) {\n e.preventDefault()\n\n flushSync(() => {\n setIsTransitioning(true)\n })\n\n const unsub = router.subscribe('onResolved', () => {\n unsub()\n setIsTransitioning(false)\n })\n\n // All is well? Navigate!\n // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing\n return router.navigate({\n ...options,\n from,\n replace,\n resetScroll,\n hashScrollIntoView,\n startTransition,\n viewTransition,\n ignoreBlocker,\n })\n }\n }\n\n // The click handler\n const handleFocus = (_: React.MouseEvent) => {\n if (disabled) return\n if (preload) {\n doPreload()\n }\n }\n\n const handleTouchStart = handleFocus\n\n const handleEnter = (e: React.MouseEvent) => {\n if (disabled || !preload) return\n\n if (!preloadDelay) {\n doPreload()\n } else {\n const eventTarget = e.target\n if (timeoutMap.has(eventTarget)) {\n return\n }\n const id = setTimeout(() => {\n timeoutMap.delete(eventTarget)\n doPreload()\n }, preloadDelay)\n timeoutMap.set(eventTarget, id)\n }\n }\n\n const handleLeave = (e: React.MouseEvent) => {\n if (disabled || !preload || !preloadDelay) return\n const eventTarget = e.target\n const id = timeoutMap.get(eventTarget)\n if (id) {\n clearTimeout(id)\n timeoutMap.delete(eventTarget)\n }\n }\n\n // Get the active props\n const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = isActive\n ? (functionalUpdate(activeProps as any, {}) ?? STATIC_ACTIVE_OBJECT)\n : STATIC_EMPTY_OBJECT\n\n // Get the inactive props\n const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> =\n isActive\n ? STATIC_EMPTY_OBJECT\n : (functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT)\n\n const resolvedClassName = [\n className,\n resolvedActiveProps.className,\n resolvedInactiveProps.className,\n ]\n .filter(Boolean)\n .join(' ')\n\n const resolvedStyle = (style ||\n resolvedActiveProps.style ||\n resolvedInactiveProps.style) && {\n ...style,\n ...resolvedActiveProps.style,\n ...resolvedInactiveProps.style,\n }\n\n return {\n ...propsSafeToSpread,\n ...resolvedActiveProps,\n ...resolvedInactiveProps,\n href: disabled\n ? undefined\n : next.maskedLocation\n ? router.history.createHref(next.maskedLocation.href)\n : router.history.createHref(next.href),\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n onClick: composeHandlers([onClick, handleClick]),\n onFocus: composeHandlers([onFocus, handleFocus]),\n onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),\n onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),\n onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),\n disabled: !!disabled,\n target,\n ...(resolvedStyle && { style: resolvedStyle }),\n ...(resolvedClassName && { className: resolvedClassName }),\n ...(disabled && STATIC_DISABLED_PROPS),\n ...(isActive && STATIC_ACTIVE_PROPS),\n ...(isTransitioning && STATIC_TRANSITIONING_PROPS),\n }\n}\n\nconst STATIC_EMPTY_OBJECT = {}\nconst STATIC_ACTIVE_OBJECT = { className: 'active' }\nconst STATIC_DISABLED_PROPS = { role: 'link', 'aria-disabled': true }\nconst STATIC_ACTIVE_PROPS = { 'data-status': 'active', 'aria-current': 'page' }\nconst STATIC_TRANSITIONING_PROPS = { 'data-transitioning': 'transitioning' }\n\nconst timeoutMap = new WeakMap<EventTarget, ReturnType<typeof setTimeout>>()\n\nconst intersectionObserverOptions: IntersectionObserverInit = {\n rootMargin: '100px',\n}\n\nconst composeHandlers =\n (handlers: Array<undefined | React.EventHandler<any>>) =>\n (e: React.SyntheticEvent) => {\n handlers.filter(Boolean).forEach((handler) => {\n if (e.defaultPrevented) return\n handler!(e)\n })\n }\n\ntype UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements\n ? React.JSX.IntrinsicElements[TComp]\n : React.PropsWithoutRef<\n TComp extends React.ComponentType<infer TProps> ? TProps : never\n > &\n React.RefAttributes<\n TComp extends\n | React.FC<{ ref: React.Ref<infer TRef> }>\n | React.Component<{ ref: React.Ref<infer TRef> }>\n ? TRef\n : never\n >\n\nexport type UseLinkPropsOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> | string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n UseLinkReactProps<'a'>\n\nexport type ActiveLinkOptions<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n ActiveLinkOptionProps<TComp>\n\ntype ActiveLinkProps<TComp> = Partial<\n LinkComponentReactProps<TComp> & {\n [key: `data-${string}`]: unknown\n }\n>\n\nexport interface ActiveLinkOptionProps<TComp = 'a'> {\n /**\n * A function that returns additional props for the `active` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n /**\n * A function that returns additional props for the `inactive` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n}\n\nexport type LinkProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n LinkPropsChildren\n\nexport interface LinkPropsChildren {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | React.ReactNode\n | ((state: {\n isActive: boolean\n isTransitioning: boolean\n }) => React.ReactNode)\n}\n\ntype LinkComponentReactProps<TComp> = Omit<\n UseLinkReactProps<TComp>,\n keyof CreateLinkProps\n>\n\nexport type LinkComponentProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkComponentReactProps<TComp> &\n LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\nexport type CreateLinkProps = LinkProps<\n any,\n any,\n string,\n string,\n string,\n string\n>\n\nexport type LinkComponent<\n in out TComp,\n in out TDefaultFrom extends string = string,\n> = <\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = TDefaultFrom,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n) => React.ReactElement\n\nexport interface LinkComponentRoute<\n in out TDefaultFrom extends string = string,\n> {\n defaultFrom: TDefaultFrom\n <\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = undefined,\n const TMaskTo extends string = '',\n >(\n props: LinkComponentProps<\n 'a',\n TRouter,\n this['defaultFrom'],\n TTo,\n this['defaultFrom'],\n TMaskTo\n >,\n ): React.ReactElement\n}\n\nexport function createLink<const TComp>(\n Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>,\n): LinkComponent<TComp> {\n return React.forwardRef(function CreatedLink(props, ref) {\n return <Link {...(props as any)} _asChild={Comp} ref={ref} />\n }) as any\n}\n\nexport const Link: LinkComponent<'a'> = React.forwardRef<Element, any>(\n (props, ref) => {\n const { _asChild, ...rest } = props\n const {\n type: _type,\n ref: innerRef,\n ...linkProps\n } = useLinkProps(rest as any, ref)\n\n const children =\n typeof rest.children === 'function'\n ? rest.children({\n isActive: (linkProps as any)['data-status'] === 'active',\n })\n : rest.children\n\n if (_asChild === undefined) {\n // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop\n // @ts-expect-error\n delete linkProps.disabled\n }\n\n return React.createElement(\n _asChild ? _asChild : 'a',\n {\n ...linkProps,\n ref: innerRef,\n },\n children,\n )\n },\n) as any\n\nfunction isCtrlEvent(e: React.MouseEvent) {\n return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)\n}\n\nexport type LinkOptionsFnOptions<\n TOptions,\n TComp,\n TRouter extends AnyRouter = RegisteredRouter,\n> =\n TOptions extends ReadonlyArray<any>\n ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>\n : ValidateLinkOptions<TRouter, TOptions, string, TComp>\n\nexport type LinkOptionsFn<TComp> = <\n const TOptions,\n TRouter extends AnyRouter = RegisteredRouter,\n>(\n options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,\n) => TOptions\n\nexport const linkOptions: LinkOptionsFn<'a'> = (options) => {\n return options as any\n}\n"],"names":["useRouter","React","useForwardedRef","useRouterState","useMatch","exactPathTest","removeTrailingSlash","deepEqual","preloadWarning","useIntersectionObserver","flushSync","functionalUpdate"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BgB,SAAA,aAOd,SACA,cACkC;AAClC,QAAM,SAASA,UAAAA,UAAU;AACzB,QAAM,CAAC,iBAAiB,kBAAkB,IAAIC,iBAAM,SAAS,KAAK;AAC5D,QAAA,mBAAmBA,iBAAM,OAAO,KAAK;AACrC,QAAA,WAAWC,sBAAgB,YAAY;AAEvC,QAAA;AAAA;A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BAAgB;AAE3E,MAAM,iCAAiB,QAAoD;AAE3E,MAAM,8BAAwD;AAAA,EAC5D,YAAY;AACd;AAEA,MAAM,kBACJ,CAAC,aACD,CAAC,MAA4B;AAC3B,WAAS,OAAO,OAAO,EAAE,QAAQ,CAAC,YAAY;AAC5C,QAAI,EAAE,iBAAkB;AACxB,YAAS,CAAC;AAAA,EAAA,CACX;AACH;AAkIK,SAAS,WACd,MACsB;AACtB,SAAOV,iBAAM,WAAW,SAAS,YAAY,OAAO,KAAK;AACvD,0CAAQ,MAAM,EAAA,GAAI,OAAe,UAAU,MAAM,KAAU;AAAA,EAAA,CAC5D;AACH;AAEO,MAAM,OAA2BA,iBAAM;AAAA,EAC5C,CAAC,OAAO,QAAQ;AACd,UAAM,EAAE,UAAU,GAAG,KAAA,IAAS;AACxB,UAAA;AAAA,MACJ,MAAM;AAAA,MACN,KAAK;AAAA,MACL,GAAG;AAAA,IAAA,IACD,aAAa,MAAa,GAAG;AAEjC,UAAM,WACJ,OAAO,KAAK,aAAa,aACrB,KAAK,SAAS;AAAA,MACZ,UAAW,UAAkB,aAAa,MAAM;AAAA,IAAA,CACjD,IACD,KAAK;AAEX,QAAI,aAAa,QAAW;AAG1B,aAAO,UAAU;AAAA,IAAA;AAGnB,WAAOA,iBAAM;AAAA,MACX,WAAW,WAAW;AAAA,MACtB;AAAA,QACE,GAAG;AAAA,QACH,KAAK;AAAA,MACP;AAAA,MACA;AAAA,IACF;AAAA,EAAA;AAEJ;AAEA,SAAS,YAAY,GAAqB;AACjC,SAAA,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE;AACpD;AAkBa,MAAA,cAAkC,CAAC,YAAY;AACnD,SAAA;AACT;;;;;"}
|
package/dist/cjs/utils.cjs
CHANGED
|
@@ -40,24 +40,18 @@ function usePrevious(value) {
|
|
|
40
40
|
return ref.current.prev;
|
|
41
41
|
}
|
|
42
42
|
function useIntersectionObserver(ref, callback, intersectionObserverOptions = {}, options = {}) {
|
|
43
|
-
const isIntersectionObserverAvailable = React__namespace.useRef(
|
|
44
|
-
typeof IntersectionObserver === "function"
|
|
45
|
-
);
|
|
46
|
-
const observerRef = React__namespace.useRef(null);
|
|
47
43
|
React__namespace.useEffect(() => {
|
|
48
|
-
if (!ref.current ||
|
|
44
|
+
if (!ref.current || options.disabled || typeof IntersectionObserver !== "function") {
|
|
49
45
|
return;
|
|
50
46
|
}
|
|
51
|
-
|
|
47
|
+
const observer = new IntersectionObserver(([entry]) => {
|
|
52
48
|
callback(entry);
|
|
53
49
|
}, intersectionObserverOptions);
|
|
54
|
-
|
|
50
|
+
observer.observe(ref.current);
|
|
55
51
|
return () => {
|
|
56
|
-
|
|
57
|
-
(_a = observerRef.current) == null ? void 0 : _a.disconnect();
|
|
52
|
+
observer.disconnect();
|
|
58
53
|
};
|
|
59
54
|
}, [callback, intersectionObserverOptions, options.disabled, ref]);
|
|
60
|
-
return observerRef.current;
|
|
61
55
|
}
|
|
62
56
|
function useForwardedRef(ref) {
|
|
63
57
|
const innerRef = React__namespace.useRef(null);
|
package/dist/cjs/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["import * as React from 'react'\n\nexport function useStableCallback<T extends (...args: Array<any>) => any>(\n fn: T,\n): T {\n const fnRef = React.useRef(fn)\n fnRef.current = fn\n\n const ref = React.useRef((...args: Array<any>) => fnRef.current(...args))\n return ref.current as T\n}\n\nexport const useLayoutEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\n/**\n * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3\n */\nexport function usePrevious<T>(value: T): T | null {\n // initialise the ref with previous and current values\n const ref = React.useRef<{ value: T; prev: T | null }>({\n value: value,\n prev: null,\n })\n\n const current = ref.current.value\n\n // if the value passed into hook doesn't match what we store as \"current\"\n // move the \"current\" to the \"previous\"\n // and store the passed value as \"current\"\n if (value !== current) {\n ref.current = {\n value: value,\n prev: current,\n }\n }\n\n // return the previous value only\n return ref.current.prev\n}\n\n/**\n * React hook to wrap `IntersectionObserver`.\n *\n * This hook will create an `IntersectionObserver` and observe the ref passed to it.\n *\n * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`.\n *\n * @param ref - The ref to observe\n * @param intersectionObserverOptions - The options to pass to the IntersectionObserver\n * @param options - The options to pass to the hook\n * @param callback - The callback to call when the intersection changes\n * @returns The IntersectionObserver instance\n * @example\n * ```tsx\n * const MyComponent = () => {\n * const ref = React.useRef<HTMLDivElement>(null)\n * useIntersectionObserver(\n * ref,\n * (entry) => { doSomething(entry) },\n * { rootMargin: '10px' },\n * { disabled: false }\n * )\n * return <div ref={ref} />\n * ```\n */\nexport function useIntersectionObserver<T extends Element>(\n ref: React.RefObject<T | null>,\n callback: (entry: IntersectionObserverEntry | undefined) => void,\n intersectionObserverOptions: IntersectionObserverInit = {},\n options: { disabled?: boolean } = {},\n)
|
|
1
|
+
{"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["import * as React from 'react'\n\nexport function useStableCallback<T extends (...args: Array<any>) => any>(\n fn: T,\n): T {\n const fnRef = React.useRef(fn)\n fnRef.current = fn\n\n const ref = React.useRef((...args: Array<any>) => fnRef.current(...args))\n return ref.current as T\n}\n\nexport const useLayoutEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\n/**\n * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3\n */\nexport function usePrevious<T>(value: T): T | null {\n // initialise the ref with previous and current values\n const ref = React.useRef<{ value: T; prev: T | null }>({\n value: value,\n prev: null,\n })\n\n const current = ref.current.value\n\n // if the value passed into hook doesn't match what we store as \"current\"\n // move the \"current\" to the \"previous\"\n // and store the passed value as \"current\"\n if (value !== current) {\n ref.current = {\n value: value,\n prev: current,\n }\n }\n\n // return the previous value only\n return ref.current.prev\n}\n\n/**\n * React hook to wrap `IntersectionObserver`.\n *\n * This hook will create an `IntersectionObserver` and observe the ref passed to it.\n *\n * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`.\n *\n * @param ref - The ref to observe\n * @param intersectionObserverOptions - The options to pass to the IntersectionObserver\n * @param options - The options to pass to the hook\n * @param callback - The callback to call when the intersection changes\n * @returns The IntersectionObserver instance\n * @example\n * ```tsx\n * const MyComponent = () => {\n * const ref = React.useRef<HTMLDivElement>(null)\n * useIntersectionObserver(\n * ref,\n * (entry) => { doSomething(entry) },\n * { rootMargin: '10px' },\n * { disabled: false }\n * )\n * return <div ref={ref} />\n * ```\n */\nexport function useIntersectionObserver<T extends Element>(\n ref: React.RefObject<T | null>,\n callback: (entry: IntersectionObserverEntry | undefined) => void,\n intersectionObserverOptions: IntersectionObserverInit = {},\n options: { disabled?: boolean } = {},\n) {\n React.useEffect(() => {\n if (\n !ref.current ||\n options.disabled ||\n typeof IntersectionObserver !== 'function'\n ) {\n return\n }\n\n const observer = new IntersectionObserver(([entry]) => {\n callback(entry)\n }, intersectionObserverOptions)\n\n observer.observe(ref.current)\n\n return () => {\n observer.disconnect()\n }\n }, [callback, intersectionObserverOptions, options.disabled, ref])\n}\n\n/**\n * React hook to take a `React.ForwardedRef` and returns a `ref` that can be used on a DOM element.\n *\n * @param ref - The forwarded ref\n * @returns The inner ref returned by `useRef`\n * @example\n * ```tsx\n * const MyComponent = React.forwardRef((props, ref) => {\n * const innerRef = useForwardedRef(ref)\n * return <div ref={innerRef} />\n * })\n * ```\n */\nexport function useForwardedRef<T>(ref?: React.ForwardedRef<T>) {\n const innerRef = React.useRef<T>(null)\n React.useImperativeHandle(ref, () => innerRef.current!, [])\n return innerRef\n}\n"],"names":["React"],"mappings":";;;;;;;;;;;;;;;;;;;;AAEO,SAAS,kBACd,IACG;AACG,QAAA,QAAQA,iBAAM,OAAO,EAAE;AAC7B,QAAM,UAAU;AAEV,QAAA,MAAMA,iBAAM,OAAO,IAAI,SAAqB,MAAM,QAAQ,GAAG,IAAI,CAAC;AACxE,SAAO,IAAI;AACb;AAEO,MAAM,kBACX,OAAO,WAAW,cAAcA,iBAAM,kBAAkBA,iBAAM;AAKzD,SAAS,YAAe,OAAoB;AAE3C,QAAA,MAAMA,iBAAM,OAAqC;AAAA,IACrD;AAAA,IACA,MAAM;AAAA,EAAA,CACP;AAEK,QAAA,UAAU,IAAI,QAAQ;AAK5B,MAAI,UAAU,SAAS;AACrB,QAAI,UAAU;AAAA,MACZ;AAAA,MACA,MAAM;AAAA,IACR;AAAA,EAAA;AAIF,SAAO,IAAI,QAAQ;AACrB;AA2BgB,SAAA,wBACd,KACA,UACA,8BAAwD,CACxD,GAAA,UAAkC,IAClC;AACAA,mBAAM,UAAU,MAAM;AACpB,QACE,CAAC,IAAI,WACL,QAAQ,YACR,OAAO,yBAAyB,YAChC;AACA;AAAA,IAAA;AAGF,UAAM,WAAW,IAAI,qBAAqB,CAAC,CAAC,KAAK,MAAM;AACrD,eAAS,KAAK;AAAA,OACb,2BAA2B;AAErB,aAAA,QAAQ,IAAI,OAAO;AAE5B,WAAO,MAAM;AACX,eAAS,WAAW;AAAA,IACtB;AAAA,EAAA,GACC,CAAC,UAAU,6BAA6B,QAAQ,UAAU,GAAG,CAAC;AACnE;AAeO,SAAS,gBAAmB,KAA6B;AACxD,QAAA,WAAWA,iBAAM,OAAU,IAAI;AACrCA,mBAAM,oBAAoB,KAAK,MAAM,SAAS,SAAU,CAAA,CAAE;AACnD,SAAA;AACT;;;;;;"}
|
package/dist/cjs/utils.d.cts
CHANGED
|
@@ -32,7 +32,7 @@ export declare function usePrevious<T>(value: T): T | null;
|
|
|
32
32
|
*/
|
|
33
33
|
export declare function useIntersectionObserver<T extends Element>(ref: React.RefObject<T | null>, callback: (entry: IntersectionObserverEntry | undefined) => void, intersectionObserverOptions?: IntersectionObserverInit, options?: {
|
|
34
34
|
disabled?: boolean;
|
|
35
|
-
}):
|
|
35
|
+
}): void;
|
|
36
36
|
/**
|
|
37
37
|
* React hook to take a `React.ForwardedRef` and returns a `ref` that can be used on a DOM element.
|
|
38
38
|
*
|
package/dist/esm/Matches.js
CHANGED
|
@@ -13,7 +13,7 @@ function Matches() {
|
|
|
13
13
|
const pendingElement = router.options.defaultPendingComponent ? /* @__PURE__ */ jsx(router.options.defaultPendingComponent, {}) : null;
|
|
14
14
|
const ResolvedSuspense = router.isServer || typeof document !== "undefined" && router.ssr ? SafeFragment : React.Suspense;
|
|
15
15
|
const inner = /* @__PURE__ */ jsxs(ResolvedSuspense, { fallback: pendingElement, children: [
|
|
16
|
-
/* @__PURE__ */ jsx(Transitioner, {}),
|
|
16
|
+
!router.isServer && /* @__PURE__ */ jsx(Transitioner, {}),
|
|
17
17
|
/* @__PURE__ */ jsx(MatchesInner, {})
|
|
18
18
|
] });
|
|
19
19
|
return router.options.InnerWrap ? /* @__PURE__ */ jsx(router.options.InnerWrap, { children: inner }) : inner;
|