Skip to content
Myr

index.ts

This file

Path

src/middleware/jsx-renderer/index.ts

163 lines · 4.5 KiB · TypeScript

Last changed by

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–21why, one step back
1/**
2 * @module3 * JSX Renderer Middleware for Hono.4 */56/* eslint-disable @typescript-eslint/no-explicit-any */7import type { Context, PropsForRenderer } from '../../context'8import { html, raw } from '../../helper/html'9import { Fragment, createContext, jsx, useContext } from '../../jsx'10import type { FC, Context as JSXContext, JSXNode, PropsWithChildren } from '../../jsx'11import { renderToReadableStream } from '../../jsx/streaming'12import type { Env, Input, MiddlewareHandler } from '../../types'1314export const RequestContext: JSXContext<Context<any, any, {}> | null> =15 createContext<Context | null>(null)1617type RendererOptions = {18 docType?: boolean | string19 stream?: boolean | Record<string, string>20}21

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 22why, one step back
22type ComponentResult = Exclude<ReturnType<FC>, null>

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 23why, one step back
23

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 24–25why, one step back
24type Component = (props: PropsForRenderer & { Layout: FC }, c: Context) => ComponentResult
25

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 26–28why, one step back
26type ComponentWithChildren = (
27 props: PropsWithChildren<PropsForRenderer & { Layout: FC }>,28 c: Context

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 29why, one step back
29) => ComponentResult

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 30–163why, one step back
30
31const createRenderer =32 (33 c: Context,34 Layout: FC,35 component?: Component,36 options?: RendererOptions | ((c: Context) => RendererOptions)37 ) =>38 (children: JSXNode, props: PropsForRenderer) => {39 options = typeof options === 'function' ? options(c) : options40 const docType =41 typeof options?.docType === 'string'42 ? options.docType43 : options?.docType === false44 ? ''45 : '<!DOCTYPE html>'4647 const currentLayout = component48 ? jsx(49 (props: any) => component(props, c),50 {51 Layout,52 ...(props as any),53 },54 children as any55 )56 : children5758 const body = html`${raw(docType)}${jsx(59 RequestContext.Provider,60 { value: c },61 currentLayout as any62 )}`6364 if (options?.stream) {65 if (options.stream === true) {66 c.header('Transfer-Encoding', 'chunked')67 c.header('Content-Type', 'text/html; charset=UTF-8')68 c.header('Content-Encoding', 'Identity')69 } else {70 for (const [key, value] of Object.entries(options.stream)) {71 c.header(key, value)72 }73 }74 return c.body(renderToReadableStream(body))75 } else {76 return c.html(body)77 }78 }7980/**81 * JSX Renderer Middleware for hono.82 *83 * @see {@link https://hono.dev/docs/middleware/builtin/jsx-renderer}84 *85 * @param {ComponentWithChildren} [component] - The component to render, which can accept children and props.86 * @param {RendererOptions} [options] - The options for the JSX renderer middleware.87 * @param {boolean | string} [options.docType=true] - The DOCTYPE to be added at the beginning of the HTML. If set to false, no DOCTYPE will be added.88 * @param {boolean | Record<string, string>} [options.stream=false] - If set to true, enables streaming response with default headers. If a record is provided, custom headers will be used.89 * @returns {MiddlewareHandler} The middleware handler function.90 *91 * @example92 * ```ts93 * const app = new Hono()94 *95 * app.get(96 * '/page/*',97 * jsxRenderer(({ children }) => {98 * return (99 * <html>100 * <body>101 * <header>Menu</header>102 * <div>{children}</div>103 * </body>104 * </html>105 * )106 * })107 * )108 *109 * app.get('/page/about', (c) => {110 * return c.render(<h1>About me!</h1>)111 * })112 * ```113 */114export const jsxRenderer = <E extends Env = Env>(115 component?: ComponentWithChildren,116 options?: RendererOptions | ((c: Context<E>) => RendererOptions)117): MiddlewareHandler =>118 function jsxRenderer(c, next) {119 const Layout = (c.getLayout() ?? Fragment) as FC120 if (component) {121 c.setLayout((props) => {122 return component({ ...props, Layout }, c)123 })124 }125 c.setRenderer(createRenderer(c, Layout, component, options) as any)126 return next()127 }128129/**130 * useRequestContext for Hono.131 *132 * @template E - The environment type.133 * @template P - The parameter type.134 * @template I - The input type.135 * @returns {Context<E, P, I>} An instance of Context.136 *137 * @example138 * ```ts139 * const RequestUrlBadge: FC = () => {140 * const c = useRequestContext()141 * return <b>{c.req.url}</b>142 * }143 *144 * app.get('/page/info', (c) => {145 * return c.render(146 * <div>147 * You are accessing: <RequestUrlBadge />148 * </div>149 * )150 * })151 * ```152 */153export const useRequestContext = <154 E extends Env = any,155 P extends string = any,156 I extends Input = {},157>(): Context<E, P, I> => {158 const c = useContext(RequestContext)159 if (!c) {160 throw new Error('RequestContext is not provided.')161 }162 return c163}