@formvk/reactive-react 0.1.0 → 1.1.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,23 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # [1.1.0](https://github.com/formvk/core/compare/v1.0.0...v1.1.0) (2026-11-16)
7
+
8
+ ### Features
9
+
10
+ - 为所有包添加中英双语 README 文件并导出 reactive-react 包 ([22f7b77](https://github.com/formvk/core/commit/22f7b7751e636d4aa8fbc844ec9b286414d4a14f))
11
+
12
+ # @formvk/reactive-react
13
+
14
+ ## 1.0.0
15
+
16
+ ### Major Changes
17
+
18
+ - 65c066c: 添加readme.md文档
19
+
20
+ ### Patch Changes
21
+
22
+ - Updated dependencies [65c066c]
23
+ - @formvk/reactive@1.0.0
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # @formvk/reactive-react
2
+
3
+ [English](./README.md) | [简体中文](./README.zh-CN.md)
4
+
5
+ React bindings for `@formvk/reactive`. Wrap a component with `observer` and it re-renders whenever observable data read during render changes.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @formvk/reactive-react
11
+ ```
12
+
13
+ `react` and `react-dom` (`>= 18`) are peer dependencies.
14
+
15
+ ## Usage
16
+
17
+ ```tsx
18
+ import { observable } from '@formvk/reactive'
19
+ import { observer } from '@formvk/reactive-react'
20
+
21
+ const state = observable({ count: 0 })
22
+
23
+ export const Counter = observer(() => <button onClick={() => (state.count += 1)}>count: {state.count}</button>)
24
+ ```
25
+
26
+ Render-prop form for local subscriptions:
27
+
28
+ ```tsx
29
+ import { Observer } from '@formvk/reactive-react'
30
+
31
+ function Count() {
32
+ return <Observer>{() => <span>{state.count}</span>}</Observer>
33
+ }
34
+ ```
35
+
36
+ `observer` accepts `{ forwardRef, displayName, scheduler }` options:
37
+
38
+ ```tsx
39
+ const Input = observer(MyInput, { forwardRef: true, displayName: 'Input' })
40
+ ```
41
+
42
+ ## API
43
+
44
+ - `observer(Component, options?)` — memoized wrapper that tracks observable reads and re-renders.
45
+ - `Observer` — component with a render-prop `children`.
46
+ - `useObserver(view, options?)` — run a render function inside the observer tracker.
47
+ - `useForceUpdate()` — force a re-render.
48
+ - Types — `IObserverOptions`, `IObserverProps`, `ReactFC`.
49
+
50
+ ## Documentation
51
+
52
+ https://formvk.github.io/core/api/react
53
+
54
+ ## License
55
+
56
+ MIT
@@ -0,0 +1,56 @@
1
+ # @formvk/reactive-react
2
+
3
+ [English](./README.md) | [简体中文](./README.zh-CN.md)
4
+
5
+ `@formvk/reactive` 的 React 绑定。用 `observer` 包裹组件后,组件在渲染期间读取的可观察数据发生变化时会自动重新渲染。
6
+
7
+ ## 安装
8
+
9
+ ```bash
10
+ pnpm add @formvk/reactive-react
11
+ ```
12
+
13
+ `react` 与 `react-dom`(`>= 18`)是 peer 依赖。
14
+
15
+ ## 使用
16
+
17
+ ```tsx
18
+ import { observable } from '@formvk/reactive'
19
+ import { observer } from '@formvk/reactive-react'
20
+
21
+ const state = observable({ count: 0 })
22
+
23
+ export const Counter = observer(() => <button onClick={() => (state.count += 1)}>count: {state.count}</button>)
24
+ ```
25
+
26
+ 用于局部订阅的 render-prop 形式:
27
+
28
+ ```tsx
29
+ import { Observer } from '@formvk/reactive-react'
30
+
31
+ function Count() {
32
+ return <Observer>{() => <span>{state.count}</span>}</Observer>
33
+ }
34
+ ```
35
+
36
+ `observer` 支持 `{ forwardRef, displayName, scheduler }` 选项:
37
+
38
+ ```tsx
39
+ const Input = observer(MyInput, { forwardRef: true, displayName: 'Input' })
40
+ ```
41
+
42
+ ## API
43
+
44
+ - `observer(Component, options?)` — 带缓存的包装器,追踪可观察读取并触发重渲染。
45
+ - `Observer` — 以 render prop 作为 `children` 的组件。
46
+ - `useObserver(view, options?)` — 在 observer 的追踪上下文中执行渲染函数。
47
+ - `useForceUpdate()` — 强制重新渲染。
48
+ - 类型 — `IObserverOptions`、`IObserverProps`、`ReactFC`。
49
+
50
+ ## 文档
51
+
52
+ https://formvk.github.io/core/zh/api/react
53
+
54
+ ## License
55
+
56
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@formvk/reactive-react",
3
- "version": "0.1.0",
3
+ "version": "1.1.0",
4
4
  "description": "Formvk Reactive React Bindings",
5
5
  "keywords": [
6
6
  "form",
@@ -11,12 +11,16 @@
11
11
  ],
12
12
  "license": "MIT",
13
13
  "author": "yiyunwan",
14
+ "files": [
15
+ "dist",
16
+ "CHANGELOG.md"
17
+ ],
14
18
  "type": "module",
15
19
  "main": "dist/index.js",
16
20
  "module": "dist/index.js",
17
21
  "types": "dist/index.d.ts",
18
22
  "dependencies": {
19
- "@formvk/reactive": "^0.1.0",
23
+ "@formvk/reactive": "~1.1.0",
20
24
  "hoist-non-react-statics": "^3.3.2"
21
25
  },
22
26
  "devDependencies": {
@@ -1,75 +0,0 @@
1
- import { reactive } from '@formvk/reactive'
2
- import { expect, test, vi } from 'vitest'
3
-
4
- import { createAdministration, createTracker } from '../hooks/useObserver'
5
-
6
- /** 模拟 useObserver 首次渲染:建立 tracker 并执行一次 track */
7
- function mountTrack(view: () => void) {
8
- const adm = createAdministration()
9
- adm.tracker = createTracker(adm)
10
- adm.tracker.track(view)
11
- return adm
12
- }
13
-
14
- test('挂载前发生变更:只更新快照,不调用 onStoreChange', () => {
15
- const state = reactive({ count: 0 })
16
- const adm = mountTrack(() => state.count)
17
- const snapshotBefore = adm.getSnapshot()
18
-
19
- // 此时尚未 subscribe,onStoreChange 为 null,通知不应抛错
20
- state.count = 1
21
- expect(adm.onStoreChange).toBeNull()
22
- expect(adm.getSnapshot()).not.toBe(snapshotBefore)
23
- })
24
-
25
- test('挂载后变更走 onStoreChange,卸载后停止通知', () => {
26
- const state = reactive({ count: 0 })
27
- const adm = mountTrack(() => state.count)
28
- const onStoreChange = vi.fn()
29
- const cleanup = adm.subscribe(onStoreChange)
30
-
31
- state.count = 1
32
- expect(onStoreChange).toHaveBeenCalledTimes(1)
33
-
34
- cleanup()
35
- state.count = 2
36
- expect(onStoreChange).toHaveBeenCalledTimes(1)
37
- expect(adm.tracker).toBeNull()
38
- })
39
-
40
- test('卸载后重挂载会重建 tracker 并刷新快照,恢复响应', () => {
41
- const state = reactive({ count: 0 })
42
- const adm = mountTrack(() => state.count)
43
- const firstCleanup = adm.subscribe(vi.fn())
44
- firstCleanup()
45
- expect(adm.tracker).toBeNull()
46
-
47
- const staleSnapshot = adm.getSnapshot()
48
- const onStoreChange = vi.fn()
49
- const cleanup = adm.subscribe(onStoreChange)
50
- expect(adm.tracker).not.toBeNull()
51
- expect(adm.getSnapshot()).not.toBe(staleSnapshot)
52
-
53
- // 重建后的 tracker 需要重新 track 才能恢复依赖收集
54
- adm.tracker?.track(() => state.count)
55
- state.count = 1
56
- expect(onStoreChange).toHaveBeenCalledTimes(1)
57
- cleanup()
58
- })
59
-
60
- test('自定义 scheduler 在挂载后接管更新回调', () => {
61
- const state = reactive({ count: 0 })
62
- const scheduler = vi.fn((updater: () => void) => updater())
63
- const adm = createAdministration({ scheduler })
64
- adm.tracker = createTracker(adm, { scheduler })
65
- adm.tracker.track(() => state.count)
66
-
67
- const onStoreChange = vi.fn()
68
- const cleanup = adm.subscribe(onStoreChange)
69
- state.count = 1
70
- expect(scheduler).toHaveBeenCalledTimes(1)
71
- expect(scheduler.mock.calls[0][0]).toBe(onStoreChange)
72
- // scheduler 内部执行了 updater,因此 onStoreChange 也被调用
73
- expect(onStoreChange).toHaveBeenCalledTimes(1)
74
- cleanup()
75
- })
@@ -1,136 +0,0 @@
1
- import { reactive, shallowRef } from '@formvk/reactive'
2
- import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
3
- import { createRef, useState } from 'react'
4
- import type React from 'react'
5
- import { afterEach, expect, test, vi } from 'vitest'
6
-
7
- import { Observer, observer } from '../observer'
8
-
9
- afterEach(cleanup)
10
-
11
- test('observer 包裹的组件随响应式数据自动刷新', () => {
12
- const state = reactive({ count: 0 })
13
- const Counter = observer(() => <div>计数:{state.count}</div>)
14
-
15
- render(<Counter />)
16
- expect(screen.getByText('计数:0')).toBeTruthy()
17
-
18
- act(() => {
19
- state.count = 1
20
- })
21
- expect(screen.getByText('计数:1')).toBeTruthy()
22
- })
23
-
24
- test('observer 自带 memo:props 不变时父组件重渲染不带动子组件', () => {
25
- const childRenderCount = vi.fn()
26
- const Child = observer((props: { label: string }) => {
27
- childRenderCount()
28
- return <div>{props.label}</div>
29
- })
30
-
31
- function Parent() {
32
- const [tick, setTick] = useState(0)
33
- return (
34
- <div>
35
- <button onClick={() => setTick(v => v + 1)}>刷新父组件{tick}</button>
36
- <Child label="固定文案" />
37
- </div>
38
- )
39
- }
40
-
41
- render(<Parent />)
42
- expect(childRenderCount).toHaveBeenCalledTimes(1)
43
-
44
- fireEvent.click(screen.getByRole('button'))
45
- expect(screen.getByText('刷新父组件1')).toBeTruthy()
46
- expect(childRenderCount).toHaveBeenCalledTimes(1)
47
- })
48
-
49
- test('observer 的 props 变化时正常刷新', () => {
50
- const Child = observer((props: { label: string }) => <div>{props.label}</div>)
51
- function Parent() {
52
- const [label, setLabel] = useState('旧文案')
53
- return (
54
- <div>
55
- <button onClick={() => setLabel('新文案')}>换文案</button>
56
- <Child label={label} />
57
- </div>
58
- )
59
- }
60
-
61
- render(<Parent />)
62
- expect(screen.getByText('旧文案')).toBeTruthy()
63
- fireEvent.click(screen.getByRole('button'))
64
- expect(screen.getByText('新文案')).toBeTruthy()
65
- })
66
-
67
- test('observer forwardRef 选项透传 ref', () => {
68
- const Input = observer(
69
- (props: { value: string; ref?: React.Ref<HTMLInputElement> }) => (
70
- <input ref={props.ref} value={props.value} readOnly />
71
- ),
72
- { forwardRef: true }
73
- )
74
-
75
- const inputRef = createRef<HTMLInputElement>()
76
- render(<Input value="hello" ref={inputRef} />)
77
- expect(inputRef.current).toBeInstanceOf(HTMLInputElement)
78
- expect(inputRef.current?.value).toBe('hello')
79
- })
80
-
81
- test('observer 支持 displayName 并提升组件静态属性', () => {
82
- const Card = observer((props: { title: string }) => <div>{props.title}</div>, {
83
- displayName: 'ObservedCard',
84
- })
85
- expect(Card.displayName).toBe('ObservedCard')
86
-
87
- const WithStatic = observer((props: { name: string }) => <div>{props.name}</div>)
88
- ;(WithStatic as any).staticFlag = 'static-value'
89
- expect((WithStatic as any).staticFlag).toBe('static-value')
90
- })
91
-
92
- test('Observer 组件以 render-prop 形式响应数据变化', () => {
93
- const state = reactive({ count: 0 })
94
-
95
- render(<Observer>{() => <div>render-prop:{state.count}</div>}</Observer>)
96
- expect(screen.getByText('render-prop:0')).toBeTruthy()
97
-
98
- act(() => {
99
- state.count = 1
100
- })
101
- expect(screen.getByText('render-prop:1')).toBeTruthy()
102
- })
103
-
104
- test('Observer 组件支持直接传入 ReactNode 子元素', () => {
105
- render(
106
- <Observer>
107
- <div>静态子节点</div>
108
- </Observer>
109
- )
110
- expect(screen.getByText('静态子节点')).toBeTruthy()
111
- })
112
-
113
- test('observer 与 2023-11 标准装饰器类协作', () => {
114
- class Store {
115
- @shallowRef accessor count = 0
116
- @shallowRef accessor name = 'formvk'
117
- }
118
- const store = new Store()
119
- const renderCount = vi.fn()
120
-
121
- const Counter = observer(() => {
122
- renderCount()
123
- return (
124
- <div>
125
- {store.name}-{store.count}
126
- </div>
127
- )
128
- })
129
-
130
- render(<Counter />)
131
- act(() => {
132
- store.count = 1
133
- })
134
- expect(screen.getByText('formvk-1')).toBeTruthy()
135
- expect(renderCount).toHaveBeenCalledTimes(2)
136
- })
@@ -1,74 +0,0 @@
1
- import { afterEach, expect, test, vi } from 'vitest'
2
-
3
- afterEach(() => {
4
- vi.useRealTimers()
5
- vi.unstubAllGlobals()
6
- vi.resetModules()
7
- })
8
-
9
- test('原生 FinalizationRegistry 可用时走原生注册与注销', async () => {
10
- vi.resetModules()
11
- const registerSpy = vi.spyOn(FinalizationRegistry.prototype, 'register')
12
- const unregisterSpy = vi.spyOn(FinalizationRegistry.prototype, 'unregister')
13
- const { trackerRegistry } = await import('../hooks/trackerRegistry')
14
-
15
- const target = {}
16
- const token = {}
17
- const dispose = vi.fn()
18
- trackerRegistry.register(target, dispose, token)
19
- expect(registerSpy).toHaveBeenCalledWith(target, dispose, token)
20
-
21
- trackerRegistry.unregister(token)
22
- expect(unregisterSpy).toHaveBeenCalledWith(token)
23
-
24
- registerSpy.mockRestore()
25
- unregisterSpy.mockRestore()
26
- })
27
-
28
- test('无原生 FinalizationRegistry 时退化为定时器,到期执行 dispose', async () => {
29
- vi.stubGlobal('FinalizationRegistry', undefined)
30
- vi.resetModules()
31
- vi.useFakeTimers()
32
- const { trackerRegistry } = await import('../hooks/trackerRegistry')
33
-
34
- const dispose = vi.fn()
35
- const token = {}
36
- trackerRegistry.register({}, dispose, token)
37
-
38
- vi.advanceTimersByTime(9999)
39
- expect(dispose).not.toHaveBeenCalled()
40
- vi.advanceTimersByTime(1)
41
- expect(dispose).toHaveBeenCalledTimes(1)
42
- })
43
-
44
- test('定时器兜底在 unregister 后取消,不再执行 dispose', async () => {
45
- vi.stubGlobal('FinalizationRegistry', undefined)
46
- vi.resetModules()
47
- vi.useFakeTimers()
48
- const { trackerRegistry } = await import('../hooks/trackerRegistry')
49
-
50
- const dispose = vi.fn()
51
- const token = {}
52
- trackerRegistry.register({}, dispose, token)
53
- trackerRegistry.unregister(token)
54
-
55
- vi.advanceTimersByTime(10000)
56
- expect(dispose).not.toHaveBeenCalled()
57
- })
58
-
59
- test('同一 token 重复注册会先清理上一次的定时器', async () => {
60
- vi.stubGlobal('FinalizationRegistry', undefined)
61
- vi.resetModules()
62
- vi.useFakeTimers()
63
- const { trackerRegistry } = await import('../hooks/trackerRegistry')
64
-
65
- const first = vi.fn()
66
- const second = vi.fn()
67
- const token = {}
68
- trackerRegistry.register({}, first, token)
69
- trackerRegistry.register({}, second, token)
70
-
71
- vi.advanceTimersByTime(10000)
72
- expect(first).not.toHaveBeenCalled()
73
- expect(second).toHaveBeenCalledTimes(1)
74
- })
@@ -1,192 +0,0 @@
1
- import { batch, reactive } from '@formvk/reactive'
2
- import { act, cleanup, render, screen } from '@testing-library/react'
3
- import { StrictMode } from 'react'
4
- import { afterEach, expect, test, vi } from 'vitest'
5
-
6
- import { useForceUpdate } from '../hooks/useForceUpdate'
7
- import { useObserver } from '../hooks/useObserver'
8
-
9
- afterEach(cleanup)
10
-
11
- test('useForceUpdate 返回稳定的刷新函数并触发重渲染', () => {
12
- const renderCount = vi.fn()
13
- let updater: () => void = () => {}
14
-
15
- function Component() {
16
- renderCount()
17
- updater = useForceUpdate()
18
- return <div>强制刷新</div>
19
- }
20
-
21
- render(<Component />)
22
- expect(renderCount).toHaveBeenCalledTimes(1)
23
-
24
- act(() => updater())
25
- expect(renderCount).toHaveBeenCalledTimes(2)
26
- })
27
-
28
- test('useObserver 读取的响应式数据变化时自动重渲染', () => {
29
- const state = reactive({ count: 0 })
30
- const renderCount = vi.fn()
31
-
32
- function Counter() {
33
- renderCount()
34
- return useObserver(() => <div>计数:{state.count}</div>)
35
- }
36
-
37
- render(<Counter />)
38
- expect(screen.getByText('计数:0')).toBeTruthy()
39
- expect(renderCount).toHaveBeenCalledTimes(1)
40
-
41
- act(() => {
42
- state.count = 1
43
- })
44
- expect(screen.getByText('计数:1')).toBeTruthy()
45
- expect(renderCount).toHaveBeenCalledTimes(2)
46
- })
47
-
48
- test('useObserver 只追踪 view 中实际读取的字段', () => {
49
- const state = reactive({ a: 1, b: 10 })
50
- const renderCount = vi.fn()
51
-
52
- function Viewer() {
53
- renderCount()
54
- return useObserver(() => <div>{state.a}</div>)
55
- }
56
-
57
- render(<Viewer />)
58
- act(() => {
59
- state.b = 20
60
- })
61
- expect(renderCount).toHaveBeenCalledTimes(1)
62
-
63
- act(() => {
64
- state.a = 2
65
- })
66
- expect(renderCount).toHaveBeenCalledTimes(2)
67
- })
68
-
69
- test('useObserver 每次渲染都会重新 track,能拿到最新 props', () => {
70
- const state = reactive({ suffix: '!' })
71
-
72
- function Viewer(props: { prefix: string }) {
73
- return useObserver(() => (
74
- <div>
75
- {props.prefix}
76
- {state.suffix}
77
- </div>
78
- ))
79
- }
80
-
81
- const { rerender } = render(<Viewer prefix="你好" />)
82
- expect(screen.getByText('你好!')).toBeTruthy()
83
-
84
- rerender(<Viewer prefix="再见" />)
85
- expect(screen.getByText('再见!')).toBeTruthy()
86
-
87
- act(() => {
88
- state.suffix = '?'
89
- })
90
- expect(screen.getByText('再见?')).toBeTruthy()
91
- })
92
-
93
- test('同步连续写入由 React 批处理合并为一次渲染', () => {
94
- const state = reactive({ count: 0 })
95
- const renderCount = vi.fn()
96
-
97
- function Counter() {
98
- renderCount()
99
- return useObserver(() => <div>{state.count}</div>)
100
- }
101
-
102
- render(<Counter />)
103
- act(() => {
104
- state.count = 1
105
- state.count = 2
106
- state.count = 3
107
- })
108
- expect(screen.getByText('3')).toBeTruthy()
109
- expect(renderCount).toHaveBeenCalledTimes(2)
110
- })
111
-
112
- test('batch 批次内的多次写入在批次结束后只渲染一次', () => {
113
- const state = reactive({ a: 0, b: 0 })
114
- const renderCount = vi.fn()
115
-
116
- function Counter() {
117
- renderCount()
118
- return useObserver(() => (
119
- <div>
120
- {state.a}-{state.b}
121
- </div>
122
- ))
123
- }
124
-
125
- render(<Counter />)
126
- act(() => {
127
- batch(() => {
128
- state.a = 1
129
- state.b = 1
130
- state.a = 2
131
- })
132
- })
133
- expect(screen.getByText('2-1')).toBeTruthy()
134
- expect(renderCount).toHaveBeenCalledTimes(2)
135
- })
136
-
137
- test('useObserver 支持自定义 scheduler 接管更新', () => {
138
- const state = reactive({ count: 0 })
139
- const scheduled = vi.fn((updater: () => void) => updater())
140
- const renderCount = vi.fn()
141
-
142
- function Counter() {
143
- renderCount()
144
- return useObserver(() => <div>{state.count}</div>, { scheduler: scheduled })
145
- }
146
-
147
- render(<Counter />)
148
- act(() => {
149
- state.count = 1
150
- })
151
- expect(scheduled).toHaveBeenCalledTimes(1)
152
- expect(screen.getByText('1')).toBeTruthy()
153
- expect(renderCount).toHaveBeenCalledTimes(2)
154
- })
155
-
156
- test('useObserver 组件卸载后不再响应数据变化', () => {
157
- const state = reactive({ count: 0 })
158
- const renderCount = vi.fn()
159
-
160
- function Counter() {
161
- renderCount()
162
- return useObserver(() => <div>{state.count}</div>)
163
- }
164
-
165
- const { unmount } = render(<Counter />)
166
- unmount()
167
- act(() => {
168
- state.count = 1
169
- state.count = 2
170
- })
171
- expect(renderCount).toHaveBeenCalledTimes(1)
172
- })
173
-
174
- test('useObserver 在 StrictMode 双挂载下行为正确且无报错', () => {
175
- const state = reactive({ count: 0 })
176
-
177
- function Counter() {
178
- return useObserver(() => <div>严格模式:{state.count}</div>)
179
- }
180
-
181
- render(
182
- <StrictMode>
183
- <Counter />
184
- </StrictMode>
185
- )
186
- expect(screen.getByText('严格模式:0')).toBeTruthy()
187
-
188
- act(() => {
189
- state.count = 1
190
- })
191
- expect(screen.getByText('严格模式:1')).toBeTruthy()
192
- })
@@ -1,2 +0,0 @@
1
- export * from './useForceUpdate'
2
- export * from './useObserver'
@@ -1,46 +0,0 @@
1
- import type { Dispose } from '@formvk/reactive'
2
-
3
- const FALLBACK_DELAY = 10000
4
-
5
- /**
6
- * 渲染期创建的 Tracker 在组件被放弃挂载(StrictMode/Concurrent 中断)时
7
- * 等不到 effect 清理,需要垃圾回收兜底:原生 FinalizationRegistry 可用时用它,
8
- * 否则退化为定时器,避免响应式订阅泄漏。
9
- */
10
- class TrackerRegistry {
11
- private native: FinalizationRegistry<Dispose> | undefined
12
- private timers = new Map<object, ReturnType<typeof setTimeout>>()
13
-
14
- constructor() {
15
- if (typeof FinalizationRegistry !== 'undefined') {
16
- this.native = new FinalizationRegistry<Dispose>(dispose => dispose())
17
- }
18
- }
19
-
20
- /** target 被 GC 时执行 dispose;token 用于后续 unregister */
21
- register(target: object, dispose: Dispose, token: object): void {
22
- this.unregister(token)
23
- if (this.native) {
24
- this.native.register(target, dispose, token)
25
- return
26
- }
27
- this.timers.set(
28
- token,
29
- setTimeout(() => {
30
- this.timers.delete(token)
31
- dispose()
32
- }, FALLBACK_DELAY)
33
- )
34
- }
35
-
36
- unregister(token: object): void {
37
- this.native?.unregister(token)
38
- const timer = this.timers.get(token)
39
- if (timer) {
40
- clearTimeout(timer)
41
- this.timers.delete(token)
42
- }
43
- }
44
- }
45
-
46
- export const trackerRegistry = new TrackerRegistry()
@@ -1,7 +0,0 @@
1
- import { useReducer } from 'react'
2
-
3
- /** 返回一个稳定的强制刷新函数,React 18+ 自动批处理会合并同一轮多次调用 */
4
- export function useForceUpdate(): () => void {
5
- const [, forceUpdate] = useReducer((tick: number) => tick + 1, 0)
6
- return forceUpdate
7
- }
@@ -1,77 +0,0 @@
1
- import { Tracker } from '@formvk/reactive'
2
- import { useRef, useSyncExternalStore } from 'react'
3
-
4
- import type { IObserverOptions } from '../types'
5
- import { trackerRegistry } from './trackerRegistry'
6
-
7
- /** @internal 仅供单元测试验证订阅状态机,不通过包入口公开 */
8
- export interface ObserverAdministration {
9
- tracker: Tracker | null
10
- onStoreChange: (() => void) | null
11
- /** 快照值:每次响应式变更都换成新 Symbol,驱动 useSyncExternalStore 重渲染 */
12
- stateVersion: symbol
13
- subscribe: (onStoreChange: () => void) => () => void
14
- getSnapshot: () => symbol
15
- }
16
-
17
- /** @internal 仅供单元测试验证订阅状态机,不通过包入口公开 */
18
- export function createTracker(adm: ObserverAdministration, options?: IObserverOptions): Tracker {
19
- return new Tracker(() => {
20
- adm.stateVersion = Symbol()
21
- // 首次渲染到挂载之间 onStoreChange 还不存在,useSyncExternalStore 会靠快照版本补刷新
22
- if (adm.onStoreChange) {
23
- if (typeof options?.scheduler === 'function') {
24
- options.scheduler(adm.onStoreChange)
25
- } else {
26
- adm.onStoreChange()
27
- }
28
- }
29
- })
30
- }
31
-
32
- /** @internal 仅供单元测试验证订阅状态机,不通过包入口公开 */
33
- export function createAdministration(options?: IObserverOptions): ObserverAdministration {
34
- const adm: ObserverAdministration = {
35
- tracker: null,
36
- onStoreChange: null,
37
- stateVersion: Symbol(),
38
- subscribe(onStoreChange) {
39
- // 正常挂载后取消 GC 兜底,改由 effect 清理负责
40
- trackerRegistry.unregister(adm)
41
- adm.onStoreChange = onStoreChange
42
- if (!adm.tracker) {
43
- // StrictMode 重挂载(中间不会重新渲染)或追踪器已被回收时,重建并刷新快照
44
- adm.tracker = createTracker(adm, options)
45
- adm.stateVersion = Symbol()
46
- }
47
- return () => {
48
- adm.onStoreChange = null
49
- adm.tracker?.dispose()
50
- adm.tracker = null
51
- }
52
- },
53
- getSnapshot() {
54
- return adm.stateVersion
55
- },
56
- }
57
- return adm
58
- }
59
-
60
- /**
61
- * 在渲染期执行 view 并追踪其中读取的响应式数据,
62
- * 依赖变化时自动调度组件重渲染;每次渲染都会重新 track 以拿到最新 props 与依赖。
63
- */
64
- export function useObserver<T>(view: () => T, options?: IObserverOptions): T {
65
- const admRef = useRef<ObserverAdministration | null>(null)
66
- if (!admRef.current) {
67
- admRef.current = createAdministration(options)
68
- }
69
- const adm = admRef.current
70
- if (!adm.tracker) {
71
- adm.tracker = createTracker(adm, options)
72
- // 渲染可能被 StrictMode/Concurrent 放弃而永不挂载,注册 GC 兜底回收
73
- trackerRegistry.register(admRef, () => adm.tracker?.dispose(), adm)
74
- }
75
- useSyncExternalStore(adm.subscribe, adm.getSnapshot, adm.getSnapshot)
76
- return adm.tracker.track(view)
77
- }
package/src/index.ts DELETED
@@ -1,3 +0,0 @@
1
- export * from './observer'
2
- export * from './hooks'
3
- export * from './types'
package/src/observer.tsx DELETED
@@ -1,54 +0,0 @@
1
- import hoistNonReactStatics from 'hoist-non-react-statics'
2
- import { createElement, forwardRef, memo, Fragment } from 'react'
3
- import type React from 'react'
4
-
5
- import { useObserver } from './hooks/useObserver'
6
- import type { IObserverOptions, IObserverProps, ReactFC } from './types'
7
-
8
- /** observer 包裹后的组件类型:按 forwardRef 选项决定是否携带 ref */
9
- type ObserverComponent<P, Options extends IObserverOptions> = React.MemoExoticComponent<
10
- ReactFC<
11
- Options extends { forwardRef: true }
12
- ? P & {
13
- ref?: 'ref' extends keyof P ? P['ref'] : React.RefAttributes<unknown>
14
- }
15
- : React.PropsWithoutRef<P>
16
- >
17
- >
18
-
19
- export function observer<P, Options extends IObserverOptions = IObserverOptions>(
20
- component: ReactFC<P>,
21
- options?: Options
22
- ): ObserverComponent<P, Options> {
23
- const realOptions: IObserverOptions = {
24
- forwardRef: false,
25
- ...options,
26
- }
27
-
28
- const wrappedComponent = realOptions.forwardRef
29
- ? forwardRef(
30
- // React 19 的 FC 返回类型含 Promise<ReactNode>,forwardRef 渲染函数不接受,此处为同步 observer 场景收窄
31
- ((props: any, ref: any) => {
32
- return useObserver(() => component({ ...props, ref }), realOptions)
33
- }) as React.ForwardRefRenderFunction<any, any>
34
- )
35
- : (props: any) => {
36
- return useObserver(() => component(props), realOptions)
37
- }
38
-
39
- const memoComponent = memo(wrappedComponent)
40
-
41
- hoistNonReactStatics(memoComponent, component)
42
-
43
- if (realOptions.displayName) {
44
- memoComponent.displayName = realOptions.displayName
45
- }
46
-
47
- // wrappedComponent 是 forwardRef/普通函数两种形态的联合,按 options 条件类型收窄到声明签名
48
- return memoComponent as ObserverComponent<P, Options>
49
- }
50
-
51
- export const Observer = observer((props: IObserverProps) => {
52
- const children = typeof props.children === 'function' ? props.children() : props.children
53
- return createElement(Fragment, null, children)
54
- })
package/src/types.ts DELETED
@@ -1,20 +0,0 @@
1
- import type React from 'react'
2
-
3
- export interface IObserverOptions {
4
- /** 是否向被包裹组件透传 ref */
5
- forwardRef?: boolean
6
- /** 自定义更新调度,收到响应式变更时默认直接触发 React 更新 */
7
- scheduler?: (updater: () => void) => void
8
- /** 包裹后组件的 displayName */
9
- displayName?: string
10
- }
11
-
12
- export interface IObserverProps {
13
- children?: (() => React.ReactElement) | React.ReactNode
14
- }
15
-
16
- export type Modify<T, R> = Omit<T, keyof R> & R
17
-
18
- export type ReactPropsWithChildren<P> = Modify<{ children?: React.ReactNode | undefined }, P>
19
-
20
- export type ReactFC<P = {}> = React.FC<ReactPropsWithChildren<P>>
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "paths": {},
5
- "types": []
6
- },
7
- "include": ["./src/**/*.ts", "./src/**/*.tsx"],
8
- "exclude": ["./src/**/__tests__/**", "./__tests__/**"]
9
- }
package/tsconfig.json DELETED
@@ -1,4 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.json",
3
- "include": ["./src/**/*.ts", "./src/**/*.tsx"]
4
- }
package/vite.config.ts DELETED
@@ -1,46 +0,0 @@
1
- import swc from '@rollup/plugin-swc'
2
- import react from '@vitejs/plugin-react'
3
- import { defineConfig, withFilter } from 'vite'
4
- import dts from 'vite-plugin-dts'
5
-
6
- export default defineConfig({
7
- plugins: [
8
- // 官方 React 插件:负责 JSX 自动运行时与 Fast Refresh(底层配置 Vite 内置 oxc)
9
- react(),
10
- dts({ tsconfigPath: './tsconfig.build.json', entryRoot: 'src', bundleTypes: true }),
11
- withFilter(
12
- swc({
13
- swc: {
14
- jsc: {
15
- parser: { syntax: 'typescript', tsx: true, decorators: true },
16
- transform: {
17
- // 使用 2023-11 版标准装饰器;插件默认值是 legacyDecorator: true,需显式关闭
18
- legacyDecorator: false,
19
- decoratorVersion: '2023-11',
20
- react: { runtime: 'automatic' },
21
- },
22
- },
23
- },
24
- }),
25
- // 仅当文件包含装饰器时才运行此转换,普通 tsx 的 JSX 交给 @vitejs/plugin-react
26
- { transform: { code: /^\s*@[\w$.]+/m } }
27
- ),
28
- ],
29
- test: {
30
- environment: 'happy-dom',
31
- },
32
- build: {
33
- lib: {
34
- entry: 'src/index.ts',
35
- name: 'Formvk.ReactiveReact',
36
- fileName: 'index',
37
- formats: ['es'],
38
- },
39
- minify: false,
40
- sourcemap: true,
41
- target: 'esnext',
42
- rollupOptions: {
43
- external: ['react', 'react-dom', 'react/jsx-runtime', 'hoist-non-react-statics', '@formvk/reactive'],
44
- },
45
- },
46
- })