Akron | b7aab87 | 2021-11-04 17:11:04 +0100 | [diff] [blame] | 1 | /** |
| 2 | * Create a state manager object, that can deserialize and |
| 3 | * serialize states of associated states. |
| 4 | * At the moment this requires an element for serialization, |
| 5 | * but it may very well serialize in a cookie. |
| 6 | * |
| 7 | * @author Nils Diewald |
| 8 | */ |
| 9 | |
| 10 | "use strict"; |
| 11 | |
| 12 | define(['state'], function(stateClass) { |
| 13 | |
| 14 | return { |
| 15 | // Create new state amanger. |
| 16 | // Expects an object with a value |
| 17 | // to contain the serialization of all states. |
| 18 | create : function (element) { |
| 19 | return Object.create(this)._init(element); |
| 20 | }, |
| 21 | |
| 22 | |
| 23 | // Initialize state manager |
| 24 | _init : function (element) { |
| 25 | this._e = element; |
| 26 | this._states = {}; |
| 27 | this._parse(element.value); |
| 28 | |
| 29 | return this; |
| 30 | }, |
| 31 | |
| 32 | |
| 33 | // Parse a value and populate states |
| 34 | _parse : function (value) { |
| 35 | if (value === undefined || value === '') |
| 36 | return; |
| 37 | |
| 38 | |
| 39 | |
Akron | 25cd928 | 2021-11-22 16:50:27 +0100 | [diff] [blame^] | 40 | this._states = JSON.parse('{' + value + '}'); |
Akron | b7aab87 | 2021-11-04 17:11:04 +0100 | [diff] [blame] | 41 | }, |
| 42 | |
| 43 | |
| 44 | // Return the string representation of all states |
| 45 | toString : function () { |
Akron | 25cd928 | 2021-11-22 16:50:27 +0100 | [diff] [blame^] | 46 | |
| 47 | if (this._states.size === 0) |
| 48 | return undefined; |
| 49 | |
| 50 | return JSON.stringify(this._states).slice(1,-1); |
Akron | b7aab87 | 2021-11-04 17:11:04 +0100 | [diff] [blame] | 51 | }, |
| 52 | |
| 53 | |
| 54 | // Update the query component for states |
| 55 | _update : function () { |
| 56 | this._e.value = this.toString(); |
| 57 | }, |
| 58 | |
| 59 | |
| 60 | // Create new state that is automatically associated |
| 61 | // with the state manager |
| 62 | newState : function (name, values) { |
| 63 | |
| 64 | const t = this; |
| 65 | let s = stateClass.create(values); |
| 66 | |
| 67 | // Load state |
| 68 | if (t._states[name] !== undefined) { |
| 69 | s.set(t._states[name]); |
| 70 | }; |
| 71 | |
| 72 | // Associate with dummy object |
| 73 | s.associate({ |
| 74 | setState : function (value) { |
| 75 | t._states[name] = value; |
| 76 | t._update(); |
| 77 | } |
| 78 | }); |
| 79 | |
| 80 | return s; |
| 81 | } |
| 82 | }; |
| 83 | }); |