-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathne-state.js
More file actions
353 lines (296 loc) · 12.9 KB
/
Copy pathne-state.js
File metadata and controls
353 lines (296 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/**
* NE STATE
* ***************************************************************************************************************************
*/
angular.module('neState', ['ngCookies'])
.factory('NeStateService',['$timeout','$location','$rootScope','$cookies','neObject', function($timeout, $location, $rootScope, $cookies, object){
function encryptString(str){
return window.btoa(str);
}
function decryptString(str){
return window.atob(str);
}
var locationStore = {
encrypt: false,
prefix: 'q',
parser: function (locationString){
var locationPrefix = this.prefix;
var encryptLocation = this.encrypt;
locationString = locationString || $location.search()[ locationPrefix ]; // decodeURIComponent not necessary, locationString is already decoded
try {
if(encryptLocation) locationString = decryptString(locationString);
return object.fromJson(locationString || '{}') || {};
}
catch(err){}
return {};
},
builder: function(stateObj){
var locationPrefix = this.prefix;
var encryptLocation = this.encrypt;
var str = JSON.stringify(stateObj, removeEmptyStates); //.replace(/=/,'%3D').replace(/\&/, '%26').replace(/\?/, '%3F');
// there don't have to be empty states in url
function removeEmptyStates(key, value){
if(!stateObj[key]) return value;
if(Object.keys(stateObj[key]).length) return value;
}
if(encryptLocation) str = encryptString(str);
return str;
},
autoUpdate: false, // auto updates on change
autoFill: false, // watch and fire state change
sync: false, // auto update and also watch
_unbinders:{}, // unbind route change listeners
init: function(state, stateId){
var locationStore = this;
if(!(locationStore.autoFill || locationStore.sync)) return;
if(stateId) locationStore._unbinders[ stateId ] = {
routeUpdate: $rootScope.$on('$routeUpdate', function (){
locationStore.fill(state, stateId);
}),
routeChangeSuccess: $rootScope.$on('$routeChangeSuccess', function (){
locationStore.fill(state, stateId);
})
};
locationStore.fill(state, stateId);
},
destroy: function(state, stateId){
return this.unbind(state, stateId);
},
unbind: function(state, stateId){
var locationStore = this;
var unbindStateIds = stateId ? [stateId] : Object.keys(locationStore._unbinders);
for(var i=0;i<unbindStateIds.length;i++){
var id = unbindStateIds[i];
if(locationStore._unbinders[id]){
locationStore._unbinders[id].routeUpdate();
locationStore._unbinders[id].routeChangeSuccess();
}
}
},
fill: function(state, stateId){
var locationStore = this;
var locationString = $location.search()[ locationStore.prefix ];
var stateObj = locationStore.parser(locationString) || {};
$timeout(function(){
if(stateId) state.change(stateId, stateObj[stateId] || {}, true);
else for(var id in state.history) state.change(id, stateObj[id] || {}, true);
});
},
update: function(state, stateId){
var locationStore = this;
if(!(locationStore.autoUpdate || locationStore.sync)) return;
var locationSearch = locationStore.builder(state.getCurrentState());
$location.search(locationStore.prefix, locationSearch);
}
};
// TODO: implement
var cookiesStore = {
//encrypt: false,
prefix: 'appState',
//domain:'',
//expires:'',
path:'/',
secure:false,
autoUpdate: false, // auto updates on change
autoFill: false, // watch and fire state change
sync: false, // auto update and also watch
init: function(state, stateId){},
destroy: function(state, stateId){},
unbind: function(state, stateId){},
fill: function(state, stateId){
var locationStore = this;
var stateObj = $cookies.getObject(locationStore.prefix) || {};
$timeout(function(){
if(stateId) state.change(stateId, stateObj[stateId] || {}, true);
else for(var id in state.history) state.change(id, stateObj[id] || {}, true);
});
},
update: function(state, stateId){
var locationStore = this;
if(!(locationStore.autoUpdate || locationStore.sync)) return;
$cookies.putObject(locationStore.prefix, state.getCurrentState(), {
domain: locationStore.domain,
expires: locationStore.expires,
path: locationStore.path,
secure: locationStore.secure,
});
}
};
var defaultOpts = {
maxHistoryStates: 5,
store: locationStore
};
function StateService(opts){
opts = opts || {};
angular.merge(this, {}, defaultOpts, opts);
this.history = {};
this.changeListeners = [];
return this;
}
StateService.locationStore = locationStore;
StateService.cookiesStore = cookiesStore;
StateService.prototype.create =
StateService.prototype.register = function(id, opts){
opts = opts || {};
var state = this;
if(state.history[id]) return state.history[id];
var stateHistory = [];
stateHistory.maxHistoryStates = opts.maxHistoryStates || state.maxHistoryStates;
if(opts.store === 'location') opts.store = locationStore;
if(opts.store === 'cookies') opts.store = cookiesStore;
stateHistory.store = angular.merge({}, state.store, opts.store || {});
stateHistory.changeListeners = [];
stateHistory.currentStateIndex = -1;
state.history[id] = stateHistory;
state.history[id].store.init(state, id);
return state.history[id];
};
StateService.prototype.changeState =
StateService.prototype.change = function(id, value, disableStoreUpdate) {
if(!angular.isObject(value)) throw new Error('StateService: cannot change state, value have to be object and is "' +value+ '"');
var state = this;
state.history[id] = state.history[id] || state.register(id);
var currIndex = state.history[id].currentStateIndex;
var howManyRemove = state.history[id].length ? state.history[id].length - 1 - currIndex : 0;
if(state.history[id].length > 0 && object.deepEquals(state.history[id][currIndex], value)) return state; // same state as previous, no change
state.history[id].splice(currIndex + 1, howManyRemove);
state.history[id].push( angular.merge({}, value) );
if(state.history[id].length > state.history[id].maxHistoryStates) state.history[id].splice(0,1);
else state.history[id].currentStateIndex++;
if(!disableStoreUpdate){
state.history[id].store.update(state, id);
}
var changedFromStore = disableStoreUpdate;
return state.fireChange(id, null, changedFromStore);
};
StateService.prototype.updateState =
StateService.prototype.update = function(id, value){
if(!angular.isObject(value)) throw new Error('StateService: cannot change state, value have to be object and is "' +value+ '"');
var state = this;
state.history[id] = state.history[id] || state.register(id);
if(!state.history[id].length) return state; // nothing to update, there is no state yet
var currIndex = state.history[id].currentStateIndex;
state.history[id][ currIndex ] = angular.merge({}, value);
return state;
};
StateService.prototype.fireChange = function(id, oldValue, changedFromStore) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
var historyIndex = this.history[id].currentStateIndex;
var specChangeListeners = this.history[id].changeListeners;
oldValue = oldValue || this.getPrevState(id) || {};
var newValue = this.getCurrentState(id) || {};
for(var i=0;i<specChangeListeners.length;i++) specChangeListeners[i]( newValue, oldValue, changedFromStore, historyIndex );
for(var i=0;i<this.changeListeners.length;i++) this.changeListeners[i]( id, newValue, oldValue, changedFromStore, historyIndex );
return this;
};
StateService.prototype.watch =
StateService.prototype.onChange = function(id, fnc) {
var state = this;
if(arguments.length === 1) {
fnc = arguments[0];
id = null;
}
if(id) {
state.history[id] = state.history[id] || state.register(id);
state.history[id].changeListeners.push(fnc);
}
else state.changeListeners.push(fnc);
return state;
};
StateService.prototype.unWatch =
StateService.prototype.unbindChange =
StateService.prototype.offChange = function(id, fnc) {
if(arguments.length === 1) {
fnc = arguments[0];
id = null;
}
var index;
if(id) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
index = this.history[id].changeListeners.indexOf(fnc);
if(index >= 0) this.history[id].changeListeners.splice(index, 1);
}
else {
index = this.changeListeners.indexOf(fnc);
if(index >= 0) this.changeListeners.splice(index, 1);
}
return this;
};
StateService.prototype.clear = function(id) {
if(id) {
this.history[id].splice(0, this.history[id].length);
this.history[id].changeListeners = [];
this.history[id].currentStateIndex = -1;
}
else {
this.history = {};
this.changeListeners = [];
}
return this;
};
StateService.prototype.destroy = function(id) {
if(id) {
this.history[id].store.unbind(this, id);
this.store.unbind(this, id);
this.clear(id);
delete this.history[id];
}
else {
this.history = {};
this.changeListeners = [];
this.store.unbind(this, id);
for(var h in this.history) this.history[h].store.unbind(this, h);
}
return this;
};
StateService.prototype.getCurrentState = function(id) {
if(arguments.length === 0){
var states = {};
for(var id in this.history) states[id] = this.history[id][ this.history[id].currentStateIndex ];
return states;
}
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
return this.history[id][ this.history[id].currentStateIndex ];
};
StateService.prototype.getPrevState = function(id) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
var prevIndex = this.history[id].currentStateIndex - 1;
if(prevIndex < 0) return {};
return this.history[id][ prevIndex ];
};
StateService.prototype.getNextState = function(id) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
var nextIndex = this.history[id].currentStateIndex + 1;
if(nextIndex >= this.history[id].length) nextIndex = this.history[id].length ? this.history[id].length - 1 : 0;
return this.history[id][ nextIndex ];
};
StateService.prototype.getFutureState = function(id, value){
var futureState = {};
if(arguments.length === 2){
futureState[id] = value;
futureState = angular.merge({}, this.getCurrentState(), futureState);
}
else futureState = this.getCurrentState();
return futureState;
};
function moveState(indexIncrement){
return function(id) {
if(!this.history[id]) throw new Error('StateService: there is no registered state with id "' +id+ '"');
var oldValue = this.getCurrentState(id);
var currStateIndex = this.history[id].currentStateIndex + indexIncrement;
if(currStateIndex < 0) currStateIndex = 0;
if(currStateIndex >= this.history[id].length) currStateIndex = this.history[id].length ? this.history[id].length - 1 : 0;
this.history[id].currentStateIndex = currStateIndex;
return oldValue === this.getCurrentState(id) ? this : this.fireChange(id, oldValue);
};
}
StateService.prototype.undo = moveState(-1);
StateService.prototype.redo = moveState(1);
StateService.prototype.undoAll = function() {
for(var id in stateObj) this.undo(id);
};
StateService.prototype.redoAll = function() {
for(var id in stateObj) this.redo(id);
};
return StateService;
}]);