@olovyannikov/effector-models 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/README.md +26 -7
- package/dist/index.cjs +53 -72
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +54 -74
- package/dist/index.mjs.map +1 -1
- package/dist/model-BNsi5pxp.mjs +260 -0
- package/dist/model-BNsi5pxp.mjs.map +1 -0
- package/dist/model-Cav66tnw.cjs +275 -0
- package/dist/react.cjs +52 -20
- package/dist/react.d.cts +29 -3
- package/dist/react.d.cts.map +1 -1
- package/dist/react.d.mts +29 -3
- package/dist/react.d.mts.map +1 -1
- package/dist/react.mjs +52 -20
- package/dist/react.mjs.map +1 -1
- package/dist/{relations-Cc9Mv0m7.d.mts → relations-CpExzbHu.d.mts} +53 -5
- package/dist/relations-CpExzbHu.d.mts.map +1 -0
- package/dist/{relations-DXJ6slzh.d.cts → relations-pJXSBtRd.d.cts} +53 -5
- package/dist/relations-pJXSBtRd.d.cts.map +1 -0
- package/package.json +1 -1
- package/dist/model-DYSAS481.mjs +0 -275
- package/dist/model-DYSAS481.mjs.map +0 -1
- package/dist/model-iPgSwajA.cjs +0 -284
- package/dist/relations-Cc9Mv0m7.d.mts.map +0 -1
- package/dist/relations-DXJ6slzh.d.cts.map +0 -1
|
@@ -0,0 +1,275 @@
|
|
|
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
|
+
const toList = (ids) => typeof ids === "string" ? [ids] : ids;
|
|
7
|
+
const toArray = (value) => Array.isArray(value) ? value : [value];
|
|
8
|
+
const withoutAliases = (aliases, isRemoved) => {
|
|
9
|
+
let next = aliases;
|
|
10
|
+
for (const [alias, id] of Object.entries(aliases)) if (isRemoved(alias, id)) {
|
|
11
|
+
if (next === aliases) next = { ...aliases };
|
|
12
|
+
delete next[alias];
|
|
13
|
+
}
|
|
14
|
+
return next;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Состояние модели из словаря экземпляров — для засева `$state` в тестах и при гидрации.
|
|
18
|
+
* Порядок id берётся из порядка ключей.
|
|
19
|
+
*/ function modelState(instances, aliases = {}) {
|
|
20
|
+
return {
|
|
21
|
+
ids: Object.keys(instances),
|
|
22
|
+
instances,
|
|
23
|
+
aliases
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const factsOf = /* @__PURE__ */ new WeakMap();
|
|
27
|
+
function commit(state, next, facts = []) {
|
|
28
|
+
const ids = next.ids ?? state.ids;
|
|
29
|
+
const instances = next.instances ?? state.instances;
|
|
30
|
+
const aliases = next.aliases ?? state.aliases;
|
|
31
|
+
if (ids === state.ids && instances === state.instances && aliases === state.aliases && facts.length === 0) return state;
|
|
32
|
+
const result = {
|
|
33
|
+
ids,
|
|
34
|
+
instances,
|
|
35
|
+
aliases
|
|
36
|
+
};
|
|
37
|
+
if (facts.length > 0) factsOf.set(result, facts);
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
function applyTo(state, action, ids, fn) {
|
|
41
|
+
const { instances, aliases } = state;
|
|
42
|
+
let next = instances;
|
|
43
|
+
const missing = [];
|
|
44
|
+
for (const id of new Set(toList(ids).map((item) => resolveAlias(aliases, item)))) {
|
|
45
|
+
if (!Object.hasOwn(instances, id)) {
|
|
46
|
+
missing.push(id);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const current = instances[id];
|
|
50
|
+
const updated = fn(current);
|
|
51
|
+
if (updated !== current) {
|
|
52
|
+
if (next === instances) next = { ...instances };
|
|
53
|
+
next[id] = updated;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return commit(state, { instances: next }, missing.length > 0 ? [{
|
|
57
|
+
type: "missed",
|
|
58
|
+
payload: {
|
|
59
|
+
action,
|
|
60
|
+
ids: missing
|
|
61
|
+
}
|
|
62
|
+
}] : []);
|
|
63
|
+
}
|
|
64
|
+
function removeFrom(state, ids) {
|
|
65
|
+
const real = [...new Set(ids)].filter((id) => Object.hasOwn(state.instances, id));
|
|
66
|
+
if (real.length === 0) return state;
|
|
67
|
+
const instances = { ...state.instances };
|
|
68
|
+
for (const id of real) delete instances[id];
|
|
69
|
+
const names = Object.keys(state.aliases).filter((alias) => real.includes(state.aliases[alias]));
|
|
70
|
+
return commit(state, {
|
|
71
|
+
ids: state.ids.filter((id) => !real.includes(id)),
|
|
72
|
+
instances,
|
|
73
|
+
aliases: withoutAliases(state.aliases, (alias) => names.includes(alias))
|
|
74
|
+
}, [{
|
|
75
|
+
type: "deleted",
|
|
76
|
+
payload: [...real, ...names]
|
|
77
|
+
}]);
|
|
78
|
+
}
|
|
79
|
+
function model(config) {
|
|
80
|
+
const { name, defaults } = config;
|
|
81
|
+
const reducers = config.events ?? {};
|
|
82
|
+
const $state = (0, effector.createStore)({
|
|
83
|
+
ids: [],
|
|
84
|
+
instances: {},
|
|
85
|
+
aliases: {}
|
|
86
|
+
}, {
|
|
87
|
+
sid: `effector-models:${name}`,
|
|
88
|
+
name: `${name}/$state`
|
|
89
|
+
});
|
|
90
|
+
const $instances = $state.map((state) => state.instances);
|
|
91
|
+
const $aliases = $state.map((state) => state.aliases);
|
|
92
|
+
const $ids = $state.map((state) => state.ids);
|
|
93
|
+
const factOf = (type) => $state.updates.filterMap((state) => factsOf.get(state)?.find((fact) => fact.type === type)?.payload);
|
|
94
|
+
const deleted = factOf("deleted");
|
|
95
|
+
const renamed = factOf("renamed");
|
|
96
|
+
const missed = factOf("missed");
|
|
97
|
+
const create = (0, effector.createEvent)({ name: `${name}/create` });
|
|
98
|
+
const reduceCreate = (state, params) => {
|
|
99
|
+
const items = toArray(params);
|
|
100
|
+
if (items.length === 0) return state;
|
|
101
|
+
const instances = { ...state.instances };
|
|
102
|
+
const added = [];
|
|
103
|
+
for (const { id, data } of items) {
|
|
104
|
+
if (!Object.hasOwn(instances, id)) added.push(id);
|
|
105
|
+
instances[id] = {
|
|
106
|
+
...defaults,
|
|
107
|
+
...data
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
return commit(state, {
|
|
111
|
+
ids: added.length > 0 ? [...state.ids, ...added] : state.ids,
|
|
112
|
+
instances,
|
|
113
|
+
aliases: withoutAliases(state.aliases, (alias) => items.some((item) => item.id === alias))
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
$state.on(create, reduceCreate);
|
|
117
|
+
const upsert = (0, effector.createEvent)({ name: `${name}/upsert` });
|
|
118
|
+
const reduceUpsert = (state, params) => {
|
|
119
|
+
const items = toArray(params);
|
|
120
|
+
if (items.length === 0) return state;
|
|
121
|
+
const instances = { ...state.instances };
|
|
122
|
+
const added = [];
|
|
123
|
+
for (const { id: given, data } of items) {
|
|
124
|
+
const id = resolveAlias(state.aliases, given);
|
|
125
|
+
const exists = Object.hasOwn(instances, id);
|
|
126
|
+
if (!exists) added.push(id);
|
|
127
|
+
instances[id] = {
|
|
128
|
+
...exists ? instances[id] : defaults,
|
|
129
|
+
...data
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
return commit(state, {
|
|
133
|
+
ids: added.length > 0 ? [...state.ids, ...added] : state.ids,
|
|
134
|
+
instances
|
|
135
|
+
});
|
|
136
|
+
};
|
|
137
|
+
$state.on(upsert, reduceUpsert);
|
|
138
|
+
const update = (0, effector.createEvent)({ name: `${name}/update` });
|
|
139
|
+
$state.on(update, (state, { id, data }) => applyTo(state, "update", id, (instance) => typeof data === "function" ? data(instance) : {
|
|
140
|
+
...instance,
|
|
141
|
+
...data
|
|
142
|
+
}));
|
|
143
|
+
const remove = (0, effector.createEvent)({ name: `${name}/delete` });
|
|
144
|
+
const reduceDelete = (state, ids) => removeFrom(state, toList(ids).map((id) => resolveAlias(state.aliases, id)));
|
|
145
|
+
$state.on(remove, reduceDelete);
|
|
146
|
+
const rename = (0, effector.createEvent)({ name: `${name}/rename` });
|
|
147
|
+
$state.on(rename, (state, params) => {
|
|
148
|
+
const from = resolveAlias(state.aliases, params.from);
|
|
149
|
+
const { to } = params;
|
|
150
|
+
if (!Object.hasOwn(state.instances, from)) return commit(state, {}, [{
|
|
151
|
+
type: "missed",
|
|
152
|
+
payload: {
|
|
153
|
+
action: "rename",
|
|
154
|
+
ids: [from]
|
|
155
|
+
}
|
|
156
|
+
}]);
|
|
157
|
+
if (from === to) return state;
|
|
158
|
+
const instances = {
|
|
159
|
+
...state.instances,
|
|
160
|
+
[to]: state.instances[from]
|
|
161
|
+
};
|
|
162
|
+
delete instances[from];
|
|
163
|
+
const ids = state.ids.filter((id) => id !== to).map((id) => id === from ? to : id);
|
|
164
|
+
let aliases = withoutAliases(state.aliases, (alias) => alias === to);
|
|
165
|
+
for (const [alias, id] of Object.entries(aliases)) if (id === from) {
|
|
166
|
+
if (aliases === state.aliases) aliases = { ...state.aliases };
|
|
167
|
+
aliases[alias] = to;
|
|
168
|
+
}
|
|
169
|
+
return commit(state, {
|
|
170
|
+
ids,
|
|
171
|
+
instances,
|
|
172
|
+
aliases
|
|
173
|
+
}, [{
|
|
174
|
+
type: "renamed",
|
|
175
|
+
payload: {
|
|
176
|
+
from,
|
|
177
|
+
to
|
|
178
|
+
}
|
|
179
|
+
}]);
|
|
180
|
+
});
|
|
181
|
+
const clear = (0, effector.createEvent)({ name: `${name}/clear` });
|
|
182
|
+
$state.on(clear, (state) => {
|
|
183
|
+
const gone = [...state.ids, ...Object.keys(state.aliases)];
|
|
184
|
+
return gone.length === 0 ? state : commit(state, {
|
|
185
|
+
ids: [],
|
|
186
|
+
instances: {},
|
|
187
|
+
aliases: {}
|
|
188
|
+
}, [{
|
|
189
|
+
type: "deleted",
|
|
190
|
+
payload: gone
|
|
191
|
+
}]);
|
|
192
|
+
});
|
|
193
|
+
const alias = (0, effector.createEvent)({ name: `${name}/alias` });
|
|
194
|
+
$state.on(alias, (state, params) => {
|
|
195
|
+
let aliases = state.aliases;
|
|
196
|
+
for (const { alias: given, id } of toArray(params)) {
|
|
197
|
+
const target = resolveAlias(aliases, id);
|
|
198
|
+
if (!Object.hasOwn(state.instances, target) || Object.hasOwn(state.instances, given) || Object.hasOwn(aliases, given) && aliases[given] === target) continue;
|
|
199
|
+
if (aliases === state.aliases) aliases = { ...state.aliases };
|
|
200
|
+
aliases[given] = target;
|
|
201
|
+
}
|
|
202
|
+
return commit(state, { aliases });
|
|
203
|
+
});
|
|
204
|
+
const unalias = (0, effector.createEvent)({ name: `${name}/unalias` });
|
|
205
|
+
$state.on(unalias, (state, ids) => {
|
|
206
|
+
const removed = toList(ids);
|
|
207
|
+
return commit(state, { aliases: withoutAliases(state.aliases, (item) => removed.includes(item)) });
|
|
208
|
+
});
|
|
209
|
+
const link = (clock, target) => {
|
|
210
|
+
$state.on(clock, (state, payload) => {
|
|
211
|
+
switch (target.to) {
|
|
212
|
+
case "create":
|
|
213
|
+
case "upsert": {
|
|
214
|
+
const params = target.fn(payload);
|
|
215
|
+
if (params === void 0) return state;
|
|
216
|
+
return target.to === "create" ? reduceCreate(state, params) : reduceUpsert(state, params);
|
|
217
|
+
}
|
|
218
|
+
case "delete": {
|
|
219
|
+
const ids = target.fn(payload);
|
|
220
|
+
return ids === void 0 ? state : reduceDelete(state, ids);
|
|
221
|
+
}
|
|
222
|
+
case "deleteWhere": {
|
|
223
|
+
const isDeleted = target.fn(payload);
|
|
224
|
+
return removeFrom(state, state.ids.filter((id) => isDeleted(state.instances[id], id)));
|
|
225
|
+
}
|
|
226
|
+
case "patch": return commit(state, { instances: target.fn(payload)(state.instances) });
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
};
|
|
230
|
+
const events = {};
|
|
231
|
+
for (const [action, reducer] of Object.entries(reducers)) {
|
|
232
|
+
const event = (0, effector.createEvent)({ name: `${name}/${action}` });
|
|
233
|
+
$state.on(event, (state, { id, payload }) => applyTo(state, action, id, (instance) => reducer(instance, payload)));
|
|
234
|
+
events[action] = event;
|
|
235
|
+
}
|
|
236
|
+
return {
|
|
237
|
+
name,
|
|
238
|
+
defaults,
|
|
239
|
+
$state,
|
|
240
|
+
$instances,
|
|
241
|
+
$ids,
|
|
242
|
+
$aliases,
|
|
243
|
+
alias,
|
|
244
|
+
unalias,
|
|
245
|
+
create,
|
|
246
|
+
upsert,
|
|
247
|
+
update,
|
|
248
|
+
delete: remove,
|
|
249
|
+
deleted,
|
|
250
|
+
rename,
|
|
251
|
+
renamed,
|
|
252
|
+
clear,
|
|
253
|
+
events,
|
|
254
|
+
missed,
|
|
255
|
+
"~link": link
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
Object.defineProperty(exports, "model", {
|
|
259
|
+
enumerable: true,
|
|
260
|
+
get: function() {
|
|
261
|
+
return model;
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
Object.defineProperty(exports, "modelState", {
|
|
265
|
+
enumerable: true,
|
|
266
|
+
get: function() {
|
|
267
|
+
return modelState;
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
Object.defineProperty(exports, "resolveAlias", {
|
|
271
|
+
enumerable: true,
|
|
272
|
+
get: function() {
|
|
273
|
+
return resolveAlias;
|
|
274
|
+
}
|
|
275
|
+
});
|
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-
|
|
5
|
+
const require_model = require("./model-Cav66tnw.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
|
|
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)({
|
|
@@ -146,22 +147,53 @@ function useRelated(spec, parentId) {
|
|
|
146
147
|
}).value;
|
|
147
148
|
}
|
|
148
149
|
const noRelated = {};
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
150
|
+
const separator = "\0";
|
|
151
|
+
function useUnionModel(union, ref) {
|
|
152
|
+
const instance = useUnionInstance(union, ref);
|
|
153
|
+
const shape = (0, react.useMemo)(() => {
|
|
154
|
+
const units = {};
|
|
155
|
+
for (const [kind, member] of Object.entries(union.models)) {
|
|
156
|
+
units[`update${separator}${kind}`] = member.update;
|
|
157
|
+
units[`delete${separator}${kind}`] = member.delete;
|
|
158
|
+
const events = member.events ?? {};
|
|
159
|
+
for (const [action, event] of Object.entries(events)) units[`event${separator}${kind}${separator}${action}`] = event;
|
|
160
|
+
}
|
|
161
|
+
return units;
|
|
162
|
+
}, [union]);
|
|
163
|
+
const bound = (0, effector_react.useUnit)(shape);
|
|
164
|
+
const kind = instance?.kind;
|
|
165
|
+
const id = instance?.id;
|
|
166
|
+
const actions = (0, react.useMemo)(() => {
|
|
167
|
+
if (kind === void 0 || id === void 0) return;
|
|
168
|
+
const events = {};
|
|
169
|
+
const prefix = `event${separator}${kind}${separator}`;
|
|
170
|
+
for (const [key, fire] of Object.entries(bound)) if (key.startsWith(prefix)) events[key.slice(prefix.length)] = (payload) => fire({
|
|
171
|
+
id,
|
|
172
|
+
payload
|
|
173
|
+
});
|
|
174
|
+
return {
|
|
175
|
+
events,
|
|
176
|
+
update: (data) => bound[`update${separator}${kind}`]({
|
|
177
|
+
id,
|
|
178
|
+
data
|
|
179
|
+
}),
|
|
180
|
+
remove: () => bound[`delete${separator}${kind}`](id)
|
|
181
|
+
};
|
|
182
|
+
}, [
|
|
183
|
+
bound,
|
|
184
|
+
kind,
|
|
185
|
+
id
|
|
186
|
+
]);
|
|
187
|
+
return (0, react.useMemo)(() => instance === void 0 || actions === void 0 ? void 0 : {
|
|
188
|
+
...instance,
|
|
189
|
+
...actions
|
|
190
|
+
}, [instance, actions]);
|
|
191
|
+
}
|
|
192
|
+
function useModel(target, idOrRef, related) {
|
|
193
|
+
if ("~kind" in target) return useUnionModel(target, idOrRef);
|
|
194
|
+
return useSingleModel(target, idOrRef, related);
|
|
195
|
+
}
|
|
196
|
+
function useSingleModel(model, id, related) {
|
|
165
197
|
const realId = useResolvedId(model, id ?? null);
|
|
166
198
|
const state = useInstance(model, realId);
|
|
167
199
|
const bound = (0, effector_react.useUnit)(model.events);
|
package/dist/react.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Store } from "effector";
|
|
2
|
-
import { _ as Instances, a as Union, c as UnionModels, g as InstanceEventParams, h as Ids, l as UnionRef, s as UnionInstances, t as Child, y as Model } from "./relations-
|
|
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-pJXSBtRd.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] : [
|
|
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,6 +75,30 @@ 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
|
}
|
|
78
|
+
type BoundFrom<Events> = { readonly [K in keyof Events]: Events[K] extends EventCallable<infer Params> ? Params extends {
|
|
79
|
+
payload: infer Payload;
|
|
80
|
+
} ? (payload: Payload) => void : Params extends {
|
|
81
|
+
payload?: infer Payload;
|
|
82
|
+
} ? unknown extends Payload ? (payload?: undefined) => void : (payload?: Payload) => void : (payload?: undefined) => void : never; };
|
|
83
|
+
type MemberState<Member> = Member extends ModelLike<infer State> ? State : never;
|
|
84
|
+
/** Экземпляр объединения со всем, что нужно компоненту; по `kind` сужаются `state` и `events`. */
|
|
85
|
+
export type UnionModelView<Models extends UnionModels> = { [K in keyof Models & string]: {
|
|
86
|
+
readonly kind: K;
|
|
87
|
+
/** Настоящий id экземпляра. */
|
|
88
|
+
readonly id: string;
|
|
89
|
+
readonly state: MemberState<Models[K]>;
|
|
90
|
+
/** События модели этого вида, привязанные к id. */
|
|
91
|
+
readonly events: Models[K] extends {
|
|
92
|
+
readonly events: infer Events;
|
|
93
|
+
} ? BoundFrom<Events> : Record<never, never>;
|
|
94
|
+
readonly update: (data: Partial<MemberState<Models[K]>> | ((state: MemberState<Models[K]>) => MemberState<Models[K]>)) => void;
|
|
95
|
+
readonly remove: () => void;
|
|
96
|
+
}; }[keyof Models & string];
|
|
97
|
+
/**
|
|
98
|
+
* Экземпляр объединения по ссылке `{ kind, id }`: состояние, события своей модели, запись и удаление.
|
|
99
|
+
* `undefined`, если экземпляра нет.
|
|
100
|
+
*/
|
|
101
|
+
export declare function useModel<Models extends UnionModels>(union: Union<Models>, ref: UnionRef<Models> | null | undefined): UnionModelView<Models> | undefined;
|
|
76
102
|
/**
|
|
77
103
|
* Всё про один экземпляр одним хуком: состояние, события, запись и — по желанию — его дети.
|
|
78
104
|
*
|
package/dist/react.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react.d.cts","names":[],"sources":["../lib/react.ts"],"mappings":";;;
|
|
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;;wBAgCa,eAAe,OAAO;KASjC,YAAY,iBAAiB,uCACtB,WAAW,eAChB,MAAM,oBAAoB,SAAS;EAAc,eAAe;KAC9D,SAAS,KACV,oBAAoB,SAAS;EAAc,gBAAgB;oBACzC,KACb,wBACA,UAAU,MACZ;;wBAKK,kBACd,sBACA,iBAAiB,yBACjB,OAAO,MAAM,OAAO,WAAW,IAAI,MAAM,YAAY;;wBAqBvC,YACd,UAAU,KAAK,yBAAyB,QAAQ,KAAK,mBACrD;;YAgBU,cAAc,eAAe,kBACtC,WAAW;EACV,MAAM;EACN;EACA,OAAO,eAAe,QAAQ;WAE1B;;;;;wBAMQ,iBAAiB,eAAe,aAC9C,OAAO,MAAM,SACb,KAAK,SAAS,6BACb,cAAc;;;;;;wBAkED,YAAY,sBAC1B,UAAU,MAAM,QAChB,sCACC;wBACa,YAAY,sBAAsB,UAChD,UAAU,MAAM,QAChB,qCACA,WAAW,UAAU,YAAY,UACjC,WAAW,MAAM,UAAU,MAAM,uBAChC;;iBAuCc,aAAa,sBAAsB;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
|
-
import { Store } from "effector";
|
|
2
|
-
import { _ as Instances, a as Union, c as UnionModels, g as InstanceEventParams, h as Ids, l as UnionRef, s as UnionInstances, t as Child, y as Model } from "./relations-
|
|
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-CpExzbHu.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] : [
|
|
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,6 +75,30 @@ 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
|
}
|
|
78
|
+
type BoundFrom<Events1> = { readonly [K in keyof Events1]: Events1[K] extends EventCallable<infer Params> ? Params extends {
|
|
79
|
+
payload: infer Payload;
|
|
80
|
+
} ? (payload: Payload) => void : Params extends {
|
|
81
|
+
payload?: infer Payload;
|
|
82
|
+
} ? unknown extends Payload ? (payload?: undefined) => void : (payload?: Payload) => void : (payload?: undefined) => void : never; };
|
|
83
|
+
type MemberState<Member> = Member extends ModelLike<infer State> ? State : never;
|
|
84
|
+
/** Экземпляр объединения со всем, что нужно компоненту; по `kind` сужаются `state` и `events`. */
|
|
85
|
+
export type UnionModelView<Models extends UnionModels> = { [K in keyof Models & string]: {
|
|
86
|
+
readonly kind: K;
|
|
87
|
+
/** Настоящий id экземпляра. */
|
|
88
|
+
readonly id: string;
|
|
89
|
+
readonly state: MemberState<Models[K]>;
|
|
90
|
+
/** События модели этого вида, привязанные к id. */
|
|
91
|
+
readonly events: Models[K] extends {
|
|
92
|
+
readonly events: infer Events;
|
|
93
|
+
} ? BoundFrom<Events> : Record<never, never>;
|
|
94
|
+
readonly update: (data: Partial<MemberState<Models[K]>> | ((state: MemberState<Models[K]>) => MemberState<Models[K]>)) => void;
|
|
95
|
+
readonly remove: () => void;
|
|
96
|
+
}; }[keyof Models & string];
|
|
97
|
+
/**
|
|
98
|
+
* Экземпляр объединения по ссылке `{ kind, id }`: состояние, события своей модели, запись и удаление.
|
|
99
|
+
* `undefined`, если экземпляра нет.
|
|
100
|
+
*/
|
|
101
|
+
export declare function useModel<Models extends UnionModels>(union: Union<Models>, ref: UnionRef<Models> | null | undefined): UnionModelView<Models> | undefined;
|
|
76
102
|
/**
|
|
77
103
|
* Всё про один экземпляр одним хуком: состояние, события, запись и — по желанию — его дети.
|
|
78
104
|
*
|
package/dist/react.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react.d.mts","names":["Store","Ids","InstanceEventParams","Instances","Model","Child","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","useModel"],"sources":["../lib/react.ts"],"mappings":";;;
|
|
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":"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"}
|
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 {
|
|
4
|
+
import { r as resolveAlias } from "./model-BNsi5pxp.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
|
|
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({
|
|
@@ -145,22 +146,53 @@ function useRelated(spec, parentId) {
|
|
|
145
146
|
}).value;
|
|
146
147
|
}
|
|
147
148
|
const noRelated = {};
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
149
|
+
const separator = "\0";
|
|
150
|
+
function useUnionModel(union, ref) {
|
|
151
|
+
const instance = useUnionInstance(union, ref);
|
|
152
|
+
const shape = useMemo(() => {
|
|
153
|
+
const units = {};
|
|
154
|
+
for (const [kind, member] of Object.entries(union.models)) {
|
|
155
|
+
units[`update${separator}${kind}`] = member.update;
|
|
156
|
+
units[`delete${separator}${kind}`] = member.delete;
|
|
157
|
+
const events = member.events ?? {};
|
|
158
|
+
for (const [action, event] of Object.entries(events)) units[`event${separator}${kind}${separator}${action}`] = event;
|
|
159
|
+
}
|
|
160
|
+
return units;
|
|
161
|
+
}, [union]);
|
|
162
|
+
const bound = useUnit(shape);
|
|
163
|
+
const kind = instance?.kind;
|
|
164
|
+
const id = instance?.id;
|
|
165
|
+
const actions = useMemo(() => {
|
|
166
|
+
if (kind === void 0 || id === void 0) return;
|
|
167
|
+
const events = {};
|
|
168
|
+
const prefix = `event${separator}${kind}${separator}`;
|
|
169
|
+
for (const [key, fire] of Object.entries(bound)) if (key.startsWith(prefix)) events[key.slice(prefix.length)] = (payload) => fire({
|
|
170
|
+
id,
|
|
171
|
+
payload
|
|
172
|
+
});
|
|
173
|
+
return {
|
|
174
|
+
events,
|
|
175
|
+
update: (data) => bound[`update${separator}${kind}`]({
|
|
176
|
+
id,
|
|
177
|
+
data
|
|
178
|
+
}),
|
|
179
|
+
remove: () => bound[`delete${separator}${kind}`](id)
|
|
180
|
+
};
|
|
181
|
+
}, [
|
|
182
|
+
bound,
|
|
183
|
+
kind,
|
|
184
|
+
id
|
|
185
|
+
]);
|
|
186
|
+
return useMemo(() => instance === void 0 || actions === void 0 ? void 0 : {
|
|
187
|
+
...instance,
|
|
188
|
+
...actions
|
|
189
|
+
}, [instance, actions]);
|
|
190
|
+
}
|
|
191
|
+
function useModel(target, idOrRef, related) {
|
|
192
|
+
if ("~kind" in target) return useUnionModel(target, idOrRef);
|
|
193
|
+
return useSingleModel(target, idOrRef, related);
|
|
194
|
+
}
|
|
195
|
+
function useSingleModel(model, id, related) {
|
|
164
196
|
const realId = useResolvedId(model, id ?? null);
|
|
165
197
|
const state = useInstance(model, realId);
|
|
166
198
|
const bound = useUnit(model.events);
|