Skip to content
Myr

components.ts

This file

Path

src/jsx/components.ts

257 lines · 8.8 KiB · TypeScript

Last changed by

chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2

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–3why, one step back
1import { raw } from '../helper/html'
2import type { HtmlEscapedCallback, HtmlEscapedString } from '../utils/html'3import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'

chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2

line 4why, one step back
4import type { Child, FC, PropsWithChildren } from './'

Merge commit from forkTaku Amanobefore adoption2b8ed40

line 5why, one step back
5import { jsx, Fragment, isUntrustedObject, renderChildren, renderUntrustedObject } from './base'

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 6why, one step back
6import { DOM_RENDERER } from './constants'

Merge commit from forkTaku Amanobefore adoptionfab3b13

line 7why, one step back
7import { captureRenderContext, useContext } from './context'

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 8–15why, one step back
8import { ErrorBoundary as ErrorBoundaryDomRenderer } from './dom/components'
9import type { HasRenderToDom } from './dom/render'10import { StreamingContext } from './streaming'1112let errorBoundaryCounter = 01314export const childrenToString = async (children: Child[]): Promise<HtmlEscapedString[]> => {15 try {

Merge commit from forkTaku Amanobefore adoption2b8ed40

line 16why, one step back
16 return children.flat().map(resolveChildEarly) as HtmlEscapedString[]

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 17–18why, one step back
17 } catch (e) {
18 if (e instanceof Promise) {

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 19–21why, one step back
19 // Capture before `await`: on the fallback path the render context is
20 // only observable during this synchronous window.21 const resume = captureRenderContext()

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 22why, one step back
22 await e

Merge commit from forkTaku Amanobefore adoptionfab3b13

line 23why, one step back
23 return resume(() => childrenToString(children))

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 24–29why, one step back
24 } else {
25 throw e26 }27 }28}29

Merge commit from forkTaku Amanobefore adoption2b8ed40

lines 30–31why, one step back
30const resolveChildEarly = (child: Child): HtmlEscapedString | Promise<HtmlEscapedString> => {
31 if (child == null || typeof child === 'boolean') {

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 32why, one step back
32 return '' as HtmlEscapedString

Merge commit from forkTaku Amanobefore adoption2b8ed40

lines 33–36why, one step back
33 } else if (typeof child === 'string' || Array.isArray(child)) {
34 return renderChildren([child])35 } else if (isUntrustedObject(child)) {36 return renderUntrustedObject(child)

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 37why, one step back
37 } else {

Merge commit from forkTaku Amanobefore adoption2b8ed40

lines 38–39why, one step back
38 const str = child.toString()
39 return str instanceof Promise ? (str as Promise<HtmlEscapedString>) : raw(str)

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 40–67why, one step back
40 }
41}4243export type ErrorHandler = (error: Error) => void44export type FallbackRender = (error: Error) => Child4546/**47 * @experimental48 * `ErrorBoundary` is an experimental feature.49 * The API might be changed.50 */51export const ErrorBoundary: FC<52 PropsWithChildren<{53 fallback?: Child54 fallbackRender?: FallbackRender55 onError?: ErrorHandler56 }>57> = async ({ children, fallback, fallbackRender, onError }) => {58 if (!children) {59 return raw('')60 }6162 if (!Array.isArray(children)) {63 children = [children]64 }6566 const nonce = useContext(StreamingContext)?.scriptNonce67

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 68–74why, one step back
68 let resume: ReturnType<typeof captureRenderContext> | undefined
69 const getResume = () => (resume ||= captureRenderContext())7071 let fallbackStrPromise: Promise<HtmlEscapedString | string | undefined> | undefined72 const resolveFallbackStr = (): Promise<HtmlEscapedString | string | undefined> =>73 (fallbackStrPromise ||= (async () => {74 const awaitedFallback = await fallback

Merge commit from forkTaku Amanobefore adoption2b8ed40

lines 75–76why, one step back
75 if (awaitedFallback === null || awaitedFallback === undefined) {
76 return

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 77why, one step back
77 }

Merge commit from forkTaku Amanobefore adoption2b8ed40

lines 78–89why, one step back
78 if (typeof awaitedFallback === 'string' || Array.isArray(awaitedFallback)) {
79 return getResume()(() => renderChildren([awaitedFallback]))80 }81 if (isUntrustedObject(awaitedFallback)) {82 return getResume()(() => renderUntrustedObject(awaitedFallback))83 }84 const fallbackResult = await getResume()(() => awaitedFallback.toString())85 return raw(86 fallbackResult,87 (fallbackResult as HtmlEscapedString).callbacks ||88 (awaitedFallback as unknown as HtmlEscapedString).callbacks89 )

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 90–99why, one step back
90 })())
91 const renderFallback = async (error: Error): Promise<HtmlEscapedString> => {92 const fallbackStr = await resolveFallbackStr()93 return getResume()(async () => {94 onError?.(error)95 const fallbackRes = (96 fallbackStr !== undefined97 ? fallbackStr98 : (fallbackRender && jsx(Fragment, {}, fallbackRender(error) as HtmlEscapedString)) || ''99 ) as HtmlEscapedString

Merge commit from forkTaku Amanobefore adoption2b8ed40

line 100why, one step back
100 const fallbackResString = await Fragment({ children: fallbackRes }).toString()

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 101–105why, one step back
101 return raw(
102 fallbackResString,103 (fallbackResString as HtmlEscapedString).callbacks || fallbackRes.callbacks104 )105 })

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 106–110why, one step back
106 }
107 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []108 try {109 resArray = children.map(resolveChildEarly) as unknown as HtmlEscapedString[]110 } catch (e) {

Merge commit from forkTaku Amanobefore adoptionfab3b13

line 111why, one step back
111 const resume = getResume()

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 112–113why, one step back
112 if (e instanceof Promise) {
113 resArray = [

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 114–116why, one step back
114 e
115 .then(() => resume(() => childrenToString(children as Child[])))116 .catch((e) => renderFallback(e)),

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 117–118why, one step back
117 ] as Promise<HtmlEscapedString[]>[]
118 } else {

Merge commit from forkTaku Amanobefore adoptionfab3b13

line 119why, one step back
119 resArray = [await renderFallback(e as Error)]

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 120–123why, one step back
120 }
121 }122123 if (resArray.some((res) => (res as {}) instanceof Promise)) {

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 124–127why, one step back
124 // Prime the context capture while still synchronous: a child that returned
125 // a Promise from `resolveChildEarly` skipped the `catch`, so the deferred126 // `catchCallback` would otherwise capture too late.127 getResume()

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 128why, one step back
128 const index = errorBoundaryCounter++

fix(jsx): replace Suspense and ErrorBoundary content across newlines (#5380)Neil Daquioagbefore adoptioncb5bea3

line 129why, one step back
129 const replaceRe = RegExp(`(<template id="E:${index}"></template>)(.*?)(<!--E:${index}-->)`, 's')

Merge commit from forkTaku Amanobefore adoptionfab3b13

line 130why, one step back
130 let caught = false

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 131–134why, one step back
131 const catchCallback = async ({ error, buffer }: { error: Error; buffer?: [string] }) => {
132 if (caught) {133 return ''134 }

Merge commit from forkTaku Amanobefore adoptionfab3b13

line 135why, one step back
135 caught = true

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 136why, one step back
136

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 137–138why, one step back
137 const fallbackResString = await renderFallback(error)
138 const fallbackCallbacks = fallbackResString.callbacks

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 139why, one step back
139 if (buffer) {

Merge commit from forkTaku Amanobefore adoption2b8ed40

line 140why, one step back
140 buffer[0] = buffer[0].replace(replaceRe, () => fallbackResString)

Merge commit from forkTaku Amanobefore adoptionfab3b13

line 141why, one step back
141 return fallbackCallbacks?.length ? raw('', fallbackCallbacks) : ''

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 142why, one step back
142 }

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 143–144why, one step back
143 return raw(
144 `<template data-hono-target="E:${index}">${fallbackResString}</template><script>

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 145–151why, one step back
145((d,c,n) => {
146c=d.currentScript.previousSibling147d=d.getElementById('E:${index}')148if(!d)return149do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='E:${index}')150d.replaceWith(c.content)151})(document)

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 152–154why, one step back
152</script>`,
153 fallbackCallbacks154 )

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 155–185why, one step back
155 }
156157 let error: unknown158 const promiseAll = Promise.all(resArray).catch((e) => (error = e))159 return raw(`<template id="E:${index}"></template><!--E:${index}-->`, [160 ({ phase, buffer, context }) => {161 if (phase === HtmlEscapedCallbackPhase.BeforeStream) {162 return163 }164 return promiseAll165 .then(async (htmlArray: HtmlEscapedString[]) => {166 if (error) {167 throw error168 }169 htmlArray = htmlArray.flat()170 const content = htmlArray.join('')171 let html = buffer172 ? ''173 : `<template data-hono-target="E:${index}">${content}</template><script${174 nonce ? ` nonce="${nonce}"` : ''175 }>176((d,c) => {177c=d.currentScript.previousSibling178d=d.getElementById('E:${index}')179if(!d)return180d.parentElement.insertBefore(c.content,d.nextSibling)181})(document)182</script>`183184 if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {185 if (buffer) {

Merge commit from forkTaku Amanobefore adoption2b8ed40

line 186why, one step back
186 buffer[0] = buffer[0].replace(replaceRe, () => content)

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 187–257why, one step back
187 }
188 return html189 }190191 if (buffer) {192 buffer[0] = buffer[0].replace(193 replaceRe,194 (_all, pre, _, post) => `${pre}${content}${post}`195 )196 }197198 const callbacks = htmlArray199 .map((html) => (html as HtmlEscapedString).callbacks || [])200 .flat()201202 if (phase === HtmlEscapedCallbackPhase.Stream) {203 html = await resolveCallback(204 html,205 HtmlEscapedCallbackPhase.BeforeStream,206 true,207 context208 )209 }210211 let resolvedCount = 0212 const promises = callbacks.map<HtmlEscapedCallback>(213 (c) =>214 (...args) =>215 c(...args)216 ?.then((content) => {217 resolvedCount++218219 if (buffer) {220 if (resolvedCount === callbacks.length) {221 buffer[0] = buffer[0].replace(replaceRe, (_all, _pre, content) => content)222 }223 buffer[0] += content224 return raw('', (content as HtmlEscapedString).callbacks)225 }226227 return raw(228 content +229 (resolvedCount !== callbacks.length230 ? ''231 : `<script>232((d,c,n) => {233d=d.getElementById('E:${index}')234if(!d)return235n=d.nextSibling236while(n.nodeType!=8||n.nodeValue!='E:${index}'){n=n.nextSibling}237n.remove()238d.remove()239})(document)240</script>`),241 (content as HtmlEscapedString).callbacks242 )243 })244 .catch((error) => catchCallback({ error, buffer }))245 )246247 // eslint-disable-next-line @typescript-eslint/no-explicit-any248 return raw(html, promises as any)249 })250 .catch((error) => catchCallback({ error, buffer }))251 },252 ])253 } else {254 return Fragment({ children: resArray as Child[] })255 }256}257;(ErrorBoundary as HasRenderToDom)[DOM_RENDERER] = ErrorBoundaryDomRenderer