All files / src connectRdtLogger.ts

100% Statements 41/41
100% Branches 15/15
100% Functions 10/10
100% Lines 41/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 1792x 2x                   2x                   2x   12x         12x       2x               10x 10x 10x 10x       11x 1x     10x 10x 10x 10x       12x 2x     10x 10x 10x 10x               10x 10x 10x 10x       10x 88x           88x 83x   5x 5x 5x 5x           5x 1x     4x 3x   1x                   4x                                                                                                                            
import { RootState, RootStateChangeEvent } from "./StateController";
export { connectRdtLogger }
 
/*
 * Redux Dev Tools
 * 
 * Docs:
 * https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Methods.md
 */
 
 
let _rdtLogger:RdtLogger|null|undefined = undefined;
 
 
/**
 * Logs root state changes to redux dev tools
 * and pushes previous state snapshots from rdt
 * to the root state and any connected controllers.
 * @param name the name of the dev tools instance
 * @returns a connected RdtLogger or null if it cannot connect.
 */
const connectRdtLogger = (name?:string):RdtLogger|null => {
    // singleton; return if defined
    _rdtLogger = _rdtLogger !== undefined ? _rdtLogger :
        // set the logger to null if no extension is installed
        !window.__REDUX_DEVTOOLS_EXTENSION__ ? null :
            // otherwise create the logger
            new RdtLogger(window.__REDUX_DEVTOOLS_EXTENSION__, name).connect();
    return _rdtLogger;
};
 
 
export class RdtLogger {
    isConnected:boolean;
    private name?:string;
    private rdtExtension:DevToolsExtension;
    private rdt!:DevToolsInstance;
    private abortController:AbortController;
 
    constructor(rdtExtension:DevToolsExtension, name?:string, ) {
        this.name = name;
        this.isConnected = false;
        this.abortController = new AbortController();
        this.rdtExtension = rdtExtension;
    }
 
    connect() {
        if (this.isConnected) {
            return this;
        }
 
        this.rdt = this.connectToDevTools(this.name);
        this.listenForRootstateChanges();
        this.isConnected = true;
        return this;
    }
 
    disconnect() {
        if (this.isConnected === false) {
            return;
        }
        
        this.rdt.unsubscribe();
        this.abortController.abort();
        this.isConnected = false;
        _rdtLogger = undefined;
    }
 
    /**
     * Calls connect on the dev tools instance
     * @param name the dev tools instance name
     */
    private connectToDevTools(name?:string):DevToolsInstance {
        const dt =  this.rdtExtension.connect({name});
        dt.init(RootState.current);
        dt.subscribe(this.updateFromDevTools.bind(this));
        return dt;
    };
 
    private listenForRootstateChanges() {
        RootState.addRootStateChangeEventListener((event:RootStateChangeEvent) =>
            this.rdt.send(this.getDevToolsActionFromEvent(event.event), event.rootState)), {
                signal: this.abortController.signal
            };
    }
 
    private getDevToolsActionFromEvent(event:Event|string):DevToolsAction {
        if (typeof event === "string") {
            return { type: event };
        }
        const action = JSON.parse(JSON.stringify(event));
        delete action.isTrusted;
        action.type = event.type;
        return action;
    }
 
    private updateFromDevTools(data:DevToolsEventData) {
 
        // return if initializing
        if (data.type === "START" || data.payload.type === "IMPORT_STATE") {
            return;
        }
    
        if (this.canHandleUpdate(data)) {            
            RootState.push(JSON.parse(data.state));
        } else {
            this.rdt.error(`DataElement RDT logging does not support payload type: ${data.type}:${data.payload.type}`);
        }
    }
 
    /**
     * Returns true if we can handle the data update from dev tools
     * @param data
     * @returns {boolean}
     */
    private canHandleUpdate(data:DevToolsEventData):boolean {
        return data.type === "DISPATCH" && (
            data.payload.type === "JUMP_TO_ACTION" ||
            data.payload.type === "JUMP_TO_STATE"
        );
    }
}
 
 
 
 
export interface DevToolsExtension {
    /** Creates a new dev tools extension instance. */
    connect({name}:{name?:string}):DevToolsInstance
}
 
 
export interface DevToolsInstance {
    /** Sends the initial state to the monitor. */
    init(state:any): void,
    /** 
     * Adds a change listener. It will be called any time an action
     * is dispatched from the monitor. Returns a function to
     * unsubscribe the current listener.
     */
    subscribe(listener:Function): void,
    /** Unsubscribes all listeners. */
    unsubscribe(): void,
    /** Sends a new action and state manually to be shown on the monitor. */
    send(action:DevToolsAction|string, state:any): void,
    /** Sends the error message to be shown in the extension's monitor. */
    error(message:string): void
}
 
 
interface DevToolsAction {
    type: string
}
 
 
interface DevToolsEventData {
    id:string,
    /**
     * "START" - on RDT init
     * "DISPATCH" - when dispatching
     */
    type: string,
    payload: {
        /**
         * JUMP_TO_ACTION - can change state here
         * TOGGLE_ACTION - dont support toggle
         */
        type: string
    },
    state: any
}
 
 
declare global {
    interface Window {
        __REDUX_DEVTOOLS_EXTENSION__?: DevToolsExtension;
    }
}