create-packer 1.17.4 → 1.17.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-packer",
3
- "version": "1.17.4",
3
+ "version": "1.17.6",
4
4
  "main": "index.js",
5
5
  "repository": "https://github.com/kevily/create-packer",
6
6
  "author": "1k <bug_zero@163.com>",
@@ -0,0 +1,78 @@
1
+ import {
2
+ forwardRef,
3
+ ForwardRefExoticComponent,
4
+ PropsWithoutRef,
5
+ RefAttributes,
6
+ useEffect,
7
+ useImperativeHandle,
8
+ useRef,
9
+ useState
10
+ } from 'react'
11
+ import { createRoot } from 'react-dom/client'
12
+
13
+ const instanceMap: Record<string, any> = {}
14
+
15
+ interface refsType<P> {
16
+ $setProps: (newProps?: P) => void
17
+ $updateProps: (newProps?: Partial<P>) => void
18
+ }
19
+
20
+ export async function create<P extends Record<string, any>, Refs extends Record<string, any>>(
21
+ key: string,
22
+ Component: ForwardRefExoticComponent<PropsWithoutRef<any> & RefAttributes<Refs>>,
23
+ props?: P
24
+ ) {
25
+ let $instance: Refs & refsType<P> = instanceMap[key]
26
+
27
+ if (!$instance) {
28
+ const div = document.createElement('div')
29
+ document.body.appendChild(div)
30
+ const ApiComponent = forwardRef<Refs & refsType<P>>((__, refs) => {
31
+ const ref = useRef<Refs>(null)
32
+ const [state, setState] = useState<P | Record<string, any>>(props || {})
33
+
34
+ useImperativeHandle(refs, () => {
35
+ return {
36
+ $setProps: newProps => {
37
+ setState(() => newProps)
38
+ },
39
+ $updateProps: newProps => {
40
+ if (newProps) {
41
+ setState(state => ({ ...state, ...props }))
42
+ }
43
+ },
44
+ ...ref.current
45
+ } as Refs & refsType<P>
46
+ })
47
+ return <Component ref={ref} {...state} />
48
+ })
49
+ await new Promise<void>(resolve => {
50
+ createRoot(div).render(
51
+ <ApiComponent
52
+ ref={instance => {
53
+ $instance = instance!
54
+ resolve()
55
+ }}
56
+ />
57
+ )
58
+ })
59
+ }
60
+ $instance.$setProps(props)
61
+ return $instance
62
+ }
63
+
64
+ export function useHooks<P extends Record<string, any>, Refs extends Record<string, any>>(
65
+ key: string,
66
+ Component: ForwardRefExoticComponent<PropsWithoutRef<any> & RefAttributes<Refs>>,
67
+ props?: P
68
+ ) {
69
+ const $instance = useRef<Refs & refsType<P>>(instanceMap[key])
70
+
71
+ useEffect(() => {
72
+ create(key, Component, props).then(instance => {
73
+ $instance.current = instance
74
+ })
75
+ }, [])
76
+
77
+ return $instance
78
+ }
@@ -1,2 +1,3 @@
1
1
  export * from './defineModel'
2
2
  export { default as request } from './request'
3
+ export * as componentInstance from './componentInstance'