@olovyannikov/effector-models 1.0.0-alpha.0 → 1.0.0-alpha.2
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 +44 -0
- package/LICENSE +22 -0
- package/README.md +160 -32
- package/dist/aliases-9ILz72OF.mjs +116 -0
- package/dist/aliases-9ILz72OF.mjs.map +1 -0
- package/dist/aliases-BuDSaLvV.cjs +125 -0
- package/dist/index.cjs +186 -9
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +181 -9
- package/dist/index.mjs.map +1 -1
- package/dist/react.cjs +70 -5
- package/dist/react.d.cts +33 -13
- package/dist/react.d.cts.map +1 -1
- package/dist/react.d.mts +33 -13
- package/dist/react.d.mts.map +1 -1
- package/dist/react.mjs +65 -4
- package/dist/react.mjs.map +1 -1
- package/dist/relations-CwzpTh9E.d.mts +154 -0
- package/dist/relations-CwzpTh9E.d.mts.map +1 -0
- package/dist/relations-iG_ubcG7.d.cts +154 -0
- package/dist/relations-iG_ubcG7.d.cts.map +1 -0
- package/package.json +35 -16
- package/dist/model-BQlT1GKR.d.mts +0 -65
- package/dist/model-BQlT1GKR.d.mts.map +0 -1
- package/dist/model-DuitmKFi.d.cts +0 -65
- package/dist/model-DuitmKFi.d.cts.map +0 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.0.0-alpha.2
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **Aliases**: `aliases(model)` — one instance reachable by several ids:
|
|
8
|
+
`$aliases`, `add`, `remove`, and `resolved(event)` to write through an
|
|
9
|
+
alias. Aliases follow `delete`, `clear` and `rename` of the instances.
|
|
10
|
+
`resolveAlias(aliases, id)` is exported for use in `sample`.
|
|
11
|
+
- **React**: `useResolvedId(aliases, id)` — the real id for an id that may
|
|
12
|
+
be an alias.
|
|
13
|
+
|
|
14
|
+
## 1.0.0-alpha.1
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- **Relations** between models. A reference is an ordinary field with an id;
|
|
19
|
+
a relation keeps such fields consistent.
|
|
20
|
+
- `child({ parent, model, key })` — children are deleted together with the
|
|
21
|
+
parent and follow its `rename`; `$idsByParent` index.
|
|
22
|
+
- Trees: a model can be a `child` of itself with a nullable key. Deleting a
|
|
23
|
+
node deletes its whole branch.
|
|
24
|
+
- `ref({ from, field, to })` — a field with one id or a list. Deleted
|
|
25
|
+
targets disappear from references, renamed ones are renamed.
|
|
26
|
+
- `union({ ... })` — several models as one collection addressed by
|
|
27
|
+
`{ kind, id }`, with `create`, `upsert` and `delete` routed to the model
|
|
28
|
+
of the kind. `ref` accepts a union as a target.
|
|
29
|
+
- **React hooks**: `useChildIds`, `useChildren` (the children of one parent
|
|
30
|
+
or an aggregate over them) and `useUnionInstance`.
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- `exports` provide separate type declarations for ESM and CJS consumers.
|
|
35
|
+
- `engines.node` is declared: `>=18`.
|
|
36
|
+
- Peer ranges are bounded: `effector >=23.4.4 <24`,
|
|
37
|
+
`effector-react >=23.3.0 <24`.
|
|
38
|
+
|
|
39
|
+
## 1.0.0-alpha.0
|
|
40
|
+
|
|
41
|
+
Initial release: `model` with immutable instances and synchronous reducers,
|
|
42
|
+
`create` / `upsert` / `update` / `delete` / `rename` / `clear`, the `missed`
|
|
43
|
+
event, and the React hooks `useInstance`, `useInstanceIds`,
|
|
44
|
+
`useInstanceEvents`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 movpushmov
|
|
4
|
+
Copyright (c) 2026 Ilya Olovyannikov
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -4,19 +4,21 @@ Keyed models for [Effector](https://effector.dev): a collection of instances add
|
|
|
4
4
|
|
|
5
5
|
Fork of [`@effector-kit/models`](https://github.com/movpushmov/effector-kit) by movpushmov, redesigned around one goal: **behave like ordinary Effector units**.
|
|
6
6
|
|
|
7
|
-
|
|
|
8
|
-
|
|
9
|
-
| Write through instance event
|
|
10
|
-
| Instance data
|
|
11
|
-
| `map` / `combine` / `useStoreMap` over `$instances` | miss writes
|
|
12
|
-
| Runtime
|
|
13
|
-
| `fork({ values })` / `serialize`
|
|
14
|
-
| Contract defaults on `create`
|
|
15
|
-
| `create` over existing id
|
|
16
|
-
| Write to missing instance
|
|
17
|
-
| React `useModel(lens)`
|
|
18
|
-
|
|
19
|
-
|
|
7
|
+
| | `@effector-kit/models` 0.4 | this package |
|
|
8
|
+
| --------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------- |
|
|
9
|
+
| Write through instance event | async effect, lands after `sample` of the same tick | synchronous, visible in the same tick |
|
|
10
|
+
| Instance data | mutated in place, `$instances` keeps its reference | immutable; untouched instances keep their reference |
|
|
11
|
+
| `map` / `combine` / `useStoreMap` over `$instances` | miss writes | just work |
|
|
12
|
+
| Runtime | global context, writes into `scope.reg` | public Effector API only |
|
|
13
|
+
| `fork({ values })` / `serialize` | `$instances` read-only in types, instance stores `serialize: 'ignore'` | one `$instances` store with sid `effector-models:<name>` |
|
|
14
|
+
| Contract defaults on `create` | not applied | applied |
|
|
15
|
+
| `create` over existing id | silently replaces | `create` replaces, `upsert` merges |
|
|
16
|
+
| Write to missing instance | silent `Promise.reject` | ignored and reported via `missed` |
|
|
17
|
+
| React `useModel(lens)` | re-renders on any instance change, new object every render | subscribed to its own instance, stable reference, selector |
|
|
18
|
+
|
|
19
|
+
`child`, `ref` and `union` are available as [relations](#relations) between models: plain data plus integrity rules. Aliases are an opt-in helper, [`aliases`](#aliases--one-instance-several-ids). Not carried over: `fn` with arbitrary graphs inside an instance — side effects stay outside, as usual in Effector.
|
|
20
|
+
|
|
21
|
+
Documentation, a step-by-step tutorial and live examples: <https://olovyannikov.github.io/effector-kit/guide/keyed-models> (also in Russian).
|
|
20
22
|
|
|
21
23
|
## Install
|
|
22
24
|
|
|
@@ -43,8 +45,12 @@ export const DocumentModel = model({
|
|
|
43
45
|
name: 'document', // unique: sid of $instances is `effector-models:document`
|
|
44
46
|
defaults,
|
|
45
47
|
events: {
|
|
46
|
-
patched: (doc, patch: Patch) => ({
|
|
47
|
-
|
|
48
|
+
patched: (doc, patch: Patch) => ({
|
|
49
|
+
...doc,
|
|
50
|
+
pending: merge(doc.pending, patch),
|
|
51
|
+
failed: false,
|
|
52
|
+
}),
|
|
53
|
+
sent: doc => ({ ...doc, pending: null }),
|
|
48
54
|
},
|
|
49
55
|
});
|
|
50
56
|
```
|
|
@@ -53,23 +59,23 @@ A reducer returning the same object means "nothing changed": no store update, no
|
|
|
53
59
|
|
|
54
60
|
## API
|
|
55
61
|
|
|
56
|
-
| Unit
|
|
57
|
-
|
|
58
|
-
| `$instances`
|
|
59
|
-
| `$ids`
|
|
60
|
-
| `create`
|
|
61
|
-
| `upsert`
|
|
62
|
-
| `update`
|
|
63
|
-
| `delete`
|
|
64
|
-
| `rename`
|
|
65
|
-
| `clear`
|
|
66
|
-
| `events.<name>` | `{ id \| id[], payload }`
|
|
67
|
-
| `missed`
|
|
62
|
+
| Unit | Payload | Behaviour |
|
|
63
|
+
| --------------- | -------------------------------------------------- | ---------------------------------------------------------- |
|
|
64
|
+
| `$instances` | — | `Record<id, State>`, writable, has sid |
|
|
65
|
+
| `$ids` | — | `string[]` |
|
|
66
|
+
| `create` | `{ id, data? }` or array | creates with defaults; replaces existing id |
|
|
67
|
+
| `upsert` | `{ id, data? }` or array | merges into existing or creates with defaults |
|
|
68
|
+
| `update` | `{ id, data: Partial<State> \| (state) => State }` | existing only |
|
|
69
|
+
| `delete` | `id` or `id[]` | |
|
|
70
|
+
| `rename` | `{ from, to }` | moves instance in one step (e.g. draft → created document) |
|
|
71
|
+
| `clear` | — | |
|
|
72
|
+
| `events.<name>` | `{ id \| id[], payload }` | applies reducer synchronously |
|
|
73
|
+
| `missed` | `{ action, ids }` | writes addressed to instances that do not exist |
|
|
68
74
|
|
|
69
75
|
```ts
|
|
70
76
|
sample({
|
|
71
77
|
clock: saved,
|
|
72
|
-
fn:
|
|
78
|
+
fn: patch => ({ id: documentId, payload: patch }),
|
|
73
79
|
target: DocumentModel.events.patched,
|
|
74
80
|
});
|
|
75
81
|
|
|
@@ -77,30 +83,152 @@ sample({
|
|
|
77
83
|
sample({
|
|
78
84
|
clock: saved,
|
|
79
85
|
source: DocumentModel.$instances,
|
|
80
|
-
fn:
|
|
86
|
+
fn: instances => instances[documentId]?.pending,
|
|
81
87
|
target: $pending,
|
|
82
88
|
});
|
|
83
89
|
```
|
|
84
90
|
|
|
85
91
|
Tests seed instances like any store: `fork({ values: [[DocumentModel.$instances, { a: { ... } }]] })`.
|
|
86
92
|
|
|
93
|
+
## Relations
|
|
94
|
+
|
|
95
|
+
Relations connect models without changing what an instance is: a reference is an ordinary field with an id, and a relation only keeps those fields consistent.
|
|
96
|
+
|
|
97
|
+
### `child` — owned instances
|
|
98
|
+
|
|
99
|
+
Children store the id of their parent in a field and are deleted together with it.
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { child, model } from '@olovyannikov/effector-models';
|
|
103
|
+
|
|
104
|
+
const Todos = model({ name: 'todos', defaults: { title: '' } });
|
|
105
|
+
const Subtasks = model({
|
|
106
|
+
name: 'subtasks',
|
|
107
|
+
defaults: { todoId: '', title: '', done: false },
|
|
108
|
+
events: {
|
|
109
|
+
toggled: subtask => ({ ...subtask, done: !subtask.done }),
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
const subtasks = child({ parent: Todos, model: Subtasks, key: 'todoId' });
|
|
114
|
+
|
|
115
|
+
subtasks.$idsByParent; // Store<Record<todoId, subtaskId[]>>, in creation order
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
- `parent.delete` / `parent.clear` delete the children
|
|
119
|
+
- `parent.rename` moves the children to the new parent id
|
|
120
|
+
- children are created like any other instance: `Subtasks.create({ id, data: { todoId } })`
|
|
121
|
+
|
|
122
|
+
A model can be a child of itself — that is a tree of any depth. The key is
|
|
123
|
+
`null` for a root, and deleting a node deletes its whole branch:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const Nodes = model({
|
|
127
|
+
name: 'nodes',
|
|
128
|
+
defaults: { parentId: null as string | null, title: '' },
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const nodes = child({ parent: Nodes, model: Nodes, key: 'parentId' });
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### `ref` — tracked instances
|
|
135
|
+
|
|
136
|
+
A field that points to instances living in another model: one id (`string | null`) or a list (`string[]`).
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import { ref } from '@olovyannikov/effector-models';
|
|
140
|
+
|
|
141
|
+
const Dashboards = model({
|
|
142
|
+
name: 'dashboards',
|
|
143
|
+
defaults: { selected: [] as string[], pinned: null as string | null },
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
ref({ from: Dashboards, field: 'selected', to: Counters });
|
|
147
|
+
ref({ from: Dashboards, field: 'pinned', to: Counters });
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
- a deleted instance disappears from lists, a single reference becomes `null`
|
|
151
|
+
- a renamed instance is renamed in references
|
|
152
|
+
- instances that did not reference it keep their object reference
|
|
153
|
+
|
|
154
|
+
### `union` — several models as one collection
|
|
155
|
+
|
|
156
|
+
An instance is addressed by `{ kind, id }`.
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
import { ref, union } from '@olovyannikov/effector-models';
|
|
160
|
+
|
|
161
|
+
const passengers = union({ adult: Adults, kid: Kids });
|
|
162
|
+
|
|
163
|
+
passengers.$instances; // Store<{ adult: Record<id, Adult>; kid: Record<id, Kid> }>
|
|
164
|
+
passengers.create({ kind: 'adult', id: 'p2', data: { name: 'Ann' } }); // routed to Adults.create
|
|
165
|
+
passengers.delete({ kind: 'kid', id: 'p1' }); // routed to Kids.delete
|
|
166
|
+
|
|
167
|
+
type Passenger = { kind: 'adult'; id: string } | { kind: 'kid'; id: string };
|
|
168
|
+
|
|
169
|
+
const Bookings = model({
|
|
170
|
+
name: 'bookings',
|
|
171
|
+
defaults: { passengers: [] as Passenger[] },
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
// References to a union are kept consistent the same way.
|
|
175
|
+
ref({ from: Bookings, field: 'passengers', to: passengers });
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### `aliases` — one instance, several ids
|
|
179
|
+
|
|
180
|
+
For the case when an instance must stay reachable by another id — a route id next to the server id. The instance is still stored once; aliases live in a separate store that follows the life of instances.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
import { aliases } from '@olovyannikov/effector-models';
|
|
184
|
+
|
|
185
|
+
const chatAliases = aliases(Chats);
|
|
186
|
+
|
|
187
|
+
chatAliases.add({ alias: 'route-id', id: 'server-id' });
|
|
188
|
+
chatAliases.$aliases; // Store<Record<alias, id>>, has a sid
|
|
189
|
+
|
|
190
|
+
// An event that accepts aliases and writes to the real instance.
|
|
191
|
+
const renamed = chatAliases.resolved(Chats.events.renamed);
|
|
192
|
+
|
|
193
|
+
renamed({ id: 'route-id', payload: 'New title' });
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
- deleting or clearing instances removes their aliases, `rename` moves them
|
|
197
|
+
- an instance created with the id of an alias displaces the alias: a real id always wins
|
|
198
|
+
- an alias to a missing instance is not created
|
|
199
|
+
|
|
200
|
+
Use `rename` when an instance simply moves to a new id, and `aliases` when both ids must keep working.
|
|
201
|
+
|
|
87
202
|
## React
|
|
88
203
|
|
|
89
204
|
```tsx
|
|
90
|
-
import {
|
|
205
|
+
import {
|
|
206
|
+
useInstance,
|
|
207
|
+
useInstanceEvents,
|
|
208
|
+
useInstanceIds,
|
|
209
|
+
} from '@olovyannikov/effector-models/react';
|
|
91
210
|
|
|
92
211
|
const Slide = ({ id }: { id: string }) => {
|
|
93
|
-
const title = useInstance(SlideModel, id,
|
|
212
|
+
const title = useInstance(SlideModel, id, slide => slide?.title);
|
|
94
213
|
const { focused } = useInstanceEvents(SlideModel, id);
|
|
95
214
|
// re-renders only when this slide's title changes
|
|
96
215
|
};
|
|
97
216
|
|
|
98
|
-
const Slides = () =>
|
|
217
|
+
const Slides = () =>
|
|
218
|
+
useInstanceIds(SlideModel).map(id => <Slide key={id} id={id} />);
|
|
99
219
|
```
|
|
100
220
|
|
|
101
221
|
- `useInstance(model, id)` — instance or `undefined`; `useInstance(model, id, selector, isEqual?)` — selected value. Pass a stable selector to avoid re-subscribing.
|
|
102
222
|
- `useInstanceIds(model)` — re-renders only when the set or order of ids changes.
|
|
103
223
|
- `useInstanceEvents(model, id)` — instance events bound to the id and to the scope from `Provider`.
|
|
224
|
+
- `useChildIds(relation, parentId)` — ids of the children of one parent; re-renders only when their set or order changes.
|
|
225
|
+
- `useChildren(relation, parentId)` — the children themselves; `useChildren(relation, parentId, selector, isEqual?)` — an aggregate over them (a total, a counter) that re-renders only when the selected value changes.
|
|
226
|
+
- `useResolvedId(aliases, id)` — the real id for an id that may be an alias: `useInstance(Chats, useResolvedId(chatAliases, routeId))`.
|
|
227
|
+
- `useUnionInstance(union, { kind, id })` — `{ kind, id, state }` or `undefined`; `kind` narrows the type of `state`.
|
|
228
|
+
|
|
229
|
+
## Releasing
|
|
230
|
+
|
|
231
|
+
Bump `version` in `package.json`, describe the changes in `CHANGELOG.md` and merge into `main`. The `models-next` workflow checks the package, installs the packed tarball into an empty project and publishes the version if it is not on npm yet: a prerelease gets the dist-tag `next`, a stable version gets `latest`.
|
|
104
232
|
|
|
105
233
|
## License
|
|
106
234
|
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { createEvent, createStore, sample } from "effector";
|
|
2
|
+
// lib/aliases.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 without = (aliases, isRemoved) => {
|
|
8
|
+
let next = aliases;
|
|
9
|
+
for (const [alias, id] of Object.entries(aliases)) if (isRemoved(alias, id)) {
|
|
10
|
+
if (next === aliases) next = { ...aliases };
|
|
11
|
+
delete next[alias];
|
|
12
|
+
}
|
|
13
|
+
return next;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Алиасы: один экземпляр доступен под несколькими id — например, под id из
|
|
17
|
+
* маршрута и под id с сервера. Экземпляр по-прежнему хранится один раз;
|
|
18
|
+
* алиасы — отдельный стор, который следует за жизнью экземпляров.
|
|
19
|
+
*/ function aliases(model) {
|
|
20
|
+
const $aliases = createStore({}, {
|
|
21
|
+
sid: `effector-models:${model.name}:aliases`,
|
|
22
|
+
name: `${model.name}/$aliases`
|
|
23
|
+
});
|
|
24
|
+
const add = createEvent({ name: `${model.name}/aliasAdded` });
|
|
25
|
+
const remove = createEvent({ name: `${model.name}/aliasRemoved` });
|
|
26
|
+
sample({
|
|
27
|
+
clock: add,
|
|
28
|
+
source: {
|
|
29
|
+
current: $aliases,
|
|
30
|
+
instances: model.$instances
|
|
31
|
+
},
|
|
32
|
+
fn: ({ current, instances }, params) => {
|
|
33
|
+
let next = current;
|
|
34
|
+
for (const { alias, id } of Array.isArray(params) ? params : [params]) {
|
|
35
|
+
const target = resolveAlias(next, id);
|
|
36
|
+
if (!Object.hasOwn(instances, target) || Object.hasOwn(instances, alias) || next[alias] === target) continue;
|
|
37
|
+
if (next === current) next = { ...current };
|
|
38
|
+
next[alias] = target;
|
|
39
|
+
}
|
|
40
|
+
return next;
|
|
41
|
+
},
|
|
42
|
+
target: $aliases
|
|
43
|
+
});
|
|
44
|
+
sample({
|
|
45
|
+
clock: remove,
|
|
46
|
+
source: $aliases,
|
|
47
|
+
fn: (current, ids) => {
|
|
48
|
+
const removed = toList(ids);
|
|
49
|
+
return without(current, (alias) => removed.includes(alias));
|
|
50
|
+
},
|
|
51
|
+
target: $aliases
|
|
52
|
+
});
|
|
53
|
+
sample({
|
|
54
|
+
clock: model.delete,
|
|
55
|
+
source: $aliases,
|
|
56
|
+
fn: (current, ids) => {
|
|
57
|
+
const deleted = toList(ids);
|
|
58
|
+
return without(current, (_, id) => deleted.includes(id));
|
|
59
|
+
},
|
|
60
|
+
target: $aliases
|
|
61
|
+
});
|
|
62
|
+
sample({
|
|
63
|
+
clock: model.clear,
|
|
64
|
+
source: $aliases,
|
|
65
|
+
filter: (current) => Object.keys(current).length > 0,
|
|
66
|
+
fn: () => ({}),
|
|
67
|
+
target: $aliases
|
|
68
|
+
});
|
|
69
|
+
sample({
|
|
70
|
+
clock: [model.create, model.upsert],
|
|
71
|
+
source: $aliases,
|
|
72
|
+
fn: (current, params) => {
|
|
73
|
+
const created = (Array.isArray(params) ? params : [params]).map(({ id }) => id);
|
|
74
|
+
return without(current, (alias) => created.includes(alias));
|
|
75
|
+
},
|
|
76
|
+
target: $aliases
|
|
77
|
+
});
|
|
78
|
+
sample({
|
|
79
|
+
clock: model.rename,
|
|
80
|
+
source: $aliases,
|
|
81
|
+
fn: (current, { from, to }) => {
|
|
82
|
+
let next = without(current, (alias) => alias === to);
|
|
83
|
+
for (const [alias, id] of Object.entries(next)) if (id === from) {
|
|
84
|
+
if (next === current) next = { ...current };
|
|
85
|
+
next[alias] = to;
|
|
86
|
+
}
|
|
87
|
+
return next;
|
|
88
|
+
},
|
|
89
|
+
target: $aliases
|
|
90
|
+
});
|
|
91
|
+
const resolved = (target) => {
|
|
92
|
+
const event = createEvent();
|
|
93
|
+
sample({
|
|
94
|
+
clock: event,
|
|
95
|
+
source: $aliases,
|
|
96
|
+
fn: (current, params) => {
|
|
97
|
+
const { id } = params;
|
|
98
|
+
return {
|
|
99
|
+
...params,
|
|
100
|
+
id: typeof id === "string" ? resolveAlias(current, id) : id.map((item) => resolveAlias(current, item))
|
|
101
|
+
};
|
|
102
|
+
},
|
|
103
|
+
target
|
|
104
|
+
});
|
|
105
|
+
return event;
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
$aliases,
|
|
109
|
+
add,
|
|
110
|
+
remove,
|
|
111
|
+
resolved
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
export { resolveAlias as n, aliases as t };
|
|
115
|
+
|
|
116
|
+
//# sourceMappingURL=aliases-9ILz72OF.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aliases-9ILz72OF.mjs","names":["createEvent","createStore","sample","resolveAlias","aliases","id","Object","hasOwn","toList","ids","without","isRemoved","next","alias","entries","model","$aliases","sid","name","add","remove","clock","source","current","instances","$instances","fn","params","Array","isArray","target","removed","includes","delete","deleted","_","clear","filter","keys","length","create","upsert","created","map","rename","from","to","resolved","event","item"],"sources":["../lib/aliases.ts"],"sourcesContent":["import {\n createEvent,\n createStore,\n type EventCallable,\n sample,\n type Store,\n} from 'effector';\n\nimport type { Ids, Model } from './model';\n\n/** Часть модели, нужная алиасам. */\nexport type AliasTarget<State extends object> = Pick<\n Model<State, Record<never, unknown>>,\n 'name' | '$instances' | 'create' | 'upsert' | 'delete' | 'clear' | 'rename'\n>;\n\nexport interface AliasParams {\n alias: string;\n /** Id экземпляра или другой алиас: хранится всегда настоящий id. */\n id: string;\n}\n\nexport interface Aliases {\n /** Алиас → настоящий id экземпляра. */\n readonly $aliases: Store<Record<string, string>>;\n /** Добавляет алиасы; алиас на несуществующий экземпляр не создаётся. */\n readonly add: EventCallable<AliasParams | AliasParams[]>;\n readonly remove: EventCallable<Ids>;\n /**\n * Событие с тем же payload, что у исходного, но id в нём могут быть алиасами:\n * перед отправкой они заменяются настоящими.\n */\n readonly resolved: <Params extends { id: Ids }>(\n target: EventCallable<Params>,\n ) => EventCallable<Params>;\n}\n\n/** Настоящий id по алиасу; id без алиаса возвращается как есть. */\nexport function resolveAlias(\n aliases: Record<string, string>,\n id: string,\n): string {\n return Object.hasOwn(aliases, id) ? aliases[id]! : id;\n}\n\nconst toList = (ids: Ids): readonly string[] =>\n typeof ids === 'string' ? [ids] : ids;\n\nconst without = (\n aliases: Record<string, string>,\n isRemoved: (alias: string, id: string) => boolean,\n): Record<string, string> => {\n let next = aliases;\n\n for (const [alias, id] of Object.entries(aliases)) {\n if (isRemoved(alias, id)) {\n if (next === aliases) {\n next = { ...aliases };\n }\n\n delete next[alias];\n }\n }\n\n return next;\n};\n\n/**\n * Алиасы: один экземпляр доступен под несколькими id — например, под id из\n * маршрута и под id с сервера. Экземпляр по-прежнему хранится один раз;\n * алиасы — отдельный стор, который следует за жизнью экземпляров.\n */\nexport function aliases<State extends object>(\n model: AliasTarget<State>,\n): Aliases {\n const $aliases = createStore<Record<string, string>>(\n {},\n {\n sid: `effector-models:${model.name}:aliases`,\n name: `${model.name}/$aliases`,\n },\n );\n const add = createEvent<AliasParams | AliasParams[]>({\n name: `${model.name}/aliasAdded`,\n });\n const remove = createEvent<Ids>({ name: `${model.name}/aliasRemoved` });\n\n sample({\n clock: add,\n source: { current: $aliases, instances: model.$instances },\n fn: ({ current, instances }, params) => {\n let next = current;\n\n for (const { alias, id } of Array.isArray(params) ? params : [params]) {\n const target = resolveAlias(next, id);\n\n // Настоящий id всегда важнее алиаса с тем же значением.\n if (\n !Object.hasOwn(instances, target) ||\n Object.hasOwn(instances, alias) ||\n next[alias] === target\n ) {\n continue;\n }\n\n if (next === current) {\n next = { ...current };\n }\n\n next[alias] = target;\n }\n\n return next;\n },\n target: $aliases,\n });\n\n sample({\n clock: remove,\n source: $aliases,\n fn: (current, ids) => {\n const removed = toList(ids);\n\n return without(current, alias => removed.includes(alias));\n },\n target: $aliases,\n });\n\n // Удалённый экземпляр забирает свои алиасы; удаление по алиасу не поддерживается самим `delete` —\n // для него есть `resolved(model.delete)`.\n sample({\n clock: model.delete,\n source: $aliases,\n fn: (current, ids) => {\n const deleted = toList(ids);\n\n return without(current, (_, id) => deleted.includes(id));\n },\n target: $aliases,\n });\n\n sample({\n clock: model.clear,\n source: $aliases,\n filter: current => Object.keys(current).length > 0,\n fn: (): Record<string, string> => ({}),\n target: $aliases,\n });\n\n // Экземпляр, созданный с id существующего алиаса, вытесняет этот алиас.\n sample({\n clock: [model.create, model.upsert],\n source: $aliases,\n fn: (current, params) => {\n const created = (Array.isArray(params) ? params : [params]).map(\n ({ id }) => id,\n );\n\n return without(current, alias => created.includes(alias));\n },\n target: $aliases,\n });\n\n sample({\n clock: model.rename,\n source: $aliases,\n fn: (current, { from, to }) => {\n let next = without(current, alias => alias === to);\n\n for (const [alias, id] of Object.entries(next)) {\n if (id === from) {\n if (next === current) {\n next = { ...current };\n }\n\n next[alias] = to;\n }\n }\n\n return next;\n },\n target: $aliases,\n });\n\n const resolved = <Params extends { id: Ids }>(\n target: EventCallable<Params>,\n ): EventCallable<Params> => {\n const event = createEvent<Params>();\n\n sample({\n clock: event,\n source: $aliases,\n fn: (current, params) => {\n const { id } = params;\n\n return {\n ...params,\n id:\n typeof id === 'string'\n ? resolveAlias(current, id)\n : id.map(item => resolveAlias(current, item)),\n };\n },\n target: target,\n });\n\n return event;\n };\n\n return { $aliases, add, remove, resolved };\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
let effector = require("effector");
|
|
2
|
+
// lib/aliases.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 without = (aliases, isRemoved) => {
|
|
8
|
+
let next = aliases;
|
|
9
|
+
for (const [alias, id] of Object.entries(aliases)) if (isRemoved(alias, id)) {
|
|
10
|
+
if (next === aliases) next = { ...aliases };
|
|
11
|
+
delete next[alias];
|
|
12
|
+
}
|
|
13
|
+
return next;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Алиасы: один экземпляр доступен под несколькими id — например, под id из
|
|
17
|
+
* маршрута и под id с сервера. Экземпляр по-прежнему хранится один раз;
|
|
18
|
+
* алиасы — отдельный стор, который следует за жизнью экземпляров.
|
|
19
|
+
*/ function aliases(model) {
|
|
20
|
+
const $aliases = (0, effector.createStore)({}, {
|
|
21
|
+
sid: `effector-models:${model.name}:aliases`,
|
|
22
|
+
name: `${model.name}/$aliases`
|
|
23
|
+
});
|
|
24
|
+
const add = (0, effector.createEvent)({ name: `${model.name}/aliasAdded` });
|
|
25
|
+
const remove = (0, effector.createEvent)({ name: `${model.name}/aliasRemoved` });
|
|
26
|
+
(0, effector.sample)({
|
|
27
|
+
clock: add,
|
|
28
|
+
source: {
|
|
29
|
+
current: $aliases,
|
|
30
|
+
instances: model.$instances
|
|
31
|
+
},
|
|
32
|
+
fn: ({ current, instances }, params) => {
|
|
33
|
+
let next = current;
|
|
34
|
+
for (const { alias, id } of Array.isArray(params) ? params : [params]) {
|
|
35
|
+
const target = resolveAlias(next, id);
|
|
36
|
+
if (!Object.hasOwn(instances, target) || Object.hasOwn(instances, alias) || next[alias] === target) continue;
|
|
37
|
+
if (next === current) next = { ...current };
|
|
38
|
+
next[alias] = target;
|
|
39
|
+
}
|
|
40
|
+
return next;
|
|
41
|
+
},
|
|
42
|
+
target: $aliases
|
|
43
|
+
});
|
|
44
|
+
(0, effector.sample)({
|
|
45
|
+
clock: remove,
|
|
46
|
+
source: $aliases,
|
|
47
|
+
fn: (current, ids) => {
|
|
48
|
+
const removed = toList(ids);
|
|
49
|
+
return without(current, (alias) => removed.includes(alias));
|
|
50
|
+
},
|
|
51
|
+
target: $aliases
|
|
52
|
+
});
|
|
53
|
+
(0, effector.sample)({
|
|
54
|
+
clock: model.delete,
|
|
55
|
+
source: $aliases,
|
|
56
|
+
fn: (current, ids) => {
|
|
57
|
+
const deleted = toList(ids);
|
|
58
|
+
return without(current, (_, id) => deleted.includes(id));
|
|
59
|
+
},
|
|
60
|
+
target: $aliases
|
|
61
|
+
});
|
|
62
|
+
(0, effector.sample)({
|
|
63
|
+
clock: model.clear,
|
|
64
|
+
source: $aliases,
|
|
65
|
+
filter: (current) => Object.keys(current).length > 0,
|
|
66
|
+
fn: () => ({}),
|
|
67
|
+
target: $aliases
|
|
68
|
+
});
|
|
69
|
+
(0, effector.sample)({
|
|
70
|
+
clock: [model.create, model.upsert],
|
|
71
|
+
source: $aliases,
|
|
72
|
+
fn: (current, params) => {
|
|
73
|
+
const created = (Array.isArray(params) ? params : [params]).map(({ id }) => id);
|
|
74
|
+
return without(current, (alias) => created.includes(alias));
|
|
75
|
+
},
|
|
76
|
+
target: $aliases
|
|
77
|
+
});
|
|
78
|
+
(0, effector.sample)({
|
|
79
|
+
clock: model.rename,
|
|
80
|
+
source: $aliases,
|
|
81
|
+
fn: (current, { from, to }) => {
|
|
82
|
+
let next = without(current, (alias) => alias === to);
|
|
83
|
+
for (const [alias, id] of Object.entries(next)) if (id === from) {
|
|
84
|
+
if (next === current) next = { ...current };
|
|
85
|
+
next[alias] = to;
|
|
86
|
+
}
|
|
87
|
+
return next;
|
|
88
|
+
},
|
|
89
|
+
target: $aliases
|
|
90
|
+
});
|
|
91
|
+
const resolved = (target) => {
|
|
92
|
+
const event = (0, effector.createEvent)();
|
|
93
|
+
(0, effector.sample)({
|
|
94
|
+
clock: event,
|
|
95
|
+
source: $aliases,
|
|
96
|
+
fn: (current, params) => {
|
|
97
|
+
const { id } = params;
|
|
98
|
+
return {
|
|
99
|
+
...params,
|
|
100
|
+
id: typeof id === "string" ? resolveAlias(current, id) : id.map((item) => resolveAlias(current, item))
|
|
101
|
+
};
|
|
102
|
+
},
|
|
103
|
+
target
|
|
104
|
+
});
|
|
105
|
+
return event;
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
$aliases,
|
|
109
|
+
add,
|
|
110
|
+
remove,
|
|
111
|
+
resolved
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
Object.defineProperty(exports, "aliases", {
|
|
115
|
+
enumerable: true,
|
|
116
|
+
get: function() {
|
|
117
|
+
return aliases;
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
Object.defineProperty(exports, "resolveAlias", {
|
|
121
|
+
enumerable: true,
|
|
122
|
+
get: function() {
|
|
123
|
+
return resolveAlias;
|
|
124
|
+
}
|
|
125
|
+
});
|