blob: 339503d682d88af42bd1c501d4fe3d3c5428e9be [file] [log] [blame]
Akronb7aab872021-11-04 17:11:04 +01001/**
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
12define(['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 = {};
Akrona8d45c42021-11-23 11:31:31 +010027 this._defaults = {};
Akronb7aab872021-11-04 17:11:04 +010028 this._parse(element.value);
29
30 return this;
31 },
32
33
34 // Parse a value and populate states
35 _parse : function (value) {
36 if (value === undefined || value === '')
37 return;
Akronb7aab872021-11-04 17:11:04 +010038
Akron25cd9282021-11-22 16:50:27 +010039 this._states = JSON.parse('{' + value + '}');
Akronb7aab872021-11-04 17:11:04 +010040 },
41
42
43 // Return the string representation of all states
44 toString : function () {
Akron25cd9282021-11-22 16:50:27 +010045
46 if (this._states.size === 0)
47 return undefined;
48
49 return JSON.stringify(this._states).slice(1,-1);
Akronb7aab872021-11-04 17:11:04 +010050 },
51
52
53 // Update the query component for states
54 _update : function () {
55 this._e.value = this.toString();
56 },
57
58
59 // Create new state that is automatically associated
60 // with the state manager
Akrona8d45c42021-11-23 11:31:31 +010061 newState : function (name, values, defValue) {
Akronb7aab872021-11-04 17:11:04 +010062
63 const t = this;
64 let s = stateClass.create(values);
65
Akrona8d45c42021-11-23 11:31:31 +010066 // Set default value
67 // TODO: It would be better to make this part
68 // of the state and serialize correctly using TOJSON()
69 if (defValue !== undefined) {
70 s.setIfNotYet(defValue);
71 t._defaults[name] = defValue;
72 };
Akronb7aab872021-11-04 17:11:04 +010073
74 // Associate with dummy object
75 s.associate({
76 setState : function (value) {
Akrona8d45c42021-11-23 11:31:31 +010077 if (t._defaults[name] !== undefined && t._defaults[name] == value) {
78 delete t._states[name];
79 } else {
80 t._states[name] = value;
81 };
Akronb7aab872021-11-04 17:11:04 +010082 t._update();
83 }
84 });
85
Akronda32e7a2021-11-16 17:28:57 +010086 // Load state
87 if (t._states[name] !== undefined) {
88 s.set(t._states[name]);
89 };
90
Akronb7aab872021-11-04 17:11:04 +010091 return s;
92 }
93 };
94});