1 | import { PureComponent, Component, ComponentClass, ClassAttributes } from "react"
|
2 | import {
|
3 | _allowStateChanges,
|
4 | Reaction,
|
5 | _allowStateReadsStart,
|
6 | _allowStateReadsEnd,
|
7 | _getGlobalState
|
8 | } from "mobx"
|
9 | import {
|
10 | isUsingStaticRendering,
|
11 | _observerFinalizationRegistry as observerFinalizationRegistry
|
12 | } from "mobx-react-lite"
|
13 | import { shallowEqual, patch } from "./utils/utils"
|
14 |
|
15 | const administrationSymbol = Symbol("ObserverAdministration")
|
16 | const isMobXReactObserverSymbol = Symbol("isMobXReactObserver")
|
17 |
|
18 | let observablePropDescriptors: PropertyDescriptorMap
|
19 | if (__DEV__) {
|
20 | observablePropDescriptors = {
|
21 | props: createObservablePropDescriptor("props"),
|
22 | state: createObservablePropDescriptor("state"),
|
23 | context: createObservablePropDescriptor("context")
|
24 | }
|
25 | }
|
26 |
|
27 | type ObserverAdministration = {
|
28 | reaction: Reaction | null
|
29 | forceUpdate: Function | null
|
30 | mounted: boolean
|
31 | reactionInvalidatedBeforeMount: boolean
|
32 | name: string
|
33 |
|
34 | props: any
|
35 | state: any
|
36 | context: any
|
37 | }
|
38 |
|
39 | function getAdministration(component: Component): ObserverAdministration {
|
40 |
|
41 |
|
42 |
|
43 | return (component[administrationSymbol] ??= {
|
44 | reaction: null,
|
45 | mounted: false,
|
46 | reactionInvalidatedBeforeMount: false,
|
47 | forceUpdate: null,
|
48 | name: getDisplayName(component.constructor as ComponentClass),
|
49 | state: undefined,
|
50 | props: undefined,
|
51 | context: undefined
|
52 | })
|
53 | }
|
54 |
|
55 | export function makeClassComponentObserver(
|
56 | componentClass: ComponentClass<any, any>
|
57 | ): ComponentClass<any, any> {
|
58 | const { prototype } = componentClass
|
59 |
|
60 | if (componentClass[isMobXReactObserverSymbol]) {
|
61 | const displayName = getDisplayName(componentClass)
|
62 | throw new Error(
|
63 | `The provided component class (${displayName}) has already been declared as an observer component.`
|
64 | )
|
65 | } else {
|
66 | componentClass[isMobXReactObserverSymbol] = true
|
67 | }
|
68 |
|
69 | if (prototype.componentWillReact) {
|
70 | throw new Error("The componentWillReact life-cycle event is no longer supported")
|
71 | }
|
72 | if (componentClass["__proto__"] !== PureComponent) {
|
73 | if (!prototype.shouldComponentUpdate) {
|
74 | prototype.shouldComponentUpdate = observerSCU
|
75 | } else if (prototype.shouldComponentUpdate !== observerSCU) {
|
76 |
|
77 | throw new Error(
|
78 | "It is not allowed to use shouldComponentUpdate in observer based components."
|
79 | )
|
80 | }
|
81 | }
|
82 |
|
83 | if (__DEV__) {
|
84 | Object.defineProperties(prototype, observablePropDescriptors)
|
85 | }
|
86 |
|
87 | const originalRender = prototype.render
|
88 | if (typeof originalRender !== "function") {
|
89 | const displayName = getDisplayName(componentClass)
|
90 | throw new Error(
|
91 | `[mobx-react] class component (${displayName}) is missing \`render\` method.` +
|
92 | `\n\`observer\` requires \`render\` being a function defined on prototype.` +
|
93 | `\n\`render = () => {}\` or \`render = function() {}\` is not supported.`
|
94 | )
|
95 | }
|
96 |
|
97 | prototype.render = function () {
|
98 | Object.defineProperty(this, "render", {
|
99 |
|
100 | configurable: false,
|
101 | writable: false,
|
102 | value: isUsingStaticRendering()
|
103 | ? originalRender
|
104 | : createReactiveRender.call(this, originalRender)
|
105 | })
|
106 | return this.render()
|
107 | }
|
108 |
|
109 | const originalComponentDidMount = prototype.componentDidMount
|
110 | prototype.componentDidMount = function () {
|
111 | if (__DEV__ && this.componentDidMount !== Object.getPrototypeOf(this).componentDidMount) {
|
112 | const displayName = getDisplayName(componentClass)
|
113 | throw new Error(
|
114 | `[mobx-react] \`observer(${displayName}).componentDidMount\` must be defined on prototype.` +
|
115 | `\n\`componentDidMount = () => {}\` or \`componentDidMount = function() {}\` is not supported.`
|
116 | )
|
117 | }
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 |
|
131 | const admin = getAdministration(this)
|
132 |
|
133 | admin.mounted = true
|
134 |
|
135 |
|
136 | observerFinalizationRegistry.unregister(this)
|
137 |
|
138 |
|
139 |
|
140 |
|
141 |
|
142 | admin.forceUpdate = () => this.forceUpdate()
|
143 |
|
144 | if (!admin.reaction || admin.reactionInvalidatedBeforeMount) {
|
145 |
|
146 |
|
147 |
|
148 |
|
149 |
|
150 |
|
151 |
|
152 |
|
153 |
|
154 |
|
155 | admin.forceUpdate()
|
156 | }
|
157 | return originalComponentDidMount?.apply(this, arguments)
|
158 | }
|
159 |
|
160 |
|
161 | patch(prototype, "componentWillUnmount", function () {
|
162 | if (isUsingStaticRendering()) {
|
163 | return
|
164 | }
|
165 | const admin = getAdministration(this)
|
166 | admin.reaction?.dispose()
|
167 | admin.reaction = null
|
168 | admin.forceUpdate = null
|
169 | admin.mounted = false
|
170 | admin.reactionInvalidatedBeforeMount = false
|
171 | })
|
172 |
|
173 | return componentClass
|
174 | }
|
175 |
|
176 |
|
177 | function getDisplayName(componentClass: ComponentClass) {
|
178 | return componentClass.displayName || componentClass.name || "<component>"
|
179 | }
|
180 |
|
181 | function createReactiveRender(originalRender: any) {
|
182 | const boundOriginalRender = originalRender.bind(this)
|
183 |
|
184 | const admin = getAdministration(this)
|
185 |
|
186 | function reactiveRender() {
|
187 | if (!admin.reaction) {
|
188 |
|
189 | admin.reaction = createReaction(admin)
|
190 | if (!admin.mounted) {
|
191 |
|
192 |
|
193 | observerFinalizationRegistry.register(this, admin, this)
|
194 | }
|
195 | }
|
196 |
|
197 | let error: unknown = undefined
|
198 | let renderResult = undefined
|
199 | admin.reaction.track(() => {
|
200 | try {
|
201 |
|
202 |
|
203 | renderResult = _allowStateChanges(false, boundOriginalRender)
|
204 | } catch (e) {
|
205 | error = e
|
206 | }
|
207 | })
|
208 | if (error) {
|
209 | throw error
|
210 | }
|
211 | return renderResult
|
212 | }
|
213 |
|
214 | return reactiveRender
|
215 | }
|
216 |
|
217 | function createReaction(admin: ObserverAdministration) {
|
218 | return new Reaction(`${admin.name}.render()`, () => {
|
219 | if (!admin.mounted) {
|
220 |
|
221 |
|
222 |
|
223 |
|
224 | admin.reactionInvalidatedBeforeMount = true
|
225 | return
|
226 | }
|
227 |
|
228 | try {
|
229 | admin.forceUpdate?.()
|
230 | } catch (error) {
|
231 | admin.reaction?.dispose()
|
232 | admin.reaction = null
|
233 | }
|
234 | })
|
235 | }
|
236 |
|
237 | function observerSCU(nextProps: ClassAttributes<any>, nextState: any): boolean {
|
238 | if (isUsingStaticRendering()) {
|
239 | console.warn(
|
240 | "[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side."
|
241 | )
|
242 | }
|
243 |
|
244 | if (this.state !== nextState) {
|
245 | return true
|
246 | }
|
247 |
|
248 |
|
249 |
|
250 |
|
251 | return !shallowEqual(this.props, nextProps)
|
252 | }
|
253 |
|
254 | function createObservablePropDescriptor(key: "props" | "state" | "context") {
|
255 | return {
|
256 | configurable: true,
|
257 | enumerable: true,
|
258 | get() {
|
259 | const admin = getAdministration(this)
|
260 | const derivation = _getGlobalState().trackingDerivation
|
261 | if (derivation && derivation !== admin.reaction) {
|
262 | throw new Error(
|
263 | `[mobx-react] Cannot read "${admin.name}.${key}" in a reactive context, as it isn't observable.
|
264 | Please use component lifecycle method to copy the value into a local observable first.
|
265 | See https://github.com/mobxjs/mobx/blob/main/packages/mobx-react/README.md#note-on-using-props-and-state-in-derivations`
|
266 | )
|
267 | }
|
268 | return admin[key]
|
269 | },
|
270 | set(value) {
|
271 | getAdministration(this)[key] = value
|
272 | }
|
273 | }
|
274 | }
|