base.ts
This file
Path
src/jsx/base.ts
490 lines · 14.3 KiB · TypeScript
Last changed by
fix(jsx): allow JSXNode function component results (#5476)Shaurya Sariabefore adoptionf23b146
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–4why, one step back1import { raw } from '../helper/html'2import { escapeToBuffer, resolveCallbackSync, stringBufferToString } from '../utils/html'3import type { HtmlEscaped, HtmlEscapedString, StringBufferWithCallbacks } from '../utils/html'4import { DOM_RENDERER, DOM_MEMO } from './constants'Merge commit from forkTaku Amanobefore adoptionfab3b13
lines 5–11why, one step back5import {6 captureRenderContext,7 createContext,8 globalContexts,9 runWithRenderContext,10 useContext,11} from './context'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 12–14why, one step back12import type { Context } from './context'13import { domRenderers } from './intrinsic-element/common'14import * as intrinsicElementTags from './intrinsic-element/components'fix(build): keep internal types private in bundled d.ts and avoid a self-referencing JSX.IntrinsicElements (#5485)Yusuke Wadabefore adoptionbe1f749
line 15why, one step back15import type { JSX as HonoJSX } from './intrinsic-elements'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 16–24why, one step back16import {17 isValidAttributeName,18 isValidTagName,19 normalizeIntrinsicElementKey,20 styleObjectForEach,21} from './utils'2223// eslint-disable-next-line @typescript-eslint/no-explicit-any24export type Props = Record<string, any>Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 25–26why, one step back25type FunctionComponentResult =26 | HtmlEscapedStringfix(jsx): allow JSXNode function component results (#5476)Shaurya Sariabefore adoptionf23b146
line 27why, one step back27 | JSXNodeMerge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 28why, one step back28 | Child[]fix(jsx): allow JSXNode function component results (#5476)Shaurya Sariabefore adoptionf23b146
line 29why, one step back29 | Promise<HtmlEscapedString | JSXNode | Child[]>Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 30why, one step back30 | nullMerge commit from forkYusuke Wadabefore adoptionf0b094d
line 31why, one step back31export type FC<P = Props> = {Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 32why, one step back32 (props: P): FunctionComponentResultMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 33–40why, one step back33 defaultProps?: Partial<P> | undefined34 displayName?: string | undefined35}36export type DOMAttributes = HonoJSX.HTMLAttributes3738// eslint-disable-next-line @typescript-eslint/no-namespace39export namespace JSX {40 export type Element = HtmlEscapedString | Promise<HtmlEscapedString>Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 41why, one step back41 export type ElementType = string | ((props: never) => FunctionComponentResult)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 42–44why, one step back42 export interface ElementChildrenAttribute {43 children: Child44 }fix(build): keep internal types private in bundled d.ts and avoid a self-referencing JSX.IntrinsicElements (#5485)Yusuke Wadabefore adoptionbe1f749
lines 45–47why, one step back45 // `HonoJSX.IntrinsicElements`, not the top-level alias: the bundled dts emit renames the namespace46 // import correctly but drops an import alias that collides with this member name (TS2310).47 export interface IntrinsicElements extends HonoJSX.IntrinsicElements {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 48–113why, one step back48 [tagName: string]: Props49 }50 export interface IntrinsicAttributes {51 key?: string | number | bigint | null | undefined52 }53}5455let nameSpaceContext: Context<string> | undefined = undefined56export const getNameSpaceContext = () => nameSpaceContext5758const toSVGAttributeName = (key: string): string =>59 /[A-Z]/.test(key) &&60 // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc.61 // Or other un-deprecated kebab-case attributes. "overline-position", "paint-order", "strikethrough-position", etc.62 key.match(63 /^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/64 )65 ? key.replace(/([A-Z])/g, '-$1').toLowerCase()66 : key6768const emptyTags = [69 'area',70 'base',71 'br',72 'col',73 'embed',74 'hr',75 'img',76 'input',77 'keygen',78 'link',79 'meta',80 'param',81 'source',82 'track',83 'wbr',84]85export const booleanAttributes = [86 'allowfullscreen',87 'async',88 'autofocus',89 'autoplay',90 'checked',91 'controls',92 'default',93 'defer',94 'disabled',95 'download',96 'formnovalidate',97 'hidden',98 'inert',99 'ismap',100 'itemscope',101 'loop',102 'multiple',103 'muted',104 'nomodule',105 'novalidate',106 'open',107 'playsinline',108 'readonly',109 'required',110 'reversed',111 'selected',112]113Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 114–120why, one step back114type SuspendedContext = <T>(callback: () => T) => T115116const resolveFunctionComponentResult = (117 result: Promise<string | JSXNode | Child[]>,118 suspendedContext?: SuspendedContext119): Promise<string> =>120 result.then((resolved) => {Merge commit from forkTaku Amanobefore adoption2b8ed40
lines 121–125why, one step back121 if (122 typeof resolved !== 'string' &&123 !Array.isArray(resolved) &&124 !(resolved instanceof JSXNode)125 ) {Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 126–127why, one step back126 return resolved127 }Merge commit from forkTaku Amanobefore adoption2b8ed40
line 128why, one step back128 const children = Array.isArray(resolved) ? resolved : [resolved as Child]Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 129–138why, one step back129 const render = () => {130 const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks131 childrenToStringToBuffer(children, buffer)132 return buffer.length === 1133 ? raw(buffer[0], buffer.callbacks)134 : stringBufferToString(buffer, buffer.callbacks)135 }136 return suspendedContext ? suspendedContext(render) : runWithRenderContext(render)137 })138Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 139–147why, one step back139const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCallbacks): void => {140 for (let i = 0, len = children.length; i < len; i++) {141 const child = children[i]142 if (typeof child === 'string') {143 escapeToBuffer(child, buffer)144 } else if (typeof child === 'boolean' || child === null || child === undefined) {145 continue146 } else if (child instanceof JSXNode) {147 child.toStringToBuffer(buffer)Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 148why, one step back148 } else if (typeof child === 'number') {Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 149why, one step back149 ;(buffer[0] as string) += childMerge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 150–156why, one step back150 } else if ((child as unknown as HtmlEscaped).isEscaped) {151 ;(buffer[0] as string) += child152 const callbacks = (child as unknown as HtmlEscapedString).callbacks153 if (callbacks) {154 buffer.callbacks ||= []155 buffer.callbacks.push(...callbacks)156 }Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 157–174why, one step back157 } else if (child instanceof Promise) {158 buffer.unshift('', child)159 } else {160 // `child` type is `Child[]`, so stringify recursively161 childrenToStringToBuffer(child, buffer)162 }163 }164}165166export type Child =167 | string168 | Promise<string>169 | number170 | JSXNode171 | null172 | undefined173 | boolean174 | Child[]Merge commit from forkTaku Amanobefore adoption2b8ed40
lines 175–201why, one step back175176export const renderChildren = (children: Child[]): HtmlEscapedString | Promise<HtmlEscapedString> =>177 runWithRenderContext(() => {178 const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks179 childrenToStringToBuffer(children, buffer)180 return buffer.length === 1181 ? raw(buffer[0], buffer.callbacks)182 : stringBufferToString(buffer, buffer.callbacks)183 })184185export const isUntrustedObject = (value: unknown): boolean =>186 typeof value === 'object' &&187 value !== null &&188 !Array.isArray(value) &&189 !(value instanceof JSXNode) &&190 !(value instanceof Promise) &&191 !(value as HtmlEscaped).isEscaped &&192 typeof (value as { toString?: unknown }).toString === 'function'193194export const renderUntrustedObject = (195 value: unknown196): HtmlEscapedString | Promise<HtmlEscapedString> => {197 const stringified = (value as { toString(): unknown }).toString()198 const escape = (result: unknown) => renderChildren([String(result)])199 return stringified instanceof Promise ? stringified.then(escape) : escape(stringified)200}201Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 202–227why, one step back202export class JSXNode implements HtmlEscaped {203 tag: string | Function204 props: Props205 key?: string206 children: Child[]207 isEscaped: true = true as const208 constructor(tag: string | Function, props: Props, children: Child[]) {209 if (typeof tag !== 'function' && !isValidTagName(tag)) {210 throw new Error(`Invalid JSX tag name: ${tag}`)211 }212 this.tag = tag213 this.props = props214 this.children = children215 }216217 get type(): string | Function {218 return this.tag as string219 }220221 // Added for compatibility with libraries that rely on React's internal structure222 // eslint-disable-next-line @typescript-eslint/no-explicit-any223 get ref(): any {224 return this.props.ref || null225 }226227 toString(): string | Promise<string> {Merge commit from forkTaku Amanobefore adoptionfab3b13
lines 228–229why, one step back228 const render = () => {229 const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacksMerge commit from forkYusuke Wadabefore adoptionf0b094d
line 230why, one step back230 this.toStringToBuffer(buffer)Merge commit from forkTaku Amanobefore adoptionfab3b13
lines 231–235why, one step back231 return buffer.length === 1232 ? 'callbacks' in buffer233 ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString()234 : buffer[0]235 : stringBufferToString(buffer, buffer.callbacks)Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 236why, one step back236 }Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 237why, one step back237 return runWithRenderContext(render)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 238–330why, one step back238 }239240 toStringToBuffer(buffer: StringBufferWithCallbacks): void {241 const tag = this.tag as string242 const props = this.props243 let { children } = this244245 buffer[0] += `<${tag}`246247 const normalizeKey: (key: string) => string =248 tag === 'svg' || (nameSpaceContext && useContext(nameSpaceContext) === 'svg')249 ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key))250 : (key) => normalizeIntrinsicElementKey(key)251 for (let [key, v] of Object.entries(props)) {252 key = normalizeKey(key)253 if (!isValidAttributeName(key)) {254 continue255 }256 if (key === 'children') {257 // skip children258 } else if (key === 'style' && typeof v === 'object') {259 // object to style strings260 let styleStr = ''261 styleObjectForEach(v, (property, value) => {262 if (value != null) {263 styleStr += `${styleStr ? ';' : ''}${property}:${value}`264 }265 })266 buffer[0] += ' style="'267 escapeToBuffer(styleStr, buffer)268 buffer[0] += '"'269 } else if (typeof v === 'string') {270 buffer[0] += ` ${key}="`271 escapeToBuffer(v, buffer)272 buffer[0] += '"'273 } else if (v === null || v === undefined) {274 // Do nothing275 } else if (typeof v === 'number' || (v as HtmlEscaped).isEscaped) {276 buffer[0] += ` ${key}="${v}"`277 } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {278 if (v) {279 buffer[0] += ` ${key}=""`280 }281 } else if (key === 'dangerouslySetInnerHTML') {282 if (children.length > 0) {283 throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.')284 }285286 children = [raw(v.__html)]287 } else if (v instanceof Promise) {288 buffer[0] += ` ${key}="`289 buffer.unshift('"', v)290 } else if (typeof v === 'function') {291 if (!key.startsWith('on') && key !== 'ref') {292 throw new Error(`Invalid prop '${key}' of type 'function' supplied to '${tag}'.`)293 }294 // maybe event handler for client components, just ignore in server components295 } else {296 buffer[0] += ` ${key}="`297 escapeToBuffer(v.toString(), buffer)298 buffer[0] += '"'299 }300 }301302 if (emptyTags.includes(tag as string) && children.length === 0) {303 buffer[0] += '/>'304 return305 }306307 buffer[0] += '>'308309 childrenToStringToBuffer(children, buffer)310311 buffer[0] += `</${tag}>`312 }313}314315class JSXFunctionNode extends JSXNode {316 override toStringToBuffer(buffer: StringBufferWithCallbacks): void {317 const { children } = this318319 const props = { ...this.props }320 if (children.length) {321 props.children = children.length === 1 ? children[0] : children322 }323324 const res = (this.tag as Function).call(null, props)325326 if (typeof res === 'boolean' || res == null) {327 // boolean or null or undefined328 return329 } else if (res instanceof Promise) {330 if (globalContexts.length === 0) {Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 331why, one step back331 buffer.unshift('', resolveFunctionComponentResult(res))Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 332why, one step back332 } else {Merge commit from forkTaku Amanobefore adoptionfab3b13
line 333why, one step back333 // save the current context state for resuming the suspended subtreeMerge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 334why, one step back334 buffer.unshift('', resolveFunctionComponentResult(res, captureRenderContext()))Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 335–337why, one step back335 }336 } else if (res instanceof JSXNode) {337 res.toStringToBuffer(buffer)Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 338–339why, one step back338 } else if (Array.isArray(res)) {339 childrenToStringToBuffer(res, buffer)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 340–440why, one step back340 } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {341 buffer[0] += res342 if (res.callbacks) {343 buffer.callbacks ||= []344 buffer.callbacks.push(...res.callbacks)345 }346 } else {347 escapeToBuffer(res, buffer)348 }349 }350}351352export class JSXFragmentNode extends JSXNode {353 override toStringToBuffer(buffer: StringBufferWithCallbacks): void {354 childrenToStringToBuffer(this.children, buffer)355 }356}357358export const jsx = (tag: string | Function, props: Props | null, ...children: Child[]): JSXNode => {359 props ??= {}360 if (children.length) {361 props.children = children.length === 1 ? children[0] : children362 }363364 const key = props.key365 delete props['key']366367 const node = jsxFn(tag, props, children)368 node.key = key369 return node370}371372let initDomRenderer = false373export const jsxFn = (tag: string | Function, props: Props, children: Child[]): JSXNode => {374 if (!initDomRenderer) {375 for (const k in domRenderers) {376 // eslint-disable-next-line @typescript-eslint/no-explicit-any377 ;(intrinsicElementTags[k as keyof typeof intrinsicElementTags] as any)[DOM_RENDERER] =378 domRenderers[k]379 }380 initDomRenderer = true381 }382383 if (typeof tag === 'function') {384 return new JSXFunctionNode(tag, props, children)385 } else if (intrinsicElementTags[tag as keyof typeof intrinsicElementTags]) {386 return new JSXFunctionNode(387 intrinsicElementTags[tag as keyof typeof intrinsicElementTags],388 props,389 children390 )391 } else if (tag === 'svg' || tag === 'head') {392 nameSpaceContext ||= createContext('')393 return new JSXNode(tag, props, [394 new JSXFunctionNode(395 nameSpaceContext,396 {397 value: tag,398 },399 children400 ),401 ])402 } else {403 return new JSXNode(tag, props, children)404 }405}406407export const shallowEqual = (a: Props, b: Props): boolean => {408 if (a === b) {409 return true410 }411412 const aKeys = Object.keys(a).sort()413 const bKeys = Object.keys(b).sort()414 if (aKeys.length !== bKeys.length) {415 return false416 }417418 for (let i = 0, len = aKeys.length; i < len; i++) {419 if (420 aKeys[i] === 'children' &&421 bKeys[i] === 'children' &&422 !a.children?.length &&423 !b.children?.length424 ) {425 continue426 } else if (a[aKeys[i]] !== b[aKeys[i]]) {427 return false428 }429 }430431 return true432}433434export type MemorableFC<T> = FC<T> & {435 [DOM_MEMO]: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean436}437export const memo = <T>(438 component: FC<T>,439 propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual440): FC<T> => {Merge commit from forkYusuke Wadabefore adoption0c45036
line 441why, one step back441 const wrapper: MemorableFC<T> = ((props: T) => component(props)) as MemorableFC<T>Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 442–490why, one step back442443 // This function is for toString(), but it can also be used for DOM renderer.444 // So, set DOM_MEMO and DOM_RENDERER for DOM renderer.445 wrapper[DOM_MEMO] = propsAreEqual446 // eslint-disable-next-line @typescript-eslint/no-explicit-any447 ;(wrapper as any)[DOM_RENDERER] = component448449 return wrapper as FC<T>450}451452export const Fragment = ({453 children,454}: {455 key?: string456 children?: Child | HtmlEscapedString457}): HtmlEscapedString => {458 return new JSXFragmentNode(459 '',460 {461 children,462 },463 Array.isArray(children) ? children : children ? [children] : []464 ) as never465}466467export const isValidElement = (element: unknown): element is JSXNode => {468 return !!(element && typeof element === 'object' && 'tag' in element && 'props' in element)469}470471export const cloneElement = <T extends JSXNode | JSX.Element>(472 element: T,473 props: Partial<Props>,474 ...children: Child[]475): T => {476 let childrenToClone477 if (children.length > 0) {478 childrenToClone = children479 } else {480 const c = (element as JSXNode).props.children481 childrenToClone = Array.isArray(c) ? c : [c]482 }483 return jsx(484 (element as JSXNode).tag,485 { ...(element as JSXNode).props, ...props },486 ...childrenToClone487 ) as T488}489490export const reactAPICompatVersion = '19.0.0-hono-jsx'