All files / react renderComponent.ts

64.29% Statements 36/56
50% Branches 11/22
66.67% Functions 8/12
70.59% Lines 36/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158                                                                                                      2x       2x 18x 18x 4x 4x 4x 4x 4x     4x       18x     2x                                                 2x 2x 2x 18x 18x   2x 1x 1x 1x 1x   1x 1x       2x         2x   2x   5x 5x       5x     5x 5x           6x 6x             1x   1x                  
import React from 'react'
import ReactDOM from 'react-dom'
import { isPromiseLike } from '../utils'
import { PickBy } from '../types'
import { useUpdate } from 'react-use'
 
export interface RenderComponentResult<
  TComponent extends React.ComponentType<any>
> {
  /**
   * 增量重渲染,新属性将与增量属性合并并成为新的增量属性。
   *
   * @param props 新属性
   */
  incrementalRerender(props: Partial<React.ComponentProps<TComponent>>): void
 
  /**
   * 部分重渲染,新属性将与初始属性合并。
   *
   * @param props 新属性
   */
  partialRerender(props: Partial<React.ComponentProps<TComponent>>): void
 
  /**
   * 完全重渲染,新属性将直接作为全部属性传给组件。
   *
   * @param props 新属性
   */
  fullRerender(props: React.ComponentProps<TComponent>): void
 
  /**
   * 销毁组件并移除 DOM 节点。
   */
  destroy(): void
}
 
/**
 * 独立渲染一个组件在 document.body 下,常应用于弹窗类组件。
 *
 * @param Component 要渲染的组件
 * @param initialProps 初始属性
 * @param injectCallbacks 回调函数注入
 */
export function renderComponent<TComponent extends React.ComponentType<any>>(
  Component: TComponent,
  initialProps: React.ComponentProps<TComponent>,
  injectCallbacks?: PickBy<
    React.ComponentProps<TComponent>,
    Function | undefined
  >,
): RenderComponentResult<TComponent> {
  let hasContainer = true
  let render!: (props: Partial<React.ComponentProps<TComponent>>) => void
  let destroy!: () => void
 
  const prepareProps = (props: Partial<React.ComponentProps<TComponent>>) => {
    props = { ...props }
    if (injectCallbacks) {
      for (const key of Object.keys(injectCallbacks)) {
        const originalCallback = props[key]
        ;(props as any)[key] = () => {
          const res = originalCallback?.()
          Iif (isPromiseLike(res)) {
            return res.then(() => (injectCallbacks as any)[key]())
          }
          return (injectCallbacks as any)[key]()
        }
      }
    }
    return props
  }
 
  Iif (hasRenderComponentContainer) {
    let childIndex: number | undefined
    render = props => {
      props = prepareProps(props)
      if (childIndex == null) {
        childIndex = renderComponentContainerChildren.length
        renderComponentContainerChildren.push(
          React.createElement(Component, props),
        )
      } else {
        renderComponentContainerChildren.splice(
          childIndex,
          1,
          React.createElement(Component, props),
        )
      }
      updateRenderComponentContainer!()
    }
    destroy = () => {
      if (childIndex != null) {
        renderComponentContainerChildren.splice(childIndex, 1)
        updateRenderComponentContainer!()
      }
    }
  } else {
    let container: HTMLDivElement | null = document.createElement('div')
    document.body.appendChild(container)
    render = props => {
      props = prepareProps(props)
      ReactDOM.render(React.createElement(Component, props), container)
    }
    destroy = () => {
      Iif (!hasContainer || !container) return
      const unmountResult = ReactDOM.unmountComponentAtNode(container)
      if (unmountResult) {
        container.parentNode?.removeChild(container)
      }
      container = null
      hasContainer = false
    }
  }
 
  let incrementalProps: React.ComponentProps<TComponent> = {
    key: Date.now(),
    ...initialProps,
  }
 
  render(incrementalProps)
 
  return {
    incrementalRerender(props: Partial<React.ComponentProps<TComponent>>) {
      Iif (!hasContainer) return
      incrementalProps = {
        ...incrementalProps,
        ...props,
      }
      render(incrementalProps)
    },
    partialRerender(props: Partial<React.ComponentProps<TComponent>>) {
      Iif (!hasContainer) return
      render({
        ...initialProps,
        ...props,
      })
    },
    fullRerender(props: React.ComponentProps<TComponent>) {
      Iif (!hasContainer) return
      render(props)
    },
    destroy: destroy,
  }
}
 
// 渲染容器
let hasRenderComponentContainer = false
let updateRenderComponentContainer: ReturnType<typeof useUpdate> | undefined
const renderComponentContainerChildren: any[] = []
 
export function RenderComponentContainer() {
  hasRenderComponentContainer = true
  updateRenderComponentContainer = useUpdate()
  return React.createElement(React.Fragment, {
    children: renderComponentContainerChildren,
  })
}