@effector-tools/models 0.0.0-stage → 0.2.4
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 +246 -0
- package/LICENSE +22 -0
- package/README.md +369 -2
- package/dist/index.cjs +332 -0
- package/dist/index.d.cts +80 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +80 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +326 -0
- package/dist/index.mjs.map +1 -0
- package/dist/model-D-BuLYdk.cjs +428 -0
- package/dist/model-Dtqtl37y.mjs +401 -0
- package/dist/model-Dtqtl37y.mjs.map +1 -0
- package/dist/react.cjs +261 -0
- package/dist/react.d.cts +120 -0
- package/dist/react.d.cts.map +1 -0
- package/dist/react.d.mts +120 -0
- package/dist/react.d.mts.map +1 -0
- package/dist/react.mjs +254 -0
- package/dist/react.mjs.map +1 -0
- package/dist/relations-BkhJCHOR.d.cts +254 -0
- package/dist/relations-BkhJCHOR.d.cts.map +1 -0
- package/dist/relations-DQSqTylt.d.mts +254 -0
- package/dist/relations-DQSqTylt.d.mts.map +1 -0
- package/package.json +80 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.4
|
|
4
|
+
|
|
5
|
+
The package is renamed: **`@effector-tools/models`** instead of
|
|
6
|
+
`@olovyannikov/effector-models`. The API is the same; replace the name in
|
|
7
|
+
`package.json` and in the imports. This version is the last one published
|
|
8
|
+
under the old name as well; later ones come out only as
|
|
9
|
+
`@effector-tools/models`.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **Lenses**: `lens(Model)` describes a selection of instances.
|
|
14
|
+
- Narrowing: `where(predicate)`, `only(ids)`, `first()`, `last()`.
|
|
15
|
+
- Reading: `$ids`, `$items`, `$count` — derived stores that update only
|
|
16
|
+
when the selection really changes.
|
|
17
|
+
- Writing: `update`, `delete` and `events.<name>` act on what is selected
|
|
18
|
+
at the moment of the write, so they go into `target` as they are.
|
|
19
|
+
- `field(key)` — a lens on a field of the selected instances: `$values`,
|
|
20
|
+
`set`, `over`.
|
|
21
|
+
|
|
22
|
+
Stores and events are properties created on first access; there is nothing
|
|
23
|
+
to call.
|
|
24
|
+
|
|
25
|
+
## 0.2.3
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
|
|
29
|
+
- `autoCreate: true` in `model(...)`: an instance is created on the first
|
|
30
|
+
write. `update` and instance events addressed to a missing id are applied
|
|
31
|
+
to `defaults` instead of going to `missed`.
|
|
32
|
+
- `model.applied` — a fact of a write through `update` or an instance event:
|
|
33
|
+
`{ action, changes: [{ id, prev, next }] }`. It fires for every call that
|
|
34
|
+
changed something, unlike a `sample` with `source`, which keeps the last
|
|
35
|
+
call of a tick.
|
|
36
|
+
|
|
37
|
+
Both are what `@olovyannikov/effector-forms` is built on.
|
|
38
|
+
|
|
39
|
+
## 0.2.2
|
|
40
|
+
|
|
41
|
+
### Fixed
|
|
42
|
+
|
|
43
|
+
- **Relations between two models and commands of the same tick.** The
|
|
44
|
+
limitation from 0.2.1 is gone. A relation reacts to a `deleted` or
|
|
45
|
+
`renamed` fact after the commands already launched in that tick, so it used
|
|
46
|
+
to reach data written after the fact: reloading lists and their cards in
|
|
47
|
+
one `sample` (`clear`, `create`, `create`) deleted the new cards and
|
|
48
|
+
cleared the new references. The model now remembers when a field used by a
|
|
49
|
+
relation was written, and a relation skips what was written after the
|
|
50
|
+
fact.
|
|
51
|
+
|
|
52
|
+
### Known limitation
|
|
53
|
+
|
|
54
|
+
- A list of references rewritten after the fact is kept as a whole, also
|
|
55
|
+
when the new list still contains the deleted id.
|
|
56
|
+
|
|
57
|
+
### Internal
|
|
58
|
+
|
|
59
|
+
- The package folder is `packages/effector-models`; `repository.directory`
|
|
60
|
+
and the release workflow follow.
|
|
61
|
+
|
|
62
|
+
## 0.2.1
|
|
63
|
+
|
|
64
|
+
A second review of the rewritten core.
|
|
65
|
+
|
|
66
|
+
### Fixed
|
|
67
|
+
|
|
68
|
+
- **Trees and self-references.** A model's reaction to its own fact (the
|
|
69
|
+
cascade of a tree, a `ref` to itself) is applied inside the same write.
|
|
70
|
+
Before, it ran after the commands already launched in the same tick, so
|
|
71
|
+
`clear` followed by `create` of the same tree deleted the new nodes.
|
|
72
|
+
- Writing a previously seen state object back into `$state` (restoring a
|
|
73
|
+
snapshot) no longer re-emits its old `deleted` / `renamed` / `missed`.
|
|
74
|
+
- The id or alias `'__proto__'` is stored as an ordinary key. It used to
|
|
75
|
+
change the prototype of the dictionary and leave `ids` and `instances`
|
|
76
|
+
out of sync.
|
|
77
|
+
- `ref` to a `union`: renaming a target keeps the other fields of the
|
|
78
|
+
reference (`{ kind, id, seat }` used to become `{ kind, id }`).
|
|
79
|
+
|
|
80
|
+
### Changed
|
|
81
|
+
|
|
82
|
+
- Deleting a branch of a tree emits one `deleted` fact with every deleted id
|
|
83
|
+
instead of one fact per level.
|
|
84
|
+
|
|
85
|
+
### Known limitation
|
|
86
|
+
|
|
87
|
+
- A relation between two models still reacts after the commands already
|
|
88
|
+
launched in the same tick. See
|
|
89
|
+
[Relations](https://olovyannikov.github.io/effector-kit/guide/keyed-models#relations).
|
|
90
|
+
|
|
91
|
+
## 0.2.0
|
|
92
|
+
|
|
93
|
+
A review of the core found that writes could be lost or reordered. The model
|
|
94
|
+
is rebuilt on one store with reducers, which changes how it is seeded and
|
|
95
|
+
serialized.
|
|
96
|
+
|
|
97
|
+
### Breaking
|
|
98
|
+
|
|
99
|
+
- **One writable store per model, `$state`**: `{ ids, instances, aliases }`
|
|
100
|
+
under the sid `effector-models:<name>`. `$instances`, `$ids` and `$aliases`
|
|
101
|
+
are derived from it and are no longer writable. The separate
|
|
102
|
+
`effector-models:<name>:aliases` sid is gone.
|
|
103
|
+
- Seed with `fork({ values: [[Model.$state, modelState({ ... })]] })`
|
|
104
|
+
instead of `[[Model.$instances, { ... }]]`.
|
|
105
|
+
- Serialized state has the new shape; state serialized by 0.1.x does not
|
|
106
|
+
hydrate.
|
|
107
|
+
- `clear` reports the deleted ids and aliases in `deleted`.
|
|
108
|
+
- `ref` requires a single-reference field to accept `null`
|
|
109
|
+
(`string | null`): that is what a deleted target is replaced with.
|
|
110
|
+
- `ModelLike` requires `$ids` and the internal `~link`.
|
|
111
|
+
|
|
112
|
+
### Fixed
|
|
113
|
+
|
|
114
|
+
- **Lost writes.** Commands launched one after another in the same tick —
|
|
115
|
+
`target: [a, b]`, two prepends of one event — were coalesced: only the last
|
|
116
|
+
payload of an instance event survived, and `rename` → `update` or
|
|
117
|
+
`delete` → `create` ran in the wrong order. Every write is a reducer of
|
|
118
|
+
`$state` now and is applied in order.
|
|
119
|
+
- **Lost facts in relations.** When `deleted` or `renamed` fired twice in one
|
|
120
|
+
tick, `child` and `ref` saw only the last one: a tree with a `ref` to
|
|
121
|
+
itself kept links to a deleted root, a tree with a second `child` kept the
|
|
122
|
+
orphans, `union.delete` with mixed kinds cleaned only the last kind.
|
|
123
|
+
- **Order of ids.** `$ids` and `$idsByParent` follow creation order also for
|
|
124
|
+
ids that look like numbers (`'10'` before `'2'`), and `rename` keeps the
|
|
125
|
+
instance in its place instead of moving it to the end.
|
|
126
|
+
- Ids equal to `Object.prototype` property names (`'constructor'`,
|
|
127
|
+
`'toString'`) were treated as existing instances by `update`, `upsert` and
|
|
128
|
+
the hooks.
|
|
129
|
+
- `useChildren` and `useModel` threw when a request switched from a selector
|
|
130
|
+
that returned `null` to plain children.
|
|
131
|
+
- `clear` on an empty model no longer marks the store as changed; `$ids` no
|
|
132
|
+
longer updates when only a field of an instance changes.
|
|
133
|
+
- A reducer with an optional payload (`(state, by?: number) => ...`) no
|
|
134
|
+
longer requires `payload` in the event params and in the bound event.
|
|
135
|
+
|
|
136
|
+
### Added
|
|
137
|
+
|
|
138
|
+
- `modelState(instances, aliases?)` — the value of `$state` for seeding.
|
|
139
|
+
- `ModelState` and `ModelLink` types.
|
|
140
|
+
|
|
141
|
+
## 0.1.2
|
|
142
|
+
|
|
143
|
+
### Added
|
|
144
|
+
|
|
145
|
+
- **React**: `useModel(union, { kind, id })` — the same hook for an instance
|
|
146
|
+
of a union. The result is narrowed by `kind`: `state` and `events` belong
|
|
147
|
+
to the model of that kind; `update` and `remove` go to it as well. It is
|
|
148
|
+
`undefined` when there is no such instance. `UnionModelView` is the type
|
|
149
|
+
of the result.
|
|
150
|
+
|
|
151
|
+
## 0.1.1
|
|
152
|
+
|
|
153
|
+
### Added
|
|
154
|
+
|
|
155
|
+
- **React**: `useModel(model, id, related?)` — one hook for one instance:
|
|
156
|
+
`state`, `exists`, the real `id`, bound `events`, `update` and `remove`,
|
|
157
|
+
plus the values requested from relations under your own keys. A relation
|
|
158
|
+
gives the ids of the children; `childrenOf(relation, selector?, isEqual?)`
|
|
159
|
+
gives the children or a value selected from them. The existing hooks stay
|
|
160
|
+
as its building blocks.
|
|
161
|
+
|
|
162
|
+
## 0.1.0
|
|
163
|
+
|
|
164
|
+
The first release on the `latest` dist-tag. The code is the same as in
|
|
165
|
+
`1.0.0-alpha.3`.
|
|
166
|
+
|
|
167
|
+
Versioning moves to `0.x`: the API may still change, and a breaking change
|
|
168
|
+
bumps the minor version (`0.2.0`), so `^0.1.0` only receives compatible
|
|
169
|
+
updates. The `1.0.0-alpha.*` versions are superseded by this one, even
|
|
170
|
+
though they sort higher — install `@olovyannikov/effector-models` without a
|
|
171
|
+
tag.
|
|
172
|
+
|
|
173
|
+
## 1.0.0-alpha.3
|
|
174
|
+
|
|
175
|
+
### Added
|
|
176
|
+
|
|
177
|
+
- **Aliases in the core.** Every model has `$aliases`, `alias` and `unalias`.
|
|
178
|
+
`update`, `upsert`, `delete`, `rename` and instance events accept an alias
|
|
179
|
+
wherever they accept an id; so do `useInstance`, `useInstanceEvents`,
|
|
180
|
+
`useChildIds`, `useChildren` and `useUnionInstance`.
|
|
181
|
+
- **Facts**: `model.deleted` (real ids of the deleted instances followed by
|
|
182
|
+
their aliases) and `model.renamed` (`{ from, to }` with the real `from`).
|
|
183
|
+
They fire only when something was actually deleted or moved.
|
|
184
|
+
- Relations see through aliases: a child or a reference that stores an alias
|
|
185
|
+
of its target is cascaded and cleaned up like one that stores the real id.
|
|
186
|
+
`$idsByParent` is always keyed by the real parent id.
|
|
187
|
+
- `union.$aliases`; `Child` has a `parent` field.
|
|
188
|
+
|
|
189
|
+
### Changed
|
|
190
|
+
|
|
191
|
+
- `upsert` with an alias id extends the aliased instance instead of creating
|
|
192
|
+
a new one. `create` still displaces the alias.
|
|
193
|
+
- `rename` to the instance's own id is a no-op. It used to delete the
|
|
194
|
+
instance.
|
|
195
|
+
- `ModelLike` also requires `$aliases`, `deleted` and `renamed`.
|
|
196
|
+
- `useUnionInstance` returns the real id when the reference holds an alias.
|
|
197
|
+
|
|
198
|
+
### Deprecated
|
|
199
|
+
|
|
200
|
+
- `aliases(model)` is a thin wrapper over the model now: `add` is
|
|
201
|
+
`model.alias`, `remove` is `model.unalias`, `resolved(event)` returns the
|
|
202
|
+
event itself. The sid of the alias store did not change, so serialized
|
|
203
|
+
state from alpha.2 hydrates as is.
|
|
204
|
+
|
|
205
|
+
## 1.0.0-alpha.2
|
|
206
|
+
|
|
207
|
+
### Added
|
|
208
|
+
|
|
209
|
+
- **Aliases**: `aliases(model)` — one instance reachable by several ids:
|
|
210
|
+
`$aliases`, `add`, `remove`, and `resolved(event)` to write through an
|
|
211
|
+
alias. Aliases follow `delete`, `clear` and `rename` of the instances.
|
|
212
|
+
`resolveAlias(aliases, id)` is exported for use in `sample`.
|
|
213
|
+
- **React**: `useResolvedId(aliases, id)` — the real id for an id that may
|
|
214
|
+
be an alias.
|
|
215
|
+
|
|
216
|
+
## 1.0.0-alpha.1
|
|
217
|
+
|
|
218
|
+
### Added
|
|
219
|
+
|
|
220
|
+
- **Relations** between models. A reference is an ordinary field with an id;
|
|
221
|
+
a relation keeps such fields consistent.
|
|
222
|
+
- `child({ parent, model, key })` — children are deleted together with the
|
|
223
|
+
parent and follow its `rename`; `$idsByParent` index.
|
|
224
|
+
- Trees: a model can be a `child` of itself with a nullable key. Deleting a
|
|
225
|
+
node deletes its whole branch.
|
|
226
|
+
- `ref({ from, field, to })` — a field with one id or a list. Deleted
|
|
227
|
+
targets disappear from references, renamed ones are renamed.
|
|
228
|
+
- `union({ ... })` — several models as one collection addressed by
|
|
229
|
+
`{ kind, id }`, with `create`, `upsert` and `delete` routed to the model
|
|
230
|
+
of the kind. `ref` accepts a union as a target.
|
|
231
|
+
- **React hooks**: `useChildIds`, `useChildren` (the children of one parent
|
|
232
|
+
or an aggregate over them) and `useUnionInstance`.
|
|
233
|
+
|
|
234
|
+
### Changed
|
|
235
|
+
|
|
236
|
+
- `exports` provide separate type declarations for ESM and CJS consumers.
|
|
237
|
+
- `engines.node` is declared: `>=18`.
|
|
238
|
+
- Peer ranges are bounded: `effector >=23.4.4 <24`,
|
|
239
|
+
`effector-react >=23.3.0 <24`.
|
|
240
|
+
|
|
241
|
+
## 1.0.0-alpha.0
|
|
242
|
+
|
|
243
|
+
Initial release: `model` with immutable instances and synchronous reducers,
|
|
244
|
+
`create` / `upsert` / `update` / `delete` / `rename` / `clear`, the `missed`
|
|
245
|
+
event, and the React hooks `useInstance`, `useInstanceIds`,
|
|
246
|
+
`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
|
@@ -1,3 +1,370 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @effector-tools/models
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Keyed models for [Effector](https://effector.dev): a collection of instances addressed by id, where every instance is plain immutable data and instance events are pure reducers.
|
|
4
|
+
|
|
5
|
+
Fork of [`@effector-kit/models`](https://github.com/movpushmov/effector-kit) by movpushmov, redesigned around one goal: **behave like ordinary Effector units**.
|
|
6
|
+
|
|
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 `$state` 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 built into the model: see [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).
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pnpm add @effector-tools/models effector
|
|
27
|
+
# React bindings
|
|
28
|
+
pnpm add effector-react react
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Up to 0.2.4 the package was published as `@olovyannikov/effector-models`; the API is the same, only the name changed.
|
|
32
|
+
|
|
33
|
+
## Model
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { model } from '@effector-tools/models';
|
|
37
|
+
|
|
38
|
+
interface Document {
|
|
39
|
+
documentId: string | null;
|
|
40
|
+
pending: Patch | null;
|
|
41
|
+
failed: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const defaults: Document = { documentId: null, pending: null, failed: false };
|
|
45
|
+
|
|
46
|
+
export const DocumentModel = model({
|
|
47
|
+
name: 'document', // unique: sid of the state is `effector-models:document`
|
|
48
|
+
defaults,
|
|
49
|
+
events: {
|
|
50
|
+
patched: (doc, patch: Patch) => ({
|
|
51
|
+
...doc,
|
|
52
|
+
pending: merge(doc.pending, patch),
|
|
53
|
+
failed: false,
|
|
54
|
+
}),
|
|
55
|
+
sent: doc => ({ ...doc, pending: null }),
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
A reducer returning the same object means "nothing changed": no store update, no re-render.
|
|
61
|
+
|
|
62
|
+
## API
|
|
63
|
+
|
|
64
|
+
| Unit | Payload | Behaviour |
|
|
65
|
+
| --------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
|
66
|
+
| `$state` | — | `{ ids, instances, aliases }`: the single writable store, has a sid |
|
|
67
|
+
| `$instances` | — | `Record<id, State>`, derived from `$state` |
|
|
68
|
+
| `$ids` | — | `string[]` in creation order; updates only when the set or the order changes |
|
|
69
|
+
| `create` | `{ id, data? }` or array | creates with defaults; replaces existing id |
|
|
70
|
+
| `upsert` | `{ id, data? }` or array | merges into existing or creates with defaults |
|
|
71
|
+
| `update` | `{ id, data: Partial<State> \| (state) => State }` | existing only |
|
|
72
|
+
| `delete` | `id` or `id[]` | |
|
|
73
|
+
| `rename` | `{ from, to }` | moves instance in one step (e.g. draft → created document) |
|
|
74
|
+
| `clear` | — | deletes everything; the ids are reported in `deleted` |
|
|
75
|
+
| `events.<name>` | `{ id \| id[], payload }` | applies reducer synchronously |
|
|
76
|
+
| `missed` | `{ action, ids }` | writes addressed to instances that do not exist |
|
|
77
|
+
| `applied` | `{ action, changes }` | fact: an instance event or `update` changed instances; `changes` holds `{ id, prev, next }` |
|
|
78
|
+
| `deleted` | `string[]` | fact: real ids of deleted instances, then their aliases |
|
|
79
|
+
| `renamed` | `{ from, to }` | fact: the instance moved, `from` is the real id |
|
|
80
|
+
| `$aliases` | — | `Record<alias, id>`, has a sid; see [aliases](#aliases--one-instance-several-ids) |
|
|
81
|
+
| `alias` | `{ alias, id }` or an array | adds aliases to existing instances |
|
|
82
|
+
| `unalias` | `alias` or `alias[]` | removes aliases, instances stay |
|
|
83
|
+
|
|
84
|
+
With `autoCreate: true` an instance is created on the first write: `update` and instance events addressed to a missing id are applied to `defaults` instead of going to `missed`. It suits a model with one instance, or one whose instances appear by themselves.
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
sample({
|
|
88
|
+
clock: saved,
|
|
89
|
+
fn: patch => ({ id: documentId, payload: patch }),
|
|
90
|
+
target: DocumentModel.events.patched,
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// same tick: this sample already sees the patched instance
|
|
94
|
+
sample({
|
|
95
|
+
clock: saved,
|
|
96
|
+
source: DocumentModel.$instances,
|
|
97
|
+
fn: instances => instances[documentId]?.pending,
|
|
98
|
+
target: $pending,
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Tests seed a model like any store: `fork({ values: [[DocumentModel.$state, modelState({ a: { ... } })]] })`.
|
|
103
|
+
|
|
104
|
+
## Relations
|
|
105
|
+
|
|
106
|
+
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.
|
|
107
|
+
|
|
108
|
+
A relation reacts to data as it was at the moment of the fact. If one `sample` deletes a list and creates it again with new cards — reloading data from a server, for example — the cascade removes the old cards and leaves the new ones, although it runs after both commands. The same holds for references: a reference written after its target was deleted points to the new instance with that id and is kept.
|
|
109
|
+
|
|
110
|
+
One case is approximate: a list of references rewritten after the fact is kept as a whole, also when the new list still contains the deleted id.
|
|
111
|
+
|
|
112
|
+
### `child` — owned instances
|
|
113
|
+
|
|
114
|
+
Children store the id of their parent in a field and are deleted together with it.
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
import { child, model } from '@effector-tools/models';
|
|
118
|
+
|
|
119
|
+
const Todos = model({ name: 'todos', defaults: { title: '' } });
|
|
120
|
+
const Subtasks = model({
|
|
121
|
+
name: 'subtasks',
|
|
122
|
+
defaults: { todoId: '', title: '', done: false },
|
|
123
|
+
events: {
|
|
124
|
+
toggled: subtask => ({ ...subtask, done: !subtask.done }),
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const subtasks = child({ parent: Todos, model: Subtasks, key: 'todoId' });
|
|
129
|
+
|
|
130
|
+
subtasks.$idsByParent; // Store<Record<todoId, subtaskId[]>>, in creation order
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
- `parent.delete` / `parent.clear` delete the children
|
|
134
|
+
- `parent.rename` moves the children to the new parent id
|
|
135
|
+
- children are created like any other instance: `Subtasks.create({ id, data: { todoId } })`
|
|
136
|
+
|
|
137
|
+
A model can be a child of itself — that is a tree of any depth. The key is
|
|
138
|
+
`null` for a root, and deleting a node deletes its whole branch:
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
const Nodes = model({
|
|
142
|
+
name: 'nodes',
|
|
143
|
+
defaults: { parentId: null as string | null, title: '' },
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
const nodes = child({ parent: Nodes, model: Nodes, key: 'parentId' });
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### `ref` — tracked instances
|
|
150
|
+
|
|
151
|
+
A field that points to instances living in another model: one id (`string | null`) or a list (`string[]`).
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
import { ref } from '@effector-tools/models';
|
|
155
|
+
|
|
156
|
+
const Dashboards = model({
|
|
157
|
+
name: 'dashboards',
|
|
158
|
+
defaults: { selected: [] as string[], pinned: null as string | null },
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
ref({ from: Dashboards, field: 'selected', to: Counters });
|
|
162
|
+
ref({ from: Dashboards, field: 'pinned', to: Counters });
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
- a deleted instance disappears from lists, a single reference becomes `null`
|
|
166
|
+
- a renamed instance is renamed in references
|
|
167
|
+
- instances that did not reference it keep their object reference
|
|
168
|
+
|
|
169
|
+
### `union` — several models as one collection
|
|
170
|
+
|
|
171
|
+
An instance is addressed by `{ kind, id }`.
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
import { ref, union } from '@effector-tools/models';
|
|
175
|
+
|
|
176
|
+
const passengers = union({ adult: Adults, kid: Kids });
|
|
177
|
+
|
|
178
|
+
passengers.$instances; // Store<{ adult: Record<id, Adult>; kid: Record<id, Kid> }>
|
|
179
|
+
passengers.create({ kind: 'adult', id: 'p2', data: { name: 'Ann' } }); // routed to Adults.create
|
|
180
|
+
passengers.delete({ kind: 'kid', id: 'p1' }); // routed to Kids.delete
|
|
181
|
+
|
|
182
|
+
type Passenger = { kind: 'adult'; id: string } | { kind: 'kid'; id: string };
|
|
183
|
+
|
|
184
|
+
const Bookings = model({
|
|
185
|
+
name: 'bookings',
|
|
186
|
+
defaults: { passengers: [] as Passenger[] },
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
// References to a union are kept consistent the same way.
|
|
190
|
+
ref({ from: Bookings, field: 'passengers', to: passengers });
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### Lenses — selections of instances
|
|
194
|
+
|
|
195
|
+
A lens describes which instances are meant, without listing them. Its stores and events are properties, created on first access.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
import { lens } from '@effector-tools/models';
|
|
199
|
+
|
|
200
|
+
const all = lens(Todos);
|
|
201
|
+
const completed = all.where(todo => todo.completed);
|
|
202
|
+
|
|
203
|
+
completed.$ids; // Store<string[]>
|
|
204
|
+
completed.$count; // Store<number>
|
|
205
|
+
|
|
206
|
+
sample({ clock: completedCleared, target: completed.delete });
|
|
207
|
+
sample({ clock: allToggled, target: all.field('completed').set });
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
- narrowing: `where(predicate)`, `only(ids)`, `first()`, `last()`
|
|
211
|
+
- reading: `$ids`, `$items`, `$count`; they update only when the selection really changes
|
|
212
|
+
- writing: `update`, `delete`, `events.<name>` — the selection is computed at the moment of the write
|
|
213
|
+
- `field(key)` — `$values`, `set`, `over` for one field of the selected instances
|
|
214
|
+
|
|
215
|
+
See the [tutorial](https://olovyannikov.github.io/effector-kit/guide/lenses).
|
|
216
|
+
|
|
217
|
+
### Aliases — one instance, several ids
|
|
218
|
+
|
|
219
|
+
One instance reachable by several ids — a route id next to the server id.
|
|
220
|
+
The instance is still stored once; aliases live in the model, in `$aliases`,
|
|
221
|
+
and follow the life of instances.
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
Chats.alias({ alias: 'route-id', id: 'server-id' });
|
|
225
|
+
Chats.$aliases; // Store<Record<alias, id>>
|
|
226
|
+
|
|
227
|
+
// Everything that takes an id takes an alias.
|
|
228
|
+
Chats.events.renamed({ id: 'route-id', payload: 'New title' });
|
|
229
|
+
Chats.update({ id: 'route-id', data: { title: 'New title' } });
|
|
230
|
+
Chats.delete('route-id');
|
|
231
|
+
|
|
232
|
+
Chats.unalias('route-id'); // the instance stays
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
```tsx
|
|
236
|
+
const chat = useInstance(Chats, routeId);
|
|
237
|
+
const { renamed } = useInstanceEvents(Chats, routeId);
|
|
238
|
+
const messageIds = useChildIds(messages, routeId);
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
- `update`, `upsert`, `delete`, `rename`, instance events and all hooks
|
|
242
|
+
resolve aliases; `create` does not — an instance created with the id of an
|
|
243
|
+
alias displaces the alias, a real id always wins
|
|
244
|
+
- deleting or clearing instances removes their aliases, `rename` moves them
|
|
245
|
+
- an alias to a missing instance, or with the id of an existing one, is not
|
|
246
|
+
created
|
|
247
|
+
- relations see through aliases: a child or a reference may store an alias
|
|
248
|
+
of its target and is still cascaded and cleaned up
|
|
249
|
+
- `unalias` does not touch references that store the alias — keep real ids
|
|
250
|
+
in data when you can; `useResolvedId(model, id)` and
|
|
251
|
+
`resolveAlias(aliases, id)` give the real id
|
|
252
|
+
|
|
253
|
+
To react to changes, subscribe to the facts instead of the commands:
|
|
254
|
+
`model.deleted` carries the real ids of deleted instances followed by their
|
|
255
|
+
aliases, `model.renamed` carries `{ from, to }` with the real `from`.
|
|
256
|
+
|
|
257
|
+
Use `rename` when an instance simply moves to a new id, and aliases when
|
|
258
|
+
both ids must keep working.
|
|
259
|
+
|
|
260
|
+
## React
|
|
261
|
+
|
|
262
|
+
`useModel` gathers everything a component needs about one instance:
|
|
263
|
+
|
|
264
|
+
```tsx
|
|
265
|
+
import {
|
|
266
|
+
childrenOf,
|
|
267
|
+
useInstanceIds,
|
|
268
|
+
useModel,
|
|
269
|
+
} from '@effector-tools/models/react';
|
|
270
|
+
|
|
271
|
+
function TodoItem({ id }: { id: string }) {
|
|
272
|
+
// One hook for one instance: state, events, writes and its children.
|
|
273
|
+
const todo = useModel(Todos, id, {
|
|
274
|
+
subtaskIds: subtasks,
|
|
275
|
+
done: childrenOf(subtasks, countCompleted),
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
if (!todo.state) return null;
|
|
279
|
+
|
|
280
|
+
return (
|
|
281
|
+
<li>
|
|
282
|
+
<label>
|
|
283
|
+
<input
|
|
284
|
+
type="checkbox"
|
|
285
|
+
checked={todo.state.completed}
|
|
286
|
+
onChange={() => todo.events.toggled()}
|
|
287
|
+
/>
|
|
288
|
+
{todo.state.title} ({todo.done}/{todo.subtaskIds.length})
|
|
289
|
+
</label>
|
|
290
|
+
<button onClick={() => todo.remove()}>×</button>
|
|
291
|
+
</li>
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function TodoList() {
|
|
296
|
+
return useInstanceIds(Todos).map(id => <TodoItem key={id} id={id} />);
|
|
297
|
+
}
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
| Field | Value |
|
|
301
|
+
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
302
|
+
| `state` | the instance or `undefined` |
|
|
303
|
+
| `exists` | whether the instance exists |
|
|
304
|
+
| `id` | the real id, also when an alias was passed |
|
|
305
|
+
| `events.<name>(payload)` | instance events bound to the id and the scope |
|
|
306
|
+
| `update(data)` | a patch or a function, as in `model.update` |
|
|
307
|
+
| `remove()` | deletes the instance |
|
|
308
|
+
| your keys | a relation gives the ids of the children, `childrenOf(relation)` the children, `childrenOf(relation, selector, isEqual?)` a value selected from them |
|
|
309
|
+
|
|
310
|
+
The component rerenders when the instance changes or when a requested value
|
|
311
|
+
changes — an aggregate only when its result does. The actions keep their
|
|
312
|
+
references while the id is the same. Keep the set of keys constant between
|
|
313
|
+
renders, and pass a stable selector to `childrenOf` to avoid re-subscribing.
|
|
314
|
+
|
|
315
|
+
A [union](#relations) takes a reference instead of an id. The result is narrowed
|
|
316
|
+
by `kind` — the state and the events are those of the model of that kind —
|
|
317
|
+
and is `undefined` when there is no such instance:
|
|
318
|
+
|
|
319
|
+
```tsx
|
|
320
|
+
const passenger = useModel(passengers, { kind: 'kid', id });
|
|
321
|
+
|
|
322
|
+
if (passenger?.kind === 'kid') {
|
|
323
|
+
passenger.state.age;
|
|
324
|
+
passenger.events.aged(7);
|
|
325
|
+
passenger.remove();
|
|
326
|
+
}
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
The hooks below are the parts `useModel` is made of. Use them when a
|
|
330
|
+
component needs one thing only — for example `useInstance` with a selector to
|
|
331
|
+
subscribe to a single field.
|
|
332
|
+
|
|
333
|
+
```tsx
|
|
334
|
+
import {
|
|
335
|
+
useInstance,
|
|
336
|
+
useInstanceEvents,
|
|
337
|
+
useInstanceIds,
|
|
338
|
+
} from '@effector-tools/models/react';
|
|
339
|
+
|
|
340
|
+
const Slide = ({ id }: { id: string }) => {
|
|
341
|
+
const title = useInstance(SlideModel, id, slide => slide?.title);
|
|
342
|
+
const { focused } = useInstanceEvents(SlideModel, id);
|
|
343
|
+
// re-renders only when this slide's title changes
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
const Slides = () =>
|
|
347
|
+
useInstanceIds(SlideModel).map(id => <Slide key={id} id={id} />);
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
- `useInstance(model, id)` — instance or `undefined`, `id` may be an alias; `useInstance(model, id, selector, isEqual?)` — selected value. Pass a stable selector to avoid re-subscribing.
|
|
351
|
+
- `useInstanceIds(model)` — re-renders only when the set or order of ids changes.
|
|
352
|
+
- `useInstanceEvents(model, id)` — instance events bound to the id and to the scope from `Provider`.
|
|
353
|
+
- `useChildIds(relation, parentId)` — ids of the children of one parent; re-renders only when their set or order changes.
|
|
354
|
+
- `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.
|
|
355
|
+
- `useResolvedId(model, id)` — the real id for an id that may be an alias. The other hooks resolve aliases themselves; use it when the real id is needed as data, for example as a `key`.
|
|
356
|
+
- `useUnionInstance(union, { kind, id })` — `{ kind, id, state }` or `undefined`; `kind` narrows the type of `state`.
|
|
357
|
+
|
|
358
|
+
## AI agents
|
|
359
|
+
|
|
360
|
+
An [agent skill](https://github.com/Olovyannikov/effector-kit/tree/main/skills/effector-models) and [`llms-full.txt`](https://olovyannikov.github.io/effector-kit/llms-full.txt) teach coding agents the rules of the library. See [Working with AI agents](https://olovyannikov.github.io/effector-kit/guide/agents).
|
|
361
|
+
|
|
362
|
+
## Releasing
|
|
363
|
+
|
|
364
|
+
Bump `version` in `package.json`, describe the changes in `CHANGELOG.md` and merge into `main`. The `package` 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`.
|
|
365
|
+
|
|
366
|
+
While the package is on `0.x`, a breaking change bumps the minor version and everything else bumps the patch.
|
|
367
|
+
|
|
368
|
+
## License
|
|
369
|
+
|
|
370
|
+
MIT. Original work © movpushmov.
|