Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * Reactive simple state manager.
18
 *
19
 * The state manager contains the state data, trigger update events and
20
 * can lock and unlock the state data.
21
 *
22
 * This file contains the three main elements of the state manager:
23
 * - State manager: the public class to alter the state, dispatch events and process update messages.
24
 * - Proxy handler: a private class to keep track of the state object changes.
25
 * - StateMap class: a private class extending Map class that triggers event when a state list is modifed.
26
 *
27
 * @module     core/local/reactive/statemanager
28
 * @class      StateManager
29
 * @copyright  2021 Ferran Recio <ferran@moodle.com>
30
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31
 */
32
 
33
import Logger from 'core/local/reactive/logger';
34
 
35
/**
36
 * State manager class.
37
 *
38
 * This class handle the reactive state and ensure only valid mutations can modify the state.
39
 * It also provide methods to apply batch state update messages (see processUpdates function doc
40
 * for more details on update messages).
41
 *
42
 * Implementing a deep state manager is complex and will require many frontend resources. To keep
43
 * the state fast and simple, the state can ONLY store two kind of data:
44
 *  - Object with attributes
45
 *  - Sets of objects with id attributes.
46
 *
47
 * This is an example of a valid state:
48
 *
49
 * {
50
 *  course: {
51
 *      name: 'course name',
52
 *      shortname: 'courseshort',
53
 *      sectionlist: [21, 34]
54
 *  },
55
 *  sections: [
56
 *      {id: 21, name: 'Topic 1', visible: true},
57
 *      {id: 34, name: 'Topic 2', visible: false,
58
 *  ],
59
 * }
60
 *
61
 * The following cases are NOT allowed at a state ROOT level (throws an exception if they are assigned):
62
 *  - Simple values (strings, boolean...).
63
 *  - Arrays of simple values.
64
 *  - Array of objects without ID attribute (all arrays will be converted to maps and requires an ID).
65
 *
66
 * Thanks to those limitations it can simplify the state update messages and the event names. If You
67
 * need to store simple data, just group them in an object.
68
 *
69
 * To grant any state change triggers the proper events, the class uses two private structures:
70
 * - proxy handler: any object stored in the state is proxied using this class.
71
 * - StateMap class: any object set in the state will be converted to StateMap using the
72
 *   objects id attribute.
73
 */
74
export default class StateManager {
75
 
76
    /**
77
     * Create a basic reactive state store.
78
     *
79
     * The state manager is meant to work with native JS events. To ensure each reactive module can use
80
     * it in its own way, the parent element must provide a valid event dispatcher function and an optional
81
     * DOM element to anchor the event.
82
     *
83
     * @param {function} dispatchEvent the function to dispatch the custom event when the state changes.
84
     * @param {element} target the state changed custom event target (document if none provided)
85
     */
86
    constructor(dispatchEvent, target) {
87
 
88
        // The dispatch event function.
89
        /** @package */
90
        this.dispatchEvent = dispatchEvent;
91
 
92
        // The DOM container to trigger events.
93
        /** @package */
94
        this.target = target ?? document;
95
 
96
        // State can be altered freely until initial state is set.
97
        /** @package */
98
        this.readonly = false;
99
 
100
        // List of state changes pending to be published as events.
101
        /** @package */
102
        this.eventsToPublish = [];
103
 
104
        // The update state types functions.
105
        /** @package */
106
        this.updateTypes = {
107
            "create": this.defaultCreate.bind(this),
108
            "update": this.defaultUpdate.bind(this),
109
            "delete": this.defaultDelete.bind(this),
110
            "put": this.defaultPut.bind(this),
111
            "override": this.defaultOverride.bind(this),
112
            "remove": this.defaultRemove.bind(this),
113
            "prepareFields": this.defaultPrepareFields.bind(this),
114
        };
115
 
116
        // The state_loaded event is special because it only happens one but all components
117
        // may react to that state, even if they are registered after the setIinitialState.
118
        // For these reason we use a promise for that event.
119
        this.initialPromise = new Promise((resolve) => {
120
            const initialStateDone = (event) => {
121
                resolve(event.detail.state);
122
            };
123
            this.target.addEventListener('state:loaded', initialStateDone);
124
        });
125
 
126
        this.logger = new Logger();
127
    }
128
 
129
    /**
130
     * Loads the initial state.
131
     *
132
     * Note this method will trigger a state changed event with "state:loaded" actionname.
133
     *
134
     * The state mode will be set to read only when the initial state is loaded.
135
     *
136
     * @param {object} initialState
137
     */
138
    setInitialState(initialState) {
139
 
140
        if (this.state !== undefined) {
141
            throw Error('Initial state can only be initialized ones');
142
        }
143
 
144
        // Create the state object.
145
        const state = new Proxy({}, new Handler('state', this, true));
146
        for (const [prop, propValue] of Object.entries(initialState)) {
147
            state[prop] = propValue;
148
        }
149
        this.state = state;
150
 
151
        // When the state is loaded we can lock it to prevent illegal changes.
152
        this.readonly = true;
153
 
154
        this.dispatchEvent({
155
            action: 'state:loaded',
156
            state: this.state,
157
        }, this.target);
158
    }
159
 
160
    /**
161
     * Generate a promise that will be resolved when the initial state is loaded.
162
     *
163
     * In most cases the final state will be loaded using an ajax call. This is the reason
164
     * why states manager are created unlocked and won't be reactive until the initial state is set.
165
     *
166
     * @return {Promise} the resulting promise
167
     */
168
    getInitialPromise() {
169
        return this.initialPromise;
170
    }
171
 
172
    /**
173
     * Locks or unlocks the state to prevent illegal updates.
174
     *
175
     * Mutations use this method to modify the state. Once the state is updated, they must
176
     * block again the state.
177
     *
178
     * All changes done while the state is writable will be registered using registerStateAction.
179
     * When the state is set again to read only the method will trigger _publishEvents to communicate
180
     * changes to all watchers.
181
     *
182
     * @param {bool} readonly if the state is in read only mode enabled
183
     */
184
    setReadOnly(readonly) {
185
 
186
        this.readonly = readonly;
187
 
188
        let mode = 'off';
189
 
190
        // When the state is in readonly again is time to publish all pending events.
191
        if (this.readonly) {
192
            mode = 'on';
193
            this._publishEvents();
194
        }
195
 
196
        // Dispatch a read only event.
197
        this.dispatchEvent({
198
            action: `readmode:${mode}`,
199
            state: this.state,
200
            element: null,
201
        }, this.target);
202
    }
203
 
204
    /**
205
     * Add methods to process update state messages.
206
     *
207
     * The state manager provide a default update, create and delete methods. However,
208
     * some applications may require to override the default methods or even add new ones
209
     * like "refresh" or "error".
210
     *
211
     * @param {Object} newFunctions the new update types functions.
212
     */
213
    addUpdateTypes(newFunctions) {
214
        for (const [updateType, updateFunction] of Object.entries(newFunctions)) {
215
            if (typeof updateFunction === 'function') {
216
                this.updateTypes[updateType] = updateFunction.bind(newFunctions);
217
            }
218
        }
219
    }
220
 
221
    /**
222
     * Process a state updates array and do all the necessary changes.
223
     *
224
     * Note this method unlocks the state while it is executing and relocks it
225
     * when finishes.
226
     *
227
     * @param {array} updates
228
     * @param {Object} updateTypes optional functions to override the default update types.
229
     */
230
    processUpdates(updates, updateTypes) {
231
        if (!Array.isArray(updates)) {
232
            throw Error('State updates must be an array');
233
        }
234
        this.setReadOnly(false);
235
        updates.forEach((update) => {
236
            if (update.name === undefined) {
237
                throw Error('Missing state update name');
238
            }
239
            this.processUpdate(
240
                update.name,
241
                update.action,
242
                update.fields,
243
                updateTypes
244
            );
245
        });
246
        this.setReadOnly(true);
247
    }
248
 
249
    /**
250
     * Process a single state update.
251
     *
252
     * Note this method will not lock or unlock the state by itself.
253
     *
254
     * @param {string} updateName the state element to update
255
     * @param {string} action to action to perform
256
     * @param {object} fields the new data
257
     * @param {Object} updateTypes optional functions to override the default update types.
258
     */
259
    processUpdate(updateName, action, fields, updateTypes) {
260
 
261
        if (!fields) {
262
            throw Error('Missing state update fields');
263
        }
264
 
265
        if (updateTypes === undefined) {
266
            updateTypes = {};
267
        }
268
 
269
        action = action ?? 'update';
270
 
271
        const method = updateTypes[action] ?? this.updateTypes[action];
272
 
273
        if (method === undefined) {
274
            throw Error(`Unkown update action ${action}`);
275
        }
276
 
277
        // Some state data may require some cooking before sending to the
278
        // state. Reactive instances can overrdide the default fieldDefaults
279
        // method to add extra logic to all updates.
280
        const prepareFields = updateTypes.prepareFields ?? this.updateTypes.prepareFields;
281
 
282
        method(this, updateName, prepareFields(this, updateName, fields));
283
    }
284
 
285
    /**
286
     * Prepare fields for processing.
287
     *
288
     * This method is used to add default values or calculations from the frontend side.
289
     *
290
     * @param {Object} stateManager the state manager
291
     * @param {String} updateName the state element to update
292
     * @param {Object} fields the new data
293
     * @returns {Object} final fields data
294
     */
295
    defaultPrepareFields(stateManager, updateName, fields) {
296
        return fields;
297
    }
298
 
299
 
300
    /**
301
     * Process a create state message.
302
     *
303
     * @param {Object} stateManager the state manager
304
     * @param {String} updateName the state element to update
305
     * @param {Object} fields the new data
306
     */
307
    defaultCreate(stateManager, updateName, fields) {
308
 
309
        let state = stateManager.state;
310
 
311
        // Create can be applied only to lists, not to objects.
312
        if (state[updateName] instanceof StateMap) {
313
            state[updateName].add(fields);
314
            return;
315
        }
316
        state[updateName] = fields;
317
    }
318
 
319
    /**
320
     * Process a delete state message.
321
     *
322
     * @param {Object} stateManager the state manager
323
     * @param {String} updateName the state element to update
324
     * @param {Object} fields the new data
325
     */
326
    defaultDelete(stateManager, updateName, fields) {
327
 
328
        // Get the current value.
329
        let current = stateManager.get(updateName, fields.id);
330
        if (!current) {
331
            throw Error(`Inexistent ${updateName} ${fields.id}`);
332
        }
333
 
334
        // Process deletion.
335
        let state = stateManager.state;
336
 
337
        if (state[updateName] instanceof StateMap) {
338
            state[updateName].delete(fields.id);
339
            return;
340
        }
341
        delete state[updateName];
342
    }
343
 
344
    /**
345
     * Process a remove state message.
346
     *
347
     * @param {Object} stateManager the state manager
348
     * @param {String} updateName the state element to update
349
     * @param {Object} fields the new data
350
     */
351
    defaultRemove(stateManager, updateName, fields) {
352
 
353
        // Get the current value.
354
        let current = stateManager.get(updateName, fields.id);
355
        if (!current) {
356
            return;
357
        }
358
 
359
        // Process deletion.
360
        let state = stateManager.state;
361
 
362
        if (state[updateName] instanceof StateMap) {
363
            state[updateName].delete(fields.id);
364
            return;
365
        }
366
        delete state[updateName];
367
    }
368
 
369
    /**
370
     * Process a update state message.
371
     *
372
     * @param {Object} stateManager the state manager
373
     * @param {String} updateName the state element to update
374
     * @param {Object} fields the new data
375
     */
376
    defaultUpdate(stateManager, updateName, fields) {
377
 
378
        // Get the current value.
379
        let current = stateManager.get(updateName, fields.id);
380
        if (!current) {
381
            throw Error(`Inexistent ${updateName} ${fields.id}`);
382
        }
383
 
384
        // Execute updates.
385
        for (const [fieldName, fieldValue] of Object.entries(fields)) {
386
            current[fieldName] = fieldValue;
387
        }
388
    }
389
 
390
    /**
391
     * Process a put state message.
392
     *
393
     * @param {Object} stateManager the state manager
394
     * @param {String} updateName the state element to update
395
     * @param {Object} fields the new data
396
     */
397
    defaultPut(stateManager, updateName, fields) {
398
 
399
        // Get the current value.
400
        let current = stateManager.get(updateName, fields.id);
401
        if (current) {
402
            // Update attributes.
403
            for (const [fieldName, fieldValue] of Object.entries(fields)) {
404
                current[fieldName] = fieldValue;
405
            }
406
        } else {
407
            // Create new object.
408
            let state = stateManager.state;
409
            if (state[updateName] instanceof StateMap) {
410
                state[updateName].add(fields);
411
                return;
412
            }
413
            state[updateName] = fields;
414
        }
415
    }
416
 
417
    /**
418
     * Process an override state message.
419
     *
420
     * @param {Object} stateManager the state manager
421
     * @param {String} updateName the state element to update
422
     * @param {Object} fields the new data
423
     */
424
    defaultOverride(stateManager, updateName, fields) {
425
 
426
        // Get the current value.
427
        let current = stateManager.get(updateName, fields.id);
428
        if (current) {
429
            // Remove any unnecessary fields.
430
            for (const [fieldName] of Object.entries(current)) {
431
                if (fields[fieldName] === undefined) {
432
                    delete current[fieldName];
433
                }
434
            }
435
            // Update field.
436
            for (const [fieldName, fieldValue] of Object.entries(fields)) {
437
                current[fieldName] = fieldValue;
438
            }
439
        } else {
440
            // Create the element if not exists.
441
            let state = stateManager.state;
442
            if (state[updateName] instanceof StateMap) {
443
                state[updateName].add(fields);
444
                return;
445
            }
446
            state[updateName] = fields;
447
        }
448
    }
449
 
450
    /**
451
     * Set the logger class instance.
452
     *
453
     * Reactive instances can provide alternative loggers to provide advanced logging.
454
     * @param {Logger} logger
455
     */
456
    setLogger(logger) {
457
        this.logger = logger;
458
    }
459
 
460
    /**
461
     * Add a new log entry into the reactive logger.
462
     * @param {LoggerEntry} entry
463
     */
464
    addLoggerEntry(entry) {
465
        this.logger.add(entry);
466
    }
467
 
468
    /**
469
     * Get an element from the state or form an alternative state object.
470
     *
471
     * The altstate param is used by external update functions that gets the current
472
     * state as param.
473
     *
474
     * @param {String} name the state object name
475
     * @param {*} id and object id for state maps.
476
     * @return {Object|undefined} the state object found
477
     */
478
    get(name, id) {
479
        const state = this.state;
480
 
481
        let current = state[name];
482
        if (current instanceof StateMap) {
483
            if (id === undefined) {
484
                throw Error(`Missing id for ${name} state update`);
485
            }
486
            current = state[name].get(id);
487
        }
488
 
489
        return current;
490
    }
491
 
492
    /**
493
     * Get all element ids from the given state.
494
     *
495
     * @param {String} name the state object name
496
     * @return {Array} the element ids.
497
     */
498
    getIds(name) {
499
        const state = this.state;
500
        const current = state[name];
501
        if (!(current instanceof StateMap)) {
502
            throw Error(`${name} is not an instance of StateMap`);
503
        }
504
        return [...state[name].keys()];
505
    }
506
 
507
    /**
508
     * Register a state modification and generate the necessary events.
509
     *
510
     * This method is used mainly by proxy helpers to dispatch state change event.
511
     * However, mutations can use it to inform components about non reactive changes
512
     * in the state (only the two first levels of the state are reactive).
513
     *
514
     * Each action can produce several events:
515
     * - The specific attribute updated, created or deleter (example: "cm.visible:updated")
516
     * - The general state object updated, created or deleted (example: "cm:updated")
517
     * - If the element has an ID attribute, the specific event with id (example: "cm[42].visible:updated")
518
     * - If the element has an ID attribute, the general event with id (example: "cm[42]:updated")
519
     * - A generic state update event "state:update"
520
     *
521
     * @param {string} field the affected state field name
522
     * @param {string|null} prop the affecter field property (null if affect the full object)
523
     * @param {string} action the action done (created/updated/deleted)
524
     * @param {*} data the affected data
525
     */
526
    registerStateAction(field, prop, action, data) {
527
 
528
        let parentAction = 'updated';
529
 
530
        if (prop !== null) {
531
            this.eventsToPublish.push({
532
                eventName: `${field}.${prop}:${action}`,
533
                eventData: data,
534
                action,
535
            });
536
        } else {
537
            parentAction = action;
538
        }
539
 
540
        // Trigger extra events if the element has an ID attribute.
541
        if (data.id !== undefined) {
542
            if (prop !== null) {
543
                this.eventsToPublish.push({
544
                    eventName: `${field}[${data.id}].${prop}:${action}`,
545
                    eventData: data,
546
                    action,
547
                });
548
            }
549
            this.eventsToPublish.push({
550
                eventName: `${field}[${data.id}]:${parentAction}`,
551
                eventData: data,
552
                action: parentAction,
553
            });
554
        }
555
 
556
        // Register the general change.
557
        this.eventsToPublish.push({
558
            eventName: `${field}:${parentAction}`,
559
            eventData: data,
560
            action: parentAction,
561
        });
562
 
563
        // Register state updated event.
564
        this.eventsToPublish.push({
565
            eventName: `state:updated`,
566
            eventData: data,
567
            action: 'updated',
568
        });
569
    }
570
 
571
    /**
572
     * Internal method to publish events.
573
     *
574
     * This is a private method, it will be invoked when the state is set back to read only mode.
575
     */
576
    _publishEvents() {
577
        const fieldChanges = this.eventsToPublish;
578
        this.eventsToPublish = [];
579
 
580
        // Dispatch a transaction start event.
581
        this.dispatchEvent({
582
            action: 'transaction:start',
583
            state: this.state,
584
            element: null,
585
            changes: fieldChanges,
586
        }, this.target);
587
 
588
        // State changes can be registered in any order. However it will avoid many
589
        // components errors if they are sorted to have creations-updates-deletes in case
590
        // some component needs to create or destroy DOM elements before updating them.
591
        fieldChanges.sort((a, b) => {
592
            const weights = {
593
                created: 0,
594
                updated: 1,
595
                deleted: 2,
596
            };
597
            const aweight = weights[a.action] ?? 0;
598
            const bweight = weights[b.action] ?? 0;
599
            // In case both have the same weight, the eventName length decide.
600
            if (aweight === bweight) {
601
                return a.eventName.length - b.eventName.length;
602
            }
603
            return aweight - bweight;
604
        });
605
 
606
        // List of the published events to prevent redundancies.
607
        let publishedEvents = new Set();
608
 
609
        fieldChanges.forEach((event) => {
610
 
611
            const eventkey = `${event.eventName}.${event.eventData.id ?? 0}`;
612
 
613
            if (!publishedEvents.has(eventkey)) {
614
                this.dispatchEvent({
615
                    action: event.eventName,
616
                    state: this.state,
617
                    element: event.eventData
618
                }, this.target);
619
 
620
                publishedEvents.add(eventkey);
621
            }
622
        });
623
 
624
        // Dispatch a transaction end event.
625
        this.dispatchEvent({
626
            action: 'transaction:end',
627
            state: this.state,
628
            element: null,
629
        }, this.target);
630
    }
631
}
632
 
633
// Proxy helpers.
634
 
635
/**
636
 * The proxy handler.
637
 *
638
 * This class will inform any value change directly to the state manager.
639
 *
640
 * The proxied variable will throw an error if it is altered when the state manager is
641
 * in read only mode.
642
 */
643
class Handler {
644
 
645
    /**
646
     * Class constructor.
647
     *
648
     * @param {string} name the variable name used for identify triggered actions
649
     * @param {StateManager} stateManager the state manager object
650
     * @param {boolean} proxyValues if new values must be proxied (used only at state root level)
651
     */
652
    constructor(name, stateManager, proxyValues) {
653
        this.name = name;
654
        this.stateManager = stateManager;
655
        this.proxyValues = proxyValues ?? false;
656
    }
657
 
658
    /**
659
     * Set trap to trigger events when the state changes.
660
     *
661
     * @param {object} obj the source object (not proxied)
662
     * @param {string} prop the attribute to set
663
     * @param {*} value the value to save
664
     * @param {*} receiver the proxied element to be attached to events
665
     * @returns {boolean} if the value is set
666
     */
667
    set(obj, prop, value, receiver) {
668
 
669
        // Only mutations should be able to set state values.
670
        if (this.stateManager.readonly) {
671
            throw new Error(`State locked. Use mutations to change ${prop} value in ${this.name}.`);
672
        }
673
 
674
        // Check any data change.
675
        if (JSON.stringify(obj[prop]) === JSON.stringify(value)) {
676
            return true;
677
        }
678
 
679
        const action = (obj[prop] !== undefined) ? 'updated' : 'created';
680
 
681
        // Proxy value if necessary (used at state root level).
682
        if (this.proxyValues) {
683
            if (Array.isArray(value)) {
684
                obj[prop] = new StateMap(prop, this.stateManager).loadValues(value);
685
            } else {
686
                obj[prop] = new Proxy(value, new Handler(prop, this.stateManager));
687
            }
688
        } else {
689
            obj[prop] = value;
690
        }
691
 
692
        // If the state is not ready yet means the initial state is not yet loaded.
693
        if (this.stateManager.state === undefined) {
694
            return true;
695
        }
696
 
697
        this.stateManager.registerStateAction(this.name, prop, action, receiver);
698
 
699
        return true;
700
    }
701
 
702
    /**
703
     * Delete property trap to trigger state change events.
704
     *
705
     * @param {*} obj the affected object (not proxied)
706
     * @param {*} prop the prop to delete
707
     * @returns {boolean} if prop is deleted
708
     */
709
    deleteProperty(obj, prop) {
710
        // Only mutations should be able to set state values.
711
        if (this.stateManager.readonly) {
712
            throw new Error(`State locked. Use mutations to delete ${prop} in ${this.name}.`);
713
        }
714
        if (prop in obj) {
715
 
716
            delete obj[prop];
717
 
718
            this.stateManager.registerStateAction(this.name, prop, 'deleted', obj);
719
        }
720
        return true;
721
    }
722
}
723
 
724
/**
725
 * Class to add events dispatching to the JS Map class.
726
 *
727
 * When the state has a list of objects (with IDs) it will be converted into a StateMap.
728
 * StateMap is used almost in the same way as a regular JS map. Because all elements have an
729
 * id attribute, it has some specific methods:
730
 *  - add: a convenient method to add an element without specifying the key ("id" attribute will be used as a key).
731
 *  - loadValues: to add many elements at once wihout specifying keys ("id" attribute will be used).
732
 *
733
 * Apart, the main difference between regular Map and MapState is that this one will inform any change to the
734
 * state manager.
735
 */
736
class StateMap extends Map {
737
 
738
    /**
739
     * Create a reactive Map.
740
     *
741
     * @param {string} name the property name
742
     * @param {StateManager} stateManager the state manager
743
     * @param {iterable} iterable an iterable object to create the Map
744
     */
745
    constructor(name, stateManager, iterable) {
746
        // We don't have any "this" until be call super.
747
        super(iterable);
748
        this.name = name;
749
        this.stateManager = stateManager;
750
    }
751
 
752
    /**
753
     * Set an element into the map.
754
     *
755
     * Each value needs it's own id attribute. Objects without id will be rejected.
756
     * The function will throw an error if the value id and the key are not the same.
757
     *
758
     * @param {*} key the key to store
759
     * @param {*} value the value to store
760
     * @returns {Map} the resulting Map object
761
     */
762
    set(key, value) {
763
 
764
        // Only mutations should be able to set state values.
765
        if (this.stateManager.readonly) {
766
            throw new Error(`State locked. Use mutations to change ${key} value in ${this.name}.`);
767
        }
768
 
769
        // Normalize keys as string to prevent json decoding errors.
770
        key = this.normalizeKey(key);
771
 
772
        this.checkValue(value);
773
 
774
        if (key === undefined || key === null) {
775
            throw Error('State lists keys cannot be null or undefined');
776
        }
777
 
778
        // ID is mandatory and should be the same as the key.
779
        if (this.normalizeKey(value.id) !== key) {
780
            throw new Error(`State error: ${this.name} list element ID (${value.id}) and key (${key}) mismatch`);
781
        }
782
 
783
        const action = (super.has(key)) ? 'updated' : 'created';
784
 
785
        // Save proxied data into the list.
786
        const result = super.set(key, new Proxy(value, new Handler(this.name, this.stateManager)));
787
 
788
        // If the state is not ready yet means the initial state is not yet loaded.
789
        if (this.stateManager.state === undefined) {
790
            return result;
791
        }
792
 
793
        this.stateManager.registerStateAction(this.name, null, action, super.get(key));
794
 
795
        return result;
796
    }
797
 
798
    /**
799
     * Check if a value is valid to be stored in a a State List.
800
     *
801
     * Only objects with id attribute can be stored in State lists.
802
     *
803
     * This method throws an error if the value is not valid.
804
     *
805
     * @param {object} value (with ID)
806
     */
807
    checkValue(value) {
808
        if (!typeof value === 'object' && value !== null) {
809
            throw Error('State lists can contain objects only');
810
        }
811
 
812
        if (value.id === undefined) {
813
            throw Error('State lists elements must contain at least an id attribute');
814
        }
815
    }
816
 
817
    /**
818
     * Return a normalized key value for state map.
819
     *
820
     * Regular maps uses strict key comparissons but state maps are indexed by ID.JSON conversions
821
     * and webservices sometimes do unexpected types conversions so we convert any integer key to string.
822
     *
823
     * @param {*} key the provided key
824
     * @returns {string}
825
     */
826
    normalizeKey(key) {
827
        return String(key).valueOf();
828
    }
829
 
830
    /**
831
     * Insert a new element int a list.
832
     *
833
     * Each value needs it's own id attribute. Objects withouts id will be rejected.
834
     *
835
     * @param {object} value the value to add (needs an id attribute)
836
     * @returns {Map} the resulting Map object
837
     */
838
    add(value) {
839
        this.checkValue(value);
840
        return this.set(value.id, value);
841
    }
842
 
843
    /**
844
     * Return a state map element.
845
     *
846
     * @param {*} key the element id
847
     * @return {Object}
848
     */
849
    get(key) {
850
        return super.get(this.normalizeKey(key));
851
    }
852
 
853
    /**
854
     * Check whether an element with the specified key exists or not.
855
     *
856
     * @param {*} key the key to find
857
     * @return {boolean}
858
     */
859
    has(key) {
860
        return super.has(this.normalizeKey(key));
861
    }
862
 
863
    /**
864
     * Delete an element from the map.
865
     *
866
     * @param {*} key
867
     * @returns {boolean}
868
     */
869
    delete(key) {
870
        // State maps uses only string keys to avoid strict comparisons.
871
        key = this.normalizeKey(key);
872
 
873
        // Only mutations should be able to set state values.
874
        if (this.stateManager.readonly) {
875
            throw new Error(`State locked. Use mutations to change ${key} value in ${this.name}.`);
876
        }
877
 
878
        const previous = super.get(key);
879
 
880
        const result = super.delete(key);
881
        if (!result) {
882
            return result;
883
        }
884
 
885
        this.stateManager.registerStateAction(this.name, null, 'deleted', previous);
886
 
887
        return result;
888
    }
889
 
890
    /**
891
     * Return a suitable structure for JSON conversion.
892
     *
893
     * This function is needed because new values are compared in JSON. StateMap has Private
894
     * attributes which cannot be stringified (like this.stateManager which will produce an
895
     * infinite recursivity).
896
     *
897
     * @returns {array}
898
     */
899
    toJSON() {
900
        let result = [];
901
        this.forEach((value) => {
902
            result.push(value);
903
        });
904
        return result;
905
    }
906
 
907
    /**
908
     * Insert a full list of values using the id attributes as keys.
909
     *
910
     * This method is used mainly to initialize the list. Note each element is indexed by its "id" attribute.
911
     * This is a basic restriction of StateMap. All elements need an id attribute, otherwise it won't be saved.
912
     *
913
     * @param {iterable} values the values to load
914
     * @returns {StateMap} return the this value
915
     */
916
    loadValues(values) {
917
        values.forEach((data) => {
918
            this.checkValue(data);
919
            let key = data.id;
920
            let newvalue = new Proxy(data, new Handler(this.name, this.stateManager));
921
            this.set(key, newvalue);
922
        });
923
        return this;
924
    }
925
}