-
Notifications
You must be signed in to change notification settings - Fork 400
/
devtools.plugin.ts
70 lines (63 loc) 路 2.45 KB
/
devtools.plugin.ts
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
import { Injectable, Inject, Injector } from '@angular/core';
import { NgxsPlugin, getActionTypeFromInstance, StateStream, Store } from '@ngxs/store';
import { tap } from 'rxjs/operators';
import { NgxsDevtoolsExtension, NgxsDevtoolsOptions, NGXS_DEVTOOLS_OPTIONS, NgxsDevtoolsAction } from './symbols';
/**
* Adds support for the Redux Devtools extension:
* http://extension.remotedev.io/
*/
@Injectable()
export class NgxsReduxDevtoolsPlugin implements NgxsPlugin {
private readonly devtoolsExtension: NgxsDevtoolsExtension | null = null;
private readonly windowObj: any = typeof window !== 'undefined' ? window : {};
constructor(
@Inject(NGXS_DEVTOOLS_OPTIONS) private _options: NgxsDevtoolsOptions,
private _state: StateStream,
private _injector: Injector
) {
const globalDevtools = this.windowObj['__REDUX_DEVTOOLS_EXTENSION__'] || this.windowObj['devToolsExtension'];
if (globalDevtools) {
this.devtoolsExtension = globalDevtools.connect(_options) as NgxsDevtoolsExtension;
this.devtoolsExtension.subscribe(a => this.dispatched(a));
}
}
/**
* Middleware handle function
*/
handle(state: any, action: any, next: any) {
const isDisabled = this._options && this._options.disabled;
if (!this.devtoolsExtension || isDisabled) {
return next(state, action);
}
return next(state, action).pipe(
tap(newState => {
// if init action, send initial state to dev tools
const isInitAction = getActionTypeFromInstance(action) === '@@INIT';
if (isInitAction) {
this.devtoolsExtension.init(state);
} else {
const type = getActionTypeFromInstance(action);
this.devtoolsExtension.send({ ...action, type }, newState);
}
})
);
}
/**
* Handle the action from the dev tools subscription
*/
dispatched(action: NgxsDevtoolsAction) {
if (action.type === 'DISPATCH') {
if (action.payload.type === 'JUMP_TO_ACTION' || action.payload.type === 'JUMP_TO_STATE') {
const prevState = JSON.parse(action.state);
this._state.next(prevState);
} else if (action.payload.type === 'TOGGLE_ACTION') {
console.warn('Skip is not supported at this time.');
}
} else if (action.type === 'ACTION') {
// Lazy get the store for circular depedency issues
const store = this._injector.get(Store);
const actionPayload = JSON.parse(action.payload);
store.dispatch(actionPayload);
}
}
}