1 | import {
|
2 | createAction,
|
3 | executeAction,
|
4 | Annotation,
|
5 | storeAnnotation,
|
6 | die,
|
7 | isFunction,
|
8 | isStringish,
|
9 | createDecoratorAnnotation,
|
10 | createActionAnnotation
|
11 | } from "../internal"
|
12 |
|
13 | export const ACTION = "action"
|
14 | export const ACTION_BOUND = "action.bound"
|
15 | export const AUTOACTION = "autoAction"
|
16 | export const AUTOACTION_BOUND = "autoAction.bound"
|
17 |
|
18 | const DEFAULT_ACTION_NAME = "<unnamed action>"
|
19 |
|
20 | const actionAnnotation = createActionAnnotation(ACTION)
|
21 | const actionBoundAnnotation = createActionAnnotation(ACTION_BOUND, {
|
22 | bound: true
|
23 | })
|
24 | const autoActionAnnotation = createActionAnnotation(AUTOACTION, {
|
25 | autoAction: true
|
26 | })
|
27 | const autoActionBoundAnnotation = createActionAnnotation(AUTOACTION_BOUND, {
|
28 | autoAction: true,
|
29 | bound: true
|
30 | })
|
31 |
|
32 | export interface IActionFactory extends Annotation, PropertyDecorator {
|
33 |
|
34 | <T extends Function | undefined | null>(fn: T): T
|
35 |
|
36 | <T extends Function | undefined | null>(name: string, fn: T): T
|
37 |
|
38 |
|
39 | (customName: string): PropertyDecorator & Annotation
|
40 |
|
41 |
|
42 | bound: Annotation & PropertyDecorator
|
43 | }
|
44 |
|
45 | function createActionFactory(autoAction: boolean): IActionFactory {
|
46 | const res: IActionFactory = function action(arg1, arg2?): any {
|
47 |
|
48 | if (isFunction(arg1))
|
49 | return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction)
|
50 |
|
51 | if (isFunction(arg2)) return createAction(arg1, arg2, autoAction)
|
52 |
|
53 | if (isStringish(arg2)) {
|
54 | return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation)
|
55 | }
|
56 |
|
57 | if (isStringish(arg1)) {
|
58 | return createDecoratorAnnotation(
|
59 | createActionAnnotation(autoAction ? AUTOACTION : ACTION, {
|
60 | name: arg1,
|
61 | autoAction
|
62 | })
|
63 | )
|
64 | }
|
65 |
|
66 | if (__DEV__) die("Invalid arguments for `action`")
|
67 | } as IActionFactory
|
68 | return res
|
69 | }
|
70 |
|
71 | export const action: IActionFactory = createActionFactory(false)
|
72 | Object.assign(action, actionAnnotation)
|
73 | export const autoAction: IActionFactory = createActionFactory(true)
|
74 | Object.assign(autoAction, autoActionAnnotation)
|
75 |
|
76 | action.bound = createDecoratorAnnotation(actionBoundAnnotation)
|
77 | autoAction.bound = createDecoratorAnnotation(autoActionBoundAnnotation)
|
78 |
|
79 | export function runInAction<T>(fn: () => T): T {
|
80 | return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined)
|
81 | }
|
82 |
|
83 | export function isAction(thing: any) {
|
84 | return isFunction(thing) && thing.isMobxAction === true
|
85 | }
|