perf(jsx/dom): improve performance (#3288)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes #3264 * fix(test): fix test name * refactor(jsx/dom): assign type and ref to node object directly. `Object.defineProperties` is too slow * fix(jsx/hooks): `useReducer` returns the same function object no matter how many times it is called. * refactor(jsx/dom): remove redundant property "s", "shadow virtual dom children" is not used * refactor(jsx/dom): use for-loop instead of recursion for findInsertBefore * perf(jsx/dom): improve performance of `getEventSpec` * perf(jsx/dom): improve performance of `toAttributeName` * perf(jsx/dom): for the same event handler, do nothing. * perf(jsx/dom): reduce `container.nodeName` access * perf(jsx/dom): remove `skipProps` and compare `key` with `'children'` directly * perf(jsx/dom): use `for-in` instead of `Object.entries` * perf(jsx/dom): if `defaultProps` does not exist, do not create a new `props` object. * perf(jsx/dom): if `callbacks` is empty, do not call `requestAnimationFrame` * perf(jsx/dom): optimize `build` function * perf(jsx/dom): skip `push` call if target list is empty. * perf(jsx/dom): optimize `apply` function * refactor(jsx/dom): remove unused type import * refactor(jsx/dom): remove redundant code `applyNode` * test(jsx/dom): add tests * refactor(jsx/dom): tweaks `delete node.vR` timing
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+272 added−156 removed
- tests:+43 added−2 removed
- other:+229 added−154 removed
Provenance
- Commit
1854e24- Tree
6d2f466- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
e6459e7
9 files changed+272 added−156 removed
modified:src/jsx/dom/intrinsic-element/components.test.tsx+1 added-1 removed
522 unmodified lines523 '<div><meta name="description" content="description" itemprop="test">Content</div>'524 )525 })526 527- it('should be ordered by precedence attribute', () => {527+ it('should ignore precedence attribute', () => {528 const App = () => {529 return (530 <div>531 <meta name='description-a' content='description-a' precedence='default' />516 unmodified linesmodified:src/jsx/dom/intrinsic-element/components.ts+35 added-19 removed
1 import type { Props } from '../../base'2 import type { FC, JSXNode, PropsWithChildren, RefObject } from '../../types'3-import { newJSXNode } from '../utils'3 import { createPortal, getNameSpaceContext } from '../render'4 import type { PreserveNodeType } from '../render'5 import { useContext } from '../../context'6 import { use, useCallback, useMemo, useState } from '../../hooks'49 unmodified lines56 supportSort: boolean,57 supportBlocking: boolean58 ) => {59 if (props?.itemProp) {61- return newJSXNode({60+ return {61 tag,62 props,64- })63+ type: tag,64+ ref: props.ref,65+ }66 }67 68 const head = document.head69 122 unmodified lines192 use(promise)193 }194 }195 195- const jsxNode = newJSXNode({196+ const jsxNode = {197 tag,198+ type: tag,199 props: {200 ...restProps,201 ref,202 },203+ ref,201- }) as JSXNode & { e?: HTMLElement; p?: PreserveNodeType }204+ } as unknown as JSXNode & { e?: HTMLElement; p?: PreserveNodeType }205 206 jsxNode.p = preserveNodeType // preserve for unmounting207 if (element) {208 jsxNode.e = element8 unmodified lines217 export const title: FC<PropsWithChildren> = (props) => {218 const nameSpaceContext = getNameSpaceContext()219 const ns = nameSpaceContext && useContext(nameSpaceContext)220 if (ns?.endsWith('svg')) {218- return newJSXNode({221+ return {222 tag: 'title',223 props,221- })224+ type: 'title',225+ // eslint-disable-next-line @typescript-eslint/no-explicit-any226+ ref: (props as any).ref,227+ } as unknown as JSXNode228 }229 return documentMetadataTag('title', props, undefined, false, false)230 }231 232 export const script: FC<PropsWithChildren<IntrinsicElements['script']>> = (props) => {233 if (!props || ['src', 'async'].some((k) => !props[k])) {228- return newJSXNode({234+ return {235 tag: 'script',236 props,231- })237+ type: 'script',238+ ref: props.ref,239+ } as unknown as JSXNode240 }241 return documentMetadataTag('script', props, 1, false, true)242 }243 244 export const style: FC<PropsWithChildren<IntrinsicElements['style']>> = (props) => {245 if (!props || !['href', 'precedence'].every((k) => k in props)) {238- return newJSXNode({246+ return {247 tag: 'style',248 props,241- })249+ type: 'style',250+ ref: props.ref,251+ } as unknown as JSXNode252 }253 props['data-href'] = props.href254 delete props.href255 return documentMetadataTag('style', props, 2, true, true)4 unmodified lines260 !props ||261 ['onLoad', 'onError'].some((k) => k in props) ||262 (props.rel === 'stylesheet' && (!('precedence' in props) || 'disabled' in props))263 ) {254- return newJSXNode({264+ return {265 tag: 'link',266 props,257- })267+ type: 'link',268+ ref: props.ref,269+ } as unknown as JSXNode270 }271 return documentMetadataTag('link', props, 1, 'precedence' in props, true)272 }273 46 unmodified lines320 })321 322 const [data, isDirty] = state323 state[1] = false312- return newJSXNode({324+ return {325 tag: FormContext as unknown as Function,326 props: {327 value: {328 pending: data !== null,329 data,330 method: data ? 'post' : null,331 action: data ? action : null,332 },321- children: newJSXNode({333+ children: {334 tag: 'form',335 props: {336 ...restProps,337 ref,338 },339+ type: 'form',340+ ref,327- }),341+ },342 },343 f: isDirty,344 // eslint-disable-next-line @typescript-eslint/no-explicit-any331- } as any) as any345+ } as any346 }347 348 const formActionableElement = (349 tag: string,20 unmodified lines370 }371 })372 }373 360- return newJSXNode({374+ return {375 tag,376 props,377+ type: tag,378+ ref: props.ref,379 // eslint-disable-next-line @typescript-eslint/no-explicit-any364- }) as any380+ } as any381 }382 383 export const input: FC<PropsWithChildren<IntrinsicElements['input']>> = (props) =>384 formActionableElement('input', props)14 unmodified linesmodified:src/jsx/dom/context.ts+2 added-2 removed
123455678922 unmodified lines3233343536363738394012 unmodified linesimport type { Child } from '../base'import { DOM_ERROR_HANDLER } from '../constants'import type { Context } from '../context'import { globalContexts } from '../context'import { newJSXNode, setInternalTagFlag } from './utils'import { setInternalTagFlag } from './utils'
export const createContextProviderFunction = <T>(values: T[]): Function => ({ value, children }: { value: T; children: Child[] }) => {22 unmodified lines values.pop() }), props: {}, }) const res = newJSXNode({ tag: '', props }) const res = { tag: '', props, type: '' } // eslint-disable-next-line @typescript-eslint/no-explicit-any ;(res as any)[DOM_ERROR_HANDLER] = (err: unknown) => { values.pop() throw err12 unmodified linesmodified:src/jsx/dom/index.test.tsx+37 added
734 unmodified lines735 })736 })737 })738 739+ describe('dangerouslySetInnerHTML', () => {740+ it('string', () => {741+ const App = () => {742+ return <div dangerouslySetInnerHTML={{ __html: '<p>Hello</p>' }} />743+ }744+ render(<App />, root)745+ expect(root.innerHTML).toBe('<div><p>Hello</p></div>')746+ })747+ })748+749 describe('Event', () => {750 it('bubbling phase', async () => {751 const clicked: string[] = []752 const App = () => {140 unmodified lines893 const addEventListenerSpy = vi.spyOn(dom.window.Node.prototype, 'addEventListener')894 render(<App />, root)895 expect(addEventListenerSpy).not.toHaveBeenCalled()896 })897+898+ it('invalid event handler value', async () => {899+ const App = () => {900+ return <div onClick={1 as unknown as () => void}></div>901+ }902+ expect(() => render(<App />, root)).toThrow()903+ })904 })905 906 it('simple Counter', async () => {907 const Counter = () => {982 unmodified lines1890 root.querySelector('p')?.click()1891 await Promise.resolve()1892 expect(root.innerHTML).toBe('<div><p>1</p></div>')1893 })1894+1895+ it('title', async () => {1896+ const App = () => {1897+ return <div>{createElement('title', {}, 'Hello')}</div>1898+ }1899+ const app = <App />1900+ render(app, root)1901+ expect(document.head.innerHTML).toBe('<title>Hello</title>')1902+ expect(root.innerHTML).toBe('<div></div>')1903+ })1904 })1905 1906 describe('dom-specific createElement', () => {1907 it('simple', async () => {7 unmodified lines1915 root.querySelector('p')?.click()1916 await Promise.resolve()1917 expect(root.innerHTML).toBe('<div><p>1</p></div>')1918 })1919+1920+ it('title', async () => {1921+ const App = () => {1922+ return <div>{createElementForDom('title', {}, 'Hello')}</div>1923+ }1924+ const app = <App />1925+ render(app, root)1926+ expect(document.head.innerHTML).toBe('<title>Hello</title>')1927+ expect(root.innerHTML).toBe('<div></div>')1928+ })1929 })1930 1931 describe('cloneElement', () => {1932 it('simple', async () => {406 unmodified linesmodified:src/jsx/dom/jsx-dev-runtime.ts+8 added-6 removed
2 unmodified lines345677891112131410111213141516171718192021222 unmodified lines * This module provides the `hono/jsx/dom` dev runtime. */
import type { JSXNode, Props } from '../base'import { newJSXNode } from './utils'import * as intrinsicElementTags from './intrinsic-element/components'
export const jsxDEV = (tag: string | Function, props: Props, key?: string): JSXNode => { return newJSXNode({ tag: (typeof tag === 'string' && intrinsicElementTags[tag as keyof typeof intrinsicElementTags]) || tag, if (typeof tag === 'string' && intrinsicElementTags[tag as keyof typeof intrinsicElementTags]) { tag = intrinsicElementTags[tag as keyof typeof intrinsicElementTags] } return { tag, type: tag, props, key, }) ref: props.ref, } as JSXNode}
export const Fragment = (props: Record<string, unknown>): JSXNode => jsxDEV('', props, undefined)modified:src/jsx/dom/render.ts+179 added-106 removed
5 unmodified lines6 import type { EffectData } from '../hooks'7 import { STASH_EFFECT } from '../hooks'8 import { normalizeIntrinsicElementKey, styleObjectForEach } from '../utils'9 import { createContext } from './context' // import dom-specific versions10-import { newJSXNode } from './utils'10 11 const HONO_PORTAL_ELEMENT = '_hp'12 13 const eventAliasMap: Record<string, string> = {5 unmodified lines19 svg: '2000/svg',20 math: '1998/Math/MathML',21 } as const22 24-const skipProps: Set<string> = new Set(['children'])25-23 // eslint-disable-next-line @typescript-eslint/no-explicit-any24 export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }25 // eslint-disable-next-line @typescript-eslint/no-explicit-any26 export type ErrorHandler = (error: any, retry: () => void) => Child | undefined10 unmodified lines37 nN: Node | undefined // next node38 vC: Node[] // virtual dom children39 pC?: Node[] // previous virtual dom children40 vR: Node[] // virtual dom children to remove44- s?: Node[] // shadow virtual dom children41 n?: string // namespace42 f?: boolean // force build43+ s?: boolean // skip build and apply44 c: Container | undefined // container45 e: SupportedElement | Text | undefined // rendered element46 p?: PreserveNodeType // preserve HTMLElement if it will be unmounted47 a?: boolean // cancel apply() if true10 unmodified lines58 } & JSXNode59 type NodeString = {60 t: string // text content61 d: boolean // is dirty62+ s?: boolean // skip build and apply63 } & {64 e?: Text65 // like a NodeObject66 vC: undefined37 unmodified lines104 export const getNameSpaceContext = () => nameSpaceContext105 106 const isNodeString = (node: Node): node is NodeString => 't' in (node as NodeString)107 108+const eventCache: Record<string, [string, boolean]> = {109+ // pre-define events that are used very frequently110+ onClick: ['click', false],111+}112 const getEventSpec = (key: string): [string, boolean] | undefined => {113+ if (!key.startsWith('on')) {114+ return undefined115+ }116+ if (eventCache[key]) {117+ return eventCache[key]118+ }119+120 const match = key.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/)121 if (match) {122 const [, eventName, capture] = match114- return [(eventAliasMap[eventName] || eventName).toLowerCase(), !!capture]123+ return (eventCache[key] = [(eventAliasMap[eventName] || eventName).toLowerCase(), !!capture])124 }125 return undefined126 }127 128 const toAttributeName = (element: SupportedElement, key: string): string =>129+ nameSpaceContext &&130 element instanceof SVGElement &&131 /[A-Z]/.test(key) &&132 (key in element.style || // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc.133 key.match(/^(?:o|pai|str|u|ve)/)) // Other un-deprecated kebab-case attributes. "overline-position", "paint-order", "strikethrough-position", etc.5 unmodified lines139 attributes: Props,140 oldAttributes?: Props141 ): void => {142 attributes ||= {}133- for (let [key, value] of Object.entries(attributes)) {134- if (!skipProps.has(key) && (!oldAttributes || oldAttributes[key] !== value)) {143+ for (let key in attributes) {144+ const value = attributes[key]145+ if (key !== 'children' && (!oldAttributes || oldAttributes[key] !== value)) {146 key = normalizeIntrinsicElementKey(key)147 const eventSpec = getEventSpec(key)148 if (eventSpec) {138- if (oldAttributes) {139- container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1])140- }141- if (value != null) {142- if (typeof value !== 'function') {143- throw new Error(`Event handler for "${key}" is not a function`)149+ if (oldAttributes?.[key] !== value) {150+ if (oldAttributes) {151+ container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1])152 }153+ if (value != null) {154+ if (typeof value !== 'function') {155+ throw new Error(`Event handler for "${key}" is not a function`)156+ }145- container.addEventListener(eventSpec[0], value, eventSpec[1])157+ container.addEventListener(eventSpec[0], value, eventSpec[1])158+ }159 }160 } else if (key === 'dangerouslySetInnerHTML' && value) {161 container.innerHTML = value.__html162 } else if (key === 'ref') {15 unmodified lines178 styleObjectForEach(value, style.setProperty.bind(style))179 }180 }181 } else {169- const nodeName = container.nodeName182 if (key === 'value') {183+ const nodeName = container.nodeName184 if (nodeName === 'INPUT' || nodeName === 'TEXTAREA' || nodeName === 'SELECT') {185 ;(container as unknown as HTMLInputElement).value =186 value === null || value === undefined || value === false ? null : value187 7 unmodified lines195 continue196 }197 }198 } else if (186- (key === 'checked' && nodeName === 'INPUT') ||187- (key === 'selected' && nodeName === 'OPTION')199+ (key === 'checked' && container.nodeName === 'INPUT') ||200+ (key === 'selected' && container.nodeName === 'OPTION')201 ) {202 // eslint-disable-next-line @typescript-eslint/no-explicit-any203 ;(container as any)[key] = value204 }12 unmodified lines217 }218 }219 }220 if (oldAttributes) {208- for (let [key, value] of Object.entries(oldAttributes)) {209- if (!skipProps.has(key) && !(key in attributes)) {221+ for (let key in oldAttributes) {222+ const value = oldAttributes[key]223+ if (key !== 'children' && !(key in attributes)) {224 key = normalizeIntrinsicElementKey(key)225 const eventSpec = getEventSpec(key)226 if (eventSpec) {227 container.removeEventListener(eventSpec[0], value, eventSpec[1])7 unmodified lines235 }236 }237 238 const invokeTag = (context: Context, node: NodeObject): Child[] => {225- if (node.s) {226- const res = node.s227- node.s = undefined228- return res as Child[]229- }230-239 node[DOM_STASH][0] = 0240 buildDataStack.push([context, node])241 const func = (node.tag as HasRenderToDom)[DOM_RENDERER] || node.tag234- try {235- return [236- func.call(null, {242+ // eslint-disable-next-line @typescript-eslint/no-explicit-any243+ const props = (func as any).defaultProps244+ ? {245 // eslint-disable-next-line @typescript-eslint/no-explicit-any238- ...((func as any).defaultProps || {}),246+ ...(func as any).defaultProps,247 ...node.props,240- }),241- ]248+ }249+ : node.props250+ try {251+ return [func.call(null, props)]252 } finally {253 buildDataStack.pop()254 }255 }4 unmodified lines260 nextChildren: Node[],261 childrenToRemove: Node[],262 callbacks: EffectData[]263 ): void => {264+ if (node.vR?.length) {254- childrenToRemove.push(...node.vR)265+ childrenToRemove.push(...node.vR)266+ // eslint-disable-next-line @typescript-eslint/no-explicit-any267+ delete (node as any).vR268+ }269 if (typeof node.tag === 'function') {270 node[DOM_STASH][1][STASH_EFFECT]?.forEach((data: EffectData) => callbacks.push(data))271 }272 node.vC.forEach((child) => {1 unmodified line274 nextChildren.push(child)275 } else {276 if (typeof child.tag === 'function' || child.tag === '') {277 child.c = container278+ const currentNextChildrenIndex = nextChildren.length279 getNextChildren(child, container, nextChildren, childrenToRemove, callbacks)280+ if (child.s) {281+ for (let i = currentNextChildrenIndex; i < nextChildren.length; i++) {282+ nextChildren[i].s = true283+ }284+ child.s = false285+ }286 } else {287 nextChildren.push(child)288+ if (child.vR?.length) {267- childrenToRemove.push(...child.vR)289+ childrenToRemove.push(...child.vR)290+ // eslint-disable-next-line @typescript-eslint/no-explicit-any291+ delete (child as any).vR292+ }293 }294 }295 })296 }297 298 const findInsertBefore = (node: Node | undefined): SupportedElement | Text | null => {274- return !node275- ? null276- : node.tag === HONO_PORTAL_ELEMENT277- ? findInsertBefore(node.nN)278- : node.e || (node.vC && node.pP && findInsertBefore(node.vC[0])) || findInsertBefore(node.nN)299+ for (; ; node = node.tag === HONO_PORTAL_ELEMENT || !node.vC || !node.pP ? node.nN : node.vC[0]) {300+ if (!node) {301+ return null302+ }303+ if (node.tag !== HONO_PORTAL_ELEMENT && node.e) {304+ return node.e305+ }306+ }307 }308 309 const removeNode = (node: Node): void => {310 if (!isNodeString(node)) {17 unmodified lines328 node.a = true329 }330 }331 304-const apply = (node: NodeObject, container: Container): void => {332+const apply = (node: NodeObject, container: Container, isNew: boolean): void => {333 node.c = container306- applyNodeObject(node, container)334+ applyNodeObject(node, container, isNew)335 }336 309-const applyNode = (node: Node, container: Container): void => {310- if (isNodeString(node)) {311- container.textContent = node.t312- } else {313- applyNodeObject(node, container)314- }315-}316-337 const findChildNodeIndex = (338 childNodes: NodeListOf<ChildNode>,339 child: ChildNode | null | undefined340 ): number | undefined => {10 unmodified lines351 return352 }353 354 const cancelBuild: symbol = Symbol()335-const applyNodeObject = (node: NodeObject, container: Container): void => {355+const applyNodeObject = (node: NodeObject, container: Container, isNew: boolean): void => {356 const next: Node[] = []357 const remove: Node[] = []358 const callbacks: EffectData[] = []359 getNextChildren(node, container, next, remove, callbacks)360+ remove.forEach(removeNode)361 341- const childNodes = container.childNodes342- let offset =343- findChildNodeIndex(childNodes, findInsertBefore(node.nN)) ??344- findChildNodeIndex(childNodes, next.find((n) => n.tag !== HONO_PORTAL_ELEMENT && n.e)?.e) ??345- childNodes.length362+ const childNodes = (isNew ? undefined : container.childNodes) as NodeListOf<ChildNode>363+ let offset: number364+ if (isNew) {365+ offset = -1366+ } else {367+ offset =368+ (childNodes.length &&369+ (findChildNodeIndex(childNodes, findInsertBefore(node.nN)) ??370+ findChildNodeIndex(371+ childNodes,372+ next.find((n) => n.tag !== HONO_PORTAL_ELEMENT && n.e)?.e373+ ))) ??374+ -1375+ if (offset === -1) {376+ isNew = true377+ }378+ }379 380 for (let i = 0, len = next.length; i < len; i++, offset++) {381 const child = next[i]382 383 let el: SupportedElement | Text351- if (isNodeString(child)) {352- if (child.e && child.d) {353- child.e.textContent = child.t354- }355- child.d = false356- el = child.e ||= document.createTextNode(child.t)384+ if (child.s && child.e) {385+ el = child.e386+ child.s = false387 } else {388+ const isNewLocal = isNew || !child.e389+ if (isNodeString(child)) {390+ if (child.e && child.d) {391+ child.e.textContent = child.t392+ }393+ child.d = false394+ el = child.e ||= document.createTextNode(child.t)395+ } else {358- el = child.e ||= child.n359- ? (document.createElementNS(child.n, child.tag as string) as SVGElement | MathMLElement)360- : document.createElement(child.tag as string)361- applyProps(el as HTMLElement, child.props, child.pP)362- applyNode(child, el as HTMLElement)396+ el = child.e ||= child.n397+ ? (document.createElementNS(child.n, child.tag as string) as SVGElement | MathMLElement)398+ : document.createElement(child.tag as string)399+ applyProps(el as HTMLElement, child.props, child.pP)400+ applyNodeObject(child, el as HTMLElement, isNewLocal)401+ }402 }403 if (child.tag === HONO_PORTAL_ELEMENT) {404 offset--366- } else if (childNodes[offset] !== el && childNodes[offset - 1] !== child.e) {367- container.insertBefore(el, childNodes[offset] || null)405+ } else if (isNew) {406+ if (!el.parentNode) {407+ container.appendChild(el)408+ }409+ } else if (childNodes[offset] !== el && childNodes[offset - 1] !== el) {410+ if (childNodes[offset + 1] === el) {411+ // Move extra elements to the back of the container. This is to be done efficiently when elements are swapped.412+ container.appendChild(childNodes[offset])413+ } else {414+ container.insertBefore(el, childNodes[offset] || null)415+ }416 }417 }370- remove.forEach(removeNode)371- callbacks.forEach(([, , , , cb]) => cb?.()) // invoke useInsertionEffect callbacks372- callbacks.forEach(([, cb]) => cb?.()) // invoke useLayoutEffect callbacks373- requestAnimationFrame(() => {374- callbacks.forEach(([, , , cb]) => cb?.()) // invoke useEffect callbacks375- })418+ if (node.pP) {419+ delete node.pP420+ }421+ if (callbacks.length) {422+ const useLayoutEffectCbs: Array<() => void> = []423+ const useEffectCbs: Array<() => void> = []424+ callbacks.forEach(([, useLayoutEffectCb, , useEffectCb, useInsertionEffectCb]) => {425+ if (useLayoutEffectCb) {426+ useLayoutEffectCbs.push(useLayoutEffectCb)427+ }428+ if (useEffectCb) {429+ useEffectCbs.push(useEffectCb)430+ }431+ useInsertionEffectCb?.() // invoke useInsertionEffect callbacks432+ })433+ useLayoutEffectCbs.forEach((cb) => cb()) // invoke useLayoutEffect callbacks434+ if (useEffectCbs.length) {435+ requestAnimationFrame(() => {436+ useEffectCbs.forEach((cb) => cb()) // invoke useEffect callbacks437+ })438+ }439+ }440 }441 442 const fallbackUpdateFnArrayMap: WeakMap<443 NodeObject,14 unmodified lines458 // eslint-disable-next-line @typescript-eslint/no-explicit-any459 foundErrorHandler = (children[0] as any)[DOM_ERROR_HANDLER] as ErrorHandler460 context[5]!.push([context, foundErrorHandler, node])461 }398- const oldVChildren: Node[] = buildWithPreviousChildren462+ const oldVChildren: Node[] | undefined = buildWithPreviousChildren463 ? [...(node.pC as Node[])]464 : node.vC465 ? [...node.vC]402- : []466+ : undefined467 const vChildren: Node[] = []404- node.vR = buildWithPreviousChildren ? [...node.vC] : []468 let prevNode: Node | undefined406- children.flat().forEach((c: Child) => {407- let child = buildNode(c)469+ for (let i = 0; i < children.length; i++) {470+ if (Array.isArray(children[i])) {471+ children.splice(i, 1, ...(children[i] as Child[]).flat())472+ }473+ let child = buildNode(children[i])474 if (child) {475 if (476 typeof child.tag === 'function' &&477 // eslint-disable-next-line @typescript-eslint/no-explicit-any6 unmodified lines484 child[DOM_STASH][3] = context[5].at(-1) as [Context, ErrorHandler, NodeObject]485 }486 }487 422- let oldChild: Node | undefined423- const i = oldVChildren.findIndex(424- isNodeString(child)425- ? (c) => isNodeString(c)426- : child.key !== undefined427- ? (c) => c.key === (child as Node).key428- : (c) => c.tag === (child as Node).tag429- )430- if (i !== -1) {431- oldChild = oldVChildren[i]432- oldVChildren.splice(i, 1)488+ let oldChild: NodeObject | undefined489+ if (oldVChildren && oldVChildren.length) {490+ const i = oldVChildren.findIndex(491+ isNodeString(child)492+ ? (c) => isNodeString(c)493+ : child.key !== undefined494+ ? (c) => c.key === (child as Node).key && c.tag === (child as Node).tag495+ : (c) => c.tag === (child as Node).tag496+ )497+498+ if (i !== -1) {499+ oldChild = oldVChildren[i] as NodeObject500+ oldVChildren.splice(i, 1)501+ }502 }503 435- let skipBuild = false504 if (oldChild) {505 if (isNodeString(child)) {438- if ((oldChild as NodeString).t !== child.t) {439- ;(oldChild as NodeString).t = child.t // update text content440- ;(oldChild as NodeString).d = true506+ if ((oldChild as unknown as NodeString).t !== child.t) {507+ ;(oldChild as unknown as NodeString).t = child.t // update text content508+ ;(oldChild as unknown as NodeString).d = true509 }510 child = oldChild443- } else if (oldChild.tag !== child.tag) {444- node.vR.push(oldChild)511 } else {512 const pP = (oldChild.pP = oldChild.props)513 oldChild.props = child.props514 oldChild.f ||= child.f || node.f3 unmodified lines518 519 if (!oldChild.f) {520 const prevPropsKeys = Object.keys(pP)521 const currentProps = oldChild.props456- skipBuild =522+ if (523 prevPropsKeys.length === Object.keys(currentProps).length &&524 prevPropsKeys.every((k) => k in currentProps && currentProps[k] === pP[k])525+ ) {526+ oldChild.s = true527+ }528 }529 }530 child = oldChild531 }3 unmodified lines535 child.n = ns536 }537 }538 470- if (!isNodeString(child) && !skipBuild) {539+ if (!isNodeString(child) && !child.s) {540 build(context, child)541 delete child.f542 }543 vChildren.push(child)544 545+ if (prevNode && !prevNode.s && !child.s) {476- for (let p = prevNode; p && !isNodeString(p); p = p.vC?.at(-1) as NodeObject) {477- p.nN = child546+ for (let p = prevNode; p && !isNodeString(p); p = p.vC?.at(-1) as NodeObject) {547+ p.nN = child548+ }549 }550 prevNode = child551 }481- })552+ }553+ node.vR = buildWithPreviousChildren ? [...node.vC, ...(oldVChildren || [])] : oldVChildren || []554 node.vC = vChildren483- node.vR.push(...oldVChildren)555 if (buildWithPreviousChildren) {556 delete node.pC557 }558 } catch (e) {36 unmodified lines595 (errorHandler.length === 1 || context !== errorHandlerContext) &&596 errorHandlerNode.c597 ) {598 // render error boundary immediately528- apply(errorHandlerNode, errorHandlerNode.c as Container)599+ apply(errorHandlerNode, errorHandlerNode.c as Container, false)600 return601 }602 }603 throw cancelBuild14 unmodified lines618 } else if (typeof node === 'string' || typeof node === 'number') {619 return { t: node.toString(), d: true } as NodeString620 } else {621 if ('vR' in node) {551- node = newJSXNode({622+ node = {623 tag: (node as NodeObject).tag,624 props: (node as NodeObject).props,625 key: (node as NodeObject).key,626 f: (node as NodeObject).f,627+ type: (node as NodeObject).tag,628+ ref: (node as NodeObject).props.ref,629 // eslint-disable-next-line @typescript-eslint/no-explicit-any557- } as any)630+ } as any631 }632 if (typeof (node as JSXNode).tag === 'function') {633 ;(node as NodeObject)[DOM_STASH] = [0, []]634 } else {38 unmodified lines673 node[DOM_STASH][2]?.forEach(([c]) => {674 c.values.pop()675 })676 if (context[0] !== 1 || !context[1]) {604- apply(node, node.c as Container)677+ apply(node, node.c as Container, false)678 }679 }680 681 type UpdateMapResolve = (node: NodeObject | undefined) => void52 unmodified lines734 build(context, node, undefined)735 ;(context as Context)[4] = false // finish top level render736 737 const fragment = document.createDocumentFragment()665- apply(node, fragment)738+ apply(node, fragment, true)739 replaceContainer(node, fragment, container)740 container.replaceChildren(fragment)741 }742 30 unmodified linesmodified:src/jsx/dom/utils.ts-17 removed
112345679101112131415161718192021222324import type { JSXNode, Props } from '../base'import { DOM_INTERNAL_TAG } from '../constants'
export const setInternalTagFlag = (fn: Function): Function => { // eslint-disable-next-line @typescript-eslint/no-explicit-any ;(fn as any)[DOM_INTERNAL_TAG] = true return fn}
const JSXNodeCompatPrototype = { type: { get(this: { tag: string | Function }): string | Function { return this.tag }, }, ref: { get(this: { props?: { ref: unknown } }): unknown { return this.props?.ref }, },}
export const newJSXNode = (obj: { tag: string | Function; props?: Props; key?: string }): JSXNode => Object.defineProperties(obj, JSXNodeCompatPrototype) as JSXNodemodified:src/jsx/hooks/dom.test.tsx+5 added-1 removed
38 unmodified lines39 })40 41 describe('useReducer()', () => {42 it('simple', async () => {43+ const reducer = (state: number, action: number) => state + action44+ const functions: Function[] = []45 const App = () => {44- const [state, dispatch] = useReducer((state: number, action: number) => state + action, 0)46+ const [state, dispatch] = useReducer(reducer, 0)47+ functions.push(dispatch)48 return (49 <div>50 <button onClick={() => dispatch(1)}>{state}</button>51 </div>3 unmodified lines55 expect(root.innerHTML).toBe('<div><button>0</button></div>')56 root.querySelector('button')?.click()57 await Promise.resolve()58 expect(root.innerHTML).toBe('<div><button>1</button></div>')59+ expect(functions[0]).toBe(functions[1])60 })61 })62 63 describe('startTransition()', () => {672 unmodified linesmodified:src/jsx/hooks/index.ts+5 added-4 removed
245 unmodified lines246 reducer: (state: T, action: A) => T,247 initialArg: T,248 init?: (initialState: T) => T249 ): [T, (action: A) => void] => {250- const [state, setState] = useState(() => (init ? init(initialArg) : initialArg))251- return [252- state,250+ const handler = useCallback(251 (action: A) => {252 setState((state) => reducer(state, action))253 },256- ]254+ [reducer]255+ )256+ const [state, setState] = useState(() => (init ? init(initialArg) : initialArg))257+ return [state, handler]258 }259 260 const useEffectCommon = (261 index: number,165 unmodified lines