Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | 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();
1441 ariadna 608
        let transactionEvents = [];
1 efrain 609
 
610
        fieldChanges.forEach((event) => {
611
 
612
            const eventkey = `${event.eventName}.${event.eventData.id ?? 0}`;
613
 
614
            if (!publishedEvents.has(eventkey)) {
615
                this.dispatchEvent({
616
                    action: event.eventName,
617
                    state: this.state,
618
                    element: event.eventData
619
                }, this.target);
620
 
621
                publishedEvents.add(eventkey);
1441 ariadna 622
                transactionEvents.push(event);
1 efrain 623
            }
624
        });
625
 
626
        // Dispatch a transaction end event.
627
        this.dispatchEvent({
628
            action: 'transaction:end',
629
            state: this.state,
630
            element: null,
1441 ariadna 631
            changes: transactionEvents,
1 efrain 632
        }, this.target);
633
    }
634
}
635
 
636
// Proxy helpers.
637
 
638
/**
639
 * The proxy handler.
640
 *
641
 * This class will inform any value change directly to the state manager.
642
 *
643
 * The proxied variable will throw an error if it is altered when the state manager is
644
 * in read only mode.
645
 */
646
class Handler {
647
 
648
    /**
649
     * Class constructor.
650
     *
651
     * @param {string} name the variable name used for identify triggered actions
652
     * @param {StateManager} stateManager the state manager object
653
     * @param {boolean} proxyValues if new values must be proxied (used only at state root level)
654
     */
655
    constructor(name, stateManager, proxyValues) {
656
        this.name = name;
657
        this.stateManager = stateManager;
658
        this.proxyValues = proxyValues ?? false;
659
    }
660
 
661
    /**
662
     * Set trap to trigger events when the state changes.
663
     *
664
     * @param {object} obj the source object (not proxied)
665
     * @param {string} prop the attribute to set
666
     * @param {*} value the value to save
667
     * @param {*} receiver the proxied element to be attached to events
668
     * @returns {boolean} if the value is set
669
     */
670
    set(obj, prop, value, receiver) {
671
 
672
        // Only mutations should be able to set state values.
673
        if (this.stateManager.readonly) {
674
            throw new Error(`State locked. Use mutations to change ${prop} value in ${this.name}.`);
675
        }
676
 
677
        // Check any data change.
678
        if (JSON.stringify(obj[prop]) === JSON.stringify(value)) {
679
            return true;
680
        }
681
 
682
        const action = (obj[prop] !== undefined) ? 'updated' : 'created';
683
 
684
        // Proxy value if necessary (used at state root level).
685
        if (this.proxyValues) {
686
            if (Array.isArray(value)) {
687
                obj[prop] = new StateMap(prop, this.stateManager).loadValues(value);
688
            } else {
689
                obj[prop] = new Proxy(value, new Handler(prop, this.stateManager));
690
            }
691
        } else {
692
            obj[prop] = value;
693
        }
694
 
695
        // If the state is not ready yet means the initial state is not yet loaded.
696
        if (this.stateManager.state === undefined) {
697
            return true;
698
        }
699
 
700
        this.stateManager.registerStateAction(this.name, prop, action, receiver);
701
 
702
        return true;
703
    }
704
 
705
    /**
706
     * Delete property trap to trigger state change events.
707
     *
708
     * @param {*} obj the affected object (not proxied)
709
     * @param {*} prop the prop to delete
710
     * @returns {boolean} if prop is deleted
711
     */
712
    deleteProperty(obj, prop) {
713
        // Only mutations should be able to set state values.
714
        if (this.stateManager.readonly) {
715
            throw new Error(`State locked. Use mutations to delete ${prop} in ${this.name}.`);
716
        }
717
        if (prop in obj) {
718
 
719
            delete obj[prop];
720
 
721
            this.stateManager.registerStateAction(this.name, prop, 'deleted', obj);
722
        }
723
        return true;
724
    }
725
}
726
 
727
/**
728
 * Class to add events dispatching to the JS Map class.
729
 *
730
 * When the state has a list of objects (with IDs) it will be converted into a StateMap.
731
 * StateMap is used almost in the same way as a regular JS map. Because all elements have an
732
 * id attribute, it has some specific methods:
733
 *  - add: a convenient method to add an element without specifying the key ("id" attribute will be used as a key).
734
 *  - loadValues: to add many elements at once wihout specifying keys ("id" attribute will be used).
735
 *
736
 * Apart, the main difference between regular Map and MapState is that this one will inform any change to the
737
 * state manager.
738
 */
739
class StateMap extends Map {
740
 
741
    /**
742
     * Create a reactive Map.
743
     *
744
     * @param {string} name the property name
745
     * @param {StateManager} stateManager the state manager
746
     * @param {iterable} iterable an iterable object to create the Map
747
     */
748
    constructor(name, stateManager, iterable) {
749
        // We don't have any "this" until be call super.
750
        super(iterable);
751
        this.name = name;
752
        this.stateManager = stateManager;
753
    }
754
 
755
    /**
756
     * Set an element into the map.
757
     *
758
     * Each value needs it's own id attribute. Objects without id will be rejected.
759
     * The function will throw an error if the value id and the key are not the same.
760
     *
761
     * @param {*} key the key to store
762
     * @param {*} value the value to store
763
     * @returns {Map} the resulting Map object
764
     */
765
    set(key, value) {
766
 
767
        // Only mutations should be able to set state values.
768
        if (this.stateManager.readonly) {
769
            throw new Error(`State locked. Use mutations to change ${key} value in ${this.name}.`);
770
        }
771
 
772
        // Normalize keys as string to prevent json decoding errors.
773
        key = this.normalizeKey(key);
774
 
775
        this.checkValue(value);
776
 
777
        if (key === undefined || key === null) {
778
            throw Error('State lists keys cannot be null or undefined');
779
        }
780
 
781
        // ID is mandatory and should be the same as the key.
782
        if (this.normalizeKey(value.id) !== key) {
783
            throw new Error(`State error: ${this.name} list element ID (${value.id}) and key (${key}) mismatch`);
784
        }
785
 
786
        const action = (super.has(key)) ? 'updated' : 'created';
787
 
788
        // Save proxied data into the list.
789
        const result = super.set(key, new Proxy(value, new Handler(this.name, this.stateManager)));
790
 
791
        // If the state is not ready yet means the initial state is not yet loaded.
792
        if (this.stateManager.state === undefined) {
793
            return result;
794
        }
795
 
796
        this.stateManager.registerStateAction(this.name, null, action, super.get(key));
797
 
798
        return result;
799
    }
800
 
801
    /**
802
     * Check if a value is valid to be stored in a a State List.
803
     *
804
     * Only objects with id attribute can be stored in State lists.
805
     *
806
     * This method throws an error if the value is not valid.
807
     *
808
     * @param {object} value (with ID)
809
     */
810
    checkValue(value) {
811
        if (!typeof value === 'object' && value !== null) {
812
            throw Error('State lists can contain objects only');
813
        }
814
 
815
        if (value.id === undefined) {
816
            throw Error('State lists elements must contain at least an id attribute');
817
        }
818
    }
819
 
820
    /**
821
     * Return a normalized key value for state map.
822
     *
823
     * Regular maps uses strict key comparissons but state maps are indexed by ID.JSON conversions
824
     * and webservices sometimes do unexpected types conversions so we convert any integer key to string.
825
     *
826
     * @param {*} key the provided key
827
     * @returns {string}
828
     */
829
    normalizeKey(key) {
830
        return String(key).valueOf();
831
    }
832
 
833
    /**
834
     * Insert a new element int a list.
835
     *
836
     * Each value needs it's own id attribute. Objects withouts id will be rejected.
837
     *
838
     * @param {object} value the value to add (needs an id attribute)
839
     * @returns {Map} the resulting Map object
840
     */
841
    add(value) {
842
        this.checkValue(value);
843
        return this.set(value.id, value);
844
    }
845
 
846
    /**
847
     * Return a state map element.
848
     *
849
     * @param {*} key the element id
850
     * @return {Object}
851
     */
852
    get(key) {
853
        return super.get(this.normalizeKey(key));
854
    }
855
 
856
    /**
857
     * Check whether an element with the specified key exists or not.
858
     *
859
     * @param {*} key the key to find
860
     * @return {boolean}
861
     */
862
    has(key) {
863
        return super.has(this.normalizeKey(key));
864
    }
865
 
866
    /**
867
     * Delete an element from the map.
868
     *
869
     * @param {*} key
870
     * @returns {boolean}
871
     */
872
    delete(key) {
873
        // State maps uses only string keys to avoid strict comparisons.
874
        key = this.normalizeKey(key);
875
 
876
        // Only mutations should be able to set state values.
877
        if (this.stateManager.readonly) {
878
            throw new Error(`State locked. Use mutations to change ${key} value in ${this.name}.`);
879
        }
880
 
881
        const previous = super.get(key);
882
 
883
        const result = super.delete(key);
884
        if (!result) {
885
            return result;
886
        }
887
 
888
        this.stateManager.registerStateAction(this.name, null, 'deleted', previous);
889
 
890
        return result;
891
    }
892
 
893
    /**
894
     * Return a suitable structure for JSON conversion.
895
     *
896
     * This function is needed because new values are compared in JSON. StateMap has Private
897
     * attributes which cannot be stringified (like this.stateManager which will produce an
898
     * infinite recursivity).
899
     *
900
     * @returns {array}
901
     */
902
    toJSON() {
903
        let result = [];
904
        this.forEach((value) => {
905
            result.push(value);
906
        });
907
        return result;
908
    }
909
 
910
    /**
911
     * Insert a full list of values using the id attributes as keys.
912
     *
913
     * This method is used mainly to initialize the list. Note each element is indexed by its "id" attribute.
914
     * This is a basic restriction of StateMap. All elements need an id attribute, otherwise it won't be saved.
915
     *
916
     * @param {iterable} values the values to load
917
     * @returns {StateMap} return the this value
918
     */
919
    loadValues(values) {
920
        values.forEach((data) => {
921
            this.checkValue(data);
922
            let key = data.id;
923
            let newvalue = new Proxy(data, new Handler(this.name, this.stateManager));
924
            this.set(key, newvalue);
925
        });
926
        return this;
927
    }
928
}