From 90de047a07d7fba1c329d0f6e57dcd7f98b5f7cf Mon Sep 17 00:00:00 2001 From: Valerio Ageno Date: Sat, 11 May 2024 16:08:51 +0200 Subject: [PATCH] feat: handle custom not found error --- .../tuono-router/src/components/Matches.tsx | 5 +++++ .../tuono-router/src/components/NotFound.tsx | 18 ++++++++++++++++ packages/tuono-router/src/router.ts | 21 ++++++++++++++----- 3 files changed, 39 insertions(+), 5 deletions(-) create mode 100644 packages/tuono-router/src/components/NotFound.tsx diff --git a/packages/tuono-router/src/components/Matches.tsx b/packages/tuono-router/src/components/Matches.tsx index 28324cfe..11f2aa36 100644 --- a/packages/tuono-router/src/components/Matches.tsx +++ b/packages/tuono-router/src/components/Matches.tsx @@ -1,6 +1,7 @@ import * as React from 'react' import { useRouter } from '../hooks/useRouter' import { useRouterStore } from '../hooks/useRouterStore' +import NotFound from './NotFound' export function Matches(): JSX.Element | undefined { const matchId = useRouterStore.getState().matches[0]?.id @@ -26,6 +27,10 @@ const Match = React.memo(function ({ id }: MatchProps) { const route = router.routesById[location?.pathname] + if (!route) { + return + } + if (route.options.hasHandler) { console.log('Has rust handler') } diff --git a/packages/tuono-router/src/components/NotFound.tsx b/packages/tuono-router/src/components/NotFound.tsx new file mode 100644 index 00000000..0dd52982 --- /dev/null +++ b/packages/tuono-router/src/components/NotFound.tsx @@ -0,0 +1,18 @@ +import { useRouter } from '../hooks/useRouter' +import Link from './Link' + +export default function NotFound(): JSX.Element { + const router = useRouter() + + // Check if exists a custom 404 error page + if (router.routesById['/404']) { + return router.routesById['/404'].options.component() + } + + return ( + <> +

404 Not found

+ Return home + + ) +} diff --git a/packages/tuono-router/src/router.ts b/packages/tuono-router/src/router.ts index 2f7d95e1..8ec2f5f1 100644 --- a/packages/tuono-router/src/router.ts +++ b/packages/tuono-router/src/router.ts @@ -1,9 +1,19 @@ -import { trimPath, trimPathRight, trimPathLeft, parsePathname } from './utils' +import { trimPath, trimPathRight } from './utils' import type { Route } from './route' +import type { ReactNode } from 'react' + +type RouteTree = any interface CreateRouter { - routeTree: any + routeTree: RouteTree basePath?: string + options: RouteOptions +} + +interface RouteOptions { + component?: ReactNode + hasHandler?: boolean + routeTree?: RouteTree } export type RouterType = any @@ -12,13 +22,14 @@ export function createRouter(options: CreateRouterArgs): Router { } export class Router { - options: any + options?: RouteOptions basePath = '/' routeTree: any history: any isServer = typeof document === 'undefined' - routesById = {} - routesByPath = {} + routesById: Record = {} + // Not used + routesByPath: Record = {} flatRoutes: any constructor(options: CreateRouter) {