Skip to content
Myr

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 file

Take it

1import { 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'5import {6  captureRenderContext,7  createContext,8  globalContexts,9  runWithRenderContext,10  useContext,11} from './context'12import type { Context } from './context'13import { domRenderers } from './intrinsic-element/common'14import * as intrinsicElementTags from './intrinsic-element/components'15import type { JSX as HonoJSX } from './intrinsic-elements'16import {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>25type FunctionComponentResult =26  | HtmlEscapedString27  | JSXNode28  | Child[]29  | Promise<HtmlEscapedString | JSXNode | Child[]>30  | null31export type FC<P = Props> = {32  (props: P): FunctionComponentResult33  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>41  export type ElementType = string | ((props: never) => FunctionComponentResult)42  export interface ElementChildrenAttribute {43    children: Child44  }45  // `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 {48    [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]113114type SuspendedContext = <T>(callback: () => T) => T115116const resolveFunctionComponentResult = (117  result: Promise<string | JSXNode | Child[]>,118  suspendedContext?: SuspendedContext119): Promise<string> =>120  result.then((resolved) => {121    if (122      typeof resolved !== 'string' &&123      !Array.isArray(resolved) &&124      !(resolved instanceof JSXNode)125    ) {126      return resolved127    }128    const children = Array.isArray(resolved) ? resolved : [resolved as Child]129    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  })138139const 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)148    } else if (typeof child === 'number') {149      ;(buffer[0] as string) += child150    } 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      }157    } 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[]175176export 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}201202export 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> {228    const render = () => {229      const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks230      this.toStringToBuffer(buffer)231      return buffer.length === 1232        ? 'callbacks' in buffer233          ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString()234          : buffer[0]235        : stringBufferToString(buffer, buffer.callbacks)236    }237    return runWithRenderContext(render)238  }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) {331        buffer.unshift('', resolveFunctionComponentResult(res))332      } else {333        // save the current context state for resuming the suspended subtree334        buffer.unshift('', resolveFunctionComponentResult(res, captureRenderContext()))335      }336    } else if (res instanceof JSXNode) {337      res.toStringToBuffer(buffer)338    } else if (Array.isArray(res)) {339      childrenToStringToBuffer(res, buffer)340    } 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> => {441  const wrapper: MemorableFC<T> = ((props: T) => component(props)) as MemorableFC<T>442443  // 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'