@olovyannikov/effector-models 0.0.0-stage → 1.0.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/LICENSE +22 -0
- package/README.md +205 -2
- package/dist/index.cjs +340 -0
- package/dist/index.d.cts +2 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +338 -0
- package/dist/index.mjs.map +1 -0
- package/dist/react.cjs +97 -0
- package/dist/react.d.cts +44 -0
- package/dist/react.d.cts.map +1 -0
- package/dist/react.d.mts +44 -0
- package/dist/react.d.mts.map +1 -0
- package/dist/react.mjs +93 -0
- package/dist/react.mjs.map +1 -0
- package/dist/relations-D1pFQ4IC.d.cts +125 -0
- package/dist/relations-D1pFQ4IC.d.cts.map +1 -0
- package/dist/relations-DF1qw49e.d.mts +125 -0
- package/dist/relations-DF1qw49e.d.mts.map +1 -0
- package/package.json +80 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.0.0-alpha.1
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **Relations** between models. A reference is an ordinary field with an id;
|
|
8
|
+
a relation keeps such fields consistent.
|
|
9
|
+
- `child({ parent, model, key })` — children are deleted together with the
|
|
10
|
+
parent and follow its `rename`; `$idsByParent` index.
|
|
11
|
+
- Trees: a model can be a `child` of itself with a nullable key. Deleting a
|
|
12
|
+
node deletes its whole branch.
|
|
13
|
+
- `ref({ from, field, to })` — a field with one id or a list. Deleted
|
|
14
|
+
targets disappear from references, renamed ones are renamed.
|
|
15
|
+
- `union({ ... })` — several models as one collection addressed by
|
|
16
|
+
`{ kind, id }`, with `create`, `upsert` and `delete` routed to the model
|
|
17
|
+
of the kind. `ref` accepts a union as a target.
|
|
18
|
+
- **React hooks**: `useChildIds`, `useChildren` (the children of one parent
|
|
19
|
+
or an aggregate over them) and `useUnionInstance`.
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
- `exports` provide separate type declarations for ESM and CJS consumers.
|
|
24
|
+
- `engines.node` is declared: `>=18`.
|
|
25
|
+
- Peer ranges are bounded: `effector >=23.4.4 <24`,
|
|
26
|
+
`effector-react >=23.3.0 <24`.
|
|
27
|
+
|
|
28
|
+
## 1.0.0-alpha.0
|
|
29
|
+
|
|
30
|
+
Initial release: `model` with immutable instances and synchronous reducers,
|
|
31
|
+
`create` / `upsert` / `update` / `delete` / `rename` / `clear`, the `missed`
|
|
32
|
+
event, and the React hooks `useInstance`, `useInstanceIds`,
|
|
33
|
+
`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,206 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @olovyannikov/effector-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 `$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. Not carried over: aliases (use `rename`) and `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 @olovyannikov/effector-models effector
|
|
27
|
+
# React bindings
|
|
28
|
+
pnpm add effector-react react
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Model
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { model } from '@olovyannikov/effector-models';
|
|
35
|
+
|
|
36
|
+
interface Document {
|
|
37
|
+
documentId: string | null;
|
|
38
|
+
pending: Patch | null;
|
|
39
|
+
failed: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const defaults: Document = { documentId: null, pending: null, failed: false };
|
|
43
|
+
|
|
44
|
+
export const DocumentModel = model({
|
|
45
|
+
name: 'document', // unique: sid of $instances is `effector-models:document`
|
|
46
|
+
defaults,
|
|
47
|
+
events: {
|
|
48
|
+
patched: (doc, patch: Patch) => ({
|
|
49
|
+
...doc,
|
|
50
|
+
pending: merge(doc.pending, patch),
|
|
51
|
+
failed: false,
|
|
52
|
+
}),
|
|
53
|
+
sent: doc => ({ ...doc, pending: null }),
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
A reducer returning the same object means "nothing changed": no store update, no re-render.
|
|
59
|
+
|
|
60
|
+
## API
|
|
61
|
+
|
|
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 |
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
sample({
|
|
77
|
+
clock: saved,
|
|
78
|
+
fn: patch => ({ id: documentId, payload: patch }),
|
|
79
|
+
target: DocumentModel.events.patched,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// same tick: this sample already sees the patched instance
|
|
83
|
+
sample({
|
|
84
|
+
clock: saved,
|
|
85
|
+
source: DocumentModel.$instances,
|
|
86
|
+
fn: instances => instances[documentId]?.pending,
|
|
87
|
+
target: $pending,
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Tests seed instances like any store: `fork({ values: [[DocumentModel.$instances, { a: { ... } }]] })`.
|
|
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
|
+
## React
|
|
179
|
+
|
|
180
|
+
```tsx
|
|
181
|
+
import {
|
|
182
|
+
useInstance,
|
|
183
|
+
useInstanceEvents,
|
|
184
|
+
useInstanceIds,
|
|
185
|
+
} from '@olovyannikov/effector-models/react';
|
|
186
|
+
|
|
187
|
+
const Slide = ({ id }: { id: string }) => {
|
|
188
|
+
const title = useInstance(SlideModel, id, slide => slide?.title);
|
|
189
|
+
const { focused } = useInstanceEvents(SlideModel, id);
|
|
190
|
+
// re-renders only when this slide's title changes
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const Slides = () =>
|
|
194
|
+
useInstanceIds(SlideModel).map(id => <Slide key={id} id={id} />);
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
- `useInstance(model, id)` — instance or `undefined`; `useInstance(model, id, selector, isEqual?)` — selected value. Pass a stable selector to avoid re-subscribing.
|
|
198
|
+
- `useInstanceIds(model)` — re-renders only when the set or order of ids changes.
|
|
199
|
+
- `useInstanceEvents(model, id)` — instance events bound to the id and to the scope from `Provider`.
|
|
200
|
+
- `useChildIds(relation, parentId)` — ids of the children of one parent; re-renders only when their set or order changes.
|
|
201
|
+
- `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.
|
|
202
|
+
- `useUnionInstance(union, { kind, id })` — `{ kind, id, state }` or `undefined`; `kind` narrows the type of `state`.
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
MIT. Original work © movpushmov.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let effector = require("effector");
|
|
3
|
+
// lib/model.ts
|
|
4
|
+
const toList$1 = (ids) => typeof ids === "string" ? [ids] : ids;
|
|
5
|
+
const toArray = (value) => Array.isArray(value) ? value : [value];
|
|
6
|
+
function applyTo(instances, ids, fn) {
|
|
7
|
+
let next = instances;
|
|
8
|
+
const missing = [];
|
|
9
|
+
for (const id of toList$1(ids)) {
|
|
10
|
+
const current = instances[id];
|
|
11
|
+
if (current === void 0) {
|
|
12
|
+
missing.push(id);
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
const updated = fn(current);
|
|
16
|
+
if (updated !== current) {
|
|
17
|
+
if (next === instances) next = { ...instances };
|
|
18
|
+
next[id] = updated;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
instances: next,
|
|
23
|
+
missing
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function model(config) {
|
|
27
|
+
const { name, defaults } = config;
|
|
28
|
+
const reducers = config.events ?? {};
|
|
29
|
+
const $instances = (0, effector.createStore)({}, {
|
|
30
|
+
sid: `effector-models:${name}`,
|
|
31
|
+
name: `${name}/$instances`
|
|
32
|
+
});
|
|
33
|
+
const $ids = $instances.map((instances) => Object.keys(instances));
|
|
34
|
+
const missed = (0, effector.createEvent)({ name: `${name}/missed` });
|
|
35
|
+
const applied = (0, effector.createEvent)();
|
|
36
|
+
(0, effector.sample)({
|
|
37
|
+
clock: applied,
|
|
38
|
+
source: $instances,
|
|
39
|
+
filter: (instances, result) => result.instances !== instances,
|
|
40
|
+
fn: (_, { instances }) => instances,
|
|
41
|
+
target: $instances
|
|
42
|
+
});
|
|
43
|
+
(0, effector.sample)({
|
|
44
|
+
clock: applied,
|
|
45
|
+
filter: ({ missing }) => missing.length > 0,
|
|
46
|
+
fn: ({ action, missing }) => ({
|
|
47
|
+
action,
|
|
48
|
+
ids: missing
|
|
49
|
+
}),
|
|
50
|
+
target: missed
|
|
51
|
+
});
|
|
52
|
+
const create = (0, effector.createEvent)({ name: `${name}/create` });
|
|
53
|
+
(0, effector.sample)({
|
|
54
|
+
clock: create,
|
|
55
|
+
source: $instances,
|
|
56
|
+
fn: (instances, params) => {
|
|
57
|
+
const next = { ...instances };
|
|
58
|
+
for (const { id, data } of toArray(params)) next[id] = {
|
|
59
|
+
...defaults,
|
|
60
|
+
...data
|
|
61
|
+
};
|
|
62
|
+
return next;
|
|
63
|
+
},
|
|
64
|
+
target: $instances
|
|
65
|
+
});
|
|
66
|
+
const upsert = (0, effector.createEvent)({ name: `${name}/upsert` });
|
|
67
|
+
(0, effector.sample)({
|
|
68
|
+
clock: upsert,
|
|
69
|
+
source: $instances,
|
|
70
|
+
fn: (instances, params) => {
|
|
71
|
+
const next = { ...instances };
|
|
72
|
+
for (const { id, data } of toArray(params)) next[id] = {
|
|
73
|
+
...next[id] ?? defaults,
|
|
74
|
+
...data
|
|
75
|
+
};
|
|
76
|
+
return next;
|
|
77
|
+
},
|
|
78
|
+
target: $instances
|
|
79
|
+
});
|
|
80
|
+
const update = (0, effector.createEvent)({ name: `${name}/update` });
|
|
81
|
+
(0, effector.sample)({
|
|
82
|
+
clock: update,
|
|
83
|
+
source: $instances,
|
|
84
|
+
fn: (instances, { id, data }) => ({
|
|
85
|
+
action: "update",
|
|
86
|
+
...applyTo(instances, id, (state) => typeof data === "function" ? data(state) : {
|
|
87
|
+
...state,
|
|
88
|
+
...data
|
|
89
|
+
})
|
|
90
|
+
}),
|
|
91
|
+
target: applied
|
|
92
|
+
});
|
|
93
|
+
const remove = (0, effector.createEvent)({ name: `${name}/delete` });
|
|
94
|
+
(0, effector.sample)({
|
|
95
|
+
clock: remove,
|
|
96
|
+
source: $instances,
|
|
97
|
+
filter: (instances, ids) => toList$1(ids).some((id) => id in instances),
|
|
98
|
+
fn: (instances, ids) => {
|
|
99
|
+
const next = { ...instances };
|
|
100
|
+
for (const id of toList$1(ids)) delete next[id];
|
|
101
|
+
return next;
|
|
102
|
+
},
|
|
103
|
+
target: $instances
|
|
104
|
+
});
|
|
105
|
+
const rename = (0, effector.createEvent)({ name: `${name}/rename` });
|
|
106
|
+
(0, effector.sample)({
|
|
107
|
+
clock: rename,
|
|
108
|
+
source: $instances,
|
|
109
|
+
fn: (instances, { from, to }) => {
|
|
110
|
+
const current = instances[from];
|
|
111
|
+
if (current === void 0) return {
|
|
112
|
+
action: "rename",
|
|
113
|
+
instances,
|
|
114
|
+
missing: [from]
|
|
115
|
+
};
|
|
116
|
+
const next = {
|
|
117
|
+
...instances,
|
|
118
|
+
[to]: current
|
|
119
|
+
};
|
|
120
|
+
delete next[from];
|
|
121
|
+
return {
|
|
122
|
+
action: "rename",
|
|
123
|
+
instances: next,
|
|
124
|
+
missing: []
|
|
125
|
+
};
|
|
126
|
+
},
|
|
127
|
+
target: applied
|
|
128
|
+
});
|
|
129
|
+
const clear = (0, effector.createEvent)({ name: `${name}/clear` });
|
|
130
|
+
(0, effector.sample)({
|
|
131
|
+
clock: clear,
|
|
132
|
+
fn: () => ({}),
|
|
133
|
+
target: $instances
|
|
134
|
+
});
|
|
135
|
+
const events = {};
|
|
136
|
+
for (const [action, reducer] of Object.entries(reducers)) {
|
|
137
|
+
const event = (0, effector.createEvent)({ name: `${name}/${action}` });
|
|
138
|
+
(0, effector.sample)({
|
|
139
|
+
clock: event,
|
|
140
|
+
source: $instances,
|
|
141
|
+
fn: (instances, { id, payload }) => ({
|
|
142
|
+
action,
|
|
143
|
+
...applyTo(instances, id, (state) => reducer(state, payload))
|
|
144
|
+
}),
|
|
145
|
+
target: applied
|
|
146
|
+
});
|
|
147
|
+
events[action] = event;
|
|
148
|
+
}
|
|
149
|
+
return {
|
|
150
|
+
name,
|
|
151
|
+
defaults,
|
|
152
|
+
$instances,
|
|
153
|
+
$ids,
|
|
154
|
+
create,
|
|
155
|
+
upsert,
|
|
156
|
+
update,
|
|
157
|
+
delete: remove,
|
|
158
|
+
rename,
|
|
159
|
+
clear,
|
|
160
|
+
events,
|
|
161
|
+
missed
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
// lib/relations.ts
|
|
165
|
+
const toList = (ids) => typeof ids === "string" ? [ids] : ids;
|
|
166
|
+
/** Несколько моделей как одна коллекция: экземпляр адресуется парой `{ kind, id }`. */ function union(models) {
|
|
167
|
+
const stores = {};
|
|
168
|
+
for (const [kind, member] of Object.entries(models)) stores[kind] = member.$instances;
|
|
169
|
+
const $instances = (0, effector.combine)(stores);
|
|
170
|
+
const remove = (0, effector.createEvent)();
|
|
171
|
+
const create = (0, effector.createEvent)();
|
|
172
|
+
const upsert = (0, effector.createEvent)();
|
|
173
|
+
const paramsOf = (params, kind) => (Array.isArray(params) ? params : [params]).filter((item) => item.kind === kind).map(({ id, data }) => data === void 0 ? { id } : {
|
|
174
|
+
id,
|
|
175
|
+
data
|
|
176
|
+
});
|
|
177
|
+
for (const [kind, member] of Object.entries(models)) {
|
|
178
|
+
(0, effector.sample)({
|
|
179
|
+
clock: create,
|
|
180
|
+
filter: (params) => paramsOf(params, kind).length > 0,
|
|
181
|
+
fn: (params) => paramsOf(params, kind),
|
|
182
|
+
target: member.create
|
|
183
|
+
});
|
|
184
|
+
(0, effector.sample)({
|
|
185
|
+
clock: upsert,
|
|
186
|
+
filter: (params) => paramsOf(params, kind).length > 0,
|
|
187
|
+
fn: (params) => paramsOf(params, kind),
|
|
188
|
+
target: member.upsert
|
|
189
|
+
});
|
|
190
|
+
(0, effector.sample)({
|
|
191
|
+
clock: remove,
|
|
192
|
+
filter: (refs) => (Array.isArray(refs) ? refs : [refs]).some((ref) => ref.kind === kind),
|
|
193
|
+
fn: (refs) => (Array.isArray(refs) ? refs : [refs]).filter((ref) => ref.kind === kind).map((ref) => ref.id),
|
|
194
|
+
target: member.delete
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
"~kind": "union",
|
|
199
|
+
models,
|
|
200
|
+
$instances,
|
|
201
|
+
create,
|
|
202
|
+
upsert,
|
|
203
|
+
delete: remove
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function isUnion(value) {
|
|
207
|
+
return "~kind" in value && value["~kind"] === "union";
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Дочерние экземпляры принадлежат родителю: хранят его id в поле `key`
|
|
211
|
+
* и удаляются вместе с ним. Переименование родителя переносит детей.
|
|
212
|
+
*/ function child(config) {
|
|
213
|
+
const { parent, model, key } = config;
|
|
214
|
+
const parentOf = (state) => state[key];
|
|
215
|
+
const $idsByParent = model.$instances.map((instances) => {
|
|
216
|
+
const index = {};
|
|
217
|
+
for (const [id, state] of Object.entries(instances)) {
|
|
218
|
+
const parentId = parentOf(state);
|
|
219
|
+
if (typeof parentId === "string") (index[parentId] ??= []).push(id);
|
|
220
|
+
}
|
|
221
|
+
return index;
|
|
222
|
+
});
|
|
223
|
+
const childrenOf = (instances, match) => Object.entries(instances).filter(([, state]) => {
|
|
224
|
+
const parentId = parentOf(state);
|
|
225
|
+
return typeof parentId === "string" && match(parentId);
|
|
226
|
+
}).map(([id]) => id);
|
|
227
|
+
const isTree = parent.$instances === model.$instances;
|
|
228
|
+
const descendantsOf = (instances, ids) => {
|
|
229
|
+
const found = /* @__PURE__ */ new Set();
|
|
230
|
+
let level = new Set(ids);
|
|
231
|
+
while (level.size > 0) {
|
|
232
|
+
const next = /* @__PURE__ */ new Set();
|
|
233
|
+
for (const id of childrenOf(instances, (parentId) => level.has(parentId))) if (!found.has(id)) {
|
|
234
|
+
found.add(id);
|
|
235
|
+
next.add(id);
|
|
236
|
+
}
|
|
237
|
+
level = isTree ? next : /* @__PURE__ */ new Set();
|
|
238
|
+
}
|
|
239
|
+
return [...found];
|
|
240
|
+
};
|
|
241
|
+
(0, effector.sample)({
|
|
242
|
+
clock: parent.delete,
|
|
243
|
+
source: model.$instances,
|
|
244
|
+
filter: (instances, ids) => descendantsOf(instances, toList(ids)).length > 0,
|
|
245
|
+
fn: (instances, ids) => descendantsOf(instances, toList(ids)),
|
|
246
|
+
target: model.delete
|
|
247
|
+
});
|
|
248
|
+
if (!isTree) (0, effector.sample)({
|
|
249
|
+
clock: parent.clear,
|
|
250
|
+
source: model.$instances,
|
|
251
|
+
filter: (instances) => childrenOf(instances, () => true).length > 0,
|
|
252
|
+
fn: (instances) => childrenOf(instances, () => true),
|
|
253
|
+
target: model.delete
|
|
254
|
+
});
|
|
255
|
+
(0, effector.sample)({
|
|
256
|
+
clock: parent.rename,
|
|
257
|
+
source: model.$instances,
|
|
258
|
+
filter: (instances, { from }) => childrenOf(instances, (parentId) => parentId === from).length > 0,
|
|
259
|
+
fn: (instances, { from, to }) => ({
|
|
260
|
+
id: childrenOf(instances, (parentId) => parentId === from),
|
|
261
|
+
data: { [key]: to }
|
|
262
|
+
}),
|
|
263
|
+
target: model.update
|
|
264
|
+
});
|
|
265
|
+
return {
|
|
266
|
+
model,
|
|
267
|
+
$idsByParent
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
function modelSignals(target, wrap, read) {
|
|
271
|
+
return {
|
|
272
|
+
removed: (0, effector.merge)([target.delete.map((ids) => {
|
|
273
|
+
const deleted = toList(ids);
|
|
274
|
+
return (item) => {
|
|
275
|
+
const id = read(item);
|
|
276
|
+
return id !== void 0 && deleted.includes(id);
|
|
277
|
+
};
|
|
278
|
+
}), target.clear.map(() => (item) => read(item) !== void 0)]),
|
|
279
|
+
replaced: target.rename.map(({ from, to }) => (item) => read(item) === from ? wrap(to) : item)
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
function targetSignals(target) {
|
|
283
|
+
if (!isUnion(target)) return modelSignals(target, (id) => id, (item) => typeof item === "string" ? item : void 0);
|
|
284
|
+
const members = Object.entries(target.models).map(([kind, member]) => modelSignals(member, (id) => ({
|
|
285
|
+
kind,
|
|
286
|
+
id
|
|
287
|
+
}), (item) => typeof item === "object" && item !== null && item.kind === kind ? item.id : void 0));
|
|
288
|
+
return {
|
|
289
|
+
removed: (0, effector.merge)(members.map((member) => member.removed)),
|
|
290
|
+
replaced: (0, effector.merge)(members.map((member) => member.replaced))
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Ссылка на экземпляры, которые живут в другой модели (или объединении).
|
|
295
|
+
* Поле остаётся обычными данными; связь лишь поддерживает его целостность:
|
|
296
|
+
* удалённые экземпляры пропадают из ссылок, переименованные — переносятся.
|
|
297
|
+
*/ function ref(config) {
|
|
298
|
+
const { from, field } = config;
|
|
299
|
+
const signals = targetSignals(config.to);
|
|
300
|
+
const rewrite = (instances, change) => {
|
|
301
|
+
let next = instances;
|
|
302
|
+
for (const [id, state] of Object.entries(instances)) {
|
|
303
|
+
const current = state[field];
|
|
304
|
+
const updated = change(current);
|
|
305
|
+
if (updated !== current) {
|
|
306
|
+
if (next === instances) next = { ...instances };
|
|
307
|
+
next[id] = {
|
|
308
|
+
...state,
|
|
309
|
+
[field]: updated
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return next;
|
|
314
|
+
};
|
|
315
|
+
(0, effector.sample)({
|
|
316
|
+
clock: signals.removed,
|
|
317
|
+
source: from.$instances,
|
|
318
|
+
fn: (instances, isRemoved) => rewrite(instances, (value) => {
|
|
319
|
+
if (Array.isArray(value)) return value.some(isRemoved) ? value.filter((item) => !isRemoved(item)) : value;
|
|
320
|
+
return value !== null && isRemoved(value) ? null : value;
|
|
321
|
+
}),
|
|
322
|
+
target: from.$instances
|
|
323
|
+
});
|
|
324
|
+
(0, effector.sample)({
|
|
325
|
+
clock: signals.replaced,
|
|
326
|
+
source: from.$instances,
|
|
327
|
+
fn: (instances, replace) => rewrite(instances, (value) => {
|
|
328
|
+
if (Array.isArray(value)) {
|
|
329
|
+
const replaced = value.map(replace);
|
|
330
|
+
return replaced.some((item, index) => item !== value[index]) ? replaced : value;
|
|
331
|
+
}
|
|
332
|
+
return value === null ? value : replace(value);
|
|
333
|
+
}),
|
|
334
|
+
target: from.$instances
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
exports.child = child;
|
|
338
|
+
exports.model = model;
|
|
339
|
+
exports.ref = ref;
|
|
340
|
+
exports.union = union;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { C as UpdateParams, S as RenameParams, _ as Missed, a as Union, b as Reducer, c as UnionModels, d as ref, f as union, g as Instances, h as InstanceEventParams, i as RefConfig, l as UnionRef, m as Ids, n as ChildConfig, o as UnionCreateParams, p as CreateParams, r as ModelLike, s as UnionInstances, t as Child, u as child, v as Model, w as model, x as Reducers, y as ModelConfig } from "./relations-D1pFQ4IC.cjs";
|
|
2
|
+
export { type Child, type ChildConfig, type CreateParams, type Ids, type InstanceEventParams, type Instances, type Missed, type Model, type ModelConfig, type ModelLike, type Reducer, type Reducers, type RefConfig, type RenameParams, type Union, type UnionCreateParams, type UnionInstances, type UnionModels, type UnionRef, type UpdateParams, child, model, ref, union };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { C as UpdateParams, S as RenameParams, _ as Missed, a as Union, b as Reducer, c as UnionModels, d as ref, f as union, g as Instances, h as InstanceEventParams, i as RefConfig, l as UnionRef, m as Ids, n as ChildConfig, o as UnionCreateParams, p as CreateParams, r as ModelLike, s as UnionInstances, t as Child, u as child, v as Model, w as model, x as Reducers, y as ModelConfig } from "./relations-DF1qw49e.mjs";
|
|
2
|
+
export { type Child, type ChildConfig, type CreateParams, type Ids, type InstanceEventParams, type Instances, type Missed, type Model, type ModelConfig, type ModelLike, type Reducer, type Reducers, type RefConfig, type RenameParams, type Union, type UnionCreateParams, type UnionInstances, type UnionModels, type UnionRef, type UpdateParams, child, model, ref, union };
|