mirror of
https://github.com/tuono-labs/tuono
synced 2026-07-29 22:02:46 -07:00
Preload chunks when links are visible in the viewport (#24)
* feat: preload chunk when links are visible in the viewport * feat: update version to v0.9.0
This commit is contained in:
@@ -1,71 +1,18 @@
|
||||
import * as React from 'react'
|
||||
import { useInternalRouter } from '../hooks/useInternalRouter'
|
||||
import { useRouterStore } from '../hooks/useRouterStore'
|
||||
import type { Route } from '../route'
|
||||
import { RouteMatch } from './RouteMatch'
|
||||
import NotFound from './NotFound'
|
||||
import useRoute from '../hooks/useRoute'
|
||||
|
||||
interface MatchesProps {
|
||||
// user defined props
|
||||
serverSideProps: any
|
||||
}
|
||||
|
||||
const DYNAMIC_PATH_REGEX = /\[(.*?)\]/
|
||||
|
||||
/*
|
||||
* This function is also implemented on server side to match the bundle
|
||||
* file to load at the first rendering.
|
||||
*
|
||||
* File: crates/tuono_lib/src/payload.rs
|
||||
*
|
||||
* Optimizations should occour on both
|
||||
*/
|
||||
export function getRouteByPathname(pathname: string): Route | undefined {
|
||||
const { routesById } = useInternalRouter()
|
||||
|
||||
if (routesById[pathname]) return routesById[pathname]
|
||||
|
||||
const dynamicRoutes = Object.keys(routesById).filter((route) =>
|
||||
DYNAMIC_PATH_REGEX.test(route),
|
||||
)
|
||||
|
||||
if (!dynamicRoutes.length) return
|
||||
|
||||
const pathSegments = pathname.split('/').filter(Boolean)
|
||||
|
||||
let match = undefined
|
||||
|
||||
// TODO: Check algo efficiency
|
||||
for (const dynamicRoute of dynamicRoutes) {
|
||||
const dynamicRouteSegments = dynamicRoute.split('/').filter(Boolean)
|
||||
|
||||
const routeSegmentsCollector: string[] = []
|
||||
|
||||
for (let i = 0; i < dynamicRouteSegments.length; i++) {
|
||||
if (
|
||||
dynamicRouteSegments[i] === pathSegments[i] ||
|
||||
DYNAMIC_PATH_REGEX.test(dynamicRouteSegments[i] || '')
|
||||
) {
|
||||
routeSegmentsCollector.push(dynamicRouteSegments[i] ?? '')
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (routeSegmentsCollector.length === pathSegments.length) {
|
||||
match = `/${routeSegmentsCollector.join('/')}`
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (!match) return
|
||||
return routesById[match]
|
||||
}
|
||||
|
||||
export function Matches({ serverSideProps }: MatchesProps): JSX.Element {
|
||||
const location = useRouterStore((st) => st.location)
|
||||
|
||||
const route = getRouteByPathname(location.pathname)
|
||||
const route = useRoute(location.pathname)
|
||||
|
||||
if (!route) {
|
||||
return <NotFound />
|
||||
|
||||
Reference in New Issue
Block a user