base.ts
This file
Path
src/jsx/base.ts
442 lines 路 12.3 KiB 路 TypeScript
Last changed by
fix(jsx): self-close wrapped empty tags (#4511)Jacob Leebefore adoptionc44c5c2
History of this fileTake 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 type { Context } from './context'6import { createContext, globalContexts, useContext } from './context'7import { domRenderers } from './intrinsic-element/common'8import * as intrinsicElementTags from './intrinsic-element/components'9import type {10 JSX as HonoJSX,11 IntrinsicElements as IntrinsicElementsDefined,12} from './intrinsic-elements'13import { normalizeIntrinsicElementKey, styleObjectForEach } from './utils'1415// eslint-disable-next-line @typescript-eslint/no-explicit-any16export type Props = Record<string, any>17export type FC<P = Props> = {18 (props: P): HtmlEscapedString | Promise<HtmlEscapedString> | null19 defaultProps?: Partial<P> | undefined20 displayName?: string | undefined21}22export type DOMAttributes = HonoJSX.HTMLAttributes2324// eslint-disable-next-line @typescript-eslint/no-namespace25export namespace JSX {26 export type Element = HtmlEscapedString | Promise<HtmlEscapedString>27 export interface ElementChildrenAttribute {28 children: Child29 }30 export interface IntrinsicElements extends IntrinsicElementsDefined {31 [tagName: string]: Props32 }33 export interface IntrinsicAttributes {34 key?: string | number | bigint | null | undefined35 }36}3738let nameSpaceContext: Context<string> | undefined = undefined39export const getNameSpaceContext = () => nameSpaceContext4041const toSVGAttributeName = (key: string): string =>42 /[A-Z]/.test(key) &&43 // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc.44 // Or other un-deprecated kebab-case attributes. "overline-position", "paint-order", "strikethrough-position", etc.45 key.match(46 /^(?: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)/47 )48 ? key.replace(/([A-Z])/g, '-$1').toLowerCase()49 : key5051const emptyTags = [52 'area',53 'base',54 'br',55 'col',56 'embed',57 'hr',58 'img',59 'input',60 'keygen',61 'link',62 'meta',63 'param',64 'source',65 'track',66 'wbr',67]68export const booleanAttributes = [69 'allowfullscreen',70 'async',71 'autofocus',72 'autoplay',73 'checked',74 'controls',75 'default',76 'defer',77 'disabled',78 'download',79 'formnovalidate',80 'hidden',81 'inert',82 'ismap',83 'itemscope',84 'loop',85 'multiple',86 'muted',87 'nomodule',88 'novalidate',89 'open',90 'playsinline',91 'readonly',92 'required',93 'reversed',94 'selected',95]9697const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCallbacks): void => {98 for (let i = 0, len = children.length; i < len; i++) {99 const child = children[i]100 if (typeof child === 'string') {101 escapeToBuffer(child, buffer)102 } else if (typeof child === 'boolean' || child === null || child === undefined) {103 continue104 } else if (child instanceof JSXNode) {105 child.toStringToBuffer(buffer)106 } else if (107 typeof child === 'number' ||108 (child as unknown as { isEscaped: boolean }).isEscaped109 ) {110 ;(buffer[0] as string) += child111 } else if (child instanceof Promise) {112 buffer.unshift('', child)113 } else {114 // `child` type is `Child[]`, so stringify recursively115 childrenToStringToBuffer(child, buffer)116 }117 }118}119120type LocalContexts = [Context<unknown>, unknown][]121export type Child =122 | string123 | Promise<string>124 | number125 | JSXNode126 | null127 | undefined128 | boolean129 | Child[]130export class JSXNode implements HtmlEscaped {131 tag: string | Function132 props: Props133 key?: string134 children: Child[]135 isEscaped: true = true as const136 localContexts?: LocalContexts137 constructor(tag: string | Function, props: Props, children: Child[]) {138 this.tag = tag139 this.props = props140 this.children = children141 }142143 get type(): string | Function {144 return this.tag as string145 }146147 // Added for compatibility with libraries that rely on React's internal structure148 // eslint-disable-next-line @typescript-eslint/no-explicit-any149 get ref(): any {150 return this.props.ref || null151 }152153 toString(): string | Promise<string> {154 const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks155 this.localContexts?.forEach(([context, value]) => {156 context.values.push(value)157 })158 try {159 this.toStringToBuffer(buffer)160 } finally {161 this.localContexts?.forEach(([context]) => {162 context.values.pop()163 })164 }165 return buffer.length === 1166 ? 'callbacks' in buffer167 ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString()168 : buffer[0]169 : stringBufferToString(buffer, buffer.callbacks)170 }171172 toStringToBuffer(buffer: StringBufferWithCallbacks): void {173 const tag = this.tag as string174 const props = this.props175 let { children } = this176177 buffer[0] += `<${tag}`178179 const normalizeKey: (key: string) => string =180 nameSpaceContext && useContext(nameSpaceContext) === 'svg'181 ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key))182 : (key) => normalizeIntrinsicElementKey(key)183 for (let [key, v] of Object.entries(props)) {184 key = normalizeKey(key)185 if (key === 'children') {186 // skip children187 } else if (key === 'style' && typeof v === 'object') {188 // object to style strings189 let styleStr = ''190 styleObjectForEach(v, (property, value) => {191 if (value != null) {192 styleStr += `${styleStr ? ';' : ''}${property}:${value}`193 }194 })195 buffer[0] += ' style="'196 escapeToBuffer(styleStr, buffer)197 buffer[0] += '"'198 } else if (typeof v === 'string') {199 buffer[0] += ` ${key}="`200 escapeToBuffer(v, buffer)201 buffer[0] += '"'202 } else if (v === null || v === undefined) {203 // Do nothing204 } else if (typeof v === 'number' || (v as HtmlEscaped).isEscaped) {205 buffer[0] += ` ${key}="${v}"`206 } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {207 if (v) {208 buffer[0] += ` ${key}=""`209 }210 } else if (key === 'dangerouslySetInnerHTML') {211 if (children.length > 0) {212 throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.')213 }214215 children = [raw(v.__html)]216 } else if (v instanceof Promise) {217 buffer[0] += ` ${key}="`218 buffer.unshift('"', v)219 } else if (typeof v === 'function') {220 if (!key.startsWith('on') && key !== 'ref') {221 throw new Error(`Invalid prop '${key}' of type 'function' supplied to '${tag}'.`)222 }223 // maybe event handler for client components, just ignore in server components224 } else {225 buffer[0] += ` ${key}="`226 escapeToBuffer(v.toString(), buffer)227 buffer[0] += '"'228 }229 }230231 if (emptyTags.includes(tag as string) && children.length === 0) {232 buffer[0] += '/>'233 return234 }235236 buffer[0] += '>'237238 childrenToStringToBuffer(children, buffer)239240 buffer[0] += `</${tag}>`241 }242}243244class JSXFunctionNode extends JSXNode {245 override toStringToBuffer(buffer: StringBufferWithCallbacks): void {246 const { children } = this247248 const props = { ...this.props }249 if (children.length) {250 props.children = children.length === 1 ? children[0] : children251 }252253 const res = (this.tag as Function).call(null, props)254255 if (typeof res === 'boolean' || res == null) {256 // boolean or null or undefined257 return258 } else if (res instanceof Promise) {259 if (globalContexts.length === 0) {260 buffer.unshift('', res)261 } else {262 // save current contexts for resuming263 const currentContexts: LocalContexts = globalContexts.map((c) => [c, c.values.at(-1)])264 buffer.unshift(265 '',266 res.then((childRes) => {267 if (childRes instanceof JSXNode) {268 childRes.localContexts = currentContexts269 }270 return childRes271 })272 )273 }274 } else if (res instanceof JSXNode) {275 res.toStringToBuffer(buffer)276 } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {277 buffer[0] += res278 if (res.callbacks) {279 buffer.callbacks ||= []280 buffer.callbacks.push(...res.callbacks)281 }282 } else {283 escapeToBuffer(res, buffer)284 }285 }286}287288export class JSXFragmentNode extends JSXNode {289 override toStringToBuffer(buffer: StringBufferWithCallbacks): void {290 childrenToStringToBuffer(this.children, buffer)291 }292}293294export const jsx = (295 tag: string | Function,296 props: Props | null,297 ...children: (string | number | HtmlEscapedString)[]298): JSXNode => {299 props ??= {}300 if (children.length) {301 props.children = children.length === 1 ? children[0] : children302 }303304 const key = props.key305 delete props['key']306307 const node = jsxFn(tag, props, children)308 node.key = key309 return node310}311312let initDomRenderer = false313export const jsxFn = (314 tag: string | Function,315 props: Props,316 children: (string | number | HtmlEscapedString)[]317): JSXNode => {318 if (!initDomRenderer) {319 for (const k in domRenderers) {320 // eslint-disable-next-line @typescript-eslint/no-explicit-any321 ;(intrinsicElementTags[k as keyof typeof intrinsicElementTags] as any)[DOM_RENDERER] =322 domRenderers[k]323 }324 initDomRenderer = true325 }326327 if (typeof tag === 'function') {328 return new JSXFunctionNode(tag, props, children)329 } else if (intrinsicElementTags[tag as keyof typeof intrinsicElementTags]) {330 return new JSXFunctionNode(331 intrinsicElementTags[tag as keyof typeof intrinsicElementTags],332 props,333 children334 )335 } else if (tag === 'svg' || tag === 'head') {336 nameSpaceContext ||= createContext('')337 return new JSXNode(tag, props, [338 new JSXFunctionNode(339 nameSpaceContext,340 {341 value: tag,342 },343 children344 ),345 ])346 } else {347 return new JSXNode(tag, props, children)348 }349}350351export const shallowEqual = (a: Props, b: Props): boolean => {352 if (a === b) {353 return true354 }355356 const aKeys = Object.keys(a).sort()357 const bKeys = Object.keys(b).sort()358 if (aKeys.length !== bKeys.length) {359 return false360 }361362 for (let i = 0, len = aKeys.length; i < len; i++) {363 if (364 aKeys[i] === 'children' &&365 bKeys[i] === 'children' &&366 !a.children?.length &&367 !b.children?.length368 ) {369 continue370 } else if (a[aKeys[i]] !== b[aKeys[i]]) {371 return false372 }373 }374375 return true376}377378export type MemorableFC<T> = FC<T> & {379 [DOM_MEMO]: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean380}381export const memo = <T>(382 component: FC<T>,383 propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual384): FC<T> => {385 let computed: ReturnType<FC<T>> = null386 let prevProps: T | undefined = undefined387 const wrapper: MemorableFC<T> = ((props: T) => {388 if (prevProps && !propsAreEqual(prevProps, props)) {389 computed = null390 }391 prevProps = props392 return (computed ||= component(props))393 }) as MemorableFC<T>394395 // This function is for toString(), but it can also be used for DOM renderer.396 // So, set DOM_MEMO and DOM_RENDERER for DOM renderer.397 wrapper[DOM_MEMO] = propsAreEqual398 // eslint-disable-next-line @typescript-eslint/no-explicit-any399 ;(wrapper as any)[DOM_RENDERER] = component400401 return wrapper as FC<T>402}403404export const Fragment = ({405 children,406}: {407 key?: string408 children?: Child | HtmlEscapedString409}): HtmlEscapedString => {410 return new JSXFragmentNode(411 '',412 {413 children,414 },415 Array.isArray(children) ? children : children ? [children] : []416 ) as never417}418419export const isValidElement = (element: unknown): element is JSXNode => {420 return !!(element && typeof element === 'object' && 'tag' in element && 'props' in element)421}422423export const cloneElement = <T extends JSXNode | JSX.Element>(424 element: T,425 props: Partial<Props>,426 ...children: Child[]427): T => {428 let childrenToClone429 if (children.length > 0) {430 childrenToClone = children431 } else {432 const c = (element as JSXNode).props.children433 childrenToClone = Array.isArray(c) ? c : [c]434 }435 return jsx(436 (element as JSXNode).tag,437 { ...(element as JSXNode).props, ...props },438 ...childrenToClone439 ) as T440}441442export const reactAPICompatVersion = '19.0.0-hono-jsx'