From 615fe4606f3e1f1d728a2362fdbbd12f47fc57fa Mon Sep 17 00:00:00 2001 From: Aris Ripandi Date: Thu, 30 Jan 2025 02:03:56 +0700 Subject: [PATCH] feat: custom error component --- app/components/base-ui/index.ts | 1 + app/components/base-ui/link/link.tsx | 48 +++++++++++++++++++ app/components/errors/boundary.tsx | 55 ++++++++++++++++++++++ app/components/errors/error.css.ts | 37 +++++++++++++++ app/root.tsx | 29 +++++------- app/routes.ts | 7 ++- app/routes/healthz.ts | 40 ++++++++++++++++ app/welcome/welcome.tsx | 69 +++++++++++++--------------- 8 files changed, 231 insertions(+), 55 deletions(-) create mode 100644 app/components/base-ui/link/link.tsx create mode 100644 app/components/errors/boundary.tsx create mode 100644 app/components/errors/error.css.ts create mode 100644 app/routes/healthz.ts diff --git a/app/components/base-ui/index.ts b/app/components/base-ui/index.ts index 6c80226..f08372e 100644 --- a/app/components/base-ui/index.ts +++ b/app/components/base-ui/index.ts @@ -1 +1,2 @@ export * from './button/button' +export * from './link/link' diff --git a/app/components/base-ui/link/link.tsx b/app/components/base-ui/link/link.tsx new file mode 100644 index 0000000..d8464ab --- /dev/null +++ b/app/components/base-ui/link/link.tsx @@ -0,0 +1,48 @@ +/** + * A custom Link component that extends the functionality of the React Router Link component. + * It adds support for opening links in a new tab and applies a consistent set of styles. + * + * @param props - The props for the Link component, including the standard Link props from React Router. + * @param props.newTab - Whether to open the link in a new tab. + * @param props.className - Additional CSS classes to apply to the link. + * @param ref - A ref to the underlying anchor element. + * @returns A React Router Link component with the custom functionality and styles applied. + * + * Example usage: + * ```tsx + * Link Text + * ``` + */ + +import type React from 'react' +import { forwardRef } from 'react' +import { Link as RouterLink, type LinkProps as RouterLinkProps } from 'react-router' +import { clx } from '#/libs/utils' + +interface LinkProps extends Omit { + href: string + newTab?: boolean +} + +const Link = forwardRef(function Component( + props: LinkProps & React.ComponentPropsWithoutRef<'a'>, + ref: React.ForwardedRef +) { + const { className, newTab, ...rest } = props + const NEW_TAB_REL = 'noopener noreferrer' + const NEW_TAB_TARGET = '_blank' + const DEFAULT_TARGET = '_self' + + return ( + + ) +}) + +export { Link } diff --git a/app/components/errors/boundary.tsx b/app/components/errors/boundary.tsx new file mode 100644 index 0000000..0fd8b6d --- /dev/null +++ b/app/components/errors/boundary.tsx @@ -0,0 +1,55 @@ +import { useNavigate } from 'react-router' +import { Link } from '#/components/base-ui' +import { errorStyles } from './error.css' + +interface InternalErrorProps { + message: string + details: string + stack: string | undefined + statusCode: number +} + +export default function InternalError({ message, details, stack, statusCode }: InternalErrorProps) { + const navigate = useNavigate() + + const handleBack = () => { + if (window.history.length > 1) { + navigate(-1) + } else { + navigate('/') + } + } + + return ( +
+
+
+
+
+
+
+

{statusCode}

+
+
+
+

{statusCode}

+

{message}

+

{details}

+ {stack && ( +
+              {stack}
+            
+ )} +
+ + + Troubleshooting Guide + +
+
+
+
+ ) +} diff --git a/app/components/errors/error.css.ts b/app/components/errors/error.css.ts new file mode 100644 index 0000000..fde9fb3 --- /dev/null +++ b/app/components/errors/error.css.ts @@ -0,0 +1,37 @@ +export const errorStyles = { + wrapper: 'relative min-h-screen bg-gray-50 dark:bg-gray-950 overflow-hidden', + decorativeGradient: 'absolute inset-0 overflow-hidden', + gradientInner: 'absolute -inset-[10px] opacity-50', + gradientBg: [ + 'absolute top-0 h-[40rem] w-full', + 'bg-gradient-to-b from-gray-500/20 via-transparent to-transparent dark:from-gray-900/30 dark:via-transparent dark:to-transparent', + 'before:absolute before:inset-0 before:bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] before:from-gray-400/10 dark:before:from-gray-500/10 before:via-transparent before:to-transparent', + 'after:absolute after:inset-0 after:bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] after:from-indigo-400/10 dark:after:from-indigo-500/10 after:via-transparent after:to-transparent', + ].join(' '), + content: + 'relative flex min-h-screen flex-col items-center justify-center px-4 py-16 sm:px-6 lg:px-8', + container: 'relative z-20 text-center', + errorCode: 'text-2xl font-bold text-red-500 dark:text-red-400', + title: 'mt-4 text-3xl font-bold tracking-tight text-gray-900 dark:text-gray-100 sm:text-5xl', + description: 'mt-6 text-base leading-7 text-gray-600 dark:text-gray-400', + actions: 'mt-10 flex items-center justify-center gap-x-4', + primaryButton: [ + 'min-w-[140px] rounded-lg bg-gray-900 px-4 py-2.5 text-sm cursor-pointer font-semibold text-white', + 'transition-all duration-200 hover:bg-gray-800 hover:shadow-lg hover:shadow-gray-500/20', + 'focus:outline-hidden focus:ring-2 focus:ring-gray-400/50 focus:ring-offset-2', + 'focus:ring-offset-gray-50 dark:focus:ring-offset-gray-950', + ].join(' '), + secondaryButton: [ + 'min-w-[140px] rounded-lg border border-gray-200 dark:border-gray-800 bg-white/80 dark:bg-gray-900/80 px-4 py-2.5', + 'text-sm cursor-pointer font-semibold text-gray-700 dark:text-gray-200', + 'transition-all duration-200 hover:bg-gray-50 dark:hover:bg-gray-800 hover:border-gray-500/30', + 'hover:text-gray-500 dark:hover:text-gray-400 hover:shadow-lg hover:shadow-gray-500/10', + 'focus:outline-hidden focus:ring-2 focus:ring-gray-400/50 focus:ring-offset-2', + 'focus:ring-offset-gray-50 dark:focus:ring-offset-gray-950', + ].join(' '), + decorativeCode: + 'fixed inset-0 flex items-center justify-center z-10 pointer-events-none select-none', + decorativeText: + 'text-[12rem] sm:text-[16rem] md:text-[20rem] font-black text-red-100/30 dark:text-red-900/20 mix-blend-overlay', + pre: 'mt-6 w-full overflow-x-auto rounded-md border bg-background/80 p-4 font-mono text-sm', +} as const diff --git a/app/root.tsx b/app/root.tsx index 023efd4..70fd698 100644 --- a/app/root.tsx +++ b/app/root.tsx @@ -3,17 +3,19 @@ import './styles/fontface.css' import './styles/globals.css' import './styles/colors.css' +import * as React from 'react' import { Links, Meta, Outlet, Scripts, ScrollRestoration } from 'react-router' import { isRouteErrorResponse } from 'react-router' +import InternalError from '#/components/errors/boundary' import type { Route } from './+types/root' export const links: Route.LinksFunction = () => [ { rel: 'preconnect', href: 'https://cdn.jsdelivr.net' }, ] -export function Layout({ children }: { children: React.ReactNode }) { +export function Layout({ children }: React.PropsWithChildren) { return ( - + @@ -35,27 +37,20 @@ export default function App() { export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { let message = 'Oops!' - let details = 'An unexpected error occurred.' + let details = 'Something went wrong on our end. Please try again later.' let stack: string | undefined + let statusCode = 500 if (isRouteErrorResponse(error)) { - message = error.status === 404 ? '404' : 'Error' - details = - error.status === 404 ? 'The requested page could not be found.' : error.statusText || details + const msgNotFound = 'The requested page could not be found.' + message = error.status === 404 ? 'Page not found' : 'Something went wrong' + details = error.status === 404 ? msgNotFound : error.statusText || details + statusCode = error.status } else if (import.meta.env.DEV && error && error instanceof Error) { details = error.message stack = error.stack + statusCode = 500 } - return ( -
-

{message}

-

{details}

- {stack && ( -
-          {stack}
-        
- )} -
- ) + return } diff --git a/app/routes.ts b/app/routes.ts index f8effb3..cacc870 100644 --- a/app/routes.ts +++ b/app/routes.ts @@ -1,3 +1,8 @@ +/* @ref: https://reactrouter.com/start/framework/routing */ + import { type RouteConfig, index } from '@react-router/dev/routes' -export default [index('routes/home.tsx')] satisfies RouteConfig +export default [ + index('./routes/home.tsx'), + // route('/healthz', './routes/healthz.ts'), +] satisfies RouteConfig diff --git a/app/routes/healthz.ts b/app/routes/healthz.ts new file mode 100644 index 0000000..6cc84ba --- /dev/null +++ b/app/routes/healthz.ts @@ -0,0 +1,40 @@ +import {} from '@react-router/node' +import consola from 'consola' +import { LoaderFunctionArgs } from 'react-router' +// import { getRequestIpAddress } from '#/utils/request.server' + +export async function loader({ request }: LoaderFunctionArgs) { + const host = request.headers.get('X-Forwarded-Host') ?? request.headers.get('host') + const url = new URL('/', `http://${host}`) + + // TODO: put some real logic here + // if we can connect to the database and make a simple query + // and make a HEAD request to ourselves, then we're good. + + try { + await Promise.all([ + fetch(url.toString(), { method: 'HEAD' }).then((r) => { + if (!r.ok) return Promise.reject(r) + }), + ]) + + const flyRegion = process.env.FLY_REGION + const flyMachineId = process.env.FLY_MACHINE_ID + const flyRequestId = request.headers.get('Fly-Request-Id') + const serviceId = `${flyRegion}::${flyMachineId}::${flyRequestId}` + const clientIpAddr = request.headers.get('X-Client-IP') + const isHostedOnFly = flyRegion && flyMachineId + + const responsePayload = { + status: '🫡 All is well!', + id: isHostedOnFly ? serviceId : host, + ip: clientIpAddr, + } + + // return json(responsePayload, { status: 200, headers: { 'Cache-Control': 'no-store' } }) + return responsePayload + } catch (error: unknown) { + consola.error('healthcheck ❌', { error }) + return new Response('Unhealthy', { status: 500, headers: { 'Cache-Control': 'no-store' } }) + } +} diff --git a/app/welcome/welcome.tsx b/app/welcome/welcome.tsx index 8d5360f..682fc2e 100644 --- a/app/welcome/welcome.tsx +++ b/app/welcome/welcome.tsx @@ -1,43 +1,7 @@ -import { Button } from '#/components/base-ui' +import { Button, Link } from '#/components/base-ui' import logoDark from './logo-dark.svg' import logoLight from './logo-light.svg' -export function Welcome({ message }: { message: string }) { - return ( -
-
-
-

{message}

-
- React Router - React Router -
-
- -
-
- ) -} - const resources = [ { href: 'https://reactrouter.com/docs', @@ -79,3 +43,34 @@ const resources = [ ), }, ] + +export function Welcome({ message }: { message: string }) { + return ( +
+
+
+

{message}

+
+ React Router + React Router +
+
+ +
+
+ ) +}