@olovyannikov/effector-models 0.1.2 → 0.2.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.
@@ -0,0 +1,346 @@
1
+ let effector = require("effector");
2
+ // lib/model.ts
3
+ /** Настоящий id по алиасу; id без алиаса возвращается как есть. */ function resolveAlias(aliases, id) {
4
+ return Object.hasOwn(aliases, id) ? aliases[id] : id;
5
+ }
6
+ /**
7
+ * Записывает собственное свойство. Обычное присваивание для ключа `__proto__` меняет прототип,
8
+ * а не добавляет ключ, — id и алиасы приходят снаружи и могут быть любыми строками.
9
+ */ function setOwn(target, key, value) {
10
+ Object.defineProperty(target, key, {
11
+ value,
12
+ enumerable: true,
13
+ writable: true,
14
+ configurable: true
15
+ });
16
+ }
17
+ const toList = (ids) => typeof ids === "string" ? [ids] : ids;
18
+ const toArray = (value) => Array.isArray(value) ? value : [value];
19
+ const withoutAliases = (aliases, isRemoved) => {
20
+ let next = aliases;
21
+ for (const [alias, id] of Object.entries(aliases)) if (isRemoved(alias, id)) {
22
+ if (next === aliases) next = { ...aliases };
23
+ delete next[alias];
24
+ }
25
+ return next;
26
+ };
27
+ /**
28
+ * Состояние модели из словаря экземпляров — для засева `$state` в тестах и при гидрации.
29
+ * Порядок id берётся из порядка ключей.
30
+ */ function modelState(instances, aliases = {}) {
31
+ return {
32
+ ids: Object.keys(instances),
33
+ instances,
34
+ aliases
35
+ };
36
+ }
37
+ const factsOf = /* @__PURE__ */ new WeakMap();
38
+ function takeFacts(state) {
39
+ const facts = factsOf.get(state) ?? [];
40
+ factsOf.delete(state);
41
+ return facts;
42
+ }
43
+ function mergeFacts(facts) {
44
+ const merged = [];
45
+ const gone = facts.flatMap((fact) => fact.type === "deleted" ? fact.payload : []);
46
+ if (gone.length > 0) merged.push({
47
+ type: "deleted",
48
+ payload: [...new Set(gone)]
49
+ });
50
+ for (const type of ["renamed", "missed"]) {
51
+ const found = facts.find((fact) => fact.type === type);
52
+ if (found) merged.push(found);
53
+ }
54
+ return merged;
55
+ }
56
+ function commit(state, next, facts = []) {
57
+ const ids = next.ids ?? state.ids;
58
+ const instances = next.instances ?? state.instances;
59
+ const aliases = next.aliases ?? state.aliases;
60
+ if (ids === state.ids && instances === state.instances && aliases === state.aliases && facts.length === 0) return state;
61
+ const result = {
62
+ ids,
63
+ instances,
64
+ aliases
65
+ };
66
+ if (facts.length > 0) factsOf.set(result, facts);
67
+ return result;
68
+ }
69
+ function applyTo(state, action, ids, fn) {
70
+ const { instances, aliases } = state;
71
+ let next = instances;
72
+ const missing = [];
73
+ for (const id of new Set(toList(ids).map((item) => resolveAlias(aliases, item)))) {
74
+ if (!Object.hasOwn(instances, id)) {
75
+ missing.push(id);
76
+ continue;
77
+ }
78
+ const current = instances[id];
79
+ const updated = fn(current);
80
+ if (updated !== current) {
81
+ if (next === instances) next = { ...instances };
82
+ setOwn(next, id, updated);
83
+ }
84
+ }
85
+ return commit(state, { instances: next }, missing.length > 0 ? [{
86
+ type: "missed",
87
+ payload: {
88
+ action,
89
+ ids: missing
90
+ }
91
+ }] : []);
92
+ }
93
+ function removeFrom(state, ids) {
94
+ const real = [...new Set(ids)].filter((id) => Object.hasOwn(state.instances, id));
95
+ if (real.length === 0) return state;
96
+ const instances = { ...state.instances };
97
+ for (const id of real) delete instances[id];
98
+ const names = Object.keys(state.aliases).filter((alias) => real.includes(state.aliases[alias]));
99
+ return commit(state, {
100
+ ids: state.ids.filter((id) => !real.includes(id)),
101
+ instances,
102
+ aliases: withoutAliases(state.aliases, (alias) => names.includes(alias))
103
+ }, [{
104
+ type: "deleted",
105
+ payload: [...real, ...names]
106
+ }]);
107
+ }
108
+ function model(config) {
109
+ const { name, defaults } = config;
110
+ const reducers = config.events ?? {};
111
+ const $state = (0, effector.createStore)({
112
+ ids: [],
113
+ instances: {},
114
+ aliases: {}
115
+ }, {
116
+ sid: `effector-models:${name}`,
117
+ name: `${name}/$state`
118
+ });
119
+ const $instances = $state.map((state) => state.instances);
120
+ const $aliases = $state.map((state) => state.aliases);
121
+ const $ids = $state.map((state) => state.ids);
122
+ const facts = $state.updates.filterMap((state) => {
123
+ const list = takeFacts(state);
124
+ return list.length > 0 ? list : void 0;
125
+ });
126
+ const factOf = (type) => facts.filterMap((list) => list.find((fact) => fact.type === type)?.payload);
127
+ const deleted = factOf("deleted");
128
+ const renamed = factOf("renamed");
129
+ const missed = factOf("missed");
130
+ const hooks = {
131
+ deleted: [],
132
+ renamed: []
133
+ };
134
+ const settle = (before, after) => {
135
+ if (after === before) return before;
136
+ let current = after;
137
+ const queue = takeFacts(current);
138
+ const seen = [];
139
+ while (queue.length > 0) {
140
+ const fact = queue.shift();
141
+ seen.push(fact);
142
+ if (fact.type === "missed") continue;
143
+ for (const hook of hooks[fact.type]) {
144
+ const next = hook(current, fact.payload);
145
+ if (next !== current) {
146
+ queue.push(...takeFacts(next));
147
+ current = next;
148
+ }
149
+ }
150
+ }
151
+ if (seen.length > 0) factsOf.set(current, mergeFacts(seen));
152
+ return current;
153
+ };
154
+ const on = (clock, reducer) => {
155
+ $state.on(clock, (state, payload) => settle(state, reducer(state, payload)));
156
+ };
157
+ const create = (0, effector.createEvent)({ name: `${name}/create` });
158
+ const reduceCreate = (state, params) => {
159
+ const items = toArray(params);
160
+ if (items.length === 0) return state;
161
+ const instances = { ...state.instances };
162
+ const added = [];
163
+ for (const { id, data } of items) {
164
+ if (!Object.hasOwn(instances, id)) added.push(id);
165
+ setOwn(instances, id, {
166
+ ...defaults,
167
+ ...data
168
+ });
169
+ }
170
+ return commit(state, {
171
+ ids: added.length > 0 ? [...state.ids, ...added] : state.ids,
172
+ instances,
173
+ aliases: withoutAliases(state.aliases, (alias) => items.some((item) => item.id === alias))
174
+ });
175
+ };
176
+ on(create, reduceCreate);
177
+ const upsert = (0, effector.createEvent)({ name: `${name}/upsert` });
178
+ const reduceUpsert = (state, params) => {
179
+ const items = toArray(params);
180
+ if (items.length === 0) return state;
181
+ const instances = { ...state.instances };
182
+ const added = [];
183
+ for (const { id: given, data } of items) {
184
+ const id = resolveAlias(state.aliases, given);
185
+ const exists = Object.hasOwn(instances, id);
186
+ if (!exists) added.push(id);
187
+ setOwn(instances, id, {
188
+ ...exists ? instances[id] : defaults,
189
+ ...data
190
+ });
191
+ }
192
+ return commit(state, {
193
+ ids: added.length > 0 ? [...state.ids, ...added] : state.ids,
194
+ instances
195
+ });
196
+ };
197
+ on(upsert, reduceUpsert);
198
+ const update = (0, effector.createEvent)({ name: `${name}/update` });
199
+ on(update, (state, { id, data }) => applyTo(state, "update", id, (instance) => typeof data === "function" ? data(instance) : {
200
+ ...instance,
201
+ ...data
202
+ }));
203
+ const remove = (0, effector.createEvent)({ name: `${name}/delete` });
204
+ const reduceDelete = (state, ids) => removeFrom(state, toList(ids).map((id) => resolveAlias(state.aliases, id)));
205
+ on(remove, reduceDelete);
206
+ const rename = (0, effector.createEvent)({ name: `${name}/rename` });
207
+ on(rename, (state, params) => {
208
+ const from = resolveAlias(state.aliases, params.from);
209
+ const { to } = params;
210
+ if (!Object.hasOwn(state.instances, from)) return commit(state, {}, [{
211
+ type: "missed",
212
+ payload: {
213
+ action: "rename",
214
+ ids: [from]
215
+ }
216
+ }]);
217
+ if (from === to) return state;
218
+ const instances = { ...state.instances };
219
+ setOwn(instances, to, state.instances[from]);
220
+ delete instances[from];
221
+ const ids = state.ids.filter((id) => id !== to).map((id) => id === from ? to : id);
222
+ let aliases = withoutAliases(state.aliases, (alias) => alias === to);
223
+ for (const [alias, id] of Object.entries(aliases)) if (id === from) {
224
+ if (aliases === state.aliases) aliases = { ...state.aliases };
225
+ setOwn(aliases, alias, to);
226
+ }
227
+ return commit(state, {
228
+ ids,
229
+ instances,
230
+ aliases
231
+ }, [{
232
+ type: "renamed",
233
+ payload: {
234
+ from,
235
+ to
236
+ }
237
+ }]);
238
+ });
239
+ const clear = (0, effector.createEvent)({ name: `${name}/clear` });
240
+ on(clear, (state) => {
241
+ const gone = [...state.ids, ...Object.keys(state.aliases)];
242
+ return gone.length === 0 ? state : commit(state, {
243
+ ids: [],
244
+ instances: {},
245
+ aliases: {}
246
+ }, [{
247
+ type: "deleted",
248
+ payload: gone
249
+ }]);
250
+ });
251
+ const alias = (0, effector.createEvent)({ name: `${name}/alias` });
252
+ on(alias, (state, params) => {
253
+ let aliases = state.aliases;
254
+ for (const { alias: given, id } of toArray(params)) {
255
+ const target = resolveAlias(aliases, id);
256
+ if (!Object.hasOwn(state.instances, target) || Object.hasOwn(state.instances, given) || Object.hasOwn(aliases, given) && aliases[given] === target) continue;
257
+ if (aliases === state.aliases) aliases = { ...state.aliases };
258
+ setOwn(aliases, given, target);
259
+ }
260
+ return commit(state, { aliases });
261
+ });
262
+ const unalias = (0, effector.createEvent)({ name: `${name}/unalias` });
263
+ on(unalias, (state, ids) => {
264
+ const removed = toList(ids);
265
+ return commit(state, { aliases: withoutAliases(state.aliases, (item) => removed.includes(item)) });
266
+ });
267
+ const applyLink = (state, target, payload) => {
268
+ switch (target.to) {
269
+ case "create":
270
+ case "upsert": {
271
+ const params = target.fn(payload);
272
+ if (params === void 0) return state;
273
+ return target.to === "create" ? reduceCreate(state, params) : reduceUpsert(state, params);
274
+ }
275
+ case "delete": {
276
+ const ids = target.fn(payload);
277
+ return ids === void 0 ? state : reduceDelete(state, ids);
278
+ }
279
+ case "deleteWhere": {
280
+ const isDeleted = target.fn(payload);
281
+ return removeFrom(state, state.ids.filter((id) => isDeleted(state.instances[id], id)));
282
+ }
283
+ case "patch": return commit(state, { instances: target.fn(payload)(state.instances) });
284
+ }
285
+ };
286
+ const link = (clock, target) => {
287
+ on(clock.map((payload) => payload), (state, payload) => applyLink(state, target, payload));
288
+ };
289
+ const react = (source, fact, target) => {
290
+ const own = fact === "deleted" ? deleted : renamed;
291
+ if (source[fact] === own) hooks[fact].push((state, payload) => applyLink(state, target, payload));
292
+ else link(source[fact], target);
293
+ };
294
+ const events = {};
295
+ for (const [action, reducer] of Object.entries(reducers)) {
296
+ const event = (0, effector.createEvent)({ name: `${name}/${action}` });
297
+ on(event, (state, { id, payload }) => applyTo(state, action, id, (instance) => reducer(instance, payload)));
298
+ events[action] = event;
299
+ }
300
+ return {
301
+ name,
302
+ defaults,
303
+ $state,
304
+ $instances,
305
+ $ids,
306
+ $aliases,
307
+ alias,
308
+ unalias,
309
+ create,
310
+ upsert,
311
+ update,
312
+ delete: remove,
313
+ deleted,
314
+ rename,
315
+ renamed,
316
+ clear,
317
+ events,
318
+ missed,
319
+ "~link": link,
320
+ "~react": react
321
+ };
322
+ }
323
+ Object.defineProperty(exports, "model", {
324
+ enumerable: true,
325
+ get: function() {
326
+ return model;
327
+ }
328
+ });
329
+ Object.defineProperty(exports, "modelState", {
330
+ enumerable: true,
331
+ get: function() {
332
+ return modelState;
333
+ }
334
+ });
335
+ Object.defineProperty(exports, "resolveAlias", {
336
+ enumerable: true,
337
+ get: function() {
338
+ return resolveAlias;
339
+ }
340
+ });
341
+ Object.defineProperty(exports, "setOwn", {
342
+ enumerable: true,
343
+ get: function() {
344
+ return setOwn;
345
+ }
346
+ });
package/dist/react.cjs CHANGED
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let effector_react = require("effector-react");
3
3
  let react = require("react");
4
4
  let effector = require("effector");
5
- const require_model = require("./model-iPgSwajA.cjs");
5
+ const require_model = require("./model-Ds45KAy9.cjs");
6
6
  // lib/react.ts
7
7
  const $noAliases = (0, effector.createStore)({}, { serialize: "ignore" });
8
8
  const identity = (value) => value;
@@ -23,7 +23,7 @@ function useInstance(model, id, selector = identity, isEqual = Object.is) {
23
23
  selector,
24
24
  isEqual
25
25
  ],
26
- fn: (instances, [key, select]) => ({ value: select(key === null ? void 0 : instances[key]) }),
26
+ fn: (instances, [key, select]) => ({ value: select(key === null || !Object.hasOwn(instances, key) ? void 0 : instances[key]) }),
27
27
  updateFilter: (next, prev) => !isEqual(next.value, prev.value)
28
28
  }).value;
29
29
  }
@@ -72,7 +72,7 @@ const noIds = [];
72
72
  const state = (0, effector_react.useStoreMap)({
73
73
  store: union.$instances,
74
74
  keys: [kind, id],
75
- fn: (instances, [currentKind, currentId]) => ({ value: currentKind === null || currentId === null ? void 0 : instances[currentKind]?.[currentId] }),
75
+ fn: (instances, [currentKind, currentId]) => ({ value: readMember(currentKind === null ? void 0 : instances[currentKind], currentId) }),
76
76
  updateFilter: (next, prev) => next.value !== prev.value
77
77
  }).value;
78
78
  return (0, react.useMemo)(() => kind === null || id === null || state === void 0 ? void 0 : {
@@ -85,7 +85,8 @@ const noIds = [];
85
85
  state
86
86
  ]);
87
87
  }
88
- const sameItems = (next, prev) => next.length === prev.length && next.every((item, index) => item === prev[index]);
88
+ const sameItems = (next, prev) => Array.isArray(next) && Array.isArray(prev) && next.length === prev.length && next.every((item, index) => item === prev[index]);
89
+ const readMember = (instances, id) => instances === void 0 || id === null || !Object.hasOwn(instances, id) ? void 0 : instances[id];
89
90
  function useChildren(relation, parentId, selector, isEqual) {
90
91
  const ids = useChildIds(relation, parentId);
91
92
  return (0, effector_react.useStoreMap)({
package/dist/react.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { EventCallable, Store } from "effector";
2
- import { _ as Instances, a as Union, c as UnionModels, g as InstanceEventParams, h as Ids, l as UnionRef, r as ModelLike, s as UnionInstances, t as Child, y as Model } from "./relations-DXJ6slzh.cjs";
2
+ import { _ as Instances, a as Union, c as UnionModels, g as InstanceEventParams, h as Ids, l as UnionRef, r as ModelLike, s as UnionInstances, t as Child, y as Model } from "./relations-NBj9Om01.cjs";
3
3
  /** Хукам чтения нужна только часть модели — подходит любая модель с этими сторами. */
4
4
  type AliasesSource = {
5
5
  readonly $aliases: Store<Record<string, string>>;
@@ -23,7 +23,9 @@ export declare function useInstance<State extends object, Selected>(model: Insta
23
23
  export declare function useInstanceIds(model: IdsSource): string[];
24
24
  type BoundEvents<Payloads extends Record<string, unknown>> = { readonly [K in keyof Payloads]: (...args: InstanceEventParams<Payloads[K]> extends {
25
25
  payload: infer P;
26
- } ? [payload: P] : [payload?: undefined]) => void; };
26
+ } ? [payload: P] : InstanceEventParams<Payloads[K]> extends {
27
+ payload?: infer P;
28
+ } ? unknown extends P ? [payload?: undefined] : [payload?: P] : [payload?: undefined]) => void; };
27
29
  /** События экземпляра, привязанные к id и к scope из Provider. */
28
30
  export declare function useInstanceEvents<State extends object, Payloads extends Record<string, unknown>>(model: Model<State, Payloads>, id: Ids): BoundEvents<Payloads>;
29
31
  /** Id детей одного родителя (по его id или алиасу); перерисовывает, только когда меняется их набор или порядок. */
@@ -73,25 +75,11 @@ export interface ModelView<State extends object, Payloads extends Record<string,
73
75
  readonly update: (data: Partial<State> | ((state: State) => State)) => void;
74
76
  readonly remove: () => void;
75
77
  }
76
- /**
77
- * Всё про один экземпляр одним хуком: состояние, события, запись и — по желанию — его дети.
78
- *
79
- * ```tsx
80
- * const todo = useModel(Todos, id, {
81
- * subtaskIds: subtasks,
82
- * done: childrenOf(subtasks, countCompleted),
83
- * });
84
- *
85
- * todo.state?.title; todo.events.toggled(); todo.remove();
86
- * todo.subtaskIds; todo.done;
87
- * ```
88
- *
89
- * Id может быть алиасом. Компонент перерисовывается, когда меняется сам экземпляр
90
- * или запрошенное из связей. Набор ключей в `related` должен быть постоянным.
91
- */
92
78
  type BoundFrom<Events> = { readonly [K in keyof Events]: Events[K] extends EventCallable<infer Params> ? Params extends {
93
79
  payload: infer Payload;
94
- } ? (payload: Payload) => void : (payload?: undefined) => void : never; };
80
+ } ? (payload: Payload) => void : Params extends {
81
+ payload?: infer Payload;
82
+ } ? unknown extends Payload ? (payload?: undefined) => void : (payload?: Payload) => void : (payload?: undefined) => void : never; };
95
83
  type MemberState<Member> = Member extends ModelLike<infer State> ? State : never;
96
84
  /** Экземпляр объединения со всем, что нужно компоненту; по `kind` сужаются `state` и `events`. */
97
85
  export type UnionModelView<Models extends UnionModels> = { [K in keyof Models & string]: {
@@ -111,6 +99,22 @@ export type UnionModelView<Models extends UnionModels> = { [K in keyof Models &
111
99
  * `undefined`, если экземпляра нет.
112
100
  */
113
101
  export declare function useModel<Models extends UnionModels>(union: Union<Models>, ref: UnionRef<Models> | null | undefined): UnionModelView<Models> | undefined;
102
+ /**
103
+ * Всё про один экземпляр одним хуком: состояние, события, запись и — по желанию — его дети.
104
+ *
105
+ * ```tsx
106
+ * const todo = useModel(Todos, id, {
107
+ * subtaskIds: subtasks,
108
+ * done: childrenOf(subtasks, countCompleted),
109
+ * });
110
+ *
111
+ * todo.state?.title; todo.events.toggled(); todo.remove();
112
+ * todo.subtaskIds; todo.done;
113
+ * ```
114
+ *
115
+ * Id может быть алиасом. Компонент перерисовывается, когда меняется сам экземпляр
116
+ * или запрошенное из связей. Набор ключей в `related` должен быть постоянным.
117
+ */
114
118
  export declare function useModel<State extends object, Payloads extends Record<string, unknown>, Related extends Record<string, RelatedSpec> = Record<never, RelatedSpec>>(model: Model<State, Payloads>, id: string | null | undefined, related?: Related & { readonly [K in ReservedKeys]?: never; }): ModelView<State, Payloads> & RelatedValues<Related>;
115
119
  export {};
116
120
  //# sourceMappingURL=react.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"react.d.cts","names":[],"sources":["../lib/react.ts"],"mappings":";;;KAsBK;WAA2B,UAAU,MAAM;;KAC3C,gBAAgB;WACV,YAAY,MAAM,UAAU;IACnC,QAAQ;KAOP;WAAuB,MAAM;;;wBASlB,cAAc,SAAS,eAAe;wBACtC,cACd,SAAS,eACT;;;;;wBAuBc,YAAY,sBAC1B,OAAO,gBAAgB,QACvB,gCACC;wBACa,YAAY,sBAAsB,UAChD,OAAO,gBAAgB,QACvB,+BACA,WAAW,OAAO,sBAAsB,UACxC,WAAW,MAAM,UAAU,MAAM,uBAChC;;wBA4Ba,eAAe,OAAO;KASjC,YAAY,iBAAiB,uCACtB,WAAW,eAChB,MAAM,oBAAoB,SAAS;EAAc,eAAe;KAC9D,SAAS,MACT;;wBAKO,kBACd,sBACA,iBAAiB,yBACjB,OAAO,MAAM,OAAO,WAAW,IAAI,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WACzC;WACA,UAAU,MAAM;WAChB,YAAY,UAAU,YAAY;WAClC,WAAW,MAAM,UAAU,MAAM;;;;;;wBAO5B,WAAW,sBACzB,UAAU,MAAM,SACf,aAAa,OAAO;wBACP,WAAW,sBAAsB,UAC/C,UAAU,MAAM,QAChB,WAAW,UAAU,YAAY,UACjC,WAAW,MAAM,UAAU,MAAM,uBAChC,aAAa,OAAO;KASlB,cAAc,aAAa;;KAG3B;KAEA,cAAc,uBACP,WAAW,UAAU,QAAQ,WAAW,wBAE1C,YAEJ;iBAIW,UACf,sBACA,iBAAiB;;WAGR;WACA;WACA,OAAO;;WAEP,QAAQ,YAAY;WACpB,SAAS,MAAM,QAAQ,WAAW,OAAO,UAAU;WACnD;;KA8CN,UAAU,sBACH,WAAW,SAAS,OAAO,WAAW,oBAAoB,UAChE;EAAiB,eAAe;KAC7B,SAAS,mBACV;EAAiB,gBAAgB;oBACf,WACb,gCACA,UAAU,oBACZ;KAIN,YAAY,UACf,eAAe,gBAAgB,SAAS;;YAG9B,eAAe,eAAe,kBACvC,WAAW;WACD,MAAM;;WAEN;WACA,OAAO,YAAY,OAAO;;WAE1B,QAAQ,OAAO;aAAsB,cAAc;MACxD,UAAU,UACV;WACK,SACP,MACI,QAAQ,YAAY,OAAO,SACzB,OAAO,YAAY,OAAO,QAAQ,YAAY,OAAO;WAEpD;WAEL;;;;;wBAmEQ,SAAS,eAAe,aACtC,OAAO,MAAM,SACb,KAAK,SAAS,6BACb,eAAe;;;;;;;;;;;;;;;;;wBAiBF,SACd,sBACA,iBAAiB,yBACjB,gBAAgB,eAAe,eAAe,cAAc,cAE5D,OAAO,MAAM,OAAO,WACpB,+BACA,UAAU,sBAAsB,KAAK,2BACpC,UAAU,OAAO,YAAY,cAAc"}
package/dist/react.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { EventCallable, Store } from "effector";
2
- import { _ as Instances, a as Union, c as UnionModels, g as InstanceEventParams, h as Ids, l as UnionRef, r as ModelLike, s as UnionInstances, t as Child, y as Model } from "./relations-Cc9Mv0m7.mjs";
2
+ import { _ as Instances, a as Union, c as UnionModels, g as InstanceEventParams, h as Ids, l as UnionRef, r as ModelLike, s as UnionInstances, t as Child, y as Model } from "./relations-BnHiRhRy.mjs";
3
3
  /** Хукам чтения нужна только часть модели — подходит любая модель с этими сторами. */
4
4
  type AliasesSource = {
5
5
  readonly $aliases: Store<Record<string, string>>;
@@ -23,7 +23,9 @@ export declare function useInstance<State extends object, Selected>(model: Insta
23
23
  export declare function useInstanceIds(model: IdsSource): string[];
24
24
  type BoundEvents<Payloads extends Record<string, unknown>> = { readonly [K in keyof Payloads]: (...args: InstanceEventParams<Payloads[K]> extends {
25
25
  payload: infer P;
26
- } ? [payload: P] : [payload?: undefined]) => void; };
26
+ } ? [payload: P] : InstanceEventParams<Payloads[K]> extends {
27
+ payload?: infer P;
28
+ } ? unknown extends P ? [payload?: undefined] : [payload?: P] : [payload?: undefined]) => void; };
27
29
  /** События экземпляра, привязанные к id и к scope из Provider. */
28
30
  export declare function useInstanceEvents<State extends object, Payloads extends Record<string, unknown>>(model: Model<State, Payloads>, id: Ids): BoundEvents<Payloads>;
29
31
  /** Id детей одного родителя (по его id или алиасу); перерисовывает, только когда меняется их набор или порядок. */
@@ -73,25 +75,11 @@ export interface ModelView<State extends object, Payloads extends Record<string,
73
75
  readonly update: (data: Partial<State> | ((state: State) => State)) => void;
74
76
  readonly remove: () => void;
75
77
  }
76
- /**
77
- * Всё про один экземпляр одним хуком: состояние, события, запись и — по желанию — его дети.
78
- *
79
- * ```tsx
80
- * const todo = useModel(Todos, id, {
81
- * subtaskIds: subtasks,
82
- * done: childrenOf(subtasks, countCompleted),
83
- * });
84
- *
85
- * todo.state?.title; todo.events.toggled(); todo.remove();
86
- * todo.subtaskIds; todo.done;
87
- * ```
88
- *
89
- * Id может быть алиасом. Компонент перерисовывается, когда меняется сам экземпляр
90
- * или запрошенное из связей. Набор ключей в `related` должен быть постоянным.
91
- */
92
78
  type BoundFrom<Events1> = { readonly [K in keyof Events1]: Events1[K] extends EventCallable<infer Params> ? Params extends {
93
79
  payload: infer Payload;
94
- } ? (payload: Payload) => void : (payload?: undefined) => void : never; };
80
+ } ? (payload: Payload) => void : Params extends {
81
+ payload?: infer Payload;
82
+ } ? unknown extends Payload ? (payload?: undefined) => void : (payload?: Payload) => void : (payload?: undefined) => void : never; };
95
83
  type MemberState<Member> = Member extends ModelLike<infer State> ? State : never;
96
84
  /** Экземпляр объединения со всем, что нужно компоненту; по `kind` сужаются `state` и `events`. */
97
85
  export type UnionModelView<Models extends UnionModels> = { [K in keyof Models & string]: {
@@ -111,6 +99,22 @@ export type UnionModelView<Models extends UnionModels> = { [K in keyof Models &
111
99
  * `undefined`, если экземпляра нет.
112
100
  */
113
101
  export declare function useModel<Models extends UnionModels>(union: Union<Models>, ref: UnionRef<Models> | null | undefined): UnionModelView<Models> | undefined;
102
+ /**
103
+ * Всё про один экземпляр одним хуком: состояние, события, запись и — по желанию — его дети.
104
+ *
105
+ * ```tsx
106
+ * const todo = useModel(Todos, id, {
107
+ * subtaskIds: subtasks,
108
+ * done: childrenOf(subtasks, countCompleted),
109
+ * });
110
+ *
111
+ * todo.state?.title; todo.events.toggled(); todo.remove();
112
+ * todo.subtaskIds; todo.done;
113
+ * ```
114
+ *
115
+ * Id может быть алиасом. Компонент перерисовывается, когда меняется сам экземпляр
116
+ * или запрошенное из связей. Набор ключей в `related` должен быть постоянным.
117
+ */
114
118
  export declare function useModel<State extends object, Payloads extends Record<string, unknown>, Related extends Record<string, RelatedSpec> = Record<never, RelatedSpec>>(model: Model<State, Payloads>, id: string | null | undefined, related?: Related & { readonly [K in ReservedKeys]?: never; }): ModelView<State, Payloads> & RelatedValues<Related>;
115
119
  export {};
116
120
  //# sourceMappingURL=react.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"react.d.mts","names":["EventCallable","Store","Ids","InstanceEventParams","Instances","Model","Child","ModelLike","Union","UnionInstances","UnionModels","UnionRef","AliasesSource","Record","InstancesSource","State","Partial","IdsSource","useResolvedId","useInstance","Selected","useInstanceIds","BoundEvents","Payloads","K","P","useInstanceEvents","useChildIds","Pick","UnionInstance","Models","useUnionInstance","useChildren","ChildrenSpec","childrenOf","RelatedSpec","ReservedKeys","RelatedValues","Related","ModelView","BoundFrom","Events","Payload","MemberState","Member","UnionModelView","useModel"],"sources":["../lib/react.ts"],"mappings":";;;KAsBKY;WAA2B,UAAUX,MAAMY;;KAC3CC,gBAAgB;WACV,YAAYb,MAAMG,UAAUW;IACnCC,QAAQJ;KAOPK;WAAuB,MAAMhB;;;wBASlBiB,cAAc,SAASN,eAAe;wBACtCM,cACd,SAASN,eACT;;;;;wBAuBcO,YAAY,sBAC1B,OAAOL,gBAAgBC,QACvB,gCACCA;wBACaI,YAAY,sBAAsB,UAChD,OAAOL,gBAAgBC,QACvB,+BACA,WAAW,OAAOA,sBAAsBK,UACxC,WAAW,MAAMA,UAAU,MAAMA,uBAChCA;;wBA4BaC,eAAe,OAAOJ;KASjCK,YAAY,iBAAiBT,uCACtB,WAAWU,eAChB,MAAMpB,oBAAoBoB,SAASC;EAAc,eAAe;KAC9D,SAASC,MACT;;wBAKOC,kBACd,sBACA,iBAAiBb,yBACjB,OAAOR,MAAMU,OAAOQ,WAAW,IAAIrB,MAAMoB,YAAYC;;wBAqBvCI,YACd,UAAUC,KAAKtB,yBAAyBU,QAAQY,KAAKtB,mBACrD;;YAgBUuB,cAAc,eAAenB,kBACtC,WAAWoB;EACV,MAAMN;EACN;EACA,OAAOf,eAAeqB,QAAQN;WAE1BM;;;;;wBAMQC,iBAAiB,eAAerB,aAC9C,OAAOF,MAAMsB,SACb,KAAKnB,SAASmB,6BACbD,cAAcC;;;;;;wBAsDDE,YAAY,sBAC1B,UAAU1B,MAAMS,QAChB,sCACCA;wBACaiB,YAAY,sBAAsB,UAChD,UAAU1B,MAAMS,QAChB,qCACA,WAAW,UAAUA,YAAYK,UACjC,WAAW,MAAMA,UAAU,MAAMA,uBAChCA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Callable","Store","Ids","InstanceEventParams","Instances","Model","Child","ModelLike","Union","UnionInstances","UnionModels","UnionRef","AliasesSource","Record","InstancesSource","State","Partial","IdsSource","useResolvedId","useInstance","Selected","useInstanceIds","BoundEvents","Payloads","K","P","useInstanceEvents","useChildIds","Pick","UnionInstance","Models","useUnionInstance","useChildren","ChildrenSpec","childrenOf","RelatedSpec","ReservedKeys","RelatedValues","Related","ModelView","BoundFrom","Events","Payload","MemberState","Member","UnionModelView","useModel"],"sources":["../lib/react.ts"],"mappings":";;;KAsBKY;WAA2B,UAAUX,MAAMY;;KAC3CC,gBAAgB;WACV,YAAYb,MAAMG,UAAUW;IACnCC,QAAQJ;KAOPK;WAAuB,MAAMhB;;;wBASlBiB,cAAc,SAASN,eAAe;wBACtCM,cACd,SAASN,eACT;;;;;wBAuBcO,YAAY,sBAC1B,OAAOL,gBAAgBC,QACvB,gCACCA;wBACaI,YAAY,sBAAsB,UAChD,OAAOL,gBAAgBC,QACvB,+BACA,WAAW,OAAOA,sBAAsBK,UACxC,WAAW,MAAMA,UAAU,MAAMA,uBAChCA;;wBAgCaC,eAAe,OAAOJ;KASjCK,YAAY,iBAAiBT,uCACtB,WAAWU,eAChB,MAAMpB,oBAAoBoB,SAASC;EAAc,eAAe;KAC9D,SAASC,KACVtB,oBAAoBoB,SAASC;EAAc,gBAAgB;oBACzC,KACb,wBACA,UAAUC,MACZ;;wBAKKC,kBACd,sBACA,iBAAiBb,yBACjB,OAAOR,MAAMU,OAAOQ,WAAW,IAAIrB,MAAMoB,YAAYC;;wBAqBvCI,YACd,UAAUC,KAAKtB,yBAAyBU,QAAQY,KAAKtB,mBACrD;;YAgBUuB,cAAc,eAAenB,kBACtC,WAAWoB;EACV,MAAMN;EACN;EACA,OAAOf,eAAeqB,QAAQN;WAE1BM;;;;;wBAMQC,iBAAiB,eAAerB,aAC9C,OAAOF,MAAMsB,SACb,KAAKnB,SAASmB,6BACbD,cAAcC;;;;;;wBAkEDE,YAAY,sBAC1B,UAA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iBAAiBjC,yBACjB,gBAAgBA,eAAesB,eAAetB,cAAcsB,cAE5D,OAAO9B,MAAMU,OAAOQ,WACpB,+BACA,UAAUe,sBAAsB,KAAKF,2BACpCG,UAAUxB,OAAOQ,YAAYc,cAAcC"}
package/dist/react.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { useStoreMap, useUnit } from "effector-react";
2
2
  import { useMemo } from "react";
3
3
  import { createStore } from "effector";
4
- import { n as resolveAlias } from "./model-DYSAS481.mjs";
4
+ import { r as resolveAlias } from "./model-CLRG64G8.mjs";
5
5
  // lib/react.ts
6
6
  const $noAliases = createStore({}, { serialize: "ignore" });
7
7
  const identity = (value) => value;
@@ -22,7 +22,7 @@ function useInstance(model, id, selector = identity, isEqual = Object.is) {
22
22
  selector,
23
23
  isEqual
24
24
  ],
25
- fn: (instances, [key, select]) => ({ value: select(key === null ? void 0 : instances[key]) }),
25
+ fn: (instances, [key, select]) => ({ value: select(key === null || !Object.hasOwn(instances, key) ? void 0 : instances[key]) }),
26
26
  updateFilter: (next, prev) => !isEqual(next.value, prev.value)
27
27
  }).value;
28
28
  }
@@ -71,7 +71,7 @@ const noIds = [];
71
71
  const state = useStoreMap({
72
72
  store: union.$instances,
73
73
  keys: [kind, id],
74
- fn: (instances, [currentKind, currentId]) => ({ value: currentKind === null || currentId === null ? void 0 : instances[currentKind]?.[currentId] }),
74
+ fn: (instances, [currentKind, currentId]) => ({ value: readMember(currentKind === null ? void 0 : instances[currentKind], currentId) }),
75
75
  updateFilter: (next, prev) => next.value !== prev.value
76
76
  }).value;
77
77
  return useMemo(() => kind === null || id === null || state === void 0 ? void 0 : {
@@ -84,7 +84,8 @@ const noIds = [];
84
84
  state
85
85
  ]);
86
86
  }
87
- const sameItems = (next, prev) => next.length === prev.length && next.every((item, index) => item === prev[index]);
87
+ const sameItems = (next, prev) => Array.isArray(next) && Array.isArray(prev) && next.length === prev.length && next.every((item, index) => item === prev[index]);
88
+ const readMember = (instances, id) => instances === void 0 || id === null || !Object.hasOwn(instances, id) ? void 0 : instances[id];
88
89
  function useChildren(relation, parentId, selector, isEqual) {
89
90
  const ids = useChildIds(relation, parentId);
90
91
  return useStoreMap({