@inglorious/ssx 0.1.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/LICENSE +9 -0
- package/README.md +883 -0
- package/package.json +60 -0
- package/src/__snapshots__/html.test.js.snap +193 -0
- package/src/html.js +39 -0
- package/src/html.test.js +375 -0
package/README.md
ADDED
|
@@ -0,0 +1,883 @@
|
|
|
1
|
+
# Inglorious Store
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@inglorious/store)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
|
|
6
|
+
A Redux-compatible, ECS-inspired state library that makes state management as elegant as game logic.
|
|
7
|
+
|
|
8
|
+
**Drop-in replacement for Redux.** Works with `react-redux` and Redux DevTools. Borrows concepts from Entity-Component-System architectures and Functional Programming to provide an environment where you can write simple, predictable, and testable code.
|
|
9
|
+
|
|
10
|
+
```javascript
|
|
11
|
+
// from redux
|
|
12
|
+
import { createStore } from "redux"
|
|
13
|
+
// to
|
|
14
|
+
import { createStore } from "@inglorious/store"
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Why Inglorious Store?
|
|
20
|
+
|
|
21
|
+
Redux is powerful but verbose. You need action creators, reducers, middleware for async operations, and a bunch of decisions about where logic should live. Redux Toolkit cuts the boilerplate, but you're still writing a lot of ceremony.
|
|
22
|
+
|
|
23
|
+
Inglorious Store eliminates the boilerplate entirely with an **entity-based architecture** inspired by game engines. Some of the patterns that power AAA games now power your state management.
|
|
24
|
+
|
|
25
|
+
Game engines solved state complexity years ago — Inglorious Store brings those lessons to web development.
|
|
26
|
+
|
|
27
|
+
**Key benefits:**
|
|
28
|
+
|
|
29
|
+
- ✅ Drop-in Redux replacement (same API with `react-redux`)
|
|
30
|
+
- ✅ Entity-based state (manage multiple instances effortlessly)
|
|
31
|
+
- ✅ No action creators, thunks, or slices
|
|
32
|
+
- ✅ Predictable, testable, purely functional code
|
|
33
|
+
- ✅ Built-in lifecycle events (`add`, `remove`, `morph`)
|
|
34
|
+
- ✅ 10x faster immutability than Redux Toolkit (Mutative vs Immer)
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Quick Comparison: Redux vs RTK vs Inglorious Store
|
|
39
|
+
|
|
40
|
+
### Redux
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
43
|
+
// Action creators
|
|
44
|
+
const addTodo = (text) => ({ type: "ADD_TODO", payload: text })
|
|
45
|
+
|
|
46
|
+
// Reducer
|
|
47
|
+
const todosReducer = (state = [], action) => {
|
|
48
|
+
switch (action.type) {
|
|
49
|
+
case "ADD_TODO":
|
|
50
|
+
return [...state, { id: Date.now(), text: action.payload }]
|
|
51
|
+
|
|
52
|
+
case "OTHER_ACTION":
|
|
53
|
+
// Handle other action
|
|
54
|
+
|
|
55
|
+
default:
|
|
56
|
+
return state
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Store setup
|
|
61
|
+
const store = configureStore({
|
|
62
|
+
reducer: {
|
|
63
|
+
work: todosReducer,
|
|
64
|
+
personal: todosReducer,
|
|
65
|
+
},
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
store.dispatch({ type: "ADD_TODO", payload: "Buy groceries" })
|
|
69
|
+
store.dispatch({ type: "OTHER_ACTION" })
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Redux Toolkit
|
|
73
|
+
|
|
74
|
+
```javascript
|
|
75
|
+
const otherAction = createAction("app:otherAction")
|
|
76
|
+
|
|
77
|
+
const todosSlice = createSlice({
|
|
78
|
+
name: "todos",
|
|
79
|
+
initialState: [],
|
|
80
|
+
reducers: {
|
|
81
|
+
addTodo: (state, action) => {
|
|
82
|
+
state.push({ id: Date.now(), text: action.payload })
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
extraReducers: (builder) => {
|
|
86
|
+
builder.addCase(otherAction, (state, action) => {
|
|
87
|
+
// Handle external action
|
|
88
|
+
})
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
const store = configureStore({
|
|
93
|
+
reducer: {
|
|
94
|
+
work: todosSlice.reducer,
|
|
95
|
+
personal: todosSlice.reducer,
|
|
96
|
+
},
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
store.dispatch(slice.actions.addTodo("Buy groceries"))
|
|
100
|
+
store.dispatch(otherAction())
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Inglorious Store
|
|
104
|
+
|
|
105
|
+
```javascript
|
|
106
|
+
// Define entity types and their behavior
|
|
107
|
+
const types = {
|
|
108
|
+
todoList: {
|
|
109
|
+
addTodo(entity, text) {
|
|
110
|
+
entity.todos.push({ id: Date.now(), text })
|
|
111
|
+
},
|
|
112
|
+
|
|
113
|
+
otherAction(entity) {
|
|
114
|
+
// Handle other action
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Define initial entities
|
|
120
|
+
const entities = {
|
|
121
|
+
work: { type: "todoList", todos: [] },
|
|
122
|
+
personal: { type: "todoList", todos: [] },
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Create store
|
|
126
|
+
const store = createStore({ types, entities })
|
|
127
|
+
|
|
128
|
+
store.dispatch({ type: "addTodo", payload: "Buy groceries" })
|
|
129
|
+
store.dispatch({ type: "otherAction" })
|
|
130
|
+
|
|
131
|
+
// or, even better:
|
|
132
|
+
store.notify("addTodo", "Buy groceries")
|
|
133
|
+
store.notify("otherAction")
|
|
134
|
+
|
|
135
|
+
// same result, 10x simpler
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
**Key differences:**
|
|
139
|
+
|
|
140
|
+
- ❌ No action creators
|
|
141
|
+
- ❌ No switch statements or cases
|
|
142
|
+
- ❌ No slice definitions with extraReducers
|
|
143
|
+
- ✅ Define what each entity type can do
|
|
144
|
+
- ✅ Add multiple instances by adding entities, not code
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## Core Concepts
|
|
149
|
+
|
|
150
|
+
### 🎮 Entities and Types
|
|
151
|
+
|
|
152
|
+
State consists of **entities** (instances) that have a **type** (behavior definition). Think of a type as a class and entities as instances:
|
|
153
|
+
|
|
154
|
+
```javascript
|
|
155
|
+
const types = {
|
|
156
|
+
todoList: {
|
|
157
|
+
addTodo(entity, text) {
|
|
158
|
+
entity.todos.push({ id: Date.now(), text })
|
|
159
|
+
},
|
|
160
|
+
toggle(entity, id) {
|
|
161
|
+
const todo = entity.todos.find((t) => t.id === id)
|
|
162
|
+
if (todo) todo.completed = !todo.completed
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
settings: {
|
|
167
|
+
setTheme(entity, theme) {
|
|
168
|
+
entity.theme = theme
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const entities = {
|
|
174
|
+
workTodos: { type: "todoList", todos: [], priority: "high" },
|
|
175
|
+
personalTodos: { type: "todoList", todos: [], priority: "low" },
|
|
176
|
+
settings: { type: "settings", theme: "dark", language: "en" },
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
**Why this matters:**
|
|
181
|
+
|
|
182
|
+
- Same behavior applies to all instances of that type
|
|
183
|
+
- No need to write separate code for each instance
|
|
184
|
+
- Your mental model matches your code structure
|
|
185
|
+
|
|
186
|
+
### 🔄 Event Handlers (Not Methods)
|
|
187
|
+
|
|
188
|
+
Even though it looks like types expose methods, they are actually **event handlers**, very similar to Redux reducers. There are a few differences though:
|
|
189
|
+
|
|
190
|
+
1. Just like RTK reducers, you can mutate the entity directly since event handlers are using an immutability library under the hood. Not Immer, but Mutative — which claims to be 10x faster than Immer.
|
|
191
|
+
|
|
192
|
+
```javascript
|
|
193
|
+
const types = {
|
|
194
|
+
counter: {
|
|
195
|
+
increment(counter) {
|
|
196
|
+
counter.value++ // Looks like mutation, immutable in reality
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
2. Event handlers accept as arguments the current entity, the event payload, and an API object that exposes a few convenient methods:
|
|
203
|
+
|
|
204
|
+
```javascript
|
|
205
|
+
const types = {
|
|
206
|
+
counter: {
|
|
207
|
+
increment(counter, value, api) {
|
|
208
|
+
api.getEntities() // access the whole state in read-only mode
|
|
209
|
+
api.getEntity(id) // access some other entity in read-only mode
|
|
210
|
+
api.notify(type, payload) // similar to dispatch. Yes, you can dispatch inside of a reducer!
|
|
211
|
+
api.dispatch(action) // optional, if you prefer Redux-style dispatching
|
|
212
|
+
},
|
|
213
|
+
},
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
---
|
|
218
|
+
|
|
219
|
+
## Installation & Setup
|
|
220
|
+
|
|
221
|
+
The Inglorious store, just like Redux, can be used standalone. However, it's commonly used together with component libraries such as React.
|
|
222
|
+
|
|
223
|
+
### Basic Setup with `react-redux`
|
|
224
|
+
|
|
225
|
+
```javascript
|
|
226
|
+
import { createStore } from "@inglorious/store"
|
|
227
|
+
import { Provider, useSelector, useDispatch } from "react-redux"
|
|
228
|
+
|
|
229
|
+
// 1. Define entity types
|
|
230
|
+
const types = {
|
|
231
|
+
counter: {
|
|
232
|
+
increment(counter) {
|
|
233
|
+
counter.value++
|
|
234
|
+
},
|
|
235
|
+
decrement(counter) {
|
|
236
|
+
counter.value--
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// 2. Define initial entities
|
|
242
|
+
const entities = {
|
|
243
|
+
counter1: { type: "counter", value: 0 },
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// 3. Create the store
|
|
247
|
+
const store = createStore({ types, entities })
|
|
248
|
+
|
|
249
|
+
// 4. Provide the store with react-redux
|
|
250
|
+
function App() {
|
|
251
|
+
return (
|
|
252
|
+
<Provider store={store}>
|
|
253
|
+
<Counter />
|
|
254
|
+
</Provider>
|
|
255
|
+
)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// 5. Wire components to the store
|
|
259
|
+
function Counter() {
|
|
260
|
+
const dispatch = useDispatch()
|
|
261
|
+
const count = useSelector((state) => state.counter1.value)
|
|
262
|
+
|
|
263
|
+
return (
|
|
264
|
+
<div>
|
|
265
|
+
<p>{count}</p>
|
|
266
|
+
<button onClick={() => dispatch({ type: "increment" })}>+</button>
|
|
267
|
+
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
|
|
268
|
+
</div>
|
|
269
|
+
)
|
|
270
|
+
}
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
### With `@inglorious/react-store` (Recommended)
|
|
274
|
+
|
|
275
|
+
For React applications, `@inglorious/react-store` provides a set of hooks and a Provider that are tightly integrated with the store. It's a lightweight wrapper around `react-redux` that offers a more ergonomic API.
|
|
276
|
+
|
|
277
|
+
```javascript
|
|
278
|
+
import { createStore } from "@inglorious/store"
|
|
279
|
+
import { createReactStore } from "@inglorious/react-store"
|
|
280
|
+
|
|
281
|
+
const store = createStore({ types, entities })
|
|
282
|
+
|
|
283
|
+
export const { Provider, useSelector, useNotify } = createReactStore(store)
|
|
284
|
+
|
|
285
|
+
function App() {
|
|
286
|
+
return (
|
|
287
|
+
// No store prop needed!
|
|
288
|
+
<Provider>
|
|
289
|
+
<Counter />
|
|
290
|
+
</Provider>
|
|
291
|
+
)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function Counter() {
|
|
295
|
+
const notify = useNotify() // less verbose than dispatch
|
|
296
|
+
const count = useSelector((state) => state.counter1.value)
|
|
297
|
+
|
|
298
|
+
return (
|
|
299
|
+
<div>
|
|
300
|
+
<p>{count}</p>
|
|
301
|
+
<button onClick={() => notify("increment")}>+</button> // simplified
|
|
302
|
+
syntax
|
|
303
|
+
<button onClick={() => notify("decrement")}>-</button>
|
|
304
|
+
</div>
|
|
305
|
+
)
|
|
306
|
+
}
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
The package is fully typed, providing a great developer experience with TypeScript.
|
|
310
|
+
|
|
311
|
+
---
|
|
312
|
+
|
|
313
|
+
## Core Features
|
|
314
|
+
|
|
315
|
+
### 🎮 Entity-Based State
|
|
316
|
+
|
|
317
|
+
The real power: add entities dynamically without code changes.
|
|
318
|
+
|
|
319
|
+
**Redux/RTK:** To manage three counters, you can reuse a reducer. But what if you want to add a new counter at runtime? Your best option is probably to reshape the whole state.
|
|
320
|
+
|
|
321
|
+
```javascript
|
|
322
|
+
// The original list of counters:
|
|
323
|
+
const store = configureStore({
|
|
324
|
+
reducer: {
|
|
325
|
+
counter1: counterReducer,
|
|
326
|
+
counter2: counterReducer,
|
|
327
|
+
counter3: counterReducer,
|
|
328
|
+
},
|
|
329
|
+
})
|
|
330
|
+
|
|
331
|
+
// becomes:
|
|
332
|
+
const store = configureStore({
|
|
333
|
+
reducer: {
|
|
334
|
+
counters: countersReducer,
|
|
335
|
+
},
|
|
336
|
+
})
|
|
337
|
+
|
|
338
|
+
// with extra actions to manage adding/removing counters:
|
|
339
|
+
store.dispatch({ type: "addCounter", payload: "counter4" })
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
**Inglorious Store** makes it trivial:
|
|
343
|
+
|
|
344
|
+
```javascript
|
|
345
|
+
const types = {
|
|
346
|
+
counter: {
|
|
347
|
+
increment(entity) {
|
|
348
|
+
entity.value++
|
|
349
|
+
},
|
|
350
|
+
},
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const entities = {
|
|
354
|
+
counter1: { type: "counter", value: 0 },
|
|
355
|
+
counter2: { type: "counter", value: 0 },
|
|
356
|
+
counter3: { type: "counter", value: 0 },
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
store.notify("add", { id: "counter4", type: "counter", value: 0 })
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
Inglorious Store has a few built-in events that you can use:
|
|
363
|
+
|
|
364
|
+
- `add`: adds a new entity to the state. Triggers a `create` lifecycle event.
|
|
365
|
+
- `remove`: removes an entity from the state. Triggers a `destroy` lifecycle event.
|
|
366
|
+
- `morph`: changes the behavior of a type (advanced, used by middlewares/rendering systems)
|
|
367
|
+
|
|
368
|
+
The lifecycle events can be used to define event handlers similar to constructor and destructor methods in OOP:
|
|
369
|
+
|
|
370
|
+
> Remember: events are broadcast to all entities, just like with reducers! Each handler decides if it should respond. More on that in the section below.
|
|
371
|
+
|
|
372
|
+
```javascript
|
|
373
|
+
const types = {
|
|
374
|
+
counter: {
|
|
375
|
+
create(entity, id) {
|
|
376
|
+
if (entity.id !== id) return // "are you talking to me?"
|
|
377
|
+
entity.createdAt = Date.now()
|
|
378
|
+
},
|
|
379
|
+
|
|
380
|
+
destroy(entity, id) {
|
|
381
|
+
if (entity.id !== id) return // "are you talking to me?"
|
|
382
|
+
entity.destroyedAt = Date.now()
|
|
383
|
+
},
|
|
384
|
+
},
|
|
385
|
+
}
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
### 🔊 Event Broadcasting
|
|
389
|
+
|
|
390
|
+
Events are broadcast to all entities via pub/sub. Every entity handler receives every event of that type, just like it does in Redux.
|
|
391
|
+
|
|
392
|
+
```javascript
|
|
393
|
+
const types = {
|
|
394
|
+
todoList: {
|
|
395
|
+
taskCompleted(entity, taskId) {
|
|
396
|
+
const task = entity.tasks.find((t) => t.id === taskId)
|
|
397
|
+
if (task) task.completed = true
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
stats: {
|
|
401
|
+
taskCompleted(entity, taskId) {
|
|
402
|
+
entity.completedCount++
|
|
403
|
+
},
|
|
404
|
+
},
|
|
405
|
+
notifications: {
|
|
406
|
+
taskCompleted(entity, taskId) {
|
|
407
|
+
entity.messages.push("Nice! Task completed.")
|
|
408
|
+
},
|
|
409
|
+
},
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// One notify call, all three entity types respond
|
|
413
|
+
store.notify("taskCompleted", "task123")
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
In RTK, such action would have be to be defined outside of the slice with `createAction` and then processed with the builder callback notation inside of the `extraReducers` section.
|
|
417
|
+
|
|
418
|
+
- What if you want to notify the event only to entities of one specific type? Define an event handler for that event only on that type.
|
|
419
|
+
- What if you want to notify the event only on one entity of that type? Add an if that checks if the entity should be bothered or not by it.
|
|
420
|
+
|
|
421
|
+
```javascript
|
|
422
|
+
const types = {
|
|
423
|
+
todoList: {
|
|
424
|
+
toggle(entity, id) {
|
|
425
|
+
// This runs for EVERY todoList entity, but only acts if it's the right one
|
|
426
|
+
if (entity.id !== id) return
|
|
427
|
+
|
|
428
|
+
const todo = entity.todos.find((t) => t.id === id)
|
|
429
|
+
if (todo) todo.completed = !todo.completed
|
|
430
|
+
},
|
|
431
|
+
},
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// Broadcast to all todo lists
|
|
435
|
+
store.notify("toggle", "todo1")
|
|
436
|
+
// Each list's toggle handler runs; only the one with todo1 actually updates
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
### ⚡ Async Operations
|
|
440
|
+
|
|
441
|
+
In **Redux/RTK**, logic should be written inside pure functions as much as possible — specifically in reducers, not action creators. But what if I need to access some other part of the state that is not visible to the reducer? What if I need to combine async behavior with sync behavior? This is where the choice of "where does my logic live?" matters.
|
|
442
|
+
|
|
443
|
+
In **Inglorious Store:** your event handlers can be async, and you get deterministic behavior automatically. Inside an async handler, you can access other parts of state (read-only), and you can trigger other events via `api.notify()`. Even if we give up on some purity, everything still maintains predictability because of the underlying **event queue**:
|
|
444
|
+
|
|
445
|
+
```javascript
|
|
446
|
+
const types = {
|
|
447
|
+
todoList: {
|
|
448
|
+
async loadTodos(entity, payload, api) {
|
|
449
|
+
try {
|
|
450
|
+
entity.loading = true
|
|
451
|
+
const { name } = api.getEntity("user")
|
|
452
|
+
const response = await fetch(`/api/todos/${name}`)
|
|
453
|
+
const data = await response.json()
|
|
454
|
+
api.notify("todosLoaded", todos)
|
|
455
|
+
} catch (error) {
|
|
456
|
+
api.notify("loadFailed", error.message)
|
|
457
|
+
}
|
|
458
|
+
},
|
|
459
|
+
|
|
460
|
+
todosLoaded(entity, todos) {
|
|
461
|
+
entity.todos = todos
|
|
462
|
+
entity.loading = false
|
|
463
|
+
},
|
|
464
|
+
|
|
465
|
+
loadFailed(entity, error) {
|
|
466
|
+
entity.error = error
|
|
467
|
+
entity.loading = false
|
|
468
|
+
},
|
|
469
|
+
},
|
|
470
|
+
}
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
Notice: you don't need pending/fulfilled/rejected actions. You stay in control of the flow — no hidden action chains. The `api` object passed to handlers provides:
|
|
474
|
+
|
|
475
|
+
- **`api.getEntities()`** - read entire state
|
|
476
|
+
- **`api.getEntity(id)`** - read one entity
|
|
477
|
+
- **`api.notify(type, payload)`** - trigger other events (queued, not immediate)
|
|
478
|
+
- **`api.dispatch(action)`** - optional, if you prefer Redux-style dispatching
|
|
479
|
+
- **`api.getTypes()`** - access type definitions (mainly for middleware/plugins)
|
|
480
|
+
- **`api.getType(typeName)`** - access type definition (mainly for overrides)
|
|
481
|
+
|
|
482
|
+
All events triggered via `api.notify()` enter the queue and process together, maintaining predictability and testability.
|
|
483
|
+
|
|
484
|
+
### 🧪 Testing
|
|
485
|
+
|
|
486
|
+
Event handlers are pure functions (or can be treated as such), making them easy to test in isolation, much like Redux reducers. The `@inglorious/store/test` module provides utility functions to make this even simpler.
|
|
487
|
+
|
|
488
|
+
#### `trigger(entity, handler, payload, api?)`
|
|
489
|
+
|
|
490
|
+
The `trigger` function executes an event handler on a single entity and returns the new state and any events that were dispatched.
|
|
491
|
+
|
|
492
|
+
```javascript
|
|
493
|
+
import { trigger } from "@inglorious/store/test"
|
|
494
|
+
|
|
495
|
+
// Define your entity handler
|
|
496
|
+
function increment(entity, payload, api) {
|
|
497
|
+
entity.value += payload.amount
|
|
498
|
+
if (entity.value > 100) {
|
|
499
|
+
api.notify("overflow", { id: entity.id })
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// Test it
|
|
504
|
+
const { entity, events } = trigger(
|
|
505
|
+
{ type: "counter", id: "counter1", value: 99 },
|
|
506
|
+
increment,
|
|
507
|
+
{ amount: 5 },
|
|
508
|
+
)
|
|
509
|
+
|
|
510
|
+
expect(entity.value).toBe(104)
|
|
511
|
+
expect(events).toEqual([{ type: "overflow", payload: { id: "counter1" } }])
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
#### `createMockApi(entities)`
|
|
515
|
+
|
|
516
|
+
If your handler needs to interact with other entities via the `api`, you can create a mock API. This is useful for testing handlers that read from other parts of the state.
|
|
517
|
+
|
|
518
|
+
```javascript
|
|
519
|
+
import { createMockApi, trigger } from "@inglorious/store/test"
|
|
520
|
+
|
|
521
|
+
// Create a mock API with some initial entities
|
|
522
|
+
const api = createMockApi({
|
|
523
|
+
counter1: { type: "counter", value: 10 },
|
|
524
|
+
counter2: { type: "counter", value: 20 },
|
|
525
|
+
})
|
|
526
|
+
|
|
527
|
+
// A handler that copies a value from another entity
|
|
528
|
+
function copyValue(entity, payload, api) {
|
|
529
|
+
const source = api.getEntity(payload.sourceId)
|
|
530
|
+
entity.value = source.value
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// Trigger the handler with the custom mock API
|
|
534
|
+
const { entity } = trigger(
|
|
535
|
+
{ type: "counter", id: "counter2", value: 20 },
|
|
536
|
+
copyValue,
|
|
537
|
+
{ sourceId: "counter1" },
|
|
538
|
+
api,
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
expect(entity.value).toBe(10)
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
The mock API provides:
|
|
545
|
+
|
|
546
|
+
- `getEntities()`: Returns all entities (frozen).
|
|
547
|
+
- `getEntity(id)`: Returns a specific entity by ID (frozen).
|
|
548
|
+
- `dispatch(event)`: Records an event for later assertions.
|
|
549
|
+
- `notify(type, payload)`: A convenience wrapper around `dispatch`.
|
|
550
|
+
- `getEvents()`: Returns all events that were dispatched.
|
|
551
|
+
|
|
552
|
+
### 🌍 Systems for Global Logic
|
|
553
|
+
|
|
554
|
+
When you need to coordinate updates across multiple entities (not just respond to individual events), use systems. Systems run after all entity handlers for the same event, ensuring global consistency, and have write access to the entire state. This concept is the 'S' in the ECS Architecture (Entity-Component-System)!
|
|
555
|
+
|
|
556
|
+
```javascript
|
|
557
|
+
const systems = [
|
|
558
|
+
{
|
|
559
|
+
taskCompleted(state, taskId) {
|
|
560
|
+
// Read from multiple todo lists
|
|
561
|
+
const allTodos = Object.values(state)
|
|
562
|
+
.filter((e) => e.type === "todoList")
|
|
563
|
+
.flatMap((e) => e.todos)
|
|
564
|
+
|
|
565
|
+
// Update global stats
|
|
566
|
+
state.stats.total = allTodos.length
|
|
567
|
+
state.stats.completed = allTodos.filter((t) => t.completed).length
|
|
568
|
+
},
|
|
569
|
+
},
|
|
570
|
+
]
|
|
571
|
+
|
|
572
|
+
const store = createStore({ types, entities, systems })
|
|
573
|
+
```
|
|
574
|
+
|
|
575
|
+
Systems receive the entire state and can modify any entity. They're useful for cross-cutting concerns, maintaining derived state, or coordinating complex state updates that can't be expressed as individual entity handlers.
|
|
576
|
+
|
|
577
|
+
### 🔗 Behavior Composition
|
|
578
|
+
|
|
579
|
+
A type can be a single behavior object, or an array of behaviors.
|
|
580
|
+
|
|
581
|
+
```javascript
|
|
582
|
+
// single-behavior type
|
|
583
|
+
const counter = {
|
|
584
|
+
increment(entity) {
|
|
585
|
+
entity.value++
|
|
586
|
+
},
|
|
587
|
+
|
|
588
|
+
decrement(entity) {
|
|
589
|
+
entity.value--
|
|
590
|
+
},
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// multiple behavior type
|
|
594
|
+
const resettableCounter = [
|
|
595
|
+
counter,
|
|
596
|
+
{
|
|
597
|
+
reset(entity) {
|
|
598
|
+
entity.value = 0
|
|
599
|
+
},
|
|
600
|
+
},
|
|
601
|
+
]
|
|
602
|
+
```
|
|
603
|
+
|
|
604
|
+
A behavior is defined as either an object with event handlers, or a function that takes a type and returns an enhanced behavior (decorator pattern):
|
|
605
|
+
|
|
606
|
+
```javascript
|
|
607
|
+
// Base behavior
|
|
608
|
+
const resettable = {
|
|
609
|
+
submit(entity, value) {
|
|
610
|
+
entity.value = ""
|
|
611
|
+
},
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// Function that wraps and enhances a behavior
|
|
615
|
+
const validated = (type) => ({
|
|
616
|
+
submit(entity, value, api) {
|
|
617
|
+
if (!value.trim()) return
|
|
618
|
+
type.submit?.(entity, value, api) // remember to always pass all args!
|
|
619
|
+
},
|
|
620
|
+
})
|
|
621
|
+
|
|
622
|
+
// Another wrapper
|
|
623
|
+
const withLoading = (type) => ({
|
|
624
|
+
submit(entity, value, api) {
|
|
625
|
+
entity.loading = true
|
|
626
|
+
type.submit?.(entity, value, api)
|
|
627
|
+
entity.loading = false
|
|
628
|
+
},
|
|
629
|
+
})
|
|
630
|
+
|
|
631
|
+
// Compose them together to form a type
|
|
632
|
+
const form = [resettable, validated, withLoading]
|
|
633
|
+
```
|
|
634
|
+
|
|
635
|
+
When multiple behaviors define the same event, they all run in order. This allows you to build middleware-like patterns: validation, logging, error handling, loading states, etc.
|
|
636
|
+
|
|
637
|
+
### ⏱️ Batched Mode
|
|
638
|
+
|
|
639
|
+
The Inglorious Store features an **event queue**. In the default `auto` update mode, each notified event will trigger and update of the state (same as Redux). But in `manual` update mode, you can process multiple events together before re-rendering:
|
|
640
|
+
|
|
641
|
+
```javascript
|
|
642
|
+
const store = createStore({ types, entities, updateMode: "manual" })
|
|
643
|
+
|
|
644
|
+
// add events to the event queue
|
|
645
|
+
store.notify("playerMoved", { x: 100, y: 50 })
|
|
646
|
+
store.notify("enemyAttacked", { damage: 10 })
|
|
647
|
+
store.notify("particleCreated", { type: "explosion" })
|
|
648
|
+
|
|
649
|
+
// process them all in batch
|
|
650
|
+
store.update()
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
Instead of re-rendering after each event, you can batch them and re-render once. This is what powers high-performance game engines and smooth animations.
|
|
654
|
+
|
|
655
|
+
---
|
|
656
|
+
|
|
657
|
+
## Comparison with Other State Libraries
|
|
658
|
+
|
|
659
|
+
| Feature | Redux | RTK | Zustand | Jotai | Pinia | MobX | Inglorious Store |
|
|
660
|
+
| ------------------------- | ------------ | ------------ | ---------- | ---------- | ---------- | ---------- | ---------------- |
|
|
661
|
+
| **Boilerplate** | 🔴 High | 🟡 Medium | 🟢 Low | 🟢 Low | 🟡 Medium | 🟢 Low | 🟢 Low |
|
|
662
|
+
| **Multiple instances** | 🔴 Manual | 🔴 Manual | 🔴 Manual | 🔴 Manual | 🟡 Medium | 🟡 Medium | 🟢 Built-in |
|
|
663
|
+
| **Lifecycle events** | 🔴 No | 🔴 No | 🔴 No | 🔴 No | 🔴 No | 🔴 No | 🟢 Yes |
|
|
664
|
+
| **Async logic placement** | 🟡 Thunks | 🟡 Complex | 🟢 Free | 🟢 Free | 🟢 Free | 🟢 Free | 🟢 In handlers |
|
|
665
|
+
| **Redux DevTools** | 🟢 Yes | 🟢 Yes | 🟡 Partial | 🟡 Partial | 🟡 Partial | 🟢 Yes | 🟢 Yes |
|
|
666
|
+
| **Time-travel debugging** | 🟢 Yes | 🟢 Yes | 🔴 No | 🔴 No | 🔴 No | 🟡 Limited | 🟢 Yes |
|
|
667
|
+
| **Testability** | 🟢 Excellent | 🟢 Excellent | 🟡 Good | 🟡 Good | 🟡 Good | 🟡 Medium | 🟢 Excellent |
|
|
668
|
+
| **Immutability** | 🔴 Manual | 🟢 Immer | 🔴 Manual | 🔴 Manual | 🔴 Manual | 🔴 Manual | 🟢 Mutative |
|
|
669
|
+
|
|
670
|
+
---
|
|
671
|
+
|
|
672
|
+
## API Reference
|
|
673
|
+
|
|
674
|
+
### `createStore(options)`
|
|
675
|
+
|
|
676
|
+
```javascript
|
|
677
|
+
const store = createStore({
|
|
678
|
+
types, // Object: entity type definitions
|
|
679
|
+
entities, // Object: initial entities
|
|
680
|
+
systems, // Array (optional): global state handlers
|
|
681
|
+
updateMode, // String (optional): 'auto' (default) or 'manual'
|
|
682
|
+
})
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
**Returns:** A Redux-compatible store
|
|
686
|
+
|
|
687
|
+
### Types Definition
|
|
688
|
+
|
|
689
|
+
```javascript
|
|
690
|
+
const types = {
|
|
691
|
+
entityType: [
|
|
692
|
+
// Behavior objects
|
|
693
|
+
{
|
|
694
|
+
eventName(entity, payload, api) {
|
|
695
|
+
entity.value = payload
|
|
696
|
+
api.notify("otherEvent", data)
|
|
697
|
+
},
|
|
698
|
+
},
|
|
699
|
+
// Behavior functions (decorators)
|
|
700
|
+
(behavior) => ({
|
|
701
|
+
eventName(entity, payload, api) {
|
|
702
|
+
// Wrap the behavior
|
|
703
|
+
behavior.eventName?.(entity, payload, api)
|
|
704
|
+
},
|
|
705
|
+
}),
|
|
706
|
+
],
|
|
707
|
+
}
|
|
708
|
+
```
|
|
709
|
+
|
|
710
|
+
### Event Handler API
|
|
711
|
+
|
|
712
|
+
Each handler receives three arguments:
|
|
713
|
+
|
|
714
|
+
- **`entity`** - the entity instance (mutate freely, immutability guaranteed)
|
|
715
|
+
- **`payload`** - data passed with the event
|
|
716
|
+
- **`api`** - access to store methods:
|
|
717
|
+
- `getEntities()` - entire state (read-only)
|
|
718
|
+
- `getEntity(id)` - single entity (read-only)
|
|
719
|
+
- `notify(type, payload)` - trigger other events
|
|
720
|
+
- `dispatch(action)` - optional, if you prefer Redux-style dispatching
|
|
721
|
+
- `getTypes()` - type definitions (for middleware)
|
|
722
|
+
- `getType(typeName)` - type definition (for overriding)
|
|
723
|
+
|
|
724
|
+
### Built-in Lifecycle Events
|
|
725
|
+
|
|
726
|
+
- **`create(entity, id)`** - triggered when entity added via `add` event
|
|
727
|
+
- **`destroy(entity, id)`** - triggered when entity removed via `remove` event
|
|
728
|
+
- **`morph(entity, newType)`** - triggered when entity type changes
|
|
729
|
+
|
|
730
|
+
### Notify vs Dispatch
|
|
731
|
+
|
|
732
|
+
Both work (`dispatch` is provided just for Redux compatibility), but `notify` is cleaner (and uses `dispatch` internally):
|
|
733
|
+
|
|
734
|
+
```javascript
|
|
735
|
+
store.notify("eventName", payload)
|
|
736
|
+
store.dispatch({ type: "eventName", payload }) // Redux-compatible alternative
|
|
737
|
+
```
|
|
738
|
+
|
|
739
|
+
### 🧩 Type Safety
|
|
740
|
+
|
|
741
|
+
Inglorious Store is written in JavaScript but comes with powerful TypeScript support out of the box, allowing for a fully type-safe experience similar to Redux Toolkit, but with less boilerplate.
|
|
742
|
+
|
|
743
|
+
You can achieve strong type safety by defining an interface for your `types` configuration. This allows you to statically define the shape of your entity handlers, ensuring that all required handlers are present and correctly typed.
|
|
744
|
+
|
|
745
|
+
Here’s how you can set it up for a TodoMVC-style application:
|
|
746
|
+
|
|
747
|
+
**1. Define Your Types**
|
|
748
|
+
|
|
749
|
+
First, create an interface that describes your entire `types` configuration. This interface will enforce the structure of your event handlers.
|
|
750
|
+
|
|
751
|
+
```typescript
|
|
752
|
+
// src/store/types.ts
|
|
753
|
+
import type {
|
|
754
|
+
FormEntity,
|
|
755
|
+
ListEntity,
|
|
756
|
+
FooterEntity,
|
|
757
|
+
// ... other payload types
|
|
758
|
+
} from "../../types"
|
|
759
|
+
|
|
760
|
+
// Define the static shape of the types configuration
|
|
761
|
+
interface TodoListTypes {
|
|
762
|
+
form: {
|
|
763
|
+
inputChange: (entity: FormEntity, value: string) => void
|
|
764
|
+
formSubmit: (entity: FormEntity) => void
|
|
765
|
+
}
|
|
766
|
+
list: {
|
|
767
|
+
formSubmit: (entity: ListEntity, value: string) => void
|
|
768
|
+
toggleClick: (entity: ListEntity, id: number) => void
|
|
769
|
+
// ... other handlers
|
|
770
|
+
}
|
|
771
|
+
footer: {
|
|
772
|
+
filterClick: (entity: FooterEntity, id: string) => void
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
export const types: TodoListTypes = {
|
|
777
|
+
form: {
|
|
778
|
+
inputChange(entity, value) {
|
|
779
|
+
entity.value = value
|
|
780
|
+
},
|
|
781
|
+
formSubmit(entity) {
|
|
782
|
+
entity.value = ""
|
|
783
|
+
},
|
|
784
|
+
},
|
|
785
|
+
// ... other type implementations
|
|
786
|
+
}
|
|
787
|
+
```
|
|
788
|
+
|
|
789
|
+
With `TodoListTypes`, TypeScript will throw an error if you forget a handler (e.g., `formSubmit`) or if its signature is incorrect.
|
|
790
|
+
|
|
791
|
+
**2. Create the Store**
|
|
792
|
+
|
|
793
|
+
When creating your store, you'll pass the `types` object. To satisfy the store's generic `TypesConfig`, you may need to use a double cast (`as unknown as`). This is a safe and intentional way to bridge your specific, statically-checked configuration with the store's more generic type.
|
|
794
|
+
|
|
795
|
+
```typescript
|
|
796
|
+
// src/store/index.ts
|
|
797
|
+
import { createStore, type TypesConfig } from "@inglorious/store"
|
|
798
|
+
import { types } from "./types"
|
|
799
|
+
import type { TodoListEntity, TodoListState } from "../../types"
|
|
800
|
+
|
|
801
|
+
export const store = createStore<TodoListEntity, TodoListState>({
|
|
802
|
+
types: types as unknown as TypesConfig<TodoListEntity>,
|
|
803
|
+
// ... other store config
|
|
804
|
+
})
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
**3. Enjoy Full Type Safety**
|
|
808
|
+
|
|
809
|
+
Now, your store is fully type-safe. The hooks provided by `@inglorious/react-store` will also be correctly typed.
|
|
810
|
+
|
|
811
|
+
---
|
|
812
|
+
|
|
813
|
+
## Use Cases
|
|
814
|
+
|
|
815
|
+
### Perfect For
|
|
816
|
+
|
|
817
|
+
- 🎮 Apps with multiple instances of the same entity type
|
|
818
|
+
- 🎯 Real-time collaborative features
|
|
819
|
+
- ⚡ Complex state coordination and async operations
|
|
820
|
+
- 📊 High-frequency updates (animations, games)
|
|
821
|
+
- 🔄 Undo/redo, time-travel debugging
|
|
822
|
+
|
|
823
|
+
### Still Great For
|
|
824
|
+
|
|
825
|
+
- Any Redux use case (true drop-in replacement)
|
|
826
|
+
- Migration path from Redux (keep using react-redux)
|
|
827
|
+
|
|
828
|
+
---
|
|
829
|
+
|
|
830
|
+
### Demos
|
|
831
|
+
|
|
832
|
+
Check out the following demos to see the Inglorious Store in action on real-case scenarios:
|
|
833
|
+
|
|
834
|
+
**React Examples:**
|
|
835
|
+
|
|
836
|
+
- **[React TodoMVC](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/react-todomvc)** - An (ugly) clone of Kent Dodds' [TodoMVC](https://todomvc.com/) experiments, showing the full compatibility with react-redux and The Redux DevTools.
|
|
837
|
+
- **[React TodoMVC-CS](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/react-todomvc-cs)** - A client-server version of the TodoMVC, which showcases the use of `notify` as a cleaner alternative to `dispatch` and async event handlers.
|
|
838
|
+
- **[React TodoMVC-RT](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/react-todomvc-rt)** - A "multiplayer" version, in which multiple clients are able to synchronize through a real-time server.
|
|
839
|
+
- **[React TodoMVC-TS](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/react-todomvc-ts)** - A typesafe version of the base TodoMVC.
|
|
840
|
+
|
|
841
|
+
For more demos and examples with `@inglorious/web`, see the [`@inglorious/web` README](../web/README.md).
|
|
842
|
+
|
|
843
|
+
---
|
|
844
|
+
|
|
845
|
+
## Frequently Unsolicited Complaints (FUCs)
|
|
846
|
+
|
|
847
|
+
It's hard to accept the new, especially on Reddit. Here are the main objections to the Inglorious Store.
|
|
848
|
+
|
|
849
|
+
**"This is not ECS."**
|
|
850
|
+
|
|
851
|
+
It's not. The Inglorious Store is _inspired_ by ECS, but doesn't strictly follow ECS. Heck, not even the major game engines out there follow ECS by the book!
|
|
852
|
+
|
|
853
|
+
Let's compare the two:
|
|
854
|
+
|
|
855
|
+
| ECS Architecture | Inglorious Store |
|
|
856
|
+
| ------------------------------------- | -------------------------------------- |
|
|
857
|
+
| Entities are ids | Entities have an id |
|
|
858
|
+
| Components are pure, consecutive data | Entities are pure bags of related data |
|
|
859
|
+
| Data and behavior are separated | Data and behavior are separated |
|
|
860
|
+
| Systems operate on the whole state | Systems operate on the whole state |
|
|
861
|
+
| Usually written in an OOP environment | Written in an FP environment |
|
|
862
|
+
|
|
863
|
+
**"This is not FP."**
|
|
864
|
+
|
|
865
|
+
It looks like it's not, and that's a feature. If you're used to classes and instances, the Inglorious Store will feel natural to you. Even behavior composition looks like inheritance, but it's actually function composition. The same [Three Principles](https://redux.js.org/understanding/thinking-in-redux/three-principles) that describe Redux are applied here (with some degree of freedom on function purity).
|
|
866
|
+
|
|
867
|
+
**"This is not Data-Oriented Design."**
|
|
868
|
+
|
|
869
|
+
It's not. Please grep this README and count how many occurrences of DoD you can find. This is not [Data-Oriented Design](https://en.wikipedia.org/wiki/Data-oriented_design), which is related to low-level CPU cache optimization. It's more similar to [Data-Driven Programming](https://en.wikipedia.org/wiki/Data-driven_programming), which is related to separating data and behavior. The Inglorious Store separates behavior in... behaviors (grouped into so-called types), while the data is stored in plain objects called entities.
|
|
870
|
+
|
|
871
|
+
---
|
|
872
|
+
|
|
873
|
+
## License
|
|
874
|
+
|
|
875
|
+
MIT © [Matteo Antony Mistretta](https://github.com/IngloriousCoderz)
|
|
876
|
+
|
|
877
|
+
Free to use, modify, and distribute.
|
|
878
|
+
|
|
879
|
+
---
|
|
880
|
+
|
|
881
|
+
## Contributing
|
|
882
|
+
|
|
883
|
+
Contributions welcome! Please read our [Contributing Guidelines](../../CONTRIBUTING.md) first.
|