Skip to content
Myr

components.ts

This file

Path

src/jsx/components.ts

231 lines · 7.3 KiB · TypeScript

Last changed by

Merge commit from forkTaku Amanobefore adoption2cf6004

History of this file

Take it

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

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 1–3why, one step back
1import { raw } from '../helper/html'
2import type { HtmlEscapedCallback, HtmlEscapedString } from '../utils/html'3import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'

Merge commit from forkTaku Amanobefore adoption2cf6004

line 4why, one step back
4import { jsx, Fragment } from './base'

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 5–28why, one step back
5import { DOM_RENDERER } from './constants'
6import { useContext } from './context'7import { ErrorBoundary as ErrorBoundaryDomRenderer } from './dom/components'8import type { HasRenderToDom } from './dom/render'9import { StreamingContext } from './streaming'10import type { Child, FC, PropsWithChildren } from './'1112let errorBoundaryCounter = 01314export const childrenToString = async (children: Child[]): Promise<HtmlEscapedString[]> => {15 try {16 return children17 .flat()18 .map((c) => (c == null || typeof c === 'boolean' ? '' : c.toString())) as HtmlEscapedString[]19 } catch (e) {20 if (e instanceof Promise) {21 await e22 return childrenToString(children)23 } else {24 throw e25 }26 }27}28

Merge commit from forkTaku Amanobefore adoption2cf6004

lines 29–43why, one step back
29const resolveChildEarly = (c: Child): HtmlEscapedString | Promise<HtmlEscapedString> => {
30 if (c == null || typeof c === 'boolean') {31 return '' as HtmlEscapedString32 } else if (typeof c === 'string') {33 return c as HtmlEscapedString34 } else {35 const str = c.toString()36 if (!(str instanceof Promise)) {37 return raw(str)38 } else {39 return str as Promise<HtmlEscapedString>40 }41 }42}43

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 44–69why, one step back
44export type ErrorHandler = (error: Error) => void
45export type FallbackRender = (error: Error) => Child4647/**48 * @experimental49 * `ErrorBoundary` is an experimental feature.50 * The API might be changed.51 */52export const ErrorBoundary: FC<53 PropsWithChildren<{54 fallback?: Child55 fallbackRender?: FallbackRender56 onError?: ErrorHandler57 }>58> = async ({ children, fallback, fallbackRender, onError }) => {59 if (!children) {60 return raw('')61 }6263 if (!Array.isArray(children)) {64 children = [children]65 }6667 const nonce = useContext(StreamingContext)?.scriptNonce6869 let fallbackStr: string | undefined

Merge commit from forkTaku Amanobefore adoption2cf6004

lines 70–82why, one step back
70 const resolveFallbackStr = async () => {
71 const awaitedFallback = await fallback72 if (typeof awaitedFallback === 'string') {73 fallbackStr = awaitedFallback74 } else {75 fallbackStr = await awaitedFallback?.toString()76 if (typeof fallbackStr === 'string') {77 // should not apply `raw` if fallbackStr is undefined, null, or boolean78 fallbackStr = raw(fallbackStr)79 }80 }81 }82 const fallbackRes = (error: Error): HtmlEscapedString | Promise<HtmlEscapedString> => {

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

line 83why, one step back
83 onError?.(error)

Merge commit from forkTaku Amanobefore adoption2cf6004

lines 84–86why, one step back
84 return (fallbackStr ||
85 (fallbackRender && jsx(Fragment, {}, fallbackRender(error) as HtmlEscapedString)) ||86 '') as HtmlEscapedString

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 87–89why, one step back
87 }
88 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []89 try {

Merge commit from forkTaku Amanobefore adoption2cf6004

line 90why, one step back
90 resArray = children.map(resolveChildEarly) as unknown as HtmlEscapedString[]

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

line 91why, one step back
91 } catch (e) {

Merge commit from forkTaku Amanobefore adoption2cf6004

line 92why, one step back
92 await resolveFallbackStr()

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 93–97why, one step back
93 if (e instanceof Promise) {
94 resArray = [95 e.then(() => childrenToString(children as Child[])).catch((e) => fallbackRes(e)),96 ] as Promise<HtmlEscapedString[]>[]97 } else {

Merge commit from forkTaku Amanobefore adoption2cf6004

line 98why, one step back
98 resArray = [fallbackRes(e as Error) as HtmlEscapedString]

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 99–102why, one step back
99 }
100 }101102 if (resArray.some((res) => (res as {}) instanceof Promise)) {

Merge commit from forkTaku Amanobefore adoption2cf6004

line 103why, one step back
103 await resolveFallbackStr()

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 104–106why, one step back
104 const index = errorBoundaryCounter++
105 const replaceRe = RegExp(`(<template id="E:${index}"></template>.*?)(.*?)(<!--E:${index}-->)`)106 const caught = false

Merge commit from forkTaku Amanobefore adoption2cf6004

line 107why, one step back
107 const catchCallback = async ({ error, buffer }: { error: Error; buffer?: [string] }) => {

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 108–111why, one step back
108 if (caught) {
109 return ''110 }111

Merge commit from forkTaku Amanobefore adoption2cf6004

lines 112–114why, one step back
112 const fallbackResString = await Fragment({
113 children: fallbackRes(error),114 }).toString()

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 115–227why, one step back
115 if (buffer) {
116 buffer[0] = buffer[0].replace(replaceRe, fallbackResString)117 }118 return buffer119 ? ''120 : `<template data-hono-target="E:${index}">${fallbackResString}</template><script>121((d,c,n) => {122c=d.currentScript.previousSibling123d=d.getElementById('E:${index}')124if(!d)return125do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='E:${index}')126d.replaceWith(c.content)127})(document)128</script>`129 }130131 let error: unknown132 const promiseAll = Promise.all(resArray).catch((e) => (error = e))133 return raw(`<template id="E:${index}"></template><!--E:${index}-->`, [134 ({ phase, buffer, context }) => {135 if (phase === HtmlEscapedCallbackPhase.BeforeStream) {136 return137 }138 return promiseAll139 .then(async (htmlArray: HtmlEscapedString[]) => {140 if (error) {141 throw error142 }143 htmlArray = htmlArray.flat()144 const content = htmlArray.join('')145 let html = buffer146 ? ''147 : `<template data-hono-target="E:${index}">${content}</template><script${148 nonce ? ` nonce="${nonce}"` : ''149 }>150((d,c) => {151c=d.currentScript.previousSibling152d=d.getElementById('E:${index}')153if(!d)return154d.parentElement.insertBefore(c.content,d.nextSibling)155})(document)156</script>`157158 if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {159 if (buffer) {160 buffer[0] = buffer[0].replace(replaceRe, content)161 }162 return html163 }164165 if (buffer) {166 buffer[0] = buffer[0].replace(167 replaceRe,168 (_all, pre, _, post) => `${pre}${content}${post}`169 )170 }171172 const callbacks = htmlArray173 .map((html) => (html as HtmlEscapedString).callbacks || [])174 .flat()175176 if (phase === HtmlEscapedCallbackPhase.Stream) {177 html = await resolveCallback(178 html,179 HtmlEscapedCallbackPhase.BeforeStream,180 true,181 context182 )183 }184185 let resolvedCount = 0186 const promises = callbacks.map<HtmlEscapedCallback>(187 (c) =>188 (...args) =>189 c(...args)190 ?.then((content) => {191 resolvedCount++192193 if (buffer) {194 if (resolvedCount === callbacks.length) {195 buffer[0] = buffer[0].replace(replaceRe, (_all, _pre, content) => content)196 }197 buffer[0] += content198 return raw('', (content as HtmlEscapedString).callbacks)199 }200201 return raw(202 content +203 (resolvedCount !== callbacks.length204 ? ''205 : `<script>206((d,c,n) => {207d=d.getElementById('E:${index}')208if(!d)return209n=d.nextSibling210while(n.nodeType!=8||n.nodeValue!='E:${index}'){n=n.nextSibling}211n.remove()212d.remove()213})(document)214</script>`),215 (content as HtmlEscapedString).callbacks216 )217 })218 .catch((error) => catchCallback({ error, buffer }))219 )220221 // eslint-disable-next-line @typescript-eslint/no-explicit-any222 return raw(html, promises as any)223 })224 .catch((error) => catchCallback({ error, buffer }))225 },226 ])227 } else {

Merge commit from forkTaku Amanobefore adoption2cf6004

line 228why, one step back
228 return Fragment({ children: resArray as Child[] })

chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda

lines 229–231why, one step back
229 }
230}231;(ErrorBoundary as HasRenderToDom)[DOM_RENDERER] = ErrorBoundaryDomRenderer