@inglorious/store 12.6.2 → 12.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/store.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import { clone } from "@inglorious/utils/data-structures/object.js"
2
- import { toCamelCase } from "@inglorious/utils/data-structures/string.js"
3
- import { create } from "mutative"
2
+ import {
3
+ namesNear,
4
+ toCamelCase,
5
+ } from "@inglorious/utils/data-structures/string.js"
6
+ import { create, current, isDraft, original } from "mutative"
4
7
 
5
8
  import { createApi } from "./api.js"
6
9
  import { augmentEntities, augmentEntity } from "./entities.js"
@@ -8,45 +11,45 @@ import { EventMap, parseEvent } from "./event-map.js"
8
11
  import { applyMiddlewares } from "./middlewares.js"
9
12
  import { augmentType, augmentTypes } from "./types.js"
10
13
 
11
- /** Copies only the entities that change, using a draft proxy. */
14
+ /** Copies only the entities that change, through a draft proxy. */
12
15
  const STRUCTURAL_SHARING = "structural-sharing"
13
16
 
14
- /** Deep-copies each entity as it is handed out, and applies events to the copy, without a proxy. */
17
+ /** Deep-copies each entity as it is handed out, with no proxy. */
15
18
  const COPY_ON_DISPATCH = "copy-on-dispatch"
16
19
 
17
20
  const UPDATE_STRATEGIES = [STRUCTURAL_SHARING, COPY_ON_DISPATCH]
18
21
 
22
+ /** Events every entity gets, whether or not its type answers them. */
23
+ const LIFECYCLE_EVENTS = ["create", "destroy"]
24
+
19
25
  /**
20
26
  * Creates a store to manage state and events.
21
27
  *
22
- * Events are queued and drained by {@link createStore|update}. The `updateStrategy` option
23
- * controls how the state is copied before the queued events are applied:
28
+ * Events are queued and applied one at a time, each in a transaction of its own:
29
+ * the handlers of one event all see the state as it was before that event, through
30
+ * `api.getEntity()` and `api.getEntities()`, and the next event in the queue sees what
31
+ * the previous one changed. Subscribers are notified once the queue is empty.
24
32
  *
25
- * - `"structural-sharing"` (default) - Applies events to a draft proxy, so only the entities
26
- * that actually changed are copied. Unchanged entities keep their previous reference, which
27
- * makes change detection cheap for consumers that rely on reference equality. This is the
28
- * right choice for UI stores, where a small number of entities change at a time.
29
- * - `"copy-on-dispatch"` - Deep-copies each entity the first time it is handed to a handler or read by
30
- * a system, and applies events directly to the copy, without a proxy. Entities nothing touches
31
- * are not copied, and there is no per-entity proxy overhead, so it scales better when
32
- * thousands of entities change every frame, as in a game simulation.
33
+ * The `updateStrategy` option controls how an event's changes are copied:
33
34
  *
34
- * Under both strategies the current state is kept intact while the queued events are applied to a
35
- * separate draft, and the two are swapped only once every event has been processed. Handlers and
36
- * systems therefore always receive the draft as their first argument and mutate it directly, and
37
- * subscribers are notified only after the swap. This also means that, during an update,
38
- * `api.getEntity()` and `api.getEntities()` read the *previous* state rather than the in-flight
39
- * changes, under either strategy.
35
+ * - `"structural-sharing"` (default) - Applies the event to a draft proxy, so only the
36
+ * entities that actually changed are copied. Unchanged entities keep their previous
37
+ * reference, which makes reference-equality change detection cheap. The right choice
38
+ * for UI stores, where a few entities change at a time.
39
+ * - `"copy-on-dispatch"` - Deep-copies each entity the first time the event hands it to a
40
+ * handler or a system, and applies the event to the copy, without a proxy. It scales
41
+ * better when thousands of entities change every frame, as in a game simulation.
40
42
  *
41
43
  * @param {StoreConfig} config - Configuration options for the store.
42
44
  * @param {Types} [config.types] - The initial types configuration.
43
45
  * @param {Entities} [config.entities] - The initial entities configuration.
44
- * @param {Object[]} [config.systems] - The initial systems configuration.
46
+ * @param {Object[]} [config.systems] - Handlers that receive every entity at once, run after the entities' own handlers.
45
47
  * @param {Function[]} [config.middlewares] - Functions that each take the store and return it,
46
48
  * changed or wrapped. The first wraps all the others, so events pass through them in order.
47
- * @param {boolean} [config.autoCreateEntities=false] - Creates entities if not defined in `config.entities`.
49
+ * @param {boolean} [config.autoCreateEntities=false] - Creates an entity for each type that has none.
48
50
  * @param {"auto" | "manual"} [config.updateMode="auto"] - Whether each event triggers an update, or updates are batched until `update()` is called.
49
- * @param {UpdateStrategy} [config.updateStrategy="structural-sharing"] - How the state is copied before events are applied.
51
+ * @param {UpdateStrategy} [config.updateStrategy="structural-sharing"] - How an event's changes are copied.
52
+ * @param {boolean} [config.devMode=false] - Freezes the state after each event under structural sharing, so a write outside a handler throws.
50
53
  * @returns {Store} The store with methods to interact with state and events.
51
54
  * @throws {TypeError} If `updateStrategy` is not a supported strategy.
52
55
  */
@@ -58,14 +61,17 @@ export function createStore({
58
61
  autoCreateEntities = false,
59
62
  updateMode = "auto",
60
63
  updateStrategy = STRUCTURAL_SHARING,
64
+ devMode = false,
61
65
  } = {}) {
62
66
  assertUpdateStrategy(updateStrategy)
63
67
 
64
68
  const listeners = new Set()
69
+ const warned = new Set()
65
70
 
66
71
  const types = augmentTypes(originalTypes)
67
72
 
68
- let state, eventMap, incomingEvents, isProcessing, isHalted
73
+ let state, activeDraft, eventMap, incomingEvents, isProcessing, isNotifying
74
+ let isHalted
69
75
  reset()
70
76
 
71
77
  const baseStore = {
@@ -106,155 +112,123 @@ export function createStore({
106
112
  }
107
113
 
108
114
  /**
109
- * Updates the state based on elapsed time and processes events.
110
- *
111
- * The current state is left untouched while the queued events are applied to a separate
112
- * draft, according to the configured `updateStrategy`. The draft only replaces the current
113
- * state once every queued event has been processed, and subscribers are notified afterwards.
115
+ * Applies the queued events and notifies subscribers once. Each event is a
116
+ * transaction: its handlers see, through the api, the state as the previous
117
+ * event left it, and the next event sees what they changed. An event notified
118
+ * by a subscriber is queued and applied after the subscribers have run, so a
119
+ * render never nests inside another.
114
120
  *
115
121
  * @returns {Event[]} The events processed during this update.
116
122
  */
117
123
  function update() {
118
- if (isProcessing) {
119
- return []
120
- }
121
-
122
- if (!incomingEvents.length) {
124
+ if (isProcessing || !incomingEvents.length) {
123
125
  return []
124
126
  }
125
127
 
126
128
  isProcessing = true
127
129
  const processedEvents = []
128
- let nextState
129
130
 
130
131
  if (updateStrategy === STRUCTURAL_SHARING) {
131
- nextState = create(state, (draft) => patch(writeThrough(draft)), {
132
- enableAutoFreeze: state.game?.devMode,
132
+ state = create(state, (root) => drain(writeThrough(root)), {
133
+ enableAutoFreeze: devMode,
133
134
  })
134
135
  } else {
135
136
  const draft = copyOnDispatch(state)
136
-
137
- patch(draft)
138
- nextState = draft.entities
137
+ drain(draft)
138
+ state = draft.entities
139
139
  }
140
140
 
141
- state = nextState
141
+ activeDraft = null
142
142
  isProcessing = false
143
143
 
144
+ isNotifying = true
144
145
  listeners.forEach((onUpdate) => onUpdate())
146
+ isNotifying = false
147
+
148
+ if (updateMode === "auto" && incomingEvents.length) {
149
+ update()
150
+ }
145
151
 
146
152
  return processedEvents
147
153
 
148
- /**
149
- * Applies every queued event to the given draft.
150
- *
151
- * The draft wraps either the proxy returned by `create` (structural sharing) or a
152
- * copy of the entity map whose entities are copied as they are handed out (copy on
153
- * dispatch). The current state is not modified, and only becomes the new state once
154
- * this function returns.
155
- *
156
- * A change made by a handler is not visible to the next handler in the same pass:
157
- * `getState` still returns the state as it was before the pass began. This is on
158
- * purpose -- every event in the pass sees one consistent world, rather than some
159
- * changes having landed and others not -- and it means a handler that asks what is
160
- * left is asking about the past. Anything reacting to a change should be told the
161
- * change rather than go looking for it.
162
- *
163
- * @param {Draft} draft - The draft to apply the queued events to.
164
- * @returns {void}
165
- */
166
- function patch(draft) {
154
+ function drain(draft) {
155
+ activeDraft = draft
167
156
  while (incomingEvents.length) {
168
157
  const event = incomingEvents.shift()
169
158
  processedEvents.push(event)
159
+ handle(draft, event)
160
+ draft.commit()
161
+ }
162
+ }
163
+ }
170
164
 
171
- if (event.type === "pause") {
172
- isHalted = true
173
- }
174
-
175
- if (event.type === "resume") {
176
- isHalted = false
177
- }
178
-
179
- if (event.type === "add") {
180
- addEntity(draft, event.payload)
181
- }
182
-
183
- if (event.type === "remove") {
184
- removeEntity(draft, event.payload)
185
- }
186
-
187
- if (event.type === "patch") {
188
- patchEntity(draft, event.payload)
189
- }
190
-
191
- if (event.type === "replace") {
192
- replaceEntity(draft, event.payload)
193
- }
194
-
195
- const { event: handlerName } = parseEvent(event.type)
196
-
197
- const entityIds = eventMap.getEntitiesForEvent(event.type)
198
-
199
- // A halted world stops handing out updates, because anything that moves by
200
- // integrating a delta time would otherwise carry on regardless. An entity that
201
- // sets `updatesWhilePaused` is exempt, which is how an overlay, a button or the
202
- // thing that takes the pause back off keeps working while the rest stands still.
203
- //
204
- // It is read off the entity rather than the type so that the type stays an index
205
- // signature of handlers, which is what lets it be called and indexed freely.
206
- const halted = isHalted && handlerName === "update"
207
-
208
- for (const id of entityIds) {
209
- const entity = draft.entities[id]
210
- const type = types[entity.type]
211
-
212
- if (halted && !entity.updatesWhilePaused) continue
165
+ /**
166
+ * Hands one event to the store's own handling, then to the entities that answer
167
+ * it, then to the systems.
168
+ * @param {Draft} draft - The draft to apply the event to.
169
+ * @param {Event} event - The event.
170
+ * @returns {void}
171
+ */
172
+ function handle(draft, event) {
173
+ if (event.type === "pause") isHalted = true
174
+ if (event.type === "resume") isHalted = false
175
+ if (event.type === "add") addEntity(draft, event.payload)
176
+ if (event.type === "remove") removeEntity(event.payload)
177
+ if (event.type === "patch") patchEntity(draft, event.payload)
178
+ if (event.type === "replace") replaceEntity(draft, event.payload)
179
+
180
+ const {
181
+ type: targetType,
182
+ entityId: targetId,
183
+ event: handlerName,
184
+ } = parseEvent(event.type)
185
+ const entityIds = eventMap.getEntitiesForEvent(event.type)
186
+
187
+ if (!entityIds.length) {
188
+ warnIfUnanswered(draft, targetType, targetId, handlerName)
189
+ }
213
190
 
214
- const handle = type[handlerName]
191
+ // A halted world hands out no `update`, so anything that integrates a delta
192
+ // time stops. An entity with `updatesWhilePaused` is exempt. It is read off the
193
+ // entity rather than the type, so that a type stays an index signature of handlers.
194
+ const halted = isHalted && handlerName === "update"
215
195
 
216
- handle?.(draft.take(id), event.payload, api)
217
- }
196
+ for (const id of entityIds) {
197
+ const entity = draft.entities[id]
198
+ if (halted && !entity.updatesWhilePaused) continue
218
199
 
219
- if (event.type.endsWith(":destroy")) {
220
- const [target] = event.type.split(":")
221
- const [, id] = target.split("#")
222
- const entity = draft.entities[id]
223
- if (entity) {
224
- const type = types[entity.type]
225
- const typeName = entity.type
226
- delete draft.entities[id]
227
-
228
- eventMap.removeEntity(id, type, typeName)
229
- }
230
- }
200
+ types[entity.type][handlerName]?.(draft.take(id), event.payload, api)
201
+ }
231
202
 
232
- systems.forEach((system) => {
233
- const handle = system[handlerName]
234
- handle?.(draft.forSystems, event.payload, api)
235
- })
203
+ if (handlerName === "destroy" && targetId) {
204
+ const entity = draft.entities[targetId]
205
+ if (entity) {
206
+ draft.remove(targetId)
207
+ eventMap.removeEntity(targetId, types[entity.type], entity.type)
236
208
  }
237
209
  }
210
+
211
+ systems.forEach((system) => {
212
+ system[handlerName]?.(draft.forSystems, event.payload, api)
213
+ })
238
214
  }
239
215
 
240
216
  /**
241
- * Notifies the store of a new event.
242
- * Supports scoped events:
243
- * - 'submit' - broadcast to all entities with submit handler
244
- * - 'form:submit' - only form entities
245
- * - 'form[loginForm]:submit' - only loginForm entity
217
+ * Notifies the store of a new event. Supports scoped events:
218
+ * - 'submit' - broadcast to all entities with a submit handler
219
+ * - 'Form:submit' - only Form entities
220
+ * - '#loginForm:submit' - only the loginForm entity
246
221
  *
247
- * Two of these are the store's own. 'pause' stops the store handing out 'update'
248
- * events, and 'resume' starts it again, which is how anything that moves by
249
- * integrating a delta time stops without being told about it. A type declares
250
- * `updatesWhilePaused` to keep updating regardless. Both keep dispatching to types
222
+ * `pause` stops the store handing out `update` events and `resume` starts it again;
223
+ * an entity with `updatesWhilePaused` keeps updating. Both still reach the types
224
+ * that handle them.
251
225
  *
252
226
  * @param {string} type - The event type to notify.
253
227
  * @param {any} payload - The event payload. Carries the least that can be had
254
228
  * about what happened.
255
229
  */
256
230
  function notify(type, payload) {
257
- // NOTE: it's important to invoke store.dispatch instead of dispatch, otherwise we cannot override it
231
+ // Through store.dispatch rather than dispatch, so that middlewares see it.
258
232
  store.dispatch({ type, payload })
259
233
  }
260
234
 
@@ -266,14 +240,13 @@ export function createStore({
266
240
  */
267
241
  function dispatch(event) {
268
242
  incomingEvents.push(event)
269
- if (updateMode === "auto") {
243
+ if (updateMode === "auto" && !isNotifying) {
270
244
  update()
271
245
  }
272
246
  }
273
247
 
274
248
  /**
275
249
  * Retrieves the augmented types configuration.
276
- * This includes composed behaviors and event handlers wrapped for immutability.
277
250
  * @returns {Object} The augmented types configuration.
278
251
  */
279
252
  function getTypes() {
@@ -314,12 +287,8 @@ export function createStore({
314
287
  }
315
288
  }
316
289
 
317
- const entityId = toCamelCase(typeName)
318
- if (autoCreateEntities && !state[entityId]) {
319
- notify("add", {
320
- id: entityId,
321
- type: typeName,
322
- })
290
+ if (autoCreateEntities && !hasEntityOfType(typeName)) {
291
+ notify("add", { id: toCamelCase(typeName), type: typeName })
323
292
  }
324
293
 
325
294
  if (oldType) {
@@ -332,32 +301,29 @@ export function createStore({
332
301
  * @returns {Object} The current state.
333
302
  */
334
303
  function getState() {
335
- return state
304
+ return activeDraft ? activeDraft.readAll() : state
336
305
  }
337
306
 
338
307
  /**
339
- * One entity by its id, or `undefined` if there is no such entity.
340
- *
341
- * This is what `api.getEntity` answers with during a handler, exposed here for the
342
- * code that runs outside one: a test looking at a world it is driving, or anything else
343
- * holding the store rather than an event's `api`.
308
+ * One entity by its id, or `undefined` if there is no such entity. During an
309
+ * update, as the previous event left it.
344
310
  *
345
311
  * @param {string} id - The entity's id.
346
- * @returns {Object|undefined} The entity, as the last finished pass left it.
312
+ * @returns {Object|undefined} The entity.
347
313
  */
348
314
  function getEntity(id) {
349
- return state?.[id]
315
+ return activeDraft ? activeDraft.read(id) : state?.[id]
350
316
  }
351
317
 
352
318
  /**
353
- * Sets the entire state of the store.
354
- * This is useful for importing state or setting initial state from a server.
319
+ * Sets the entire state of the store, such as state coming from a server.
320
+ * Entities that are new get `create`, entities that are gone get `destroy`.
355
321
  * @param {Entities} nextState - The new state to set.
356
322
  * @returns {void}
357
323
  */
358
324
  function setState(nextState) {
359
325
  const oldEntities = state ?? {}
360
- let newEntities = augmentEntities(nextState)
326
+ const newEntities = augmentEntities(nextState)
361
327
 
362
328
  const oldEntityIds = new Set(Object.keys(oldEntities))
363
329
  const newEntityIds = new Set(Object.keys(newEntities))
@@ -374,11 +340,13 @@ export function createStore({
374
340
 
375
341
  state = oldEntities
376
342
  eventMap = new EventMap(types, oldEntities)
343
+ activeDraft = null
377
344
  incomingEvents = []
378
345
  isProcessing = false
346
+ isNotifying = false
379
347
 
380
348
  entitiesToDestroy.forEach((id) => {
381
- removeEntity(state, id)
349
+ removeEntity(id)
382
350
  })
383
351
 
384
352
  entitiesToCreate.forEach((id) => {
@@ -399,13 +367,11 @@ export function createStore({
399
367
 
400
368
  if (autoCreateEntities) {
401
369
  for (const typeName of Object.keys(types)) {
402
- const entityId = toCamelCase(typeName)
403
- const hasEntity = Object.values(state).some(
404
- (entity) => entity.type === typeName,
405
- )
406
-
407
- if (!hasEntity) {
408
- addEntity(writeThrough(state), { id: entityId, type: typeName })
370
+ if (!hasEntityOfType(typeName)) {
371
+ addEntity(writeThrough(state), {
372
+ id: toCamelCase(typeName),
373
+ type: typeName,
374
+ })
409
375
  }
410
376
  }
411
377
  }
@@ -429,26 +395,20 @@ export function createStore({
429
395
  function addEntity(draft, payload) {
430
396
  const { id, ...entity } = payload
431
397
  draft.put(id, augmentEntity(id, entity))
432
- const type = types[entity.type]
398
+ warnIfUndeclared(id, entity.type)
433
399
 
434
- eventMap.addEntity(id, type, entity.type)
400
+ eventMap.addEntity(id, types[entity.type], entity.type)
435
401
  incomingEvents.unshift({ type: `#${id}:create` })
436
402
  }
437
403
 
438
404
  /**
439
- * Moves a standing thing onto the handlers of whatever type it now names.
440
- *
441
- * A type is the only thing about a thing that cannot be merged: there is no such thing
442
- * as being half a sort, so naming a different one means taking the thing out of the old
443
- * one's list of entities before putting it in the new one.
444
- *
445
- * @param {Draft} draft - The draft it stands in.
446
- * @param {string} id - The thing being moved.
405
+ * Moves an entity onto the handlers of the type it now names, if it changed.
406
+ * @param {string} id - The entity.
447
407
  * @param {string} previousType - The type it was under.
448
- * @param {string|undefined} type - The type it is under now, if it has named one.
408
+ * @param {string|undefined} type - The type it is under now, if it named one.
449
409
  * @returns {void}
450
410
  */
451
- function moveToType(draft, id, previousType, type) {
411
+ function moveToType(id, previousType, type) {
452
412
  if (!type || type === previousType) return
453
413
 
454
414
  eventMap.removeEntity(id, types[previousType], previousType)
@@ -456,40 +416,29 @@ export function createStore({
456
416
  }
457
417
 
458
418
  /**
459
- * Merges a new configuration into a thing that is already standing.
460
- *
461
- * Only the fields the configuration names are touched, so anything the world has done
462
- * to the thing since it was made survives unless the
463
- * new configuration says otherwise. A field named as `undefined` is set to nothing,
464
- * which is what taking a key off a mapping means.
465
- *
419
+ * Merges a configuration into an existing entity. Only the fields it names
420
+ * change; a field set to `undefined` is cleared.
466
421
  * @param {Draft} draft - The draft to change it in.
467
- * @param {Entity} payload - The thing and the fields to merge into it.
422
+ * @param {Entity} payload - The entity's id and the fields to merge.
468
423
  * @returns {void}
469
424
  */
470
425
  function patchEntity(draft, payload) {
471
426
  const { id, ...config } = payload
472
- // Taken rather than looked at, because the merge keeps whatever the configuration
473
- // does not mention, and what it keeps must not be shared with the previous state.
427
+ // Taken rather than read, so that what the merge keeps is not shared with the
428
+ // previous state.
474
429
  const existing = draft.take(id)
475
430
 
476
431
  if (!existing) return
477
432
 
478
433
  draft.put(id, augmentEntity(id, { ...existing, ...config }))
479
434
 
480
- moveToType(draft, id, existing.type, config.type)
435
+ moveToType(id, existing.type, config.type)
481
436
  }
482
437
 
483
438
  /**
484
- * Installs a new configuration on a standing thing, dropping what it does not mention.
485
- *
486
- * The thing keeps its place in the world and its name; everything else is whatever it
487
- * is told, and anything it is not told is gone. A field set to `undefined` is set to
488
- * nothing here as much as it is in a patch -- the difference between the two is what
489
- * happens to the fields neither mentions.
490
- *
439
+ * Replaces an existing entity with a configuration, dropping what it does not name.
491
440
  * @param {Draft} draft - The draft to change it in.
492
- * @param {Entity} payload - The thing and the fields it is to be.
441
+ * @param {Entity} payload - The entity's id and the fields it is to have.
493
442
  * @returns {void}
494
443
  */
495
444
  function replaceEntity(draft, payload) {
@@ -500,19 +449,94 @@ export function createStore({
500
449
 
501
450
  draft.put(id, augmentEntity(id, config))
502
451
 
503
- moveToType(draft, id, existing.type, config.type)
452
+ moveToType(id, existing.type, config.type)
504
453
  }
505
454
 
506
455
  /**
507
- * Queues the destruction of an entity. The entity is removed by the `#id:destroy` event.
508
- * @param {Draft|Entities} draft - Where it stands. The removal itself is queued, so
509
- * nothing is written to it here.
456
+ * Queues the destruction of an entity: the `#id:destroy` event removes it.
510
457
  * @param {string} id - The id of the entity to remove.
511
458
  * @returns {void}
512
459
  */
513
- function removeEntity(draft, id) {
460
+ function removeEntity(id) {
514
461
  incomingEvents.unshift({ type: `#${id}:destroy` })
515
462
  }
463
+
464
+ function hasEntityOfType(typeName) {
465
+ return Object.values(state).some((entity) => entity.type === typeName)
466
+ }
467
+
468
+ /**
469
+ * Warns once about an entity whose type looks like a misspelling of a declared
470
+ * one. A type with no declared name near it may still be registered later, as
471
+ * a lazily loaded page's is, so nothing is said about it.
472
+ * @param {string} id - The entity.
473
+ * @param {string} typeName - The type it names.
474
+ * @returns {void}
475
+ */
476
+ function warnIfUndeclared(id, typeName) {
477
+ if (types[typeName]) return
478
+
479
+ const near = namesNear(typeName, Object.keys(types))
480
+ if (!near.length) return
481
+
482
+ warnOnce(
483
+ `undeclared:${typeName}`,
484
+ `Entity "${id}" has type "${typeName}", which is not declared: did you mean ${near.map((name) => `"${name}"`).join(" or ")}?`,
485
+ )
486
+ }
487
+
488
+ /**
489
+ * Warns once about a targeted event that nothing answers: an entity whose type
490
+ * has no such handler, or a type name that is not declared. A broadcast that
491
+ * nobody answers is fine, and so is an entity that is gone or whose type is
492
+ * still to come.
493
+ * @param {Draft} draft - The draft the event was applied to.
494
+ * @param {string|null} targetType - The type the event names.
495
+ * @param {string|null} targetId - The entity the event names.
496
+ * @param {string} handlerName - The event.
497
+ * @returns {void}
498
+ */
499
+ function warnIfUnanswered(draft, targetType, targetId, handlerName) {
500
+ if (LIFECYCLE_EVENTS.includes(handlerName)) return
501
+ if (systems.some((system) => system[handlerName])) return
502
+
503
+ if (targetId) {
504
+ const entity = draft.entities[targetId]
505
+ const type = entity && types[entity.type]
506
+ if (!type || type[handlerName]) return
507
+
508
+ warnOnce(
509
+ `${entity.type}:${handlerName}`,
510
+ `"${handlerName}" reached "${targetId}", whose type "${entity.type}" has no such handler.`,
511
+ )
512
+ return
513
+ }
514
+
515
+ if (!targetType) return
516
+
517
+ const type = types[targetType]
518
+ if (!type) {
519
+ const near = namesNear(targetType, Object.keys(types))
520
+ warnOnce(
521
+ `type:${targetType}`,
522
+ `"${targetType}:${handlerName}" names a type that is not declared${near.length ? `: did you mean ${near.map((name) => `"${name}"`).join(" or ")}?` : "."}`,
523
+ )
524
+ return
525
+ }
526
+
527
+ if (type[handlerName]) return
528
+
529
+ warnOnce(
530
+ `${targetType}:${handlerName}`,
531
+ `"${targetType}:${handlerName}" reached no entity: the type has no such handler.`,
532
+ )
533
+ }
534
+
535
+ function warnOnce(key, message) {
536
+ if (warned.has(key)) return
537
+ warned.add(key)
538
+ console.warn(`[store] ${message}`)
539
+ }
516
540
  }
517
541
 
518
542
  /**
@@ -532,64 +556,102 @@ export function defineType() {
532
556
  }
533
557
 
534
558
  /**
535
- * A draft that writes straight into the entities it is given.
536
- *
537
- * This is the whole of structural sharing's draft, because Mutative's proxy already copies
538
- * an entity the moment it is written to, and of the state being built by `setState`,
539
- * which has no previous state to protect.
559
+ * A draft over Mutative's proxy, which copies an entity the moment it is written
560
+ * to. What an event reads through the api is what stood before the event: an
561
+ * entity no earlier event of the pass wrote to is read from the original state,
562
+ * and the value of one that an earlier event wrote to is kept when this event
563
+ * writes to it again.
540
564
  *
541
565
  * @param {Entities} entities - The entities to write into.
542
566
  * @returns {Draft} The draft.
543
567
  */
544
568
  function writeThrough(entities) {
569
+ const base = isDraft(entities) ? original(entities) : entities
570
+ const writtenEarlier = new Set()
571
+ const before = new Map()
572
+ let all = null
573
+
574
+ function remember(id) {
575
+ if (before.has(id)) return
576
+ before.set(id, writtenEarlier.has(id) ? plain(entities[id]) : base[id])
577
+ }
578
+
545
579
  return {
546
580
  entities,
547
581
  forSystems: entities,
548
- take: (id) => entities[id],
582
+ take(id) {
583
+ remember(id)
584
+ return entities[id]
585
+ },
549
586
  put(id, entity) {
587
+ remember(id)
550
588
  entities[id] = entity
551
589
  },
590
+ remove(id) {
591
+ remember(id)
592
+ delete entities[id]
593
+ },
594
+ read(id) {
595
+ if (before.has(id)) return before.get(id)
596
+ return writtenEarlier.has(id) ? plain(entities[id]) : base[id]
597
+ },
598
+ readAll() {
599
+ if (!all) {
600
+ all = { ...base }
601
+ for (const id of writtenEarlier) {
602
+ if (Object.hasOwn(entities, id)) all[id] = plain(entities[id])
603
+ else delete all[id]
604
+ }
605
+ all = overlay(all, before)
606
+ }
607
+ return all
608
+ },
609
+ commit() {
610
+ for (const id of before.keys()) writtenEarlier.add(id)
611
+ before.clear()
612
+ all = null
613
+ },
552
614
  }
553
615
  }
554
616
 
555
617
  /**
556
- * A draft that copies an entity the first time it is handed to anything that could
557
- * write to it.
558
- *
559
- * This is what `copy-on-dispatch` is named after: an entity is copied when an event is
560
- * dispatched to it, and the entities that nothing touches are never paid for. The map is
561
- * copied straight away, which is cheap -- a reference for every entity -- and an entity
562
- * is deep-copied only when it is taken: handed to one of its handlers, merged by a
563
- * `patch`, or read by a system. A frame on which only the pointer moves copies the
564
- * pointer, and a frame on which nothing at all happens copies nothing but the map.
565
- *
566
- * There is no proxy on the entities themselves, which is what still sets this apart
567
- * from structural sharing: a handler is given a plain object, and pays nothing for
568
- * writing to it however many times it does. The one proxy is over the map handed to
569
- * systems, which have no single entity to be given and so have to be given all of them.
570
- * Each entity a system reads through it is taken, which means a system that walks every
571
- * entity copies every entity: one that only needs to know how things stood can ask
572
- * `api.getEntities()` instead, and take only what it writes to.
618
+ * A draft that copies an entity the first time an event hands it to anything
619
+ * that could write to it: one of its handlers, a `patch`, or a system. The map
620
+ * is copied once, which costs a reference per entity, and the entities nothing
621
+ * touches are never copied. The copy an earlier event made is what a later
622
+ * event reads, and is copied again if that event writes to it. A system that
623
+ * only reads should go through `api.getEntities()`, since each entity it reads
624
+ * through its first argument is copied.
573
625
  *
574
626
  * @param {Entities} state - The state to leave as it is.
575
627
  * @returns {Draft} The draft.
576
628
  */
577
629
  function copyOnDispatch(state) {
578
630
  const entities = { ...state }
579
- const taken = new Set()
631
+ const before = new Map()
632
+ let all = null
633
+
634
+ function remember(id) {
635
+ if (!before.has(id)) before.set(id, entities[id])
636
+ }
580
637
 
581
638
  function take(id) {
582
- if (!taken.has(id) && Object.hasOwn(entities, id)) {
639
+ if (!before.has(id) && Object.hasOwn(entities, id)) {
640
+ before.set(id, entities[id])
583
641
  entities[id] = clone(entities[id])
584
- taken.add(id)
585
642
  }
586
643
 
587
644
  return entities[id]
588
645
  }
589
646
 
590
647
  function put(id, entity) {
648
+ remember(id)
591
649
  entities[id] = entity
592
- taken.add(id)
650
+ }
651
+
652
+ function remove(id) {
653
+ remember(id)
654
+ delete entities[id]
593
655
  }
594
656
 
595
657
  const forSystems = new Proxy(entities, {
@@ -603,9 +665,55 @@ function copyOnDispatch(state) {
603
665
  put(key, value)
604
666
  return true
605
667
  },
668
+
669
+ deleteProperty(target, key) {
670
+ remove(key)
671
+ return true
672
+ },
606
673
  })
607
674
 
608
- return { entities, forSystems, take, put }
675
+ return {
676
+ entities,
677
+ forSystems,
678
+ take,
679
+ put,
680
+ remove,
681
+ read(id) {
682
+ return before.has(id) ? before.get(id) : entities[id]
683
+ },
684
+ readAll() {
685
+ all ??= overlay(entities, before)
686
+ return all
687
+ },
688
+ commit() {
689
+ before.clear()
690
+ all = null
691
+ },
692
+ }
693
+ }
694
+
695
+ /**
696
+ * The value of a draft as it stands, or the value itself if it is not a draft.
697
+ * @param {any} value - A draft or a plain value.
698
+ * @returns {any} A plain value.
699
+ */
700
+ function plain(value) {
701
+ return isDraft(value) ? current(value) : value
702
+ }
703
+
704
+ /**
705
+ * The entities with the values kept from before the event put back.
706
+ * @param {Entities} entities - The entities as they stand.
707
+ * @param {Map<string, Entity|undefined>} before - The values from before the event.
708
+ * @returns {Entities} The entities as they stood before the event.
709
+ */
710
+ function overlay(entities, before) {
711
+ const all = { ...entities }
712
+ for (const [id, entity] of before) {
713
+ if (entity === undefined) delete all[id]
714
+ else all[id] = entity
715
+ }
716
+ return all
609
717
  }
610
718
 
611
719
  /**
@@ -625,17 +733,22 @@ function assertUpdateStrategy(updateStrategy) {
625
733
  }
626
734
 
627
735
  /**
628
- * @typedef {"structural-sharing" | "copy-on-dispatch"} UpdateStrategy - How the state is copied before events are applied.
736
+ * @typedef {"structural-sharing" | "copy-on-dispatch"} UpdateStrategy - How an event's changes are copied.
629
737
  * @typedef {Object} StoreConfig - Configuration options accepted by {@link createStore}.
630
738
  * @typedef {Object.<string, any>} Type - An augmented entity type.
631
739
  * @typedef {Object.<string, Type>} Types - A collection of augmented types.
632
740
  * @typedef {Object.<string, any>} Entity - An object representing an entity.
633
741
  * @typedef {Object.<string, Entity>} Entities - A collection of entities indexed by id.
634
- * @typedef {Object} Draft - The entities an update writes to, and how it gets at them.
742
+ * @typedef {{ type: string, payload?: any }} Event - An event.
743
+ * @typedef {Object} Draft - The entities an event writes to, and how it gets at them.
635
744
  * @property {Entities} Draft.entities - The entities being built, read without copying.
636
745
  * @property {Entities} Draft.forSystems - The entities as handed to systems.
637
746
  * @property {(id: string) => Entity|undefined} Draft.take - The entity to write to.
638
747
  * @property {(id: string, entity: Entity) => void} Draft.put - Sets an entity outright.
748
+ * @property {(id: string) => void} Draft.remove - Deletes an entity.
749
+ * @property {(id: string) => Entity|undefined} Draft.read - An entity as it stood before the event.
750
+ * @property {() => Entities} Draft.readAll - The entities as they stood before the event.
751
+ * @property {() => void} Draft.commit - Ends the event: what it changed is what the next one reads.
639
752
  * @typedef {(listener: () => void) => () => void} Listener - Subscribes to state updates and returns an unsubscribe function.
640
753
  * @typedef {Object} Store - The store returned by {@link createStore}.
641
754
  */