mobx-mantle 0.3.6 → 0.6.1
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/README.md +897 -154
- package/dist/behaviors/index.cjs +419 -0
- package/dist/behaviors/index.cjs.map +1 -0
- package/dist/behaviors/index.d.cts +275 -0
- package/dist/behaviors/index.d.ts +275 -0
- package/dist/behaviors/index.js +419 -0
- package/dist/behaviors/index.js.map +1 -0
- package/dist/chunk-LP5TAGSI.js +9 -0
- package/dist/chunk-LP5TAGSI.js.map +1 -0
- package/dist/chunk-WNF647U6.cjs +9 -0
- package/dist/chunk-WNF647U6.cjs.map +1 -0
- package/dist/index.cjs +1172 -258
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +431 -83
- package/dist/index.d.ts +431 -83
- package/dist/index.js +1159 -200
- package/dist/index.js.map +1 -1
- package/dist/reactive-args-BBucrU54.d.cts +32 -0
- package/dist/reactive-args-BBucrU54.d.ts +32 -0
- package/dist/testing/index.cjs +33 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +18 -0
- package/dist/testing/index.d.ts +18 -0
- package/dist/testing/index.js +33 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +42 -8
package/dist/index.js
CHANGED
|
@@ -1,21 +1,31 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { useObserver } from "mobx-react-lite";
|
|
1
|
+
import {
|
|
2
|
+
toValue
|
|
3
|
+
} from "./chunk-LP5TAGSI.js";
|
|
5
4
|
|
|
6
|
-
// src/
|
|
7
|
-
import
|
|
5
|
+
// src/services.tsx
|
|
6
|
+
import React from "react";
|
|
8
7
|
|
|
9
8
|
// src/config.ts
|
|
9
|
+
import { configure as mobxConfigure } from "mobx";
|
|
10
10
|
var globalConfig = {
|
|
11
|
-
autoObservable: true
|
|
11
|
+
autoObservable: true,
|
|
12
|
+
cacheAnnotations: true,
|
|
13
|
+
manageMobxActions: false
|
|
12
14
|
};
|
|
15
|
+
var actionPolicyApplied = false;
|
|
16
|
+
function applyMobxActionPolicy() {
|
|
17
|
+
if (actionPolicyApplied) return;
|
|
18
|
+
actionPolicyApplied = true;
|
|
19
|
+
if (globalConfig.manageMobxActions === true) {
|
|
20
|
+
mobxConfigure({ enforceActions: "never" });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
13
23
|
function reportError(error, context) {
|
|
14
24
|
if (globalConfig.onError) {
|
|
15
25
|
globalConfig.onError(error, context);
|
|
16
26
|
} else {
|
|
17
27
|
console.error(
|
|
18
|
-
`[mobx-mantle] Error in ${context.isBehavior ? "behavior" : "
|
|
28
|
+
`[mobx-mantle] Error in ${context.isBehavior ? "behavior" : "component"} ${context.name}.${context.phase}():`,
|
|
19
29
|
error
|
|
20
30
|
);
|
|
21
31
|
}
|
|
@@ -24,18 +34,349 @@ function configure(config) {
|
|
|
24
34
|
Object.assign(globalConfig, config);
|
|
25
35
|
}
|
|
26
36
|
|
|
37
|
+
// src/services.tsx
|
|
38
|
+
import { jsx } from "react/jsx-runtime";
|
|
39
|
+
function createServiceToken(description) {
|
|
40
|
+
return Symbol(description);
|
|
41
|
+
}
|
|
42
|
+
var ServiceContext = React.createContext(void 0);
|
|
43
|
+
function ServiceProvider({ resolve, children }) {
|
|
44
|
+
return /* @__PURE__ */ jsx(ServiceContext.Provider, { value: resolve, children });
|
|
45
|
+
}
|
|
46
|
+
var constructingScope;
|
|
47
|
+
var scopes = /* @__PURE__ */ new WeakMap();
|
|
48
|
+
function runWithScope(scope, construct) {
|
|
49
|
+
const previous = constructingScope;
|
|
50
|
+
constructingScope = scope;
|
|
51
|
+
try {
|
|
52
|
+
return construct();
|
|
53
|
+
} finally {
|
|
54
|
+
constructingScope = previous;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function withInjectionScope(resolve, construct) {
|
|
58
|
+
return runWithScope({ resolve: resolve ?? globalConfig.resolveService, values: /* @__PURE__ */ new WeakSet() }, construct);
|
|
59
|
+
}
|
|
60
|
+
function captureServiceScope(owner) {
|
|
61
|
+
scopes.set(owner, constructingScope ?? { resolve: globalConfig.resolveService, values: /* @__PURE__ */ new WeakSet() });
|
|
62
|
+
}
|
|
63
|
+
function resolveService(owner, token) {
|
|
64
|
+
return resolveInScope(scopes.get(owner), token);
|
|
65
|
+
}
|
|
66
|
+
function inject(token) {
|
|
67
|
+
if (!constructingScope) {
|
|
68
|
+
throw new Error("[mobx-mantle] inject() requires an active construction scope. Use this.inject() in later methods, or withInjectionScope() outside React.");
|
|
69
|
+
}
|
|
70
|
+
return resolveInScope(constructingScope, token);
|
|
71
|
+
}
|
|
72
|
+
function resolveInScope(scope, token) {
|
|
73
|
+
if (!scope?.resolve) throw new Error("[mobx-mantle] Service injection requires configure({ resolveService }), a ServiceProvider, or withInjectionScope() during construction.");
|
|
74
|
+
const value = scope.resolve(token);
|
|
75
|
+
if ((typeof value !== "object" || value === null) && typeof value !== "function") {
|
|
76
|
+
throw new Error("[mobx-mantle] Services must be objects or functions; wrap primitive configuration in an object.");
|
|
77
|
+
}
|
|
78
|
+
scope.values.add(value);
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
function isServiceValue(owner, value) {
|
|
82
|
+
return scopes.get(owner)?.values.has(value) ?? false;
|
|
83
|
+
}
|
|
84
|
+
function withOwnerServiceScope(owner, construct) {
|
|
85
|
+
const scope = scopes.get(owner);
|
|
86
|
+
if (!scope) throw new Error("[mobx-mantle] Missing owner service scope.");
|
|
87
|
+
return runWithScope(scope, construct);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/model-scope.tsx
|
|
91
|
+
import React2 from "react";
|
|
92
|
+
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
93
|
+
var ModelContext = React2.createContext(void 0);
|
|
94
|
+
function ModelProvider({ models, children }) {
|
|
95
|
+
const [snapshot] = React2.useState(() => new Map(Array.from(models, ([type, replacement]) => [type, { ...replacement }])));
|
|
96
|
+
return /* @__PURE__ */ jsx2(ModelContext.Provider, { value: snapshot, children });
|
|
97
|
+
}
|
|
98
|
+
var identities = /* @__PURE__ */ new WeakMap();
|
|
99
|
+
function setModelIdentity(model, type) {
|
|
100
|
+
identities.set(model, type);
|
|
101
|
+
}
|
|
102
|
+
function isModel(model, type) {
|
|
103
|
+
const logical = identities.get(model);
|
|
104
|
+
return model instanceof type || logical === type || !!logical && logical.prototype instanceof type;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/mantle.tsx
|
|
108
|
+
import React4, { useRef as useRef2, useEffect as useEffect2, forwardRef as reactForwardRef, memo as memo2 } from "react";
|
|
109
|
+
import { makeObservable as makeObservable2, observable as observable4, computed as computed4, runInAction as runInAction3, reaction as reaction2, autorun as autorun2, createAtom, isObservableProp, _getGlobalState as _getGlobalState2 } from "mobx";
|
|
110
|
+
|
|
111
|
+
// src/observer.ts
|
|
112
|
+
import { memo, useRef, useSyncExternalStore, useEffect, useLayoutEffect } from "react";
|
|
113
|
+
import { Reaction } from "mobx";
|
|
114
|
+
var useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
|
|
115
|
+
var uncommittedReactionRegistry = typeof FinalizationRegistry !== "undefined" ? new FinalizationRegistry((adm) => {
|
|
116
|
+
adm.reaction?.dispose();
|
|
117
|
+
adm.reaction = null;
|
|
118
|
+
}) : void 0;
|
|
119
|
+
if (process.env.NODE_ENV !== "production" && !uncommittedReactionRegistry) {
|
|
120
|
+
console.warn(
|
|
121
|
+
"[mobx-mantle] FinalizationRegistry is not available in this environment. Reactions created for renders that React discards cannot be cleaned up, which can leak under Suspense and concurrent rendering."
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
var isServer = typeof window === "undefined";
|
|
125
|
+
function createReaction(adm) {
|
|
126
|
+
adm.reaction = new Reaction(`mantle-observer(${adm.name})`, () => {
|
|
127
|
+
adm.stateVersion = /* @__PURE__ */ Symbol();
|
|
128
|
+
adm.onStoreChange?.();
|
|
129
|
+
});
|
|
130
|
+
if (adm.holder) {
|
|
131
|
+
adm.holder.current = adm.reaction;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function useMantleObserver(render, name, holder) {
|
|
135
|
+
if (isServer) {
|
|
136
|
+
return render();
|
|
137
|
+
}
|
|
138
|
+
const admRef = useRef(null);
|
|
139
|
+
if (!admRef.current) {
|
|
140
|
+
const adm2 = {
|
|
141
|
+
reaction: null,
|
|
142
|
+
onStoreChange: null,
|
|
143
|
+
stateVersion: /* @__PURE__ */ Symbol(),
|
|
144
|
+
name,
|
|
145
|
+
holder,
|
|
146
|
+
subscribe(onStoreChange) {
|
|
147
|
+
uncommittedReactionRegistry?.unregister(adm2);
|
|
148
|
+
adm2.onStoreChange = onStoreChange;
|
|
149
|
+
if (!adm2.reaction) {
|
|
150
|
+
createReaction(adm2);
|
|
151
|
+
adm2.stateVersion = /* @__PURE__ */ Symbol();
|
|
152
|
+
onStoreChange();
|
|
153
|
+
}
|
|
154
|
+
return () => {
|
|
155
|
+
adm2.onStoreChange = null;
|
|
156
|
+
adm2.reaction?.dispose();
|
|
157
|
+
adm2.reaction = null;
|
|
158
|
+
if (adm2.holder) {
|
|
159
|
+
adm2.holder.current = null;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
},
|
|
163
|
+
getSnapshot() {
|
|
164
|
+
return adm2.stateVersion;
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
admRef.current = adm2;
|
|
168
|
+
}
|
|
169
|
+
const adm = admRef.current;
|
|
170
|
+
adm.holder = holder;
|
|
171
|
+
if (!adm.reaction) {
|
|
172
|
+
createReaction(adm);
|
|
173
|
+
uncommittedReactionRegistry?.register(admRef, adm, adm);
|
|
174
|
+
}
|
|
175
|
+
useSyncExternalStore(adm.subscribe, adm.getSnapshot, adm.getSnapshot);
|
|
176
|
+
let result;
|
|
177
|
+
let didThrow = false;
|
|
178
|
+
let thrown;
|
|
179
|
+
adm.reaction.track(() => {
|
|
180
|
+
try {
|
|
181
|
+
result = render();
|
|
182
|
+
} catch (e) {
|
|
183
|
+
didThrow = true;
|
|
184
|
+
thrown = e;
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
if (didThrow) {
|
|
188
|
+
throw thrown;
|
|
189
|
+
}
|
|
190
|
+
return result;
|
|
191
|
+
}
|
|
192
|
+
function observer(fc) {
|
|
193
|
+
const name = fc.displayName || fc.name || "observed";
|
|
194
|
+
const Observed = (props) => useMantleObserver(() => fc(props), name);
|
|
195
|
+
Observed.displayName = `observer(${name})`;
|
|
196
|
+
return memo(Observed);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// src/decorators.ts
|
|
200
|
+
import * as mobx from "mobx";
|
|
201
|
+
var ANNOTATIONS = /* @__PURE__ */ Symbol("mantle:annotations");
|
|
202
|
+
var legacy = /* @__PURE__ */ new WeakMap();
|
|
203
|
+
function annotation(value, kind) {
|
|
204
|
+
return function(_target, key, descriptor) {
|
|
205
|
+
let map;
|
|
206
|
+
let name;
|
|
207
|
+
if (typeof key === "object") {
|
|
208
|
+
if (key.static || key.private || key.kind !== kind) {
|
|
209
|
+
throw new Error(`[mobx-mantle] This decorator requires a public instance ${kind}. Use an ordinary field, not an auto-accessor, for @observable.`);
|
|
210
|
+
}
|
|
211
|
+
if (!key.metadata) throw new Error("[mobx-mantle] TC39 decorators require Symbol.metadata. Load its polyfill before decorated classes.");
|
|
212
|
+
if (!Object.prototype.hasOwnProperty.call(key.metadata, ANNOTATIONS)) key.metadata[ANNOTATIONS] = /* @__PURE__ */ Object.create(null);
|
|
213
|
+
map = key.metadata[ANNOTATIONS];
|
|
214
|
+
name = key.name;
|
|
215
|
+
} else {
|
|
216
|
+
if (typeof _target === "function" || kind === "method" && typeof descriptor?.value !== "function" || kind === "getter" && !descriptor?.get || kind === "field" && descriptor) {
|
|
217
|
+
throw new Error(`[mobx-mantle] This decorator requires a public instance ${kind}.`);
|
|
218
|
+
}
|
|
219
|
+
map = legacy.get(_target) ?? /* @__PURE__ */ Object.create(null);
|
|
220
|
+
legacy.set(_target, map);
|
|
221
|
+
name = key;
|
|
222
|
+
}
|
|
223
|
+
map[name] = value;
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
var observable2 = Object.assign(annotation(mobx.observable, "field"), {
|
|
227
|
+
ref: annotation(mobx.observable.ref, "field"),
|
|
228
|
+
shallow: annotation(mobx.observable.shallow, "field"),
|
|
229
|
+
deep: annotation(mobx.observable.deep, "field"),
|
|
230
|
+
struct: annotation(mobx.observable.struct, "field")
|
|
231
|
+
});
|
|
232
|
+
var actionMethod = annotation(mobx.action.bound, "method");
|
|
233
|
+
var actionField = annotation(mobx.action, "field");
|
|
234
|
+
var action2 = function(target, key, descriptor) {
|
|
235
|
+
const isField = typeof key === "object" ? key.kind === "field" : !descriptor;
|
|
236
|
+
return (isField ? actionField : actionMethod)(target, key, descriptor);
|
|
237
|
+
};
|
|
238
|
+
var computed2 = annotation(mobx.computed, "getter");
|
|
239
|
+
function getAnnotations(instance) {
|
|
240
|
+
const chain = [];
|
|
241
|
+
for (let proto = Object.getPrototypeOf(instance); proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) chain.unshift(proto);
|
|
242
|
+
const result = /* @__PURE__ */ Object.create(null);
|
|
243
|
+
for (const proto of chain) {
|
|
244
|
+
const constructor = proto.constructor;
|
|
245
|
+
const symbol = Symbol.metadata;
|
|
246
|
+
const metadata = symbol && Object.prototype.hasOwnProperty.call(constructor, symbol) ? constructor[symbol] : void 0;
|
|
247
|
+
const modern = metadata && Object.prototype.hasOwnProperty.call(metadata, ANNOTATIONS) ? metadata[ANNOTATIONS] : void 0;
|
|
248
|
+
for (const own of [legacy.get(proto), modern]) {
|
|
249
|
+
if (!own) continue;
|
|
250
|
+
for (const key of Reflect.ownKeys(own)) {
|
|
251
|
+
if (key in result && result[key] !== own[key]) throw new Error(`[mobx-mantle] Cannot change the inherited annotation of ${String(key)}.`);
|
|
252
|
+
result[key] = own[key];
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
for (const key of Reflect.ownKeys(result)) {
|
|
257
|
+
const own = Object.getOwnPropertyDescriptor(instance, key);
|
|
258
|
+
if (own && "value" in own && isServiceValue(instance, own.value)) throw new Error(`[mobx-mantle] Leave service field ${String(key)} undecorated; its resolver owns observability.`);
|
|
259
|
+
}
|
|
260
|
+
return Reflect.ownKeys(result).length ? result : void 0;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// src/behavior.ts
|
|
264
|
+
import { makeObservable, observable as observable3, computed as computed3, reaction, autorun, intercept, runInAction as runInAction2 } from "mobx";
|
|
265
|
+
|
|
266
|
+
// src/internals.ts
|
|
267
|
+
import { _getGlobalState, runInAction } from "mobx";
|
|
268
|
+
function smartBind(fn, context) {
|
|
269
|
+
return function(...args) {
|
|
270
|
+
const globalState = _getGlobalState();
|
|
271
|
+
const isInTrackingContext = globalState.trackingDerivation !== null;
|
|
272
|
+
if (isInTrackingContext) {
|
|
273
|
+
return fn.apply(context, args);
|
|
274
|
+
}
|
|
275
|
+
return runInAction(() => fn.apply(context, args));
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
if (process.env.NODE_ENV !== "production") {
|
|
279
|
+
const globalState = _getGlobalState();
|
|
280
|
+
if (!globalState || !("trackingDerivation" in globalState)) {
|
|
281
|
+
console.warn(
|
|
282
|
+
"[mobx-mantle] MobX internal state no longer exposes trackingDerivation. smartBind cannot detect tracking contexts and props reads cannot skip self-notification, so method calls may not batch correctly and prop changes may double-render. Check mobx version compatibility."
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function toWatchExpression(source, fireImmediately, ownerName) {
|
|
287
|
+
if (typeof source === "function") {
|
|
288
|
+
return source;
|
|
289
|
+
}
|
|
290
|
+
if (process.env.NODE_ENV !== "production" && !fireImmediately) {
|
|
291
|
+
console.warn(
|
|
292
|
+
`[mobx-mantle] ${ownerName}.watch() received a plain value, which can never change \u2014 the callback will never fire. Pass a getter (() => expr) to watch a live source, or add { fireImmediately: true } if a single immediate call is intended.`
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
return () => source;
|
|
296
|
+
}
|
|
297
|
+
function registerReactive(host, create) {
|
|
298
|
+
if (host._mounted) {
|
|
299
|
+
return create();
|
|
300
|
+
}
|
|
301
|
+
const spec = { create, stopped: false, dispose: null };
|
|
302
|
+
host._reactiveSpecs.push(spec);
|
|
303
|
+
return () => {
|
|
304
|
+
spec.stopped = true;
|
|
305
|
+
spec.dispose?.();
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
function activateSpecs(host) {
|
|
309
|
+
if (host._wasUnmounted) {
|
|
310
|
+
host._wasUnmounted = false;
|
|
311
|
+
for (const spec of host._reactiveSpecs) {
|
|
312
|
+
if (!spec.stopped) {
|
|
313
|
+
spec.dispose = spec.create();
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
} else if (!host._mounted) {
|
|
317
|
+
for (const spec of host._reactiveSpecs) {
|
|
318
|
+
if (!spec.stopped && spec.dispose === null) {
|
|
319
|
+
spec.dispose = spec.create();
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
host._mounted = true;
|
|
324
|
+
}
|
|
325
|
+
function collectProtoInfo(instance, stopProto, excludes, cache) {
|
|
326
|
+
const ctor = instance.constructor;
|
|
327
|
+
const useCache = globalConfig.cacheAnnotations !== false;
|
|
328
|
+
if (useCache) {
|
|
329
|
+
const cached = cache.get(ctor);
|
|
330
|
+
if (cached) return cached;
|
|
331
|
+
}
|
|
332
|
+
const info = { computedKeys: [], methodKeys: [] };
|
|
333
|
+
const seen = /* @__PURE__ */ new Set();
|
|
334
|
+
let proto = Object.getPrototypeOf(instance);
|
|
335
|
+
while (proto && proto !== stopProto && proto !== Object.prototype) {
|
|
336
|
+
const descriptors = Object.getOwnPropertyDescriptors(proto);
|
|
337
|
+
for (const [key, descriptor] of Object.entries(descriptors)) {
|
|
338
|
+
if (excludes.has(key) || seen.has(key)) continue;
|
|
339
|
+
seen.add(key);
|
|
340
|
+
if (descriptor.get) {
|
|
341
|
+
info.computedKeys.push(key);
|
|
342
|
+
} else if (typeof descriptor.value === "function") {
|
|
343
|
+
info.methodKeys.push(key);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
proto = Object.getPrototypeOf(proto);
|
|
347
|
+
}
|
|
348
|
+
if (useCache) cache.set(ctor, info);
|
|
349
|
+
return info;
|
|
350
|
+
}
|
|
351
|
+
|
|
27
352
|
// src/behavior.ts
|
|
28
|
-
var BEHAVIOR_MARKER = /* @__PURE__ */ Symbol("behavior");
|
|
353
|
+
var BEHAVIOR_MARKER = /* @__PURE__ */ Symbol.for("mobx-mantle.behavior");
|
|
29
354
|
var BEHAVIOR_EXCLUDES = /* @__PURE__ */ new Set([
|
|
30
355
|
"onCreate",
|
|
31
356
|
"onLayoutMount",
|
|
32
357
|
"onMount",
|
|
33
358
|
"onUnmount",
|
|
359
|
+
"addCleanup",
|
|
360
|
+
"_addCleanup",
|
|
34
361
|
"watch",
|
|
362
|
+
"effect",
|
|
363
|
+
"sync",
|
|
35
364
|
"constructor",
|
|
365
|
+
"inject",
|
|
36
366
|
"_watchDisposers",
|
|
37
|
-
"_disposeWatchers"
|
|
367
|
+
"_disposeWatchers",
|
|
368
|
+
"_reactiveSpecs",
|
|
369
|
+
"_behaviors",
|
|
370
|
+
"_pendingSyncs",
|
|
371
|
+
"_syncWriting",
|
|
372
|
+
"_mounted",
|
|
373
|
+
"_wasUnmounted"
|
|
38
374
|
]);
|
|
375
|
+
var SyncMarker = class {
|
|
376
|
+
constructor(source) {
|
|
377
|
+
this.source = source;
|
|
378
|
+
}
|
|
379
|
+
};
|
|
39
380
|
function isRefLike(value) {
|
|
40
381
|
if (value === null || typeof value !== "object") return false;
|
|
41
382
|
if (Array.isArray(value)) return false;
|
|
@@ -45,16 +386,72 @@ var Behavior = class {
|
|
|
45
386
|
constructor() {
|
|
46
387
|
/** @internal */
|
|
47
388
|
this._watchDisposers = [];
|
|
389
|
+
/** @internal — pre-mount watch/effect registrations, materialized at mount */
|
|
390
|
+
this._reactiveSpecs = [];
|
|
391
|
+
/** @internal — child behaviors declared as fields, collected at construction */
|
|
392
|
+
this._behaviors = [];
|
|
393
|
+
/** @internal — true after the parent Component first mounts */
|
|
394
|
+
this._mounted = false;
|
|
395
|
+
/** @internal — set when effects clean up so StrictMode replay can resurrect pre-mount watchers */
|
|
396
|
+
this._wasUnmounted = false;
|
|
397
|
+
/** @internal — sync() markers awaiting the post-onCreate field scan; null once construction completes */
|
|
398
|
+
this._pendingSyncs = [];
|
|
399
|
+
/** @internal — true while the hidden sync effect writes a mirrored field (dev write-guard) */
|
|
400
|
+
this._syncWriting = false;
|
|
401
|
+
captureServiceScope(this);
|
|
402
|
+
}
|
|
403
|
+
inject(token) {
|
|
404
|
+
return resolveService(this, token);
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Register a cleanup function to run automatically on unmount.
|
|
408
|
+
* Returns a function that can be called for early cleanup.
|
|
409
|
+
*
|
|
410
|
+
* Cleanups are one-shot: they are not re-created during React StrictMode's
|
|
411
|
+
* same-instance effect replay. Call this from onMount (which is replayed),
|
|
412
|
+
* or use effect() for a replay-safe setup/teardown pair.
|
|
413
|
+
*/
|
|
414
|
+
addCleanup(cleanup) {
|
|
415
|
+
if (process.env.NODE_ENV !== "production" && !this._mounted) {
|
|
416
|
+
console.warn(
|
|
417
|
+
`[mobx-mantle] ${this.constructor.name}.addCleanup() called before mount. Cleanups are one-shot: they run when mount effects clean up and are not re-created during React StrictMode's same-instance effect replay. Acquire resources in onMount(), or use effect() for a replay-safe setup/teardown pair.`
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
return this._addCleanup(cleanup);
|
|
421
|
+
}
|
|
422
|
+
/** @internal — addCleanup without the pre-mount dev warning (used by watch/effect) */
|
|
423
|
+
_addCleanup(cleanup) {
|
|
424
|
+
let active = true;
|
|
425
|
+
const dispose = () => {
|
|
426
|
+
if (!active) return;
|
|
427
|
+
active = false;
|
|
428
|
+
try {
|
|
429
|
+
runInAction2(cleanup);
|
|
430
|
+
} finally {
|
|
431
|
+
const idx = this._watchDisposers.indexOf(dispose);
|
|
432
|
+
if (idx !== -1) this._watchDisposers.splice(idx, 1);
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
this._watchDisposers.push(dispose);
|
|
436
|
+
return dispose;
|
|
48
437
|
}
|
|
49
438
|
/**
|
|
50
439
|
* Watch a reactive expression and run a callback when it changes.
|
|
51
|
-
* Automatically disposed on unmount
|
|
52
|
-
*
|
|
53
|
-
*
|
|
440
|
+
* Automatically disposed on unmount and re-created during React StrictMode's
|
|
441
|
+
* same-instance effect replay.
|
|
442
|
+
*
|
|
443
|
+
* Safe to call from onCreate: registration is recorded and comes alive
|
|
444
|
+
* when the parent commits (just before first paint), so the watcher
|
|
445
|
+
* tracks observable fields correctly and renders that React discards
|
|
446
|
+
* never leak reactions.
|
|
447
|
+
*
|
|
448
|
+
* @param source - Reactive expression (getter) to watch, or a MaybeGetter
|
|
449
|
+
* argument passed through as-is. To watch a value that is itself a
|
|
450
|
+
* function, wrap it: `watch(() => this.callback, …)`
|
|
54
451
|
* @param callback - Called when the expression result changes
|
|
55
452
|
* @param options - Optional configuration (delay, fireImmediately)
|
|
56
453
|
* @returns Dispose function for early teardown
|
|
57
|
-
*
|
|
454
|
+
*
|
|
58
455
|
* @example
|
|
59
456
|
* ```tsx
|
|
60
457
|
* onCreate(url: string) {
|
|
@@ -63,36 +460,119 @@ var Behavior = class {
|
|
|
63
460
|
* }
|
|
64
461
|
* ```
|
|
65
462
|
*/
|
|
66
|
-
watch(
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
463
|
+
watch(source, callback, options) {
|
|
464
|
+
const expr = toWatchExpression(source, options?.fireImmediately, this.constructor.name);
|
|
465
|
+
return registerReactive(this, () => {
|
|
466
|
+
const dispose = reaction(
|
|
467
|
+
expr,
|
|
468
|
+
(value, prevValue) => {
|
|
469
|
+
try {
|
|
470
|
+
callback(value, prevValue);
|
|
471
|
+
} catch (e) {
|
|
472
|
+
reportError(e, { phase: "watch", name: this.constructor.name, isBehavior: true });
|
|
473
|
+
}
|
|
474
|
+
},
|
|
475
|
+
{
|
|
476
|
+
delay: options?.delay,
|
|
477
|
+
fireImmediately: options?.fireImmediately
|
|
74
478
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
479
|
+
);
|
|
480
|
+
return this._addCleanup(dispose);
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Run a side effect that auto-tracks reactive dependencies.
|
|
485
|
+
* Re-runs whenever any accessed observable changes.
|
|
486
|
+
* Automatically disposed on unmount.
|
|
487
|
+
*
|
|
488
|
+
* Best for simple synchronization (DOM updates, logging). For complex
|
|
489
|
+
* side effects with explicit triggers, prefer `watch()`.
|
|
490
|
+
*
|
|
491
|
+
* @param fn - Effect function. May return a cleanup function.
|
|
492
|
+
* @param options - Optional configuration (delay)
|
|
493
|
+
* @returns Dispose function for early teardown
|
|
494
|
+
*
|
|
495
|
+
* @example
|
|
496
|
+
* ```tsx
|
|
497
|
+
* onCreate() {
|
|
498
|
+
* this.effect(() => {
|
|
499
|
+
* console.log('Current value:', this.value);
|
|
500
|
+
* });
|
|
501
|
+
* }
|
|
502
|
+
* ```
|
|
503
|
+
*/
|
|
504
|
+
effect(fn, options) {
|
|
505
|
+
return registerReactive(this, () => {
|
|
506
|
+
let cleanup;
|
|
507
|
+
const dispose = autorun(
|
|
508
|
+
() => {
|
|
509
|
+
runInAction2(() => cleanup?.());
|
|
510
|
+
cleanup = void 0;
|
|
511
|
+
try {
|
|
512
|
+
const result = fn();
|
|
513
|
+
if (typeof result === "function") {
|
|
514
|
+
cleanup = result;
|
|
515
|
+
}
|
|
516
|
+
} catch (e) {
|
|
517
|
+
reportError(e, { phase: "effect", name: this.constructor.name, isBehavior: true });
|
|
518
|
+
}
|
|
519
|
+
},
|
|
520
|
+
{ delay: options?.delay }
|
|
521
|
+
);
|
|
522
|
+
return this._addCleanup(() => {
|
|
523
|
+
runInAction2(() => cleanup?.());
|
|
524
|
+
dispose();
|
|
525
|
+
});
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Normalize a MaybeGetter argument into an ordinary field that stays
|
|
530
|
+
* current. Call once in onCreate (or a field initializer) and assign the
|
|
531
|
+
* result to a field; everywhere else, read the field like normal state:
|
|
532
|
+
*
|
|
533
|
+
* ```tsx
|
|
534
|
+
* url!: string;
|
|
535
|
+
*
|
|
536
|
+
* onCreate(url: MaybeGetter<string>) {
|
|
537
|
+
* this.url = this.sync(url); // the one convention line
|
|
538
|
+
* this.watch(() => this.url, (u) => this.load(u));
|
|
539
|
+
* }
|
|
540
|
+
* refresh() { this.load(this.url); } // plain read, always current
|
|
541
|
+
* ```
|
|
542
|
+
*
|
|
543
|
+
* - Plain value → the field just holds it (no effect registered).
|
|
544
|
+
* - Getter → a hidden effect keeps the field updated whenever the getter's
|
|
545
|
+
* observable sources change (alive from mount, like watch/effect).
|
|
546
|
+
*
|
|
547
|
+
* The sync is one-way (argument → field). Don't write to the field from
|
|
548
|
+
* outside: the next source change overwrites it (dev mode warns).
|
|
549
|
+
*/
|
|
550
|
+
sync(source) {
|
|
551
|
+
if (typeof source !== "function") {
|
|
552
|
+
return source;
|
|
553
|
+
}
|
|
554
|
+
if (this._pendingSyncs === null) {
|
|
555
|
+
if (process.env.NODE_ENV !== "production") {
|
|
556
|
+
console.warn(
|
|
557
|
+
`[mobx-mantle] ${this.constructor.name}.sync() called after construction. sync() only works in field initializers or onCreate; returning a one-time snapshot instead. Use watch()/effect() for post-mount reactions.`
|
|
558
|
+
);
|
|
79
559
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
if (idx !== -1) this._watchDisposers.splice(idx, 1);
|
|
86
|
-
};
|
|
560
|
+
return toValue(source);
|
|
561
|
+
}
|
|
562
|
+
const marker = new SyncMarker(source);
|
|
563
|
+
this._pendingSyncs.push(marker);
|
|
564
|
+
return marker;
|
|
87
565
|
}
|
|
88
566
|
/** @internal */
|
|
89
567
|
_disposeWatchers() {
|
|
90
|
-
|
|
568
|
+
const disposers = this._watchDisposers.slice();
|
|
569
|
+
this._watchDisposers.length = 0;
|
|
570
|
+
for (const dispose of disposers) {
|
|
91
571
|
dispose();
|
|
92
572
|
}
|
|
93
|
-
this._watchDisposers.length = 0;
|
|
94
573
|
}
|
|
95
574
|
};
|
|
575
|
+
var behaviorProtoInfo = /* @__PURE__ */ new WeakMap();
|
|
96
576
|
function makeBehaviorObservable(instance) {
|
|
97
577
|
const annotations = {};
|
|
98
578
|
const ownKeys = /* @__PURE__ */ new Set([
|
|
@@ -103,43 +583,118 @@ function makeBehaviorObservable(instance) {
|
|
|
103
583
|
if (BEHAVIOR_EXCLUDES.has(key)) continue;
|
|
104
584
|
if (key in annotations) continue;
|
|
105
585
|
const value = instance[key];
|
|
106
|
-
if (typeof value === "function") continue;
|
|
586
|
+
if (typeof value === "function" || isServiceValue(instance, value)) continue;
|
|
587
|
+
if (isBehavior(value)) {
|
|
588
|
+
annotations[key] = observable3.ref;
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
107
591
|
if (isRefLike(value)) {
|
|
108
|
-
annotations[key] =
|
|
592
|
+
annotations[key] = observable3.ref;
|
|
109
593
|
} else {
|
|
110
|
-
annotations[key] =
|
|
594
|
+
annotations[key] = observable3;
|
|
111
595
|
}
|
|
112
596
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
if (BEHAVIOR_EXCLUDES.has(key)) continue;
|
|
118
|
-
if (key in annotations) continue;
|
|
119
|
-
if (descriptor.get) {
|
|
120
|
-
annotations[key] = computed;
|
|
121
|
-
} else if (typeof descriptor.value === "function") {
|
|
122
|
-
annotations[key] = action.bound;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
proto = Object.getPrototypeOf(proto);
|
|
597
|
+
const protoInfo = collectProtoInfo(instance, Behavior.prototype, BEHAVIOR_EXCLUDES, behaviorProtoInfo);
|
|
598
|
+
for (const key of protoInfo.computedKeys) {
|
|
599
|
+
if (key in annotations) continue;
|
|
600
|
+
annotations[key] = computed3;
|
|
126
601
|
}
|
|
127
602
|
makeObservable(instance, annotations);
|
|
603
|
+
for (const key of protoInfo.methodKeys) {
|
|
604
|
+
if (key in annotations) continue;
|
|
605
|
+
const method = instance[key];
|
|
606
|
+
if (typeof method === "function") {
|
|
607
|
+
instance[key] = smartBind(method, instance);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
128
610
|
}
|
|
129
611
|
function createBehavior(Def, options) {
|
|
130
612
|
var _a, _b, _c;
|
|
131
613
|
const BehaviorClass = (_c = class extends (_b = Def, _a = BEHAVIOR_MARKER, _b) {
|
|
132
614
|
constructor(...args) {
|
|
615
|
+
applyMobxActionPolicy();
|
|
133
616
|
super(...args);
|
|
134
617
|
if (typeof this.onCreate === "function") {
|
|
135
|
-
this.onCreate(...args);
|
|
618
|
+
withOwnerServiceScope(this, () => runInAction2(() => this.onCreate(...args)));
|
|
619
|
+
}
|
|
620
|
+
const children = [];
|
|
621
|
+
for (const key of Object.keys(this)) {
|
|
622
|
+
if (key.startsWith("_")) continue;
|
|
623
|
+
const value = this[key];
|
|
624
|
+
if (isBehavior(value) && !isServiceValue(this, value)) {
|
|
625
|
+
children.push({ instance: value });
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
this._behaviors = children;
|
|
629
|
+
const syncedFields = [];
|
|
630
|
+
const pending = this._pendingSyncs ?? null;
|
|
631
|
+
if (Array.isArray(pending) && pending.length > 0) {
|
|
632
|
+
for (const key of Object.keys(this)) {
|
|
633
|
+
const value = this[key];
|
|
634
|
+
if (value instanceof SyncMarker) {
|
|
635
|
+
syncedFields.push({ key, source: value.source });
|
|
636
|
+
this[key] = value.source();
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
if (process.env.NODE_ENV !== "production" && syncedFields.length !== pending.length) {
|
|
640
|
+
console.warn(
|
|
641
|
+
`[mobx-mantle] ${Def.name}: ${pending.length - syncedFields.length} sync() result(s) were not assigned to a field. Assign sync() directly to a field (this.url = this.sync(url)) so Mantle can keep it updated.`
|
|
642
|
+
);
|
|
643
|
+
}
|
|
136
644
|
}
|
|
645
|
+
this._pendingSyncs = null;
|
|
137
646
|
const autoObservable = options?.autoObservable ?? globalConfig.autoObservable;
|
|
138
|
-
|
|
647
|
+
const annotations = getAnnotations(this);
|
|
648
|
+
if (annotations) {
|
|
649
|
+
makeObservable(this, annotations);
|
|
650
|
+
const info = collectProtoInfo(this, Behavior.prototype, BEHAVIOR_EXCLUDES, behaviorProtoInfo);
|
|
651
|
+
for (const key of info.methodKeys) if (!(key in annotations)) this[key] = smartBind(this[key], this);
|
|
652
|
+
} else if (autoObservable) {
|
|
139
653
|
makeBehaviorObservable(this);
|
|
140
654
|
} else {
|
|
141
655
|
makeObservable(this);
|
|
142
656
|
}
|
|
657
|
+
if (syncedFields.length > 0) {
|
|
658
|
+
const self = this;
|
|
659
|
+
const specs = syncedFields.map(({ key, source }) => ({
|
|
660
|
+
create: () => {
|
|
661
|
+
const dispose = autorun(() => {
|
|
662
|
+
try {
|
|
663
|
+
const next = source();
|
|
664
|
+
self._syncWriting = true;
|
|
665
|
+
try {
|
|
666
|
+
runInAction2(() => {
|
|
667
|
+
self[key] = next;
|
|
668
|
+
});
|
|
669
|
+
} finally {
|
|
670
|
+
self._syncWriting = false;
|
|
671
|
+
}
|
|
672
|
+
} catch (e) {
|
|
673
|
+
reportError(e, { phase: "sync", name: self.constructor.name, isBehavior: true });
|
|
674
|
+
}
|
|
675
|
+
});
|
|
676
|
+
return self._addCleanup(dispose);
|
|
677
|
+
},
|
|
678
|
+
stopped: false,
|
|
679
|
+
dispose: null
|
|
680
|
+
}));
|
|
681
|
+
self._reactiveSpecs.unshift(...specs);
|
|
682
|
+
if (process.env.NODE_ENV !== "production") {
|
|
683
|
+
for (const { key } of syncedFields) {
|
|
684
|
+
try {
|
|
685
|
+
intercept(self, key, (change) => {
|
|
686
|
+
if (!self._syncWriting) {
|
|
687
|
+
console.warn(
|
|
688
|
+
`[mobx-mantle] ${Def.name}.${key} is a one-way synced field (this.sync()). Writing to it from outside will be overwritten by the next source change. Derive with a computed getter, or own the state in a plain field instead.`
|
|
689
|
+
);
|
|
690
|
+
}
|
|
691
|
+
return change;
|
|
692
|
+
});
|
|
693
|
+
} catch {
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
143
698
|
}
|
|
144
699
|
}, _c[_a] = true, _c);
|
|
145
700
|
Object.defineProperty(BehaviorClass, "name", { value: Def.name });
|
|
@@ -153,33 +708,55 @@ function isBehavior(value) {
|
|
|
153
708
|
if (value === null || typeof value !== "object") return false;
|
|
154
709
|
return value.constructor?.[BEHAVIOR_MARKER] === true;
|
|
155
710
|
}
|
|
156
|
-
function
|
|
711
|
+
function childBehaviors(inst) {
|
|
712
|
+
return Array.isArray(inst._behaviors) ? inst._behaviors : [];
|
|
713
|
+
}
|
|
714
|
+
function layoutMountBehavior(behavior, visited = /* @__PURE__ */ new WeakSet()) {
|
|
157
715
|
const inst = behavior.instance;
|
|
716
|
+
if (visited.has(inst)) return;
|
|
717
|
+
visited.add(inst);
|
|
718
|
+
for (const child of childBehaviors(inst)) {
|
|
719
|
+
layoutMountBehavior(child, visited);
|
|
720
|
+
}
|
|
721
|
+
if (Array.isArray(inst._reactiveSpecs)) {
|
|
722
|
+
activateSpecs(inst);
|
|
723
|
+
} else {
|
|
724
|
+
inst._mounted = true;
|
|
725
|
+
}
|
|
158
726
|
if ("onLayoutMount" in inst && typeof inst.onLayoutMount === "function") {
|
|
159
727
|
try {
|
|
160
|
-
|
|
728
|
+
const result = runInAction2(() => inst.onLayoutMount());
|
|
729
|
+
behavior.layoutCleanup = typeof result === "function" ? result : void 0;
|
|
161
730
|
} catch (e) {
|
|
162
731
|
reportError(e, { phase: "onLayoutMount", name: inst.constructor.name, isBehavior: true });
|
|
163
732
|
}
|
|
164
733
|
}
|
|
165
734
|
}
|
|
166
|
-
function mountBehavior(behavior) {
|
|
735
|
+
function mountBehavior(behavior, visited = /* @__PURE__ */ new WeakSet()) {
|
|
167
736
|
const inst = behavior.instance;
|
|
737
|
+
if (visited.has(inst)) return;
|
|
738
|
+
visited.add(inst);
|
|
739
|
+
for (const child of childBehaviors(inst)) {
|
|
740
|
+
mountBehavior(child, visited);
|
|
741
|
+
}
|
|
168
742
|
if ("onMount" in inst && typeof inst.onMount === "function") {
|
|
169
743
|
try {
|
|
170
|
-
|
|
744
|
+
const result = runInAction2(() => inst.onMount());
|
|
745
|
+
behavior.cleanup = typeof result === "function" ? result : void 0;
|
|
171
746
|
} catch (e) {
|
|
172
747
|
reportError(e, { phase: "onMount", name: inst.constructor.name, isBehavior: true });
|
|
173
748
|
}
|
|
174
749
|
}
|
|
175
750
|
}
|
|
176
|
-
function unmountBehavior(behavior) {
|
|
177
|
-
behavior.layoutCleanup?.();
|
|
178
|
-
behavior.cleanup?.();
|
|
751
|
+
function unmountBehavior(behavior, visited = /* @__PURE__ */ new WeakSet()) {
|
|
179
752
|
const inst = behavior.instance;
|
|
753
|
+
if (visited.has(inst)) return;
|
|
754
|
+
visited.add(inst);
|
|
755
|
+
runInAction2(() => behavior.layoutCleanup?.());
|
|
756
|
+
runInAction2(() => behavior.cleanup?.());
|
|
180
757
|
if ("onUnmount" in inst && typeof inst.onUnmount === "function") {
|
|
181
758
|
try {
|
|
182
|
-
inst.onUnmount();
|
|
759
|
+
runInAction2(() => inst.onUnmount());
|
|
183
760
|
} catch (e) {
|
|
184
761
|
reportError(e, { phase: "onUnmount", name: inst.constructor.name, isBehavior: true });
|
|
185
762
|
}
|
|
@@ -187,44 +764,63 @@ function unmountBehavior(behavior) {
|
|
|
187
764
|
if (typeof inst._disposeWatchers === "function") {
|
|
188
765
|
inst._disposeWatchers();
|
|
189
766
|
}
|
|
767
|
+
inst._wasUnmounted = true;
|
|
768
|
+
const children = childBehaviors(inst);
|
|
769
|
+
for (let i = children.length - 1; i >= 0; i--) {
|
|
770
|
+
unmountBehavior(children[i], visited);
|
|
771
|
+
}
|
|
190
772
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
}
|
|
212
|
-
observable3.deep = function(_value, context) {
|
|
213
|
-
setAnnotation(context, mobx.observable.deep);
|
|
214
|
-
};
|
|
215
|
-
function action3(_value, context) {
|
|
216
|
-
setAnnotation(context, mobx.action.bound);
|
|
217
|
-
}
|
|
218
|
-
function computed3(_value, context) {
|
|
219
|
-
setAnnotation(context, mobx.computed);
|
|
220
|
-
}
|
|
221
|
-
function getAnnotations(instance) {
|
|
222
|
-
const metadata = instance.constructor[Symbol.metadata];
|
|
223
|
-
return metadata?.[ANNOTATIONS];
|
|
773
|
+
function warnUncollectedBehaviors(host, hostName, entries, visited = /* @__PURE__ */ new WeakSet()) {
|
|
774
|
+
if (visited.has(host)) return;
|
|
775
|
+
visited.add(host);
|
|
776
|
+
const collected = new Set(entries.map((e) => e.instance));
|
|
777
|
+
for (const key of Object.keys(host)) {
|
|
778
|
+
if (key.startsWith("_")) continue;
|
|
779
|
+
const value = host[key];
|
|
780
|
+
if (isBehavior(value) && !isServiceValue(host, value) && !collected.has(value)) {
|
|
781
|
+
console.warn(
|
|
782
|
+
`[mobx-mantle] ${hostName}.${key} holds a behavior that was assigned after construction, so its lifecycle (onMount, watchers, cleanup) will never run. Create behaviors as class fields so they are collected when the host is constructed.`
|
|
783
|
+
);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
for (const entry of entries) {
|
|
787
|
+
warnUncollectedBehaviors(
|
|
788
|
+
entry.instance,
|
|
789
|
+
entry.instance.constructor.name,
|
|
790
|
+
childBehaviors(entry.instance),
|
|
791
|
+
visited
|
|
792
|
+
);
|
|
793
|
+
}
|
|
224
794
|
}
|
|
225
795
|
|
|
226
796
|
// src/mantle.tsx
|
|
227
|
-
|
|
797
|
+
import { jsx as jsx3 } from "react/jsx-runtime";
|
|
798
|
+
var componentRefs = /* @__PURE__ */ new WeakSet();
|
|
799
|
+
var ComponentParentContext = React4.createContext(void 0);
|
|
800
|
+
var componentParents = /* @__PURE__ */ new WeakMap();
|
|
801
|
+
var activeComponentConstruction;
|
|
802
|
+
function constructComponent(ComponentClass, props, parentHandle) {
|
|
803
|
+
const previousScope = activeComponentConstruction;
|
|
804
|
+
const scope = {
|
|
805
|
+
expectedClass: ComponentClass,
|
|
806
|
+
parentHandle,
|
|
807
|
+
consumed: false
|
|
808
|
+
};
|
|
809
|
+
activeComponentConstruction = scope;
|
|
810
|
+
try {
|
|
811
|
+
return new ComponentClass(props);
|
|
812
|
+
} finally {
|
|
813
|
+
activeComponentConstruction = previousScope;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
function captureConstructingComponentParent(instance) {
|
|
817
|
+
const scope = activeComponentConstruction;
|
|
818
|
+
if (!scope || scope.consumed || instance.constructor !== scope.expectedClass) {
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
scope.consumed = true;
|
|
822
|
+
componentParents.set(instance, scope.parentHandle);
|
|
823
|
+
}
|
|
228
824
|
function shallowEqual(a, b) {
|
|
229
825
|
if (a === b) return true;
|
|
230
826
|
if (!a || !b) return false;
|
|
@@ -236,37 +832,140 @@ function shallowEqual(a, b) {
|
|
|
236
832
|
}
|
|
237
833
|
return true;
|
|
238
834
|
}
|
|
239
|
-
var
|
|
240
|
-
constructor() {
|
|
835
|
+
var PropsBox = class {
|
|
836
|
+
constructor(value, name) {
|
|
837
|
+
/**
|
|
838
|
+
* @internal The owning component's render reaction. Reads coming from it
|
|
839
|
+
* are not tracked: React already re-renders the component on prop change
|
|
840
|
+
* (via memo), so letting the render reaction observe the props atom would
|
|
841
|
+
* only schedule a redundant second render after every prop change.
|
|
842
|
+
* Computeds, watchers, and other components track normally.
|
|
843
|
+
*/
|
|
844
|
+
this._renderReaction = null;
|
|
845
|
+
this._value = value;
|
|
846
|
+
this._atom = createAtom(name);
|
|
847
|
+
}
|
|
848
|
+
get() {
|
|
849
|
+
const own = this._renderReaction?.current;
|
|
850
|
+
if (!own || _getGlobalState2().trackingDerivation !== own) {
|
|
851
|
+
this._atom.reportObserved();
|
|
852
|
+
}
|
|
853
|
+
return this._value;
|
|
854
|
+
}
|
|
855
|
+
setSilently(value) {
|
|
856
|
+
this._value = value;
|
|
857
|
+
}
|
|
858
|
+
set(value) {
|
|
859
|
+
this._value = value;
|
|
860
|
+
this._atom.reportChanged();
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
var Component = class {
|
|
864
|
+
constructor(props) {
|
|
241
865
|
/** @internal */
|
|
242
866
|
this._behaviors = [];
|
|
243
867
|
/** @internal */
|
|
244
868
|
this._watchDisposers = [];
|
|
869
|
+
/** @internal — pre-mount watch/effect registrations, materialized at mount */
|
|
870
|
+
this._reactiveSpecs = [];
|
|
871
|
+
/** @internal — true after the first (layout) mount */
|
|
872
|
+
this._mounted = false;
|
|
873
|
+
/** @internal — set when effects clean up so StrictMode replay can resurrect watchers */
|
|
874
|
+
this._wasUnmounted = false;
|
|
875
|
+
this._propsBox = new PropsBox(props, `${this.constructor.name}.props`);
|
|
876
|
+
captureConstructingComponentParent(this);
|
|
877
|
+
captureServiceScope(this);
|
|
245
878
|
}
|
|
246
879
|
get props() {
|
|
247
880
|
return this._propsBox.get();
|
|
248
881
|
}
|
|
249
|
-
/**
|
|
882
|
+
/** Resolve through the scope captured during construction; preserve service identity. */
|
|
883
|
+
inject(token) {
|
|
884
|
+
return resolveService(this, token);
|
|
885
|
+
}
|
|
886
|
+
/** Return the immediate ancestor in the live Mantle view tree. */
|
|
887
|
+
getParent() {
|
|
888
|
+
return componentParents.get(this)?.current;
|
|
889
|
+
}
|
|
890
|
+
/** Find the nearest parent with the supplied logical model identity. */
|
|
891
|
+
findParent(type) {
|
|
892
|
+
for (const parent of this.getParents()) {
|
|
893
|
+
if (isModel(parent, type)) return parent;
|
|
894
|
+
}
|
|
895
|
+
return void 0;
|
|
896
|
+
}
|
|
897
|
+
/** Return all Mantle parents, ordered from the immediate parent to the root. */
|
|
898
|
+
getParents() {
|
|
899
|
+
const parents = [];
|
|
900
|
+
let current = this.getParent();
|
|
901
|
+
while (current) {
|
|
902
|
+
parents.push(current);
|
|
903
|
+
current = current.getParent();
|
|
904
|
+
}
|
|
905
|
+
return parents;
|
|
906
|
+
}
|
|
907
|
+
/** Return the highest Mantle ancestor, or this instance when already root. */
|
|
908
|
+
getRoot() {
|
|
909
|
+
const parents = this.getParents();
|
|
910
|
+
return parents[parents.length - 1] ?? this;
|
|
911
|
+
}
|
|
912
|
+
/** @internal — called by createComponent to silently update props during render */
|
|
250
913
|
_syncProps(value) {
|
|
251
|
-
this._propsBox.
|
|
914
|
+
this._propsBox.setSilently(value);
|
|
252
915
|
}
|
|
253
916
|
ref() {
|
|
254
917
|
const r = { current: null };
|
|
255
|
-
|
|
918
|
+
componentRefs.add(r);
|
|
256
919
|
return r;
|
|
257
920
|
}
|
|
921
|
+
/**
|
|
922
|
+
* Register a cleanup function to run automatically on unmount.
|
|
923
|
+
* Returns a function that can be called for early cleanup.
|
|
924
|
+
*
|
|
925
|
+
* Cleanups are one-shot: they are not re-created during React StrictMode's
|
|
926
|
+
* same-instance effect replay. Call this from onMount (which is replayed),
|
|
927
|
+
* or use effect() for a replay-safe setup/teardown pair.
|
|
928
|
+
*/
|
|
929
|
+
addCleanup(cleanup) {
|
|
930
|
+
if (process.env.NODE_ENV !== "production" && !this._mounted) {
|
|
931
|
+
console.warn(
|
|
932
|
+
`[mobx-mantle] ${this.constructor.name}.addCleanup() called before mount. Cleanups are one-shot: they run when mount effects clean up and are not re-created during React StrictMode's same-instance effect replay. Acquire resources in onMount(), or use effect() for a replay-safe setup/teardown pair.`
|
|
933
|
+
);
|
|
934
|
+
}
|
|
935
|
+
return this._addCleanup(cleanup);
|
|
936
|
+
}
|
|
937
|
+
/** @internal — addCleanup without the pre-mount dev warning (used by watch/effect) */
|
|
938
|
+
_addCleanup(cleanup) {
|
|
939
|
+
let active = true;
|
|
940
|
+
const dispose = () => {
|
|
941
|
+
if (!active) return;
|
|
942
|
+
active = false;
|
|
943
|
+
try {
|
|
944
|
+
runInAction3(cleanup);
|
|
945
|
+
} finally {
|
|
946
|
+
const idx = this._watchDisposers.indexOf(dispose);
|
|
947
|
+
if (idx !== -1) this._watchDisposers.splice(idx, 1);
|
|
948
|
+
}
|
|
949
|
+
};
|
|
950
|
+
this._watchDisposers.push(dispose);
|
|
951
|
+
return dispose;
|
|
952
|
+
}
|
|
258
953
|
/**
|
|
259
954
|
* Watch a reactive expression and run a callback when it changes.
|
|
260
|
-
* Automatically disposed on unmount.
|
|
261
|
-
*
|
|
262
|
-
*
|
|
955
|
+
* Automatically disposed on unmount. Watchers declared before mount
|
|
956
|
+
* (field initializers, onCreate) are re-created during React StrictMode's
|
|
957
|
+
* same-instance effect replay.
|
|
958
|
+
*
|
|
959
|
+
* @param source - Reactive expression (getter) to watch, or a MaybeGetter
|
|
960
|
+
* argument passed through as-is. To watch a value that is itself a
|
|
961
|
+
* function, wrap it: `watch(() => this.callback, …)`
|
|
263
962
|
* @param callback - Called when the expression result changes
|
|
264
963
|
* @param options - Optional configuration (delay, fireImmediately)
|
|
265
964
|
* @returns Dispose function for early teardown
|
|
266
965
|
*
|
|
267
966
|
* @example
|
|
268
967
|
* ```tsx
|
|
269
|
-
*
|
|
968
|
+
* onMount() {
|
|
270
969
|
* this.watch(
|
|
271
970
|
* () => this.query,
|
|
272
971
|
* async (query) => {
|
|
@@ -279,41 +978,98 @@ var View = class {
|
|
|
279
978
|
* }
|
|
280
979
|
* ```
|
|
281
980
|
*/
|
|
282
|
-
watch(
|
|
283
|
-
const
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
981
|
+
watch(source, callback, options) {
|
|
982
|
+
const expr = toWatchExpression(source, options?.fireImmediately, this.constructor.name);
|
|
983
|
+
return registerReactive(this, () => {
|
|
984
|
+
const dispose = reaction2(
|
|
985
|
+
expr,
|
|
986
|
+
(value, prevValue) => {
|
|
987
|
+
try {
|
|
988
|
+
callback(value, prevValue);
|
|
989
|
+
} catch (e) {
|
|
990
|
+
reportError(e, { phase: "watch", name: this.constructor.name, isBehavior: false });
|
|
991
|
+
}
|
|
992
|
+
},
|
|
993
|
+
{
|
|
994
|
+
delay: options?.delay,
|
|
995
|
+
fireImmediately: options?.fireImmediately
|
|
290
996
|
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
997
|
+
);
|
|
998
|
+
return this._addCleanup(dispose);
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Run a side effect that auto-tracks reactive dependencies.
|
|
1003
|
+
* Re-runs whenever any accessed observable changes.
|
|
1004
|
+
* Automatically disposed on unmount. Effects declared before mount
|
|
1005
|
+
* (field initializers, onCreate) are re-created during React StrictMode's
|
|
1006
|
+
* same-instance effect replay.
|
|
1007
|
+
*
|
|
1008
|
+
* Best for simple synchronization (DOM updates, logging). For complex
|
|
1009
|
+
* side effects with explicit triggers, prefer `watch()`.
|
|
1010
|
+
*
|
|
1011
|
+
* @param fn - Effect function. May return a cleanup function.
|
|
1012
|
+
* @param options - Optional configuration (delay)
|
|
1013
|
+
* @returns Dispose function for early teardown
|
|
1014
|
+
*
|
|
1015
|
+
* @example
|
|
1016
|
+
* ```tsx
|
|
1017
|
+
* onMount() {
|
|
1018
|
+
* this.effect(() => {
|
|
1019
|
+
* document.title = `${this.items.length} items`;
|
|
1020
|
+
* });
|
|
1021
|
+
* }
|
|
1022
|
+
* ```
|
|
1023
|
+
*
|
|
1024
|
+
* @example With cleanup
|
|
1025
|
+
* ```tsx
|
|
1026
|
+
* onMount() {
|
|
1027
|
+
* this.effect(() => {
|
|
1028
|
+
* const handler = () => console.log(this.count);
|
|
1029
|
+
* window.addEventListener('click', handler);
|
|
1030
|
+
* return () => window.removeEventListener('click', handler);
|
|
1031
|
+
* });
|
|
1032
|
+
* }
|
|
1033
|
+
* ```
|
|
1034
|
+
*/
|
|
1035
|
+
effect(fn, options) {
|
|
1036
|
+
return registerReactive(this, () => {
|
|
1037
|
+
let cleanup;
|
|
1038
|
+
const dispose = autorun2(
|
|
1039
|
+
() => {
|
|
1040
|
+
runInAction3(() => cleanup?.());
|
|
1041
|
+
cleanup = void 0;
|
|
1042
|
+
try {
|
|
1043
|
+
const result = fn();
|
|
1044
|
+
if (typeof result === "function") {
|
|
1045
|
+
cleanup = result;
|
|
1046
|
+
}
|
|
1047
|
+
} catch (e) {
|
|
1048
|
+
reportError(e, { phase: "effect", name: this.constructor.name, isBehavior: false });
|
|
1049
|
+
}
|
|
1050
|
+
},
|
|
1051
|
+
{ delay: options?.delay }
|
|
1052
|
+
);
|
|
1053
|
+
return this._addCleanup(() => {
|
|
1054
|
+
runInAction3(() => cleanup?.());
|
|
1055
|
+
dispose();
|
|
1056
|
+
});
|
|
1057
|
+
});
|
|
303
1058
|
}
|
|
304
1059
|
/** @internal */
|
|
305
1060
|
_disposeWatchers() {
|
|
306
|
-
|
|
1061
|
+
const disposers = this._watchDisposers.slice();
|
|
1062
|
+
this._watchDisposers.length = 0;
|
|
1063
|
+
for (const dispose of disposers) {
|
|
307
1064
|
dispose();
|
|
308
1065
|
}
|
|
309
|
-
this._watchDisposers.length = 0;
|
|
310
1066
|
}
|
|
311
1067
|
/** @internal - Scan own properties for behavior instances and register them */
|
|
312
1068
|
_collectBehaviors() {
|
|
313
1069
|
for (const key of Object.keys(this)) {
|
|
314
1070
|
if (key.startsWith("_")) continue;
|
|
315
1071
|
const value = this[key];
|
|
316
|
-
if (isBehavior(value)) {
|
|
1072
|
+
if (isBehavior(value) && !isServiceValue(this, value)) {
|
|
317
1073
|
this._behaviors.push({ instance: value });
|
|
318
1074
|
}
|
|
319
1075
|
}
|
|
@@ -339,6 +1095,10 @@ var View = class {
|
|
|
339
1095
|
};
|
|
340
1096
|
var BASE_EXCLUDES = /* @__PURE__ */ new Set([
|
|
341
1097
|
"props",
|
|
1098
|
+
"getParent",
|
|
1099
|
+
"findParent",
|
|
1100
|
+
"getParents",
|
|
1101
|
+
"getRoot",
|
|
342
1102
|
"_propsBox",
|
|
343
1103
|
"forwardRef",
|
|
344
1104
|
"onCreate",
|
|
@@ -348,8 +1108,12 @@ var BASE_EXCLUDES = /* @__PURE__ */ new Set([
|
|
|
348
1108
|
"onUnmount",
|
|
349
1109
|
"render",
|
|
350
1110
|
"ref",
|
|
1111
|
+
"addCleanup",
|
|
1112
|
+
"_addCleanup",
|
|
351
1113
|
"watch",
|
|
1114
|
+
"effect",
|
|
352
1115
|
"constructor",
|
|
1116
|
+
"inject",
|
|
353
1117
|
"_behaviors",
|
|
354
1118
|
"_collectBehaviors",
|
|
355
1119
|
"_layoutMountBehaviors",
|
|
@@ -357,12 +1121,16 @@ var BASE_EXCLUDES = /* @__PURE__ */ new Set([
|
|
|
357
1121
|
"_unmountBehaviors",
|
|
358
1122
|
"_syncProps",
|
|
359
1123
|
"_watchDisposers",
|
|
360
|
-
"_disposeWatchers"
|
|
1124
|
+
"_disposeWatchers",
|
|
1125
|
+
"_reactiveSpecs",
|
|
1126
|
+
"_mounted",
|
|
1127
|
+
"_wasUnmounted"
|
|
361
1128
|
]);
|
|
362
|
-
function
|
|
363
|
-
return value !== null && typeof value === "object" &&
|
|
1129
|
+
function isComponentRef(value) {
|
|
1130
|
+
return value !== null && typeof value === "object" && componentRefs.has(value);
|
|
364
1131
|
}
|
|
365
|
-
|
|
1132
|
+
var componentProtoInfo = /* @__PURE__ */ new WeakMap();
|
|
1133
|
+
function makeComponentObservable(instance, autoBind) {
|
|
366
1134
|
const annotations = {};
|
|
367
1135
|
const ownKeys = /* @__PURE__ */ new Set([
|
|
368
1136
|
...Object.keys(instance),
|
|
@@ -372,69 +1140,95 @@ function makeViewObservable(instance, autoBind) {
|
|
|
372
1140
|
if (BASE_EXCLUDES.has(key)) continue;
|
|
373
1141
|
if (key in annotations) continue;
|
|
374
1142
|
const value = instance[key];
|
|
375
|
-
if (typeof value === "function") continue;
|
|
1143
|
+
if (typeof value === "function" || isServiceValue(instance, value)) continue;
|
|
376
1144
|
if (isBehavior(value)) {
|
|
377
1145
|
annotations[key] = observable4.ref;
|
|
378
1146
|
continue;
|
|
379
1147
|
}
|
|
380
|
-
if (
|
|
1148
|
+
if (isComponentRef(value)) {
|
|
381
1149
|
annotations[key] = observable4.ref;
|
|
382
1150
|
} else {
|
|
383
1151
|
annotations[key] = observable4;
|
|
384
1152
|
}
|
|
385
1153
|
}
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
1154
|
+
const protoInfo = collectProtoInfo(instance, Component.prototype, BASE_EXCLUDES, componentProtoInfo);
|
|
1155
|
+
for (const key of protoInfo.computedKeys) {
|
|
1156
|
+
if (key in annotations) continue;
|
|
1157
|
+
annotations[key] = computed4;
|
|
1158
|
+
}
|
|
1159
|
+
makeObservable2(instance, annotations);
|
|
1160
|
+
if (autoBind) {
|
|
1161
|
+
for (const key of protoInfo.methodKeys) {
|
|
391
1162
|
if (key in annotations) continue;
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
annotations[key] = autoBind ? action4.bound : action4;
|
|
1163
|
+
const method = instance[key];
|
|
1164
|
+
if (typeof method === "function") {
|
|
1165
|
+
instance[key] = smartBind(method, instance);
|
|
396
1166
|
}
|
|
397
1167
|
}
|
|
398
|
-
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
var SubstituteComponent = class extends Component {
|
|
1171
|
+
};
|
|
1172
|
+
function installSubstituteState(instance, state) {
|
|
1173
|
+
const annotations = {};
|
|
1174
|
+
for (const key of Reflect.ownKeys(state)) {
|
|
1175
|
+
if (typeof key !== "string" || key.startsWith("_") || key in instance || BASE_EXCLUDES.has(key)) throw new Error("[mobx-mantle] Substitute state cannot replace framework member " + String(key));
|
|
1176
|
+
const descriptor = Object.getOwnPropertyDescriptor(state, key);
|
|
1177
|
+
if (!("value" in descriptor)) throw new Error("[mobx-mantle] Substitute state must contain data/callbacks, not getters.");
|
|
1178
|
+
Object.defineProperty(instance, key, { value: descriptor.value, enumerable: true, writable: true, configurable: true });
|
|
1179
|
+
annotations[key] = observable4.ref;
|
|
399
1180
|
}
|
|
400
1181
|
makeObservable2(instance, annotations);
|
|
401
1182
|
}
|
|
402
|
-
function
|
|
1183
|
+
function createComponent(ComponentClass, templateOrOptions) {
|
|
403
1184
|
const template = typeof templateOrOptions === "function" ? templateOrOptions : void 0;
|
|
404
1185
|
const options = typeof templateOrOptions === "object" ? templateOrOptions : {};
|
|
405
1186
|
const { autoObservable = globalConfig.autoObservable } = options;
|
|
406
|
-
const
|
|
407
|
-
const
|
|
408
|
-
const
|
|
409
|
-
const
|
|
410
|
-
const
|
|
411
|
-
|
|
412
|
-
|
|
1187
|
+
const ReactComponent = reactForwardRef((props, ref) => {
|
|
1188
|
+
const parentHandle = React4.useContext(ComponentParentContext);
|
|
1189
|
+
const resolver = React4.useContext(ServiceContext);
|
|
1190
|
+
const substitutions = React4.useContext(ModelContext);
|
|
1191
|
+
const substitutedTemplate = useRef2(void 0);
|
|
1192
|
+
const vmRef = useRef2(null);
|
|
1193
|
+
const componentHandleRef = useRef2(null);
|
|
1194
|
+
const classRef = useRef2(ComponentClass);
|
|
1195
|
+
const prevPropsRef = useRef2(null);
|
|
1196
|
+
const propsNotifyingRef = useRef2(false);
|
|
1197
|
+
const renderReactionRef = useRef2({ current: null });
|
|
1198
|
+
if (!componentHandleRef.current) {
|
|
1199
|
+
componentHandleRef.current = { current: void 0 };
|
|
1200
|
+
}
|
|
1201
|
+
const componentHandle = componentHandleRef.current;
|
|
1202
|
+
if (vmRef.current && classRef.current !== ComponentClass) {
|
|
1203
|
+
classRef.current = ComponentClass;
|
|
413
1204
|
vmRef.current = null;
|
|
414
1205
|
}
|
|
415
1206
|
if (!vmRef.current) {
|
|
416
|
-
|
|
417
|
-
|
|
1207
|
+
applyMobxActionPolicy();
|
|
1208
|
+
const substitution = substitutions?.get(ComponentClass);
|
|
1209
|
+
if (substitution && !substitution.template && !template) throw new Error("[mobx-mantle] A substituted integrated model requires an explicit test template.");
|
|
1210
|
+
const instance = withInjectionScope(resolver, () => substitution ? constructComponent(SubstituteComponent, props, parentHandle) : constructComponent(ComponentClass, props, parentHandle));
|
|
1211
|
+
substitutedTemplate.current = substitution?.template;
|
|
1212
|
+
setModelIdentity(instance, ComponentClass);
|
|
1213
|
+
if (substitution) installSubstituteState(instance, substitution.state());
|
|
418
1214
|
instance.forwardRef = ref;
|
|
419
|
-
instance.
|
|
1215
|
+
instance._propsBox._renderReaction = renderReactionRef.current;
|
|
1216
|
+
if (!substitution) instance._collectBehaviors();
|
|
420
1217
|
const decoratorAnnotations = getAnnotations(instance);
|
|
421
|
-
if (
|
|
1218
|
+
if (substitution) {
|
|
1219
|
+
} else if (decoratorAnnotations) {
|
|
422
1220
|
const annotations = { ...decoratorAnnotations };
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
annotations[key] = action4.bound;
|
|
431
|
-
}
|
|
1221
|
+
makeObservable2(instance, annotations);
|
|
1222
|
+
const protoInfo = collectProtoInfo(instance, Component.prototype, BASE_EXCLUDES, componentProtoInfo);
|
|
1223
|
+
for (const key of protoInfo.methodKeys) {
|
|
1224
|
+
if (key in annotations) continue;
|
|
1225
|
+
const method = instance[key];
|
|
1226
|
+
if (typeof method === "function") {
|
|
1227
|
+
instance[key] = smartBind(method, instance);
|
|
432
1228
|
}
|
|
433
|
-
proto = Object.getPrototypeOf(proto);
|
|
434
1229
|
}
|
|
435
|
-
makeObservable2(instance, annotations);
|
|
436
1230
|
} else if (autoObservable) {
|
|
437
|
-
|
|
1231
|
+
makeComponentObservable(instance, true);
|
|
438
1232
|
} else {
|
|
439
1233
|
makeObservable2(instance);
|
|
440
1234
|
}
|
|
@@ -444,99 +1238,264 @@ function createView(ViewClass, templateOrOptions) {
|
|
|
444
1238
|
ownKeys: () => Reflect.ownKeys(instance.props),
|
|
445
1239
|
getOwnPropertyDescriptor: (_, key) => Reflect.getOwnPropertyDescriptor(instance.props, key)
|
|
446
1240
|
});
|
|
447
|
-
instance.onCreate?.(reactiveProps);
|
|
1241
|
+
withOwnerServiceScope(instance, () => runInAction3(() => instance.onCreate?.(reactiveProps)));
|
|
1242
|
+
if (process.env.NODE_ENV !== "production" && autoObservable && !decoratorAnnotations && !substitution) {
|
|
1243
|
+
for (const key of Object.keys(instance)) {
|
|
1244
|
+
if (BASE_EXCLUDES.has(key) || key.startsWith("_")) continue;
|
|
1245
|
+
const value = instance[key];
|
|
1246
|
+
if (typeof value === "function" || isServiceValue(instance, value)) continue;
|
|
1247
|
+
if (!isObservableProp(instance, key)) {
|
|
1248
|
+
console.warn(
|
|
1249
|
+
`[mobx-mantle] ${ComponentClass.name}.${key} was first assigned in onCreate() and is not reactive. Declare it as a class field so it can be made observable.`
|
|
1250
|
+
);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
448
1254
|
vmRef.current = instance;
|
|
449
1255
|
prevPropsRef.current = props;
|
|
450
1256
|
}
|
|
451
1257
|
const vm = vmRef.current;
|
|
1258
|
+
const renderTemplate = substitutedTemplate.current ?? template;
|
|
1259
|
+
componentParents.set(vm, parentHandle);
|
|
1260
|
+
componentHandle.current = vm;
|
|
452
1261
|
if (process.env.NODE_ENV !== "production" && propsNotifyingRef.current) {
|
|
453
1262
|
console.warn(
|
|
454
|
-
`[mobx-mantle] ${
|
|
1263
|
+
`[mobx-mantle] ${ComponentClass.name}: A reaction to a prop change modified observable state, which caused an extra re-render. Consider using a computed getter instead.`
|
|
455
1264
|
);
|
|
456
1265
|
propsNotifyingRef.current = false;
|
|
457
1266
|
}
|
|
458
1267
|
vm._syncProps(props);
|
|
459
1268
|
vm.forwardRef = ref;
|
|
460
|
-
|
|
1269
|
+
useIsomorphicLayoutEffect(() => {
|
|
461
1270
|
if (!shallowEqual(prevPropsRef.current, props)) {
|
|
462
1271
|
prevPropsRef.current = props;
|
|
463
1272
|
propsNotifyingRef.current = true;
|
|
464
|
-
|
|
1273
|
+
runInAction3(() => {
|
|
465
1274
|
vm._propsBox.set(props);
|
|
466
1275
|
});
|
|
467
1276
|
propsNotifyingRef.current = false;
|
|
468
1277
|
}
|
|
469
1278
|
});
|
|
470
|
-
|
|
1279
|
+
useIsomorphicLayoutEffect(() => {
|
|
1280
|
+
activateSpecs(vm);
|
|
471
1281
|
vm._layoutMountBehaviors();
|
|
472
1282
|
let cleanup;
|
|
473
1283
|
try {
|
|
474
|
-
const result = vm.onLayoutMount?.();
|
|
1284
|
+
const result = runInAction3(() => vm.onLayoutMount?.());
|
|
475
1285
|
if (process.env.NODE_ENV !== "production" && result instanceof Promise) {
|
|
476
1286
|
console.error(
|
|
477
|
-
`[mobx-mantle] ${
|
|
1287
|
+
`[mobx-mantle] ${ComponentClass.name}.onLayoutMount() returned a Promise. Lifecycle methods must be synchronous. Use a sync onLayoutMount that calls an async method instead.`
|
|
478
1288
|
);
|
|
479
1289
|
}
|
|
480
|
-
cleanup = result;
|
|
1290
|
+
cleanup = typeof result === "function" ? result : void 0;
|
|
481
1291
|
} catch (e) {
|
|
482
|
-
reportError(e, { phase: "onLayoutMount", name:
|
|
1292
|
+
reportError(e, { phase: "onLayoutMount", name: ComponentClass.name, isBehavior: false });
|
|
483
1293
|
}
|
|
484
1294
|
return () => {
|
|
485
|
-
cleanup?.();
|
|
1295
|
+
runInAction3(() => cleanup?.());
|
|
486
1296
|
};
|
|
487
1297
|
}, [vm]);
|
|
488
|
-
|
|
1298
|
+
useEffect2(() => {
|
|
489
1299
|
vm._mountBehaviors();
|
|
490
1300
|
let cleanup;
|
|
491
1301
|
try {
|
|
492
|
-
const result = vm.onMount?.();
|
|
1302
|
+
const result = runInAction3(() => vm.onMount?.());
|
|
493
1303
|
if (process.env.NODE_ENV !== "production" && result instanceof Promise) {
|
|
494
1304
|
console.error(
|
|
495
|
-
`[mobx-mantle] ${
|
|
1305
|
+
`[mobx-mantle] ${ComponentClass.name}.onMount() returned a Promise. Lifecycle methods must be synchronous. Use a sync onMount that calls an async method instead.`
|
|
496
1306
|
);
|
|
497
1307
|
}
|
|
498
|
-
cleanup = result;
|
|
1308
|
+
cleanup = typeof result === "function" ? result : void 0;
|
|
499
1309
|
} catch (e) {
|
|
500
|
-
reportError(e, { phase: "onMount", name:
|
|
1310
|
+
reportError(e, { phase: "onMount", name: ComponentClass.name, isBehavior: false });
|
|
1311
|
+
}
|
|
1312
|
+
if (process.env.NODE_ENV !== "production") {
|
|
1313
|
+
warnUncollectedBehaviors(vm, ComponentClass.name, vm._behaviors);
|
|
501
1314
|
}
|
|
502
1315
|
return () => {
|
|
503
|
-
cleanup?.();
|
|
1316
|
+
runInAction3(() => cleanup?.());
|
|
504
1317
|
try {
|
|
505
|
-
vm.onUnmount?.();
|
|
1318
|
+
runInAction3(() => vm.onUnmount?.());
|
|
506
1319
|
} catch (e) {
|
|
507
|
-
reportError(e, { phase: "onUnmount", name:
|
|
1320
|
+
reportError(e, { phase: "onUnmount", name: ComponentClass.name, isBehavior: false });
|
|
508
1321
|
}
|
|
509
1322
|
vm._disposeWatchers();
|
|
510
1323
|
vm._unmountBehaviors();
|
|
1324
|
+
vm._wasUnmounted = true;
|
|
511
1325
|
};
|
|
512
1326
|
}, [vm]);
|
|
513
|
-
|
|
1327
|
+
useEffect2(() => {
|
|
514
1328
|
try {
|
|
515
|
-
vm.onUpdate?.();
|
|
1329
|
+
runInAction3(() => vm.onUpdate?.());
|
|
516
1330
|
} catch (e) {
|
|
517
|
-
reportError(e, { phase: "onUpdate", name:
|
|
1331
|
+
reportError(e, { phase: "onUpdate", name: ComponentClass.name, isBehavior: false });
|
|
518
1332
|
}
|
|
519
1333
|
});
|
|
520
|
-
if (!
|
|
1334
|
+
if (!renderTemplate && !vm.render) {
|
|
521
1335
|
throw new Error(
|
|
522
|
-
`[mobx-mantle] ${
|
|
1336
|
+
`[mobx-mantle] ${ComponentClass.name}: Missing render() method. Either define render() in your Component class or pass a template function to createComponent().`
|
|
523
1337
|
);
|
|
524
1338
|
}
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
1339
|
+
const rendered = useMantleObserver(
|
|
1340
|
+
() => renderTemplate ? renderTemplate(vm) : vm.render(),
|
|
1341
|
+
ComponentClass.name,
|
|
1342
|
+
renderReactionRef.current
|
|
1343
|
+
);
|
|
1344
|
+
return /* @__PURE__ */ jsx3(ComponentParentContext.Provider, { value: componentHandle, children: rendered });
|
|
1345
|
+
});
|
|
1346
|
+
return memo2(ReactComponent);
|
|
1347
|
+
}
|
|
1348
|
+
function createForwardRef(ComponentClass, templateOrOptions) {
|
|
1349
|
+
return createComponent(ComponentClass, templateOrOptions);
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
// src/useBehavior.ts
|
|
1353
|
+
import { useContext } from "react";
|
|
1354
|
+
import { useEffect as useEffect3, useState } from "react";
|
|
1355
|
+
function useBehavior(create) {
|
|
1356
|
+
const resolver = useContext(ServiceContext);
|
|
1357
|
+
const [entry] = useState(() => {
|
|
1358
|
+
const instance = withInjectionScope(resolver, create);
|
|
1359
|
+
if (process.env.NODE_ENV !== "production" && !isBehavior(instance)) {
|
|
1360
|
+
console.warn(
|
|
1361
|
+
"[mobx-mantle] useBehavior() expected the factory to return a behavior instance (created with a factory from createBehavior). Lifecycle relay will be skipped for this value."
|
|
1362
|
+
);
|
|
1363
|
+
}
|
|
1364
|
+
return { instance };
|
|
528
1365
|
});
|
|
529
|
-
|
|
1366
|
+
useIsomorphicLayoutEffect(() => {
|
|
1367
|
+
if (!isBehavior(entry.instance)) return;
|
|
1368
|
+
layoutMountBehavior(entry);
|
|
1369
|
+
}, [entry]);
|
|
1370
|
+
useEffect3(() => {
|
|
1371
|
+
if (!isBehavior(entry.instance)) return;
|
|
1372
|
+
mountBehavior(entry);
|
|
1373
|
+
return () => unmountBehavior(entry);
|
|
1374
|
+
}, [entry]);
|
|
1375
|
+
return entry.instance;
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// src/shared.ts
|
|
1379
|
+
import { isObservableProp as isObservableProp2, reaction as reaction3, runInAction as runInAction4, toJS } from "mobx";
|
|
1380
|
+
var registry = /* @__PURE__ */ new WeakMap();
|
|
1381
|
+
function ownDataFields(store) {
|
|
1382
|
+
return Object.keys(store).filter((key) => {
|
|
1383
|
+
if (key.startsWith("_")) return false;
|
|
1384
|
+
if (typeof store[key] === "function") return false;
|
|
1385
|
+
return isObservableProp2(store, key);
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
function serialize(store, fields) {
|
|
1389
|
+
const values = {};
|
|
1390
|
+
for (const field of fields) values[field] = toJS(store[field]);
|
|
1391
|
+
return JSON.stringify(values);
|
|
1392
|
+
}
|
|
1393
|
+
function apply(store, fields, json) {
|
|
1394
|
+
let parsed;
|
|
1395
|
+
try {
|
|
1396
|
+
parsed = JSON.parse(json);
|
|
1397
|
+
} catch {
|
|
1398
|
+
return false;
|
|
1399
|
+
}
|
|
1400
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
|
|
1401
|
+
const values = parsed;
|
|
1402
|
+
runInAction4(() => {
|
|
1403
|
+
for (const field of fields) {
|
|
1404
|
+
if (field in values) store[field] = values[field];
|
|
1405
|
+
}
|
|
1406
|
+
});
|
|
1407
|
+
return true;
|
|
1408
|
+
}
|
|
1409
|
+
function safeStorage() {
|
|
1410
|
+
try {
|
|
1411
|
+
return typeof localStorage === "undefined" ? null : localStorage;
|
|
1412
|
+
} catch {
|
|
1413
|
+
return null;
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
function shared(store, key, options = {}) {
|
|
1417
|
+
if (registry.has(store) || typeof window === "undefined") return store;
|
|
1418
|
+
const target = store;
|
|
1419
|
+
const fields = options.fields ? [...options.fields] : ownDataFields(store);
|
|
1420
|
+
const storage = options.persist === false ? null : safeStorage();
|
|
1421
|
+
const channel = typeof BroadcastChannel === "function" ? new BroadcastChannel(`mantle-shared:${key}`) : null;
|
|
1422
|
+
channel?.unref?.();
|
|
1423
|
+
let stored = null;
|
|
1424
|
+
try {
|
|
1425
|
+
stored = storage?.getItem(key) ?? null;
|
|
1426
|
+
} catch {
|
|
1427
|
+
stored = null;
|
|
1428
|
+
}
|
|
1429
|
+
if (stored !== null) apply(target, fields, stored);
|
|
1430
|
+
let current = serialize(target, fields);
|
|
1431
|
+
const stopPublish = reaction3(
|
|
1432
|
+
() => serialize(target, fields),
|
|
1433
|
+
(json) => {
|
|
1434
|
+
if (json === current) return;
|
|
1435
|
+
current = json;
|
|
1436
|
+
try {
|
|
1437
|
+
storage?.setItem(key, json);
|
|
1438
|
+
} catch {
|
|
1439
|
+
}
|
|
1440
|
+
channel?.postMessage(json);
|
|
1441
|
+
}
|
|
1442
|
+
);
|
|
1443
|
+
const receive = (json) => {
|
|
1444
|
+
if (json === current) return;
|
|
1445
|
+
current = json;
|
|
1446
|
+
apply(target, fields, json);
|
|
1447
|
+
};
|
|
1448
|
+
const onMessage = (event) => {
|
|
1449
|
+
if (typeof event.data === "string") receive(event.data);
|
|
1450
|
+
};
|
|
1451
|
+
const onStorage = (event) => {
|
|
1452
|
+
if (event.key === key && event.newValue !== null) receive(event.newValue);
|
|
1453
|
+
};
|
|
1454
|
+
channel?.addEventListener("message", onMessage);
|
|
1455
|
+
window.addEventListener("storage", onStorage);
|
|
1456
|
+
registry.set(store, {
|
|
1457
|
+
dispose() {
|
|
1458
|
+
stopPublish();
|
|
1459
|
+
channel?.removeEventListener("message", onMessage);
|
|
1460
|
+
channel?.close();
|
|
1461
|
+
window.removeEventListener("storage", onStorage);
|
|
1462
|
+
registry.delete(store);
|
|
1463
|
+
}
|
|
1464
|
+
});
|
|
1465
|
+
return store;
|
|
1466
|
+
}
|
|
1467
|
+
function unshare(store) {
|
|
1468
|
+
registry.get(store)?.dispose();
|
|
1469
|
+
}
|
|
1470
|
+
function shareStores(stores, options = {}) {
|
|
1471
|
+
const { prefix = "shared", ...rest } = options;
|
|
1472
|
+
for (const [name, store] of Object.entries(stores)) {
|
|
1473
|
+
shared(store, `${prefix}:${name}`, rest);
|
|
1474
|
+
}
|
|
1475
|
+
return stores;
|
|
530
1476
|
}
|
|
531
1477
|
export {
|
|
532
1478
|
Behavior,
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
1479
|
+
Component,
|
|
1480
|
+
ModelProvider,
|
|
1481
|
+
ServiceProvider,
|
|
1482
|
+
Component as ViewModel,
|
|
1483
|
+
action2 as action,
|
|
1484
|
+
computed2 as computed,
|
|
537
1485
|
configure,
|
|
538
1486
|
createBehavior,
|
|
539
|
-
|
|
540
|
-
|
|
1487
|
+
createComponent,
|
|
1488
|
+
createForwardRef,
|
|
1489
|
+
createServiceToken,
|
|
1490
|
+
inject,
|
|
1491
|
+
isModel,
|
|
1492
|
+
observable2 as observable,
|
|
1493
|
+
observer,
|
|
1494
|
+
shareStores,
|
|
1495
|
+
shared,
|
|
1496
|
+
toValue,
|
|
1497
|
+
unshare,
|
|
1498
|
+
useBehavior,
|
|
1499
|
+
withInjectionScope
|
|
541
1500
|
};
|
|
542
1501
|
//# sourceMappingURL=index.js.map
|