forked from jakesgordon/javascript-state-machine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhistory.js
More file actions
83 lines (65 loc) · 2.16 KB
/
history.js
File metadata and controls
83 lines (65 loc) · 2.16 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
'use strict'
//-------------------------------------------------------------------------------------------------
var camelize = require('../util/camelize');
//-------------------------------------------------------------------------------------------------
module.exports = function(options) { options = options || {};
var past = camelize(options.name || options.past || 'history'),
future = camelize( options.future || 'future'),
clear = camelize.prepended('clear', past),
back = camelize.prepended(past, 'back'),
forward = camelize.prepended(past, 'forward'),
canBack = camelize.prepended('can', back),
canForward = camelize.prepended('can', forward),
max = options.max;
var plugin = {
configure: function(config) {
config.addTransitionLifecycleNames(back);
config.addTransitionLifecycleNames(forward);
},
init: function(instance) {
instance[past] = [];
instance[future] = [];
},
lifecycle: function(instance, lifecycle) {
if (lifecycle.event === 'onEnterState') {
instance[past].push(lifecycle.to);
if (max && instance[past].length > max)
instance[past].shift();
if (lifecycle.transition !== back && lifecycle.transition !== forward)
instance[future].length = 0;
}
},
methods: {},
properties: {}
}
plugin.methods[clear] = function() {
this[past].length = 0
this[future].length = 0
}
plugin.properties[canBack] = {
get: function() {
return this[past].length > 1
}
}
plugin.properties[canForward] = {
get: function() {
return this[future].length > 0
}
}
plugin.methods[back] = function() {
if (!this[canBack])
throw Error('no history');
var from = this[past].pop(),
to = this[past].pop();
this[future].push(from);
this._fsm.transit(back, from, to, []);
}
plugin.methods[forward] = function() {
if (!this[canForward])
throw Error('no history');
var from = this.state,
to = this[future].pop();
this._fsm.transit(forward, from, to, []);
}
return plugin;
}