state-machine.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. /*
  2. Javascript State Machine Library - https://github.com/jakesgordon/javascript-state-machine
  3. Copyright (c) 2012, 2013 Jake Gordon and contributors
  4. Released under the MIT license - https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE
  5. */
  6. (function (window) {
  7. var StateMachine = {
  8. //---------------------------------------------------------------------------
  9. VERSION: "2.2.0",
  10. //---------------------------------------------------------------------------
  11. Result: {
  12. SUCCEEDED: 1, // the event transitioned successfully from one state to another
  13. NOTRANSITION: 2, // the event was successfull but no state transition was necessary
  14. CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
  15. PENDING: 4 // the event is asynchronous and the caller is in control of when the transition occurs
  16. },
  17. Error: {
  18. INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
  19. PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
  20. INVALID_CALLBACK: 300 // caller provided callback function threw an exception
  21. },
  22. WILDCARD: '*',
  23. ASYNC: 'async',
  24. //---------------------------------------------------------------------------
  25. create: function(cfg, target) {
  26. var initial = (typeof cfg.initial == 'string') ? { state: cfg.initial } : cfg.initial; // allow for a simple string, or an object with { state: 'foo', event: 'setup', defer: true|false }
  27. var terminal = cfg.terminal || cfg['final'];
  28. var fsm = target || cfg.target || {};
  29. var events = cfg.events || [];
  30. var callbacks = cfg.callbacks || {};
  31. var map = {};
  32. var add = function(e) {
  33. var from = (e.from instanceof Array) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
  34. map[e.name] = map[e.name] || {};
  35. for (var n = 0 ; n < from.length ; n++)
  36. map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
  37. };
  38. if (initial) {
  39. initial.event = initial.event || 'startup';
  40. add({ name: initial.event, from: 'none', to: initial.state });
  41. }
  42. for(var n = 0 ; n < events.length ; n++)
  43. add(events[n]);
  44. for(var name in map) {
  45. if (map.hasOwnProperty(name))
  46. fsm[name] = StateMachine.buildEvent(name, map[name]);
  47. }
  48. for(var name in callbacks) {
  49. if (callbacks.hasOwnProperty(name))
  50. fsm[name] = callbacks[name]
  51. }
  52. fsm.current = 'none';
  53. fsm.is = function(state) { return (state instanceof Array) ? (state.indexOf(this.current) >= 0) : (this.current === state); };
  54. fsm.can = function(event) { return !this.transition && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); }
  55. fsm.cannot = function(event) { return !this.can(event); };
  56. fsm.error = cfg.error || function(name, from, to, args, error, msg, e) { throw e || msg; }; // default behavior when something unexpected happens is to throw an exception, but caller can override this behavior if desired (see github issue #3 and #17)
  57. fsm.isFinished = function() { return this.is(terminal); };
  58. if (initial && !initial.defer)
  59. fsm[initial.event]();
  60. return fsm;
  61. },
  62. //===========================================================================
  63. doCallback: function(fsm, func, name, from, to, args) {
  64. if (func) {
  65. try {
  66. return func.apply(fsm, [name, from, to].concat(args));
  67. }
  68. catch(e) {
  69. return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function", e);
  70. }
  71. }
  72. },
  73. beforeAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbeforeevent'], name, from, to, args); },
  74. afterAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafterevent'] || fsm['onevent'], name, from, to, args); },
  75. leaveAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleavestate'], name, from, to, args); },
  76. enterAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenterstate'] || fsm['onstate'], name, from, to, args); },
  77. changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
  78. beforeThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
  79. afterThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
  80. leaveThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
  81. enterThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
  82. beforeEvent: function(fsm, name, from, to, args) {
  83. if ((false === StateMachine.beforeThisEvent(fsm, name, from, to, args)) ||
  84. (false === StateMachine.beforeAnyEvent( fsm, name, from, to, args)))
  85. return false;
  86. },
  87. afterEvent: function(fsm, name, from, to, args) {
  88. StateMachine.afterThisEvent(fsm, name, from, to, args);
  89. StateMachine.afterAnyEvent( fsm, name, from, to, args);
  90. },
  91. leaveState: function(fsm, name, from, to, args) {
  92. var specific = StateMachine.leaveThisState(fsm, name, from, to, args),
  93. general = StateMachine.leaveAnyState( fsm, name, from, to, args);
  94. if ((false === specific) || (false === general))
  95. return false;
  96. else if ((StateMachine.ASYNC === specific) || (StateMachine.ASYNC === general))
  97. return StateMachine.ASYNC;
  98. },
  99. enterState: function(fsm, name, from, to, args) {
  100. StateMachine.enterThisState(fsm, name, from, to, args);
  101. StateMachine.enterAnyState( fsm, name, from, to, args);
  102. },
  103. //===========================================================================
  104. buildEvent: function(name, map) {
  105. return function() {
  106. var from = this.current;
  107. var to = map[from] || map[StateMachine.WILDCARD] || from;
  108. var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
  109. if (this.transition)
  110. return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
  111. if (this.cannot(name))
  112. return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
  113. if (false === StateMachine.beforeEvent(this, name, from, to, args))
  114. return StateMachine.Result.CANCELLED;
  115. if (from === to) {
  116. StateMachine.afterEvent(this, name, from, to, args);
  117. return StateMachine.Result.NOTRANSITION;
  118. }
  119. // prepare a transition method for use EITHER lower down, or by caller if they want an async transition (indicated by an ASYNC return value from leaveState)
  120. var fsm = this;
  121. this.transition = function() {
  122. fsm.transition = null; // this method should only ever be called once
  123. fsm.current = to;
  124. StateMachine.enterState( fsm, name, from, to, args);
  125. StateMachine.changeState(fsm, name, from, to, args);
  126. StateMachine.afterEvent( fsm, name, from, to, args);
  127. return StateMachine.Result.SUCCEEDED;
  128. };
  129. this.transition.cancel = function() { // provide a way for caller to cancel async transition if desired (issue #22)
  130. fsm.transition = null;
  131. StateMachine.afterEvent(fsm, name, from, to, args);
  132. }
  133. var leave = StateMachine.leaveState(this, name, from, to, args);
  134. if (false === leave) {
  135. this.transition = null;
  136. return StateMachine.Result.CANCELLED;
  137. }
  138. else if (StateMachine.ASYNC === leave) {
  139. return StateMachine.Result.PENDING;
  140. }
  141. else {
  142. if (this.transition) // need to check in case user manually called transition() but forgot to return StateMachine.ASYNC
  143. return this.transition();
  144. }
  145. };
  146. }
  147. }; // StateMachine
  148. //===========================================================================
  149. if ("function" === typeof define) {
  150. define(function(require) { return StateMachine; });
  151. }
  152. else {
  153. window.StateMachine = StateMachine;
  154. }
  155. }(this));