1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import State from "../states/State";
|
7 | import { AxesEventType, ValueOf, FlickingContext, StateType } from "../types";
|
8 | import { AXES_EVENTS, STATE_TYPE } from "../consts";
|
9 | import IdleState from "../states/IdleState";
|
10 | import HoldingState from "../states/HoldingState";
|
11 | import DraggingState from "../states/DraggingState";
|
12 | import AnimatingState from "../states/AnimatingState";
|
13 | import DisabledState from "../states/DisabledState";
|
14 |
|
15 | class StateMachine {
|
16 | private state: State = new IdleState();
|
17 |
|
18 | public fire(eventType: ValueOf<AxesEventType>, e: any, context: FlickingContext) {
|
19 | const currentState = this.state;
|
20 | switch (eventType) {
|
21 | case AXES_EVENTS.HOLD:
|
22 | currentState.onHold(e, context);
|
23 | break;
|
24 | case AXES_EVENTS.CHANGE:
|
25 | currentState.onChange(e, context);
|
26 | break;
|
27 | case AXES_EVENTS.RELEASE:
|
28 | currentState.onRelease(e, context);
|
29 | break;
|
30 | case AXES_EVENTS.ANIMATION_END:
|
31 | currentState.onAnimationEnd(e, context);
|
32 | break;
|
33 | case AXES_EVENTS.FINISH:
|
34 | currentState.onFinish(e, context);
|
35 | break;
|
36 | }
|
37 | }
|
38 |
|
39 | public getState(): State {
|
40 | return this.state;
|
41 | }
|
42 |
|
43 | public transitTo = (nextStateType: ValueOf<StateType>): State => {
|
44 | const currentState = this.state;
|
45 |
|
46 | if (currentState.type !== nextStateType) {
|
47 | let nextState: State;
|
48 |
|
49 | switch (nextStateType) {
|
50 | case STATE_TYPE.IDLE:
|
51 | nextState = new IdleState();
|
52 | break;
|
53 | case STATE_TYPE.HOLDING:
|
54 | nextState = new HoldingState();
|
55 | break;
|
56 | case STATE_TYPE.DRAGGING:
|
57 | nextState = new DraggingState();
|
58 | break;
|
59 | case STATE_TYPE.ANIMATING:
|
60 | nextState = new AnimatingState();
|
61 | break;
|
62 | case STATE_TYPE.DISABLED:
|
63 | nextState = new DisabledState();
|
64 | break;
|
65 | }
|
66 |
|
67 | currentState.onExit(nextState!);
|
68 | nextState!.onEnter(currentState);
|
69 |
|
70 | this.state = nextState!;
|
71 | }
|
72 | return this.state;
|
73 | }
|
74 | }
|
75 |
|
76 | export default StateMachine;
|