iFSM.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  1. /**
  2. * -----------------------------------------------------------------------------------------
  3. * INTERSEL - 4 cité d'Hauteville - 75010 PARIS
  4. * RCS PARIS 488 379 660 - NAF 721Z
  5. *
  6. * File : iFSM.js
  7. * iFSM : a finite state machine with jQuery
  8. *
  9. * -----------------------------------------------------------------------------------------
  10. * Modifications :
  11. * - 2013/10/23 - E.Podvin - V1.0 - Creation
  12. * - 2013/11/03 - E.Podvin - V1.1 - add
  13. * - 2013/11/04 - E.Podvin - V1.2 - add process_event_if condition
  14. * - 2013/11/05 - E.Podvin - V1.3 - add sub machine to manage hierarchical state machines (HSM)
  15. * - 2013/11/12 - E.Podvin - V1.4 - debug on submachine management
  16. * - 2013/11/22 - E.Podvin - V1.5 - add 'next_state_on_target' to change a state according to the submachine states
  17. * - 2014/03/19 - E.Podvin - V1.6.1 - add options.initState in the jquery call to be able to define the initial state
  18. * - 2014/06/06 - E.Podvin - 1.6.8 - add synonymous events
  19. * - 2014/06/16 - E.Podvin - 1.6.9 - patch to correctly process process_on_UItarget option
  20. * - 2014/06/16 - E.Podvin - 1.6.10 - copy state definition in order to be able to have it dynamic
  21. * - 2014/07/01 - E.Podvin - 1.6.11 - patch on the reinitialisation of the event iterations when changing state
  22. * - 2014/07/08 - E.Podvin - 1.6.13 - propagate_event may be an array of events to propagate
  23. * - 2014/07/14 - E.Podvin - 1.6.14 - improve performance
  24. * - 2014/09/04 - E.Podvin - 1.6.15 - fix on the 'exitMachine' message when it was sent
  25. * - 2014/09/11 - E.Podvin - 1.6.16 - fix on synonymous event that was not set when still defined in a previous state
  26. * - 2016/04/26 - E.Podvin - 1.6.17 - fix on delayed events
  27. * - 2016/04/26 - E.Podvin - 1.6.18 - fix on delayed events on "DefaultState"
  28. * - 2017/03/08 - E.Podvin - 1.7.0 - myFSM.eventCalled available for script + 'propagate_event_on_localmachine' directive + catchEvent
  29. * - 2017/03/13 - E.Podvin - 1.7.1 - add myFSM.lastState
  30. * - 2017/03/20 - E.Podvin - 1.7.2 - fixes to be compliant with jquery 3.2.0
  31. * - 2017/10/14 - E.Podvin - 1.7.3 - small fix in case event is triggered with multiple parameters
  32. * - 2017/10/17 - E.POdvin - 1.7.4 - change log level - by default, displays the state&event processing step in the console
  33. * - 2018/03/08 - E.POdvin - 1.7.5 - transfer data transmitted by trigger to enterEvent and exitEvent
  34. * - 2018/03/13 - E.Podvin - 1.7.6 - add some controls when starting the state machines: can't start if no id on the object or if still exists
  35. * - 2019/11/22 - E.Podvin - 1.7.7 - prevent preventCancel event to stack if delayed again (see preventCancelSet)
  36. * add console.warn (instead of log) for errors message
  37. * - 2020/06/18 - E.Podvin - 1.7.8 - Add alert when next_state does not exist (not defined)
  38. * - 2021/04/19 - E.Podvin - 1.7.9 - fix delayProcess when data is not set
  39. * -----------------------------------------------------------------------------------------
  40. *
  41. * @copyright Intersel 2013-2021
  42. * @fileoverview : iFSM : a finite state machine with jQuery
  43. * @see {@link https://github.com/intersel/iFSM}
  44. * @author : Emmanuel Podvin - emmanuel.podvin@intersel.fr
  45. * @version : 1.7.9
  46. * -----------------------------------------------------------------------------------------
  47. */
  48. /**
  49. * How to use it :
  50. * ===============
  51. * <code>
  52. * <script type="text/javascript" src="jquery-3.6.0.min.js"></script>
  53. * <script type="text/javascript" src="jquery.dorequesttimeout.js"></script>
  54. * <script type="text/javascript" src="jquery.attrchange.js"></script>
  55. * <script type="text/javascript" src="ifsm.js"></script>
  56. * //Example of use :
  57. * <script type="text/javascript">
  58. * var aStateDefinition = {
  59. * FirstState :
  60. * {
  61. * enterState:
  62. * {
  63. * init_function: function(){alert("First State");}
  64. * },
  65. * click:
  66. * {
  67. * next_state: 'NextState'
  68. * }
  69. * },
  70. * NextState :
  71. * {
  72. * enterState:
  73. * {
  74. * init_function: function(){alert("Next State");}
  75. * },
  76. * click:
  77. * {
  78. * next_state: 'FirstState'
  79. * }
  80. * },
  81. * DefaultState :
  82. * {
  83. * start :
  84. * {
  85. * next_state : 'FirstState'
  86. * }
  87. * }
  88. * };
  89. *
  90. * $('#myButton').iFSM(aStateDefinition);
  91. * myFSM = $('#myButton').getFSM(aStateDefinition); //get the linked FSM object if needed
  92. *
  93. * </script>
  94. * </code>
  95. *
  96. */
  97. (function($){
  98. /**
  99. * @param integer nb_FSM - number of active FSM
  100. */
  101. var nb_FSM = 0;
  102. /**
  103. *
  104. * fsm_manager - class constructor
  105. * @param {object} aStateDefinition - states definition
  106. * {
  107. * <aStateName1> :
  108. * {
  109. * delegate_machines :
  110. * {
  111. * <aSubMachine name 1> :
  112. * {
  113. * submachine : <a State definition>,
  114. * no_reinitialisation : <boolean, default:false>
  115. * },
  116. * <aSubMachine name i> :
  117. * {
  118. * submachine : <a State definition>
  119. * },
  120. * ...
  121. * },
  122. *
  123. * <aEventName1>:
  124. * {
  125. * how_process_event: <immediate||push (default)||{delay:<adelay>,preventcancel:<false(default)|true>}>,
  126. * init_function: <a function(parameters, event, data)>,
  127. * properties_init_function: <parameters for init_function>,
  128. * next_state: <aStateName>,
  129. * pushpop_state: <'PushState'||'PopState'>,
  130. * next_state_when: <a statement that returns boolean>,
  131. * next_state_on_target :
  132. * {
  133. * condition : <'||'||'&&'>
  134. * submachines :
  135. * {
  136. * <submachineName1> :
  137. * {
  138. * condition : <''(default)||'not'>
  139. * target_list : [<targetState1>,...,<targetStaten>],
  140. * }
  141. * ...
  142. * <submachineNamen> : ...
  143. * }
  144. * }
  145. * next_state_if_error: <aStateName>,
  146. * pushpop_state_if_error: <'PushState'||'PopState'>,
  147. * propagate_event: <true||anEventName||[aEVN1,aEVN2,...]>
  148. * process_event_if : <a statement that returns boolean>,
  149. * propagate_event_on_refused : <anEventName>
  150. * out_function: <a function(parameters, event, data)>,
  151. * properties_out_function: <parameters for out_function>,
  152. * prevent_bubble: <true|false(default)>
  153. * process_on_UItarget: <true|false(default)>
  154. * UI_event_bubble: <true|false(default)>
  155. * },
  156. * <aEventName....>: <anOtherEventName>,
  157. * <aEventName....>:
  158. * {
  159. * ....
  160. * },
  161. * enterState : ...
  162. * exitState : ...
  163. * },
  164. * <aStateName...> : <anAnotherStateName>,
  165. * <aStateName...> :
  166. * {
  167. * ....
  168. * },
  169. * DefaultState :
  170. * {
  171. * start: //a default start event received at the FSM start
  172. * {
  173. * },
  174. * <aEventName....>:
  175. * {
  176. * }
  177. * }
  178. * }
  179. *
  180. * - <aStateName> :
  181. * <aStateName> is the name of a state.
  182. * - delegate_machines : sub machines list to delegate the events on the state
  183. * - submachine : the variable name of a state definition or a state definition description
  184. * - <aEventName> :
  185. * '<aEventName>' is the name of an event. It may be any event name supported by javascript or JQuery.
  186. * It defines an event we want to be alerted when it occurs on the object
  187. * Specific events :
  188. * - 'start' : this event is automatically sent when the FSM starts. should be defined in the initial state (or 'DefaultState')
  189. * - 'enterState' : this event is automatically sent and immediatly executed when the FSM enter the state
  190. * - 'exitState' : this event is automatically sent and immediatly executed when the FSM exit the state
  191. * - 'exitMachine' : this event is automatically sent when the (sub)machine will exit/close
  192. * - 'attrchange' : received if any attribute of the jquery object (myUIObject) changed
  193. * - data sent : event - event object
  194. * * event.attributeName - Name of the attribute modified
  195. * * event.oldValue - Previous value of the modified attribute
  196. * * event.newValue - New value of the modified attribute
  197. * - 'attrchange_<attributename>' (ex: 'attrchange_class') : received if the attribute of the jquery object changed
  198. * - data sent :
  199. * * newValue - New value of the modified attribute
  200. * * oldValue - Previous value of the modified attribute
  201. * - 'attrchange_style_<cssattributename_in_camelcase>' (ex:'attrchange_style_width') : received if the css attribute of the jquery object changed
  202. * - data sent :
  203. * * newValue - New value of the modified attribute
  204. * * oldValue - Previous value of the modified attribute
  205. *
  206. * its description is using an object with the following properties:
  207. * - how_process_event [default:{push}] : {immediate}||{push}||{delay:delay_value,preventcancel:<false(default)|true>}
  208. * if delay is defined, the processing of the event is delayed and activated at 'delay'
  209. * by default, any event delayed will be cancelled if the state changes
  210. * if preventcancel is defined, the delayed event won't be cancelled
  211. * - process_event_if :
  212. * Definition of condition test that will be evaluated, and if result is true then event will be processed
  213. * if not, see if a propagate_event_on_refused in order to trigger it... and exit...
  214. * - propagate_event_on_refused : an event name to trigger if process_event_if is false
  215. * - init_function : function name or a function statement
  216. * - properties_init_function : parameters to send to init_function
  217. * - next_state : next state once init_function done. If not defined, there is no state change.
  218. * - pushpop_state :
  219. * If 'PushState', then current state is pushed in the StateStack then next_state takes place.
  220. * If 'PopState', then the next state will be the one on top of the StateStack which is poped. next_state is so overwritten... If the stack is void, there is no state change.
  221. * - next_state_when :
  222. * Definition of condition test that will be evaluated, and if result is true then state will change
  223. * Following variables may be used for the test
  224. * this : the FSM object
  225. * this.EventIteration : variable that gives the iteration of the number of calls of the current event.
  226. * EventIteration is reset when the state changes
  227. * - next_state_on_target :
  228. * Definition of condition test based on the current states of the defined submachines
  229. * the test consist to :
  230. * - get the current states of each defined sub-machines,
  231. * - match the current state to the given array, resulting to true if found
  232. * - apply the defined operator between the results
  233. * - next_state_if_error (default: does not change state) : state set if init_function returns false. .
  234. * - pushpop_state_if_error :
  235. * If 'PushState', then current state is pushed in the StateStack then next_state_if_error takes place.
  236. * If 'PopState', then the next state will be the one on top of the StateStack which is poped. If the stack is void, there is no state change. next_state_if_error is so overwritten...
  237. * - out_function : function name to do once next_state changed
  238. * - properties_out_function : parameters to send to out_function
  239. * - propagate_event : if == 'true', the current event is propagated to the next state
  240. * if it's the name of an event, triggers the event...
  241. * if an array of events, events are triggered in sequence
  242. * - prevent_bubble : if defined and true, the current event will not bubble to its parent machine
  243. * - UI_event_bubble : if defined and true, the current event will bubble. By default, no UI event bubbling...
  244. * - process_on_UItarget : if defined and true, the current event will be processed only if the event was directly targeting
  245. * the UI jQuery object linked to the machine
  246. * An event may be synonymous with another event. In this case, we simply give the name of the synonymous event.
  247. *
  248. * @remarks
  249. * - any FSM is automatically initialised with a 'start' event
  250. * - state function should return a boolean : true: ok works fine; false: error
  251. * - state function should have the following input :
  252. * - parameters : the properties_<init/out>_function
  253. * - event : the event
  254. * - data : the data sent with the event
  255. * - a default statename 'DefaultState' can be defined to define the default behaviour of some events...
  256. * - an event is first search in the current state, then if not found in the 'DefaultState'
  257. * - if an event is not found, nothing is done...
  258. * - a 'start' event is triggered when the FSM is started with InitManager
  259. * - when there are sub machines defined for a state :
  260. * - the events are sent to each defined submachines in the order
  261. * - once the event is processed by the submachines, it is bubbled to the upper machines
  262. * - it is possible to prevent the bubbling of events with the directive 'prevent_bubble' to true
  263. * - a submachine works as the main one :
  264. * - if no_reinitialisation == false (default) it is initialised
  265. * - then starts once entering in the state
  266. * - a start event is triggered to it
  267. *
  268. * - to trigger an event to the machine itself, use can use the 'trigger' function
  269. * ex: myFSM.trigger('myevent');
  270. * - it is possible to trigger any event to a machine with the jquery trigger function :
  271. * ex: $('#myButton1').trigger('start',{targetFSM:myFsm});
  272. * - within a state function, it is possible to trigger event to any machine using its linked jQuery object : myFSM.myUIObject
  273. * ex : this.myUIObject.trigger('aEventName')
  274. * - if multiple machines are assigned to the same jQuery Object, it also possible to specify the FSM in the parameter :
  275. * ex : this.myUIObject.trigger('aEventName',{targetFSM:this})
  276. * - beware that if the submachine is no more accessible, it won't perhaps receive the message you triggered from it.
  277. * a workaround is to directly "push" an event in order that it will be processed within the flow of the current event processing.
  278. * the function to use is myFSM.pushEvent(anEventName, data) (or this.pushEvent in a FSM function)
  279. * ex: init_function : function(){this.pushEvent('setText','I push an event');},
  280. * - if a delayed event is sent again before a previous one was processed, the previous event is cancelled and the new one re-started
  281. * - a sub machine can manage its first state by handling the 'start' event in the DefaultState
  282. * - as the structure definition of the states of a machine is a javascript object,
  283. * it is then possible to define generic states or generic events as this example :
  284. * <code>
  285. * var myGenericEvent = {
  286. * next_state : aState,
  287. * propagate_event : anEvent,
  288. * ....
  289. * }
  290. * var myMachine = {
  291. * aState1 :
  292. * firstEvent : $.extend(true, {}, myGenericEvent), //copy of the myGenericEvent object
  293. * secondEvent : {...eventdefinition...},
  294. * thirdEvent : myGenericEvent,
  295. * ....
  296. * }
  297. * </code>
  298. * - if you stay coherent, it is possible to define and to change dynamically the states definition through myFSM._stateDefinition
  299. * - enterState and exitState can't be delayed
  300. * - all events in a submachine should have the prevent_bubble to true, except for those you'd like to be processed in other parts of the machine
  301. * - delegate machines should not be created on the DefaultState state
  302. * - if UI_event_bubble for an UI event is set to false by any part of the machine or submachine it will stay to false
  303. *
  304. *
  305. * The public available variables :
  306. * - myFSM.currentState : current processed state name
  307. * - myFSM.currentEvent : current processed event
  308. * - myFSM.myUIObject : the jQuery object associated to the FSM
  309. * - myFSM._stateDefinition : the definition of the states and events
  310. * - myFSM._stateDefinition.<statename>.<eventname>.EventIteration - the number of times an event has been called
  311. * - myFSM.opts - the defined options. Generally used to store local data
  312. * - myFSM.rootMachine : the root machine
  313. * - myFSM.parentMachine : the parent machine if it's in a sub machine (null if none)
  314. *
  315. * Within the call of FSM function, you can refer to the FSM by 'this', examples :
  316. * - this.currentState
  317. * - this.currentEvent
  318. * - this.currentEvent.type (name of the current processed event)
  319. * - this.myUIObject
  320. * - ...
  321. * plus about event:
  322. * - this.EventIteration : the current event iteration
  323. * - this.actualTarget : the jQuery object that is currently targetted by an event
  324. *
  325. * @param anObject - a jquery object on which the FSM applies.
  326. * ATTENTION : the property 'id' needs to be defined to have the machine working properly
  327. * @param options - an object defining the options:
  328. * - boolean debug
  329. * - integer LogLevel -
  330. * - 1 only errors displayed
  331. * - 2 - errors and warnings
  332. * - 3 - all
  333. * - boolean AlertError - send an alert box when error
  334. * - boolean startEvent - name of the starting event
  335. * - integer maxPushEvent - size of the push events array
  336. * - string logFSM - list of FSM names to follow on debug (ex: "FSM_1 FSM_4"). If void, then displays all machine messages
  337. */
  338. var fsm_manager = window.fsm_manager = function (anObject, aStateDefinition, options)
  339. {
  340. var $defaults = {
  341. debug : true,
  342. LogLevel : 1,
  343. AlertError : false,
  344. maxPushEvent : 100,
  345. startEvent : 'start',
  346. prefixFsmName : 'FSM_',
  347. logFSM : ""
  348. };
  349. nb_FSM = nb_FSM+1;
  350. // on charge les options passées en paramètre
  351. if (options == undefined) options=null;
  352. this.opts = jQuery.extend( {}, $defaults, options || {});
  353. /**
  354. * @param string FSMName - name of the FSM
  355. */
  356. this.FSMName = this.opts.prefixFsmName+nb_FSM;
  357. /**
  358. * @param Object _stateDefinition - the definition of the states of the FSM
  359. */
  360. this._stateDefinition = jQuery.extend(true, {}, aStateDefinition);
  361. this._originalstateDefinition = aStateDefinition;//keep the original definition here
  362. /**
  363. * currentState - current state of the fsm
  364. *
  365. */
  366. this.currentState = '';
  367. /**
  368. * lastState - previous state of the current state
  369. */
  370. this.lastState=this.currentState;
  371. /**
  372. * @param currentEvent - current event processed by the fsm
  373. *
  374. */
  375. this.currentEvent = '';
  376. /**
  377. * @param pushStateList array - a state list pushed that can be poped
  378. *
  379. */
  380. this.pushStateList = new Array();
  381. /**
  382. * @param processEventStatus - status of the process event execution
  383. * - idle : not working
  384. * - processing : is processing an event
  385. *
  386. */
  387. this.processEventStatus = 'idle';
  388. /**
  389. * @param pushEventList array - an event list waiting to be processed
  390. *
  391. */
  392. this.pushEventList = new Array();
  393. /**
  394. * @param myUIObject - Target object of the FSM
  395. */
  396. this.myUIObject = anObject;
  397. /**
  398. * @param listEvents - array of the events subscribed
  399. */
  400. this.listEvents ={};
  401. /**
  402. * @param currentDataEvent - the data of the event currently processed
  403. */
  404. this.currentDataEvent ={};
  405. /**
  406. * @param returnGeneralEventStatus - status to send back to the event triggering (if false, generally will prevent event propagation)
  407. */
  408. this.returnGeneralEventStatus = true;
  409. /**
  410. * @param rootMachine - root FSM machine of this current FSM
  411. */
  412. if (this.opts.rootMachine == undefined) this.opts.rootMachine = this;
  413. this.rootMachine = this.opts.rootMachine;
  414. /**
  415. * @param parentMachine - parent machine of this current one
  416. */
  417. if (this.opts.nextParent == undefined) this.parentMachine = null;
  418. else this.parentMachine = this.opts.nextParent;
  419. this.opts.nextParent = this; //
  420. /**
  421. * @param childrenMachine - list of children of the current machine
  422. */
  423. this.childrenMachine = new Array();
  424. if (this.parentMachine) this.parentMachine.childrenMachine.push(this);//update the children of the parent if any
  425. /**
  426. * preventCancelId to manage the preventcancel by creating a unique id for doTimeout
  427. * @type {Number}
  428. */
  429. this.preventCancelId=0;
  430. var aState;
  431. var aEvent;
  432. var theEvents ='';
  433. var space ='';
  434. var theTarget=$(document);
  435. var attrChangeRequested = false;
  436. var attrStyleChangeRequested = false;
  437. var attrChangeEvents = new Array();
  438. var setStart = false;
  439. // look for all the defined and unique events
  440. // as we're on it, copy the synonym states and events
  441. for(aState in this._stateDefinition)
  442. {
  443. if (typeof this._stateDefinition[aState] == 'string') //the state is synomym to another... so copy it
  444. this._stateDefinition[aState]=this._stateDefinition[this._stateDefinition[aState]];
  445. for(aEvent in this._stateDefinition[aState])
  446. {
  447. //to process synonymous events
  448. if (typeof this._stateDefinition[aState][aEvent] == 'string')
  449. this._stateDefinition[aState][aEvent] = this._stateDefinition[aState][this._stateDefinition[aState][aEvent]];
  450. // filter to the events list not subscribed by the root machine
  451. // start is always sent to the current machine
  452. if (!this.rootMachine.listEvents[aEvent] && aEvent != 'delegate_machines'
  453. && aEvent != this.opts.startEvent)
  454. {
  455. this.listEvents[aEvent]=aEvent;
  456. if (this != this.rootMachine)
  457. this.rootMachine.listEvents[aEvent]=aEvent;
  458. }
  459. else if (aEvent == this.opts.startEvent) setStart= true;
  460. }
  461. }
  462. //list all defined events in the FSM in a $.on format
  463. var splitevent='';
  464. for(aEvent in this.listEvents)
  465. {
  466. splitevent = aEvent.split('_');
  467. if ( splitevent[0] == 'attrchange' )
  468. {
  469. attrChangeRequested=true;
  470. attrChangeEvents.push(aEvent);
  471. if ( (splitevent[1] == 'style') && (splitevent.length > 2) )
  472. attrStyleChangeRequested=true;
  473. }
  474. theEvents=theEvents+space+aEvent;
  475. space=' ';
  476. }
  477. //define a selector object if none defined
  478. if ( (!anObject.selector)
  479. && (anObject.attr('id')
  480. && (anObject.attr('id') != 'iFSMDocumentRoot'))
  481. )
  482. anObject.selector='#'+anObject.attr('id');// set to the #id
  483. else anObject.selector='';
  484. //define the triggers for attrchange
  485. if ( attrChangeRequested && (anObject.selector) )
  486. {
  487. var aStyleListNew;
  488. var aStyleCssListNew={};
  489. var aStyleListOld;
  490. var aStyleCssListOld={};
  491. var splitres;
  492. var i;
  493. var aCssStyle;
  494. $(anObject.selector).attrchange({
  495. trackValues: true, // Default to false, if set to true the event object is updated with old and new value.
  496. callback: function (event) {
  497. //event - event object
  498. //event.attributeName - Name of the attribute modified
  499. //event.oldValue - Previous value of the modified attribute
  500. //event.newValue - New value of the modified attribute
  501. //Triggered when the selected elements attribute is added/updated/removed
  502. //send trigger event if an attribute change...
  503. if (jQuery.inArray('attrchange', attrChangeEvents)>=0)
  504. $(this).trigger('attrchange',event);
  505. //send trigger event on attribute changes
  506. if (jQuery.inArray('attrchange'+'_'+event.attributeName, attrChangeEvents)>=0)
  507. $(this).trigger('attrchange'+'_'+event.attributeName,{newValue:event.newValue,oldValue:event.oldValue});
  508. //send trigger for the style changes
  509. if ( (event.attributeName == 'style') && attrStyleChangeRequested)
  510. {
  511. if (event.newValue) aStyleListNew=event.newValue.split(';');
  512. else aStyleListNew = [];
  513. if (event.oldValue) aStyleListOld=event.oldValue.split(';');
  514. else aStyleListOld = [];
  515. for(i= 0; i < aStyleListNew.length; i++)
  516. {
  517. splitres=aStyleListNew[i].split(':');
  518. if (splitres.length==2)
  519. aStyleCssListNew[splitres[0]]=splitres[1].replace(/^\s+/g,'').replace(/\s+$/g,'');
  520. }
  521. for(i= 0; i < aStyleListOld.length; i++)
  522. {
  523. splitres=aStyleListOld[i].split(':');
  524. if (splitres.length==2)
  525. aStyleCssListOld[splitres[0]]=splitres[1].replace(/^\s+/g,'').replace(/\s+$/g,'');
  526. }
  527. for(aCssStyle in aStyleCssListNew)
  528. {
  529. if (aStyleCssListOld[aCssStyle] == undefined
  530. || (aStyleCssListOld[aCssStyle] && aStyleCssListOld[aCssStyle] != aStyleCssListNew[aCssStyle])
  531. )
  532. $(this).trigger('attrchange_style_'+fsm_manager_getcss3prop(aCssStyle),{newValue:aStyleCssListNew[aCssStyle],oldValue:aStyleCssListOld[aCssStyle]});
  533. }
  534. }//end if
  535. }//end callback
  536. }); //end attrchange selector
  537. }//end if
  538. //if target object not a document one
  539. if ($.isWindow(anObject[0])) theTarget = $(window);
  540. //activate the listening of events on object/FSM
  541. var myFSM=this.rootMachine;
  542. if (theEvents!='')
  543. theTarget.on(theEvents, anObject.selector, function( event, dataevent )
  544. {
  545. myFSM.returnGeneralEventStatus=true;
  546. myFSM.processEvent(event.type,arguments);
  547. return myFSM.returnGeneralEventStatus;
  548. });
  549. //activate the start event if defined
  550. if (setStart)
  551. {
  552. var myLocalFSM = this;
  553. theTarget.on(this.opts.startEvent, anObject.selector, function( event, dataevent )
  554. {
  555. myLocalFSM.processEvent(event.type,arguments);
  556. });
  557. }
  558. this._log('new fsm_manager:'+this.FSMName+'-'+anObject.selector,2);
  559. };//fsm_manager
  560. /*available functions*/
  561. /**
  562. * InitManager - init the One Page Fonction State machine
  563. * - a 'start' event is triggered.
  564. * public method
  565. * @aInitState - the init state at start
  566. */
  567. fsm_manager.prototype.InitManager = function(aInitState)
  568. {
  569. this._log('InitManager');
  570. if (aInitState==undefined)
  571. this.currentState = 'DefaultState';
  572. else
  573. this.currentState = aInitState;
  574. if (this._stateDefinition['DefaultState']==undefined)
  575. this._stateDefinition.DefaultState={};
  576. //send 'start' event
  577. if (!this.parentMachine)
  578. this.trigger(this.opts.startEvent);
  579. else //directly talk to the sub machine to process the start
  580. {
  581. var anEv = new Array();
  582. anEv[0] = fsm_manager_create_event(this.myUIObject,this.opts.startEvent,null);
  583. this.processEvent(this.opts.startEvent,anEv,true);
  584. }
  585. };//
  586. /**
  587. * procesEvent - process an event according to the current state
  588. * public Method
  589. * @param string anEvent : an event name
  590. * @param Array data : arguments sent by the triggering event [event, dataevent]
  591. * @param boolean forceProcess: force event to be processed
  592. * @return false to stop propagation
  593. * @comment
  594. * it is possible to pass the FSM Object to test the target through 'data' : data[data.length-1].targetFSM
  595. * ex : the function this.trigger always send the FSM through this way;
  596. */
  597. fsm_manager.prototype.processEvent= function(anEvent,data,forceProcess) {
  598. var thisFSM = this;
  599. var currentState = this.currentState;
  600. var currentEvent = this.currentUIEvent = data[0];
  601. this.receivedEvent = anEvent;
  602. this.currentDataEvent = data;
  603. this.currentEvent = currentEvent;
  604. var currentStateEvent = this.currentState;
  605. var doForceProcess = (forceProcess==undefined?false:true);
  606. var anEv = new Array();//dummy event to be used in 'processEvent' function (see processing of enterEvent and exitEvent)
  607. anEv[0] = fsm_manager_create_event(this.myUIObject,'',null); // to use it, just change anEv[0].type='an_event_name';
  608. anEv[1] = data[1]; anEv[2]= data[2];
  609. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> START Processing Event',3,1);
  610. //targetFSM is sent through the this.trigger function
  611. //we consider the sub FSMs of a machine as the same machine...
  612. //except if the event was triggered as addressing only the "localmachine"
  613. if (data.length > 1
  614. && data[(data.length - 1)] != null
  615. && data[data.length-1].targetFSM
  616. && (data[data.length-1].targetFSM != this)
  617. && (
  618. (data[data.length-1].localMachine)
  619. || (data[data.length-1].targetFSM.rootMachine != this.rootMachine)
  620. )
  621. )
  622. {
  623. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> not for the current machine ---> exit',3);
  624. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  625. return; //not for this machine...
  626. }
  627. if (data.length > 1 && data[(data.length - 1)] != null && data[data.length-1].localMachine)
  628. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> process event locally',3);
  629. // submachine needs to be active only if in the correct parent state where it was defined
  630. if (this.subMachineName)
  631. {
  632. if (
  633. (!this.parentMachine._stateDefinition[this.parentMachine.currentState].delegate_machines)
  634. || (
  635. (this.parentMachine._stateDefinition[this.parentMachine.currentState].delegate_machines)
  636. && (!this.parentMachine._stateDefinition[this.parentMachine.currentState].delegate_machines[this.subMachineName])
  637. )
  638. )
  639. {
  640. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> submachine can\'t run if the parent state is not active for the submachine ---> exit',3);
  641. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  642. return; //not in the correct parent state
  643. }
  644. }
  645. if (this._stateDefinition[currentState]==undefined)
  646. {
  647. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> currentState does not exist!',3);
  648. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  649. return;
  650. }
  651. if ( ( anEvent == 'enterState' ) || ( anEvent == 'exitState' ) ) doForceProcess = true;
  652. //element is not a right target...?
  653. if (
  654. !this.myUIObject.is(currentEvent.currentTarget)
  655. && !this.myUIObject.is(currentEvent.target)
  656. && (this.myUIObject[0] != document)
  657. && !$.isWindow(currentEvent.currentTarget)
  658. && !$.isWindow(currentEvent.target)
  659. )
  660. {
  661. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> object not a good target ---> '+$(currentEvent.currentTarget).attr('id')+'---> exit',3);
  662. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  663. return;
  664. }
  665. else
  666. {
  667. if (this.myUIObject[0] == document) this.actualTarget=$(document);
  668. else this.actualTarget = $(currentEvent.currentTarget);
  669. }
  670. var currentEventConfiguration = null;
  671. currentEventConfiguration = this._stateDefinition[currentState][anEvent];
  672. //if we are still processing we push the event, except if explicitly asked otherwise
  673. //see if we should push the event
  674. if ( doForceProcess == false
  675. && this.processEventStatus != 'idle'
  676. && (
  677. currentEventConfiguration == undefined
  678. || ( currentEventConfiguration
  679. && currentEventConfiguration.how_process_event == undefined
  680. )
  681. || ( currentEventConfiguration
  682. && currentEventConfiguration.how_process_event
  683. && currentEventConfiguration.how_process_event.immediate == undefined
  684. && currentEventConfiguration.how_process_event.delay == undefined
  685. )
  686. )
  687. )
  688. {
  689. this.pushEvent(anEvent,data);
  690. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Event pushed (lastevent)---> '+this.lastevent+' --> exit',3);
  691. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  692. return;
  693. }
  694. this.lastevent=currentState+'-'+anEvent;//unused...mainly for debug...
  695. /*
  696. * Processing of the sub machines
  697. */
  698. if ( ( this._stateDefinition[currentState].delegate_machines )
  699. )
  700. {
  701. var aSubMachineDefinition;
  702. for(aSubMachine in this._stateDefinition[currentState].delegate_machines)
  703. {
  704. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> delegate to submachine---> '+aSubMachine,3);
  705. aSubMachineDefinition = this._stateDefinition[currentState].delegate_machines[aSubMachine];
  706. //initialize the sub machines if needed
  707. if (aSubMachineDefinition.myFSM == undefined)
  708. {
  709. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> process submachine ---> create FSM for the submachine '+aSubMachine,3);
  710. this._stateDefinition[currentState].delegate_machines[aSubMachine].myFSM = new fsm_manager(this.myUIObject,aSubMachineDefinition.submachine,this.opts); //create the machine
  711. this._stateDefinition[currentState].delegate_machines[aSubMachine].myFSM.opts.FSMParent=this;
  712. this._stateDefinition[currentState].delegate_machines[aSubMachine].myFSM.subMachineName=aSubMachine;
  713. }
  714. if ( anEvent == 'enterState' )
  715. {
  716. if ( (aSubMachineDefinition.myFSM.currentState =='')//never initialised if ==''
  717. || (aSubMachineDefinition.no_reinitialisation == undefined)
  718. || (aSubMachineDefinition.no_reinitialisation == false)
  719. )
  720. {
  721. aSubMachineDefinition.myFSM.InitManager();//reinit the sub machine
  722. }
  723. }
  724. else if ( anEvent == 'exitState' )
  725. {
  726. anEv[0].type='exitMachine';
  727. aSubMachineDefinition.myFSM.processEvent('exitMachine',anEv,true);//stop the sub machine
  728. //we cancel any waiting events on the state
  729. aSubMachineDefinition.myFSM.cancelDelayedProcess();
  730. }
  731. // process event except on the enterState and exitState events that are not to be delegated... or if we dont propagate the event amongst the different machines
  732. else
  733. {
  734. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> process submachine (event)---> '+aSubMachine+'('+anEvent+') Start',3);
  735. aSubMachineDefinition.myFSM.processEvent(anEvent,data);
  736. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> process submachine (event)---> '+aSubMachine+'('+anEvent+') Processed',3);
  737. //current state changed during the process of the submachine...?
  738. //not sure it is a normal behaviour... if it occurs, we exit...
  739. if (currentState != this.currentState)
  740. {
  741. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> process submachine changed the current environment (event)',3);
  742. this.cleanExitProcess();
  743. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  744. return;
  745. }
  746. if (
  747. ( aSubMachineDefinition.myFSM._stateDefinition[aSubMachineDefinition.myFSM.currentState][anEvent]
  748. && aSubMachineDefinition.myFSM._stateDefinition[aSubMachineDefinition.myFSM.currentState][anEvent].prevent_bubble
  749. )
  750. ||
  751. ( aSubMachineDefinition.myFSM._stateDefinition.DefaultState[anEvent]
  752. && aSubMachineDefinition.myFSM._stateDefinition.DefaultState[anEvent].prevent_bubble
  753. )
  754. || (anEvent == this.opts.startEvent)
  755. )
  756. {
  757. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> submachine processed and exit due to prevent_bubble directive',3);
  758. this.cleanExitProcess();
  759. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> submachine exit',3);
  760. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  761. return;
  762. }
  763. }
  764. }
  765. }
  766. /*
  767. * Processing of the current event on the current state
  768. */
  769. //is the event to be processed?
  770. if ( (currentState=='DefaultState') || (currentEventConfiguration == undefined) )
  771. {
  772. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> take Event '+anEvent+' configuration from DefaultState (not present in current state)',3);
  773. currentEventConfiguration = this._stateDefinition.DefaultState[anEvent];
  774. if (currentEventConfiguration == undefined) {
  775. if ( ['start','enterState','exitState','exitMachine'].indexOf(anEvent) < 0)
  776. {
  777. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> take Event '+anEvent+' configuration from catchEvent',3);
  778. currentEventConfiguration = this._stateDefinition.DefaultState["catchEvent"];
  779. //we create the dummy event in the default state if it does not exist for the catchall
  780. if (!this._stateDefinition['DefaultState'][anEvent])
  781. this._stateDefinition['DefaultState'][anEvent]=jQuery.extend( true,{}, currentEventConfiguration);
  782. }
  783. }
  784. if (currentEventConfiguration == undefined) {
  785. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Event '+anEvent+' does not exist and no catchEvent--> will exit',3);
  786. this.cleanExitProcess();
  787. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  788. return;
  789. }
  790. currentStateEvent = 'DefaultState';
  791. }
  792. //is this a potential Pop State?
  793. if (currentEventConfiguration.pushpop_state
  794. && (currentEventConfiguration.pushpop_state =='PopState')
  795. && (this.pushStateList.length > 0)
  796. )
  797. currentEventConfiguration.next_state = this.pushStateList[this.pushStateList.length-1];
  798. if (currentEventConfiguration.pushpop_state_if_error
  799. && (currentEventConfiguration.pushpop_state_if_error =='PopState')
  800. && (this.pushStateList.length > 0)
  801. )
  802. currentEventConfiguration.next_state_if_error = this.pushStateList[this.pushStateList.length-1];
  803. //look if event is processed when coming from any target
  804. if ( !this.myUIObject.is(currentEvent.target)
  805. && (this.myUIObject[0] != document)
  806. && !$.isWindow(currentEvent.currentTarget)
  807. && !$.isWindow(currentEvent.target)
  808. && currentEventConfiguration.process_on_UItarget
  809. && currentEventConfiguration.process_on_UItarget == true
  810. )
  811. {
  812. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Event '+anEvent+' does not address the correct UI target (see process_on_UItarget) will exit',3);
  813. this.cleanExitProcess();
  814. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  815. return;
  816. }
  817. //look if we let the bubbling of UI event on this event
  818. // no bubbling by default
  819. if ( /*(this.myUIObject[0] != document)
  820. &&*/
  821. (!currentEventConfiguration.UI_event_bubble
  822. || currentEventConfiguration.UI_event_bubble==false
  823. )
  824. )
  825. {
  826. currentEvent.stopPropagation();
  827. this.returnGeneralEventStatus=false;
  828. this.rootMachine.returnGeneralEventStatus=false;//the UI events always call the root machine
  829. }
  830. //is it a delayed event?
  831. if ( doForceProcess == false
  832. && currentEventConfiguration
  833. && currentEventConfiguration.how_process_event
  834. && currentEventConfiguration.how_process_event.delay
  835. )
  836. {
  837. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Event '+anEvent+' delayed will exit',3);
  838. this.delayProcess(anEvent, currentEventConfiguration.how_process_event.delay, data);
  839. this.cleanExitProcess();
  840. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  841. return;
  842. }
  843. //compute EventIteration
  844. if (this._stateDefinition[currentStateEvent][anEvent].EventIteration == undefined)
  845. this._stateDefinition[currentStateEvent][anEvent].EventIteration =0;
  846. this._stateDefinition[currentStateEvent][anEvent].EventIteration++;
  847. this.EventIteration = this._stateDefinition[currentStateEvent][anEvent].EventIteration;
  848. //verify if the event can be processed according to 'enter' condition
  849. if ( (currentEventConfiguration.process_event_if)
  850. && (eval(currentEventConfiguration.process_event_if) == false)
  851. )
  852. {
  853. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Event '+anEvent+' event not allowed to process (process_event_if rule is not OK) will exit',3);
  854. if (currentEventConfiguration.propagate_event_on_refused)
  855. {
  856. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Event '+currentEventConfiguration.propagate_event_on_refused+' triggered on exit because of propagate_event_on_refused',3);
  857. this.trigger(currentEventConfiguration.propagate_event_on_refused,null,currentEventConfiguration.propagate_event_on_localmachine);
  858. }
  859. //exit as not accepted...
  860. this.cleanExitProcess();
  861. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  862. return;
  863. }
  864. //*********************************************
  865. //ok we will really process this event...
  866. //*********************************************
  867. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> currently processing',2);
  868. var lastprocessEventStatus = this.processEventStatus;
  869. this.processEventStatus = 'processing';
  870. var funcReturn = true;
  871. var localdata;
  872. //clear any preventCancel tag
  873. if (data && data[1] && data[1].preventCancelSet) delete(data[1].preventCancelSet);
  874. //call to the action (init_function) before transition state
  875. if (currentEventConfiguration.init_function)
  876. {
  877. localdata = [].slice.call(data);
  878. localdata.unshift(currentEventConfiguration.properties_init_function);
  879. funcReturn= currentEventConfiguration.init_function.apply(this,localdata);
  880. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> init_function done',3);
  881. }
  882. /*
  883. * Process the transition of state
  884. *
  885. */
  886. // do we change state?
  887. //is this a Push/Pop State?
  888. if (funcReturn != false)//it's ok for next_state
  889. {
  890. if (currentEventConfiguration.pushpop_state)
  891. {
  892. switch(currentEventConfiguration.pushpop_state)
  893. {
  894. case 'PushState':
  895. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Push state to state '+this.currentState,3);
  896. this.pushStateList.push(this.currentState); //do not use currentStateEvent!
  897. break;
  898. case 'PopState':
  899. if (this.pushStateList.length > 0)
  900. {
  901. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Pop state to state '+currentEventConfiguration.next_state,3);
  902. this.pushStateList.pop();
  903. }
  904. break;
  905. }
  906. }
  907. }
  908. //do we change of state?
  909. if ( (funcReturn != false)
  910. && (currentEventConfiguration.next_state)
  911. && (currentState != currentEventConfiguration.next_state)
  912. && (
  913. (
  914. (currentEventConfiguration.next_state_when == undefined)
  915. && (currentEventConfiguration.next_state_on_target == undefined)
  916. )
  917. || (
  918. (currentEventConfiguration.next_state_when)
  919. && (eval(currentEventConfiguration.next_state_when) == true)
  920. )
  921. || (
  922. (currentEventConfiguration.next_state_on_target)
  923. && (this.subMachinesRespectTargets(anEvent) == true)
  924. )
  925. )
  926. )
  927. {
  928. //we reinit the iteration on the events
  929. $.each(this._stateDefinition[this.currentState],
  930. function(aKey,aValue)
  931. {
  932. if (!thisFSM._stateDefinition[thisFSM.currentState][aKey])
  933. {
  934. thisFSM._log(aKey+" does not exist in state "+thisFSM.currentState,1);
  935. }
  936. else if (aKey!='delegate_machines')
  937. thisFSM._stateDefinition[thisFSM.currentState][aKey].EventIteration =0;
  938. });
  939. //we cancel any waiting events on the state
  940. this.cancelDelayedProcess();
  941. anEv[0].type='exitState';
  942. //we alert that we're exiting the state (except if we're starting the machine...
  943. if (anEvent !=this.opts.startEvent)
  944. {
  945. this.processEvent('exitState',anEv,true);
  946. }
  947. /*
  948. *********************************************
  949. * we change the current state Here!
  950. *********************************************
  951. */
  952. if (this._stateDefinition[currentEventConfiguration.next_state])
  953. {
  954. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Go to (see next_state) '+currentEventConfiguration.next_state,3);
  955. this.lastState=this.currentState;
  956. this.currentState = currentEventConfiguration.next_state;
  957. }
  958. else
  959. {
  960. this._log('processEvent: '+this.FSMName+':'+currentEventConfiguration.next_state+'-> DOES NOT EXIST!',1);
  961. this.lastState=this.currentState;
  962. }
  963. //*********************************************
  964. //and now we're entering the new state
  965. //*********************************************
  966. anEv[0].type='enterState';
  967. this.processEvent('enterState',anEv,true);
  968. //propagate event if asked
  969. //propagate event(s)
  970. if (currentEventConfiguration.propagate_event != undefined)
  971. {
  972. if (!(currentEventConfiguration.propagate_event instanceof Array))
  973. currentEventConfiguration.propagate_event=[currentEventConfiguration.propagate_event];
  974. $.each(currentEventConfiguration.propagate_event,
  975. function(aKey,aPropagateEvent)
  976. {
  977. thisFSM._log('processEvent: '+thisFSM.FSMName+':'+currentState+':'+anEvent+'-> trigger event (see propagate_event) ---> '+aPropagateEvent,3);
  978. if (aPropagateEvent === true)
  979. thisFSM.trigger( anEvent, data[1],currentEventConfiguration.propagate_event_on_localmachine);
  980. else
  981. thisFSM.trigger( aPropagateEvent, data[1],currentEventConfiguration.propagate_event_on_localmachine);
  982. });
  983. }
  984. }
  985. /*
  986. * we stay in the same state?
  987. * so process the event propagation
  988. */
  989. else if ( (funcReturn != false)
  990. && (currentEventConfiguration.propagate_event != undefined)
  991. )
  992. {
  993. if (!(currentEventConfiguration.propagate_event instanceof Array))
  994. currentEventConfiguration.propagate_event=[currentEventConfiguration.propagate_event];
  995. //propagate event(s)
  996. $.each(currentEventConfiguration.propagate_event,
  997. function(aKey,aPropagateEvent)
  998. {
  999. thisFSM._log('processEvent: '+thisFSM.FSMName+':'+currentState+':'+anEvent+'-> trigger event (see propagate_event) ---> '+aPropagateEvent,3);
  1000. if (aPropagateEvent === true)
  1001. thisFSM.trigger( anEvent, data[1], currentEventConfiguration.propagate_event_on_localmachine);
  1002. else
  1003. thisFSM.trigger( aPropagateEvent, data[1], currentEventConfiguration.propagate_event_on_localmachine);
  1004. });
  1005. }
  1006. /*
  1007. * oups there was an error during the processing of the action
  1008. */
  1009. else if ( (funcReturn == false) && (currentEventConfiguration.next_state_if_error) )
  1010. {
  1011. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> error in init_function',3);
  1012. //is this a Push/Pop State?
  1013. if (currentEventConfiguration.pushpop_state_if_error)
  1014. {
  1015. switch(currentEventConfiguration.pushpop_state_if_error)
  1016. {
  1017. case 'PushState':
  1018. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Push state to state '+this.currentState,3);
  1019. this.pushStateList.push(this.currentState); //do not use currentStateEvent!
  1020. break;
  1021. case 'PopState':
  1022. if (this.pushStateList.length > 0)
  1023. {
  1024. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Pop state to state '+currentEventConfiguration.next_state_if_error,3);
  1025. this.pushStateList.pop();
  1026. }
  1027. break;
  1028. }
  1029. }
  1030. /*
  1031. *********************************************
  1032. * we change the current state Here!
  1033. *********************************************
  1034. */
  1035. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> Go to (see next_state_if_error) '+currentEventConfiguration.next_state_if_error,3);
  1036. this.lastState=this.currentState;
  1037. this.currentState = currentEventConfiguration.next_state_if_error;
  1038. //and now that we're entering the new state
  1039. anEv[0].type='enterState';
  1040. this.processEvent('enterState',anEv,true);
  1041. }
  1042. else
  1043. {
  1044. //nothing to do?
  1045. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> nothing to do',3);
  1046. }
  1047. // do the exit action
  1048. if (currentEventConfiguration.out_function)
  1049. {
  1050. localdata = [].slice.call(data);
  1051. localdata.unshift(currentEventConfiguration.properties_out_function);
  1052. funcReturn= currentEventConfiguration.out_function.apply(this,localdata);
  1053. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> out_function done',3);
  1054. }
  1055. this.processEventStatus = lastprocessEventStatus; //we globally finished the job...
  1056. this.cleanExitProcess();
  1057. this._log('processEvent: '+this.FSMName+':'+currentState+':'+anEvent+'-> EXIT PROCESS',3,-1);
  1058. };//end of processEvent
  1059. /*
  1060. * cleanExitProcess - clean for exit the processing of an event
  1061. */
  1062. fsm_manager.prototype.cleanExitProcess = function(anEvent,data) {
  1063. // processing lasting events
  1064. //we don't process the events if we were currently on an immediate event...
  1065. if (
  1066. (this.pushEventList.length)
  1067. && (this.processEventStatus == 'idle' || this.pushEventList.length>this.opts.maxPushEvent)
  1068. )
  1069. {
  1070. this.popEvent();
  1071. }
  1072. };
  1073. /**
  1074. * pushEvent - push an event in the flow of the processing of an event
  1075. * public Method
  1076. * @param anEvent : an event name
  1077. * @param data : {event, data}
  1078. * if data is not an array, we consider that it is an external pushed event...then create one from anEvent and data.
  1079. */
  1080. fsm_manager.prototype.pushEvent = function(anEvent,data) {
  1081. this._log('pushEvent: ---> '+anEvent);
  1082. if (this.pushEventList.length>this.opts.maxPushEvent)
  1083. {
  1084. this._log('pushEvent: too much events... ---> '+this.pushEventList.length,2);
  1085. return;
  1086. }
  1087. if ( (data == undefined) || (data.length == 0) || data[0].type == undefined )
  1088. {
  1089. var datatmp = new Array();
  1090. datatmp[0] = fsm_manager_create_event(this.myUIObject,anEvent);
  1091. datatmp[1] = data;
  1092. data = datatmp;
  1093. }
  1094. var anEventToPush = {anEvent:anEvent, data:data};
  1095. this.pushEventList.push( anEventToPush );
  1096. this._log('pushEvent: push nb event ---> '+this.pushEventList.length);
  1097. };
  1098. /*
  1099. * popEvent - pop an event and process it
  1100. * private Method
  1101. * we process event in a FIFO order
  1102. */
  1103. fsm_manager.prototype.popEvent = function() {
  1104. this._log('popEvent');
  1105. if (this.pushEventList.length > 0)
  1106. {
  1107. anEventToProcess = this.pushEventList.shift();
  1108. this._log('popEvent:'+anEventToProcess.anEvent,3);
  1109. if (anEventToProcess == undefined || anEventToProcess.anEvent == undefined) return false;
  1110. this.processEvent(anEventToProcess.anEvent,anEventToProcess.data);
  1111. return true;
  1112. }
  1113. else this._log('popEvent void list');
  1114. return false;
  1115. };//
  1116. /**
  1117. * delayProcess - push an event after a delay
  1118. * private Method
  1119. * @param anEvent : an event name
  1120. * @param aDelay : a delay to do the processing
  1121. * @param data : {event, data}
  1122. */
  1123. fsm_manager.prototype.delayProcess = function(anEvent, aDelay, data) {
  1124. this._log('delayProcess: ---> '+anEvent);
  1125. this.preventCancelId++;
  1126. //let aHashData = this.hashCode(JSON.stringify(data[1]));
  1127. let currentState = this.currentState;
  1128. let aDelayedProcessName=this.myUIObject.attr('id')+currentState+anEvent+this.preventCancelId;
  1129. if (!data[1]) data[1]={};//no data defined.... so define one
  1130. if (!this._stateDefinition[this.currentState][anEvent]) currentState = "DefaultState";
  1131. if (!this._stateDefinition[currentState][anEvent].how_process_event.DelayedProcessNames)
  1132. {
  1133. this._stateDefinition[currentState][anEvent].how_process_event.DelayedProcessNames=[];
  1134. }
  1135. if (this._stateDefinition[currentState][anEvent].how_process_event.preventcancel)
  1136. {
  1137. if (data[1].preventCancelSet) aDelayedProcessName=data[1].preventCancelSet; // same request that needs to be delayed again
  1138. else data[1]['preventCancelSet']=aDelayedProcessName;
  1139. }
  1140. this._stateDefinition[currentState][anEvent].how_process_event.DelayedProcessNames[aDelayedProcessName]=aDelayedProcessName;
  1141. //setTimeout(this.launchProcess,aDelay,this,anEvent,data);
  1142. jQuery.doTimeout(aDelayedProcessName,aDelay,fsm_manager_launchProcess,this,anEvent,data);
  1143. };
  1144. /**
  1145. * hash function
  1146. * from https://stackoverflow.com/questions/6122571/simple-non-secure-hash-function-for-javascript
  1147. * @todo needed?
  1148. **/
  1149. fsm_manager.prototype.hashCode = function(source) {
  1150. let hash = 0;
  1151. if (source.length == 0) {
  1152. return hash;
  1153. }
  1154. for (var i = 0; i < source.length; i++) {
  1155. var char = source.charCodeAt(i);
  1156. hash = ((hash<<5)-hash)+char;
  1157. hash = hash & hash; // Convert to 32bit integer
  1158. }
  1159. return hash;
  1160. }
  1161. /**
  1162. * cancelDelayedProcess - delete all delayed events of the current state except those declared as prevented
  1163. * public Method
  1164. */
  1165. fsm_manager.prototype.cancelDelayedProcess = function() {
  1166. this._log('cancelDelayedProcess');
  1167. var currentState = null;
  1168. var currentEventConfiguration;
  1169. for(aEvent in this._stateDefinition[this.currentState])
  1170. {
  1171. currentState = this.currentState;
  1172. if (!this._stateDefinition[currentState][aEvent]) currentState = "DefaultState";
  1173. if (!this._stateDefinition[currentState][aEvent])
  1174. {
  1175. this._log('cancelDelayedProcess: '+aEvent+" has no definition for "+this.currentState,1);
  1176. return;
  1177. }
  1178. currentEventConfiguration = this._stateDefinition[currentState][aEvent];
  1179. if ( currentEventConfiguration.how_process_event
  1180. && ( currentEventConfiguration.how_process_event.preventcancel == undefined
  1181. || currentEventConfiguration.how_process_event.preventcancel != true
  1182. )
  1183. )
  1184. {
  1185. if (currentEventConfiguration.how_process_event.DelayedProcessNames)
  1186. {
  1187. for(aDelayedProcessName in currentEventConfiguration.how_process_event.DelayedProcessNames)
  1188. {
  1189. jQuery.doTimeout(aDelayedProcessName);//cancel event
  1190. }
  1191. currentEventConfiguration.how_process_event.DelayedProcessNames=[];
  1192. }
  1193. }
  1194. }
  1195. };
  1196. /**
  1197. * this.trigger - trigger an event to the machine
  1198. * public function
  1199. * @param aEventName - name of an event
  1200. * @param [object](option) data parameters linked to the event
  1201. * @param sendToLocalMachine [true|false(default)](option) - if true, send event to the local machine, if not to the root machine
  1202. */
  1203. fsm_manager.prototype.trigger = function (aEventName,data,sendToLocalMachine) {
  1204. if (!sendToLocalMachine) sendToLocalMachine=false;
  1205. var anEv = new Array();
  1206. anEv[0] = fsm_manager_create_event(this.myUIObject,aEventName,null);
  1207. anEv[1] = data;
  1208. anEv[2] = {targetFSM:this,localMachine:sendToLocalMachine};
  1209. if (!sendToLocalMachine)
  1210. this.rootMachine.processEvent(aEventName,anEv);
  1211. else
  1212. this.processEvent(aEventName,anEv);
  1213. };//end of
  1214. /**
  1215. * subMachinesRespectTargets - verify if the set of submachines respects the target of the current event
  1216. * @param String anEvent
  1217. * @return boolean - true if target is respected
  1218. */
  1219. fsm_manager.prototype.subMachinesRespectTargets = function (anEvent) {
  1220. this._log('subMachinesRespectTargets:');
  1221. var aStateDefinition = this._stateDefinition[this.currentState];
  1222. var targetConfiguration = aStateDefinition[anEvent].next_state_on_target;
  1223. var condition = targetConfiguration.condition;
  1224. var aResult = (condition == '||') ? false:true;
  1225. var aSMList = targetConfiguration.submachines;
  1226. var localRes;
  1227. for(aSubMachine in aSMList)
  1228. {
  1229. localRes = targetConfiguration.submachines[aSubMachine].target_list.indexOf(aStateDefinition.delegate_machines[aSubMachine].myFSM.currentState) > -1 ;
  1230. if (
  1231. (targetConfiguration.submachines[aSubMachine].condition != undefined)
  1232. && (targetConfiguration.submachines[aSubMachine].condition == 'not')
  1233. )
  1234. localRes = !localRes;
  1235. if (condition == '||')
  1236. {
  1237. aResult = aResult || localRes;
  1238. if (aResult == true) return aResult;//we can stop as it a && operator
  1239. }
  1240. else if (condition == '&&')
  1241. {
  1242. aResult = aResult && localRes;
  1243. if (aResult == false) return aResult;//we can stop as it a && operator
  1244. }
  1245. else
  1246. {
  1247. this._log('operator unknown'+condition);
  1248. return aResult;
  1249. }
  1250. }
  1251. return aResult;
  1252. };
  1253. /**
  1254. * this._log - log function
  1255. * private function
  1256. * @param message - message to log
  1257. * @param error_level (default : 3)
  1258. * - 1 : it's an error
  1259. * - 2 : it's a warning
  1260. * - 3 : it's a notice
  1261. * @param add_offset (default:0) :
  1262. * 1 : add blank offset on the left of the message
  1263. * -1 : remove left blank offset on the left of the message
  1264. * @remarks
  1265. * - this.opts.debug needs to be set to have errors raised
  1266. * - if this.opts.AlertError is set, then error message will raise an alert box
  1267. * - if this.opts.logFSM is set, and contains a FSM name list, then only FSM in this list will raise errors
  1268. */
  1269. fsm_manager.prototype.log_offsetstring='';
  1270. fsm_manager.prototype._log = function (message) {
  1271. /*global console:true */
  1272. let error = (arguments[1])? arguments[1] : 3;
  1273. //show only errors if debug is not set
  1274. if ( (error >= 2) && (!this.opts.debug) ) return;
  1275. if ( error > this.opts.LogLevel) return; //we continue if error_level <= LogLevel
  1276. // if logFSM is defined, only log the FSM listed in it
  1277. if ( this.opts.logFSM && this.opts.logFSM.indexOf(this.FSMName)<0) return;
  1278. if ( (arguments.length > 2) && (arguments[2] == -1))
  1279. this.log_offsetstring = this.log_offsetstring.replace(' ','');
  1280. if (window.console && console.log)
  1281. {
  1282. if (error == 1)
  1283. {
  1284. console.error('[fsm] ' + this.log_offsetstring + message);
  1285. }
  1286. else if (error == 2)
  1287. {
  1288. console.warn('[fsm] ' + this.log_offsetstring + message);
  1289. }
  1290. else
  1291. {
  1292. console.log('[fsm] ' + this.log_offsetstring + message);
  1293. }
  1294. if ( (error == 1) && this.opts.AlertError) alert(message);
  1295. if ( ( arguments.length > 2 ) && (arguments[2] == 1) )
  1296. this.log_offsetstring = this.log_offsetstring+" ";
  1297. }
  1298. };//end of _log
  1299. /*
  1300. * functions that can be used for the events of a state machine
  1301. */
  1302. /**
  1303. * triggerMe - trigger an event on an object
  1304. * to be used within a state function
  1305. * example :
  1306. * init_function : fsm_manager_triggerMe,
  1307. * properties_init_function : {objectToTrigger:'#myButton',eventNameToTrigger:'click'} ,
  1308. * @param objectParameters
  1309. * - {objectToTrigger: a jquery selector ,eventNameToTrigger: a event name to trigger}
  1310. * @param event - the FSM event that called the function
  1311. * @param data - the FSM event data
  1312. *
  1313. * @param this - the FSM object (well... if called in a state function)
  1314. * @deprecated
  1315. */
  1316. fsm_manager_triggerMe = function(objectParameters, event, data)
  1317. {
  1318. this._log('[fsm_manager_triggerMe]'+$(objectParameters.objectToTrigger).attr('id')+'-'+objectParameters.eventNameToTrigger);
  1319. $(objectParameters.objectToTrigger).trigger( objectParameters.eventNameToTrigger );
  1320. };
  1321. /**
  1322. * fsm_manager_getcss3prop -
  1323. * pass in an unaltered CSS property, and the function will return the vendor specific JavaScript equivalent property
  1324. * supported by the browser
  1325. * @param string cssprop - a css property
  1326. *
  1327. * <code>
  1328. * getcss3prop('border-radius'); // returns 'borderRadius' or one of the variants, such as 'MozBorderRadius', 'WebkitBorderRadius' etc
  1329. * </code>
  1330. */
  1331. function fsm_manager_getcss3prop(cssprop){
  1332. var css3vendors = ['', '-moz-','-webkit-','-o-','-ms-','-khtml-'];
  1333. var root = document.documentElement;
  1334. function camelCase(str){
  1335. return str.replace(/\-([a-z])/gi, function (match, p1){ // p1 references submatch in parentheses
  1336. return p1.toUpperCase(); // convert first letter after "-" to uppercase
  1337. });
  1338. }
  1339. for (var i=0; i<css3vendors.length; i++){
  1340. var css3propcamel = camelCase( css3vendors[i] + cssprop );
  1341. if (css3propcamel.substr(0,2) == 'Ms') // if property starts with 'Ms'
  1342. css3propcamel = 'm' + css3propcamel.substr(1); // Convert 'M' to lowercase
  1343. if (css3propcamel in root.style)
  1344. return css3propcamel;
  1345. };
  1346. return undefined;
  1347. }
  1348. /**
  1349. * fsm_manager_create_event -
  1350. * create a dummy event compliant with the FSM processing
  1351. * @param string anEventName - an event name
  1352. * @param {} aTarget - a javascript DOM object
  1353. */
  1354. function fsm_manager_create_event(aTarget,anEventName,data){
  1355. var aDummyEvent = {};
  1356. aDummyEvent.data = data;
  1357. aDummyEvent.target = aTarget;
  1358. aDummyEvent.currentTarget = aTarget;
  1359. aDummyEvent.type = anEventName;
  1360. aDummyEvent.stopPropagation=function(){return true;};
  1361. return aDummyEvent;
  1362. }
  1363. /**
  1364. * launchProcess -
  1365. * private Method
  1366. * @param anEvent : an event name
  1367. * @param aDelay : a delay to do the processing
  1368. * @param data : {event, data}
  1369. */
  1370. fsm_manager_launchProcess = function(aFsm, anEvent, data) {
  1371. aFsm._log('launchProcess: ---> '+anEvent);
  1372. aFsm.processEvent(anEvent,data,true);
  1373. };
  1374. /**
  1375. * @param iFSMList - array of the created FSM linked with their Objects
  1376. * iFSMList[aStateDefinition]
  1377. */
  1378. var iFSMList = {};
  1379. //jQuery definition
  1380. /**
  1381. * $.iFSM - iterate over a jQuery object to assign for each matched element a FSM machine
  1382. * @param aStateDefinition - a state definition
  1383. * @param options - options of the FSM machine
  1384. * Remarks :
  1385. * - any DOM object involved with a FSM needs to have its 'id' attribute defined
  1386. * - the init state may be defined with options.initState
  1387. */
  1388. $.fn.iFSM = function(aStateDefinition, options)
  1389. {
  1390. return this.each(
  1391. function()
  1392. {
  1393. if ( ($(this)[0] == document) && !$(this).attr('id') )
  1394. {
  1395. // set an id to document... a iFSM needs one...
  1396. $(this).attr('id','iFSMDocumentRoot');
  1397. }
  1398. if ($(this).attr('id') != undefined)
  1399. {
  1400. if (iFSMList[$(this).attr('id')]==undefined)
  1401. {
  1402. iFSMList[$(this).attr('id')]=[];
  1403. }
  1404. var iFSM = new fsm_manager($(this), aStateDefinition, options);
  1405. if ($(this).getFSM(aStateDefinition))
  1406. {
  1407. console.warn('[warn][fsm] state machine was already set for this state definition on '+$(this).attr('id'));
  1408. }
  1409. iFSMList[$(this).attr('id')].push(iFSM) ;
  1410. if (options && options.initState != undefined) iFSM.InitManager(options.initState); //start it
  1411. else iFSM.InitManager(); //start it
  1412. }
  1413. else
  1414. {
  1415. if (options && options.debug) alert('Can\'t initialized state machine because the DOM object has no "id" property');
  1416. console.warn('[error][fsm] Can\'t initialized state machine because the DOM object has no "id" property');
  1417. }
  1418. });
  1419. };
  1420. /**
  1421. * $.getFSM - returns the array of FSM linked to the object
  1422. * @param aStateDefinition (optional) - if defined
  1423. * @return an array of the FSMs linked to the object
  1424. */
  1425. $.fn.getFSM = function(aStateDefinition) {
  1426. if ( (this.length != 1) || (this.attr('id') == undefined) )
  1427. return [];
  1428. if (aStateDefinition == undefined)
  1429. return iFSMList[$(this).attr('id')];
  1430. else
  1431. {
  1432. var aFSM = null;
  1433. for (var i = 0, aFSMItem = null; i < iFSMList[$(this).attr('id')].length ; i++)
  1434. {
  1435. aFSMItem = iFSMList[$(this).attr('id')][i];
  1436. if (aFSMItem._originalstateDefinition == aStateDefinition)
  1437. {
  1438. aFSM = aFSMItem;
  1439. break;
  1440. }
  1441. }
  1442. return aFSM;
  1443. }
  1444. };
  1445. })(jQuery);