UNPKG

1.72 kBPlain TextView Raw
1import {createLogger} from "@gongt/ts-stl-library/debug/create-logger";
2import {LOG_LEVEL} from "@gongt/ts-stl-library/debug/levels";
3import {MonkeyPatch} from "@gongt/ts-stl-library/pattern/monkey-patch";
4import * as React from "react";
5
6export function injectRenderInspect() {
7 const hintRender = createLogger(LOG_LEVEL.SILLY, 'render');
8 if (hintRender.enabled) {
9 hintRender.fn = console.group.bind(console);
10 const m = new MonkeyPatch(React.createElement);
11 let timeout, times = {};
12 const defTimes = {};
13 const cb = () => {
14 hintRender('render tick: ');
15 const dbg = Object.keys(times).filter((k) => times[k]).map(k => [k, times[k]]);
16 console.table(dbg);
17 Object.assign(times, defTimes);
18 console.groupEnd();
19 timeout = null;
20 };
21 const handle = (name: string) => {
22 times[name]++;
23 if (!timeout) {
24 timeout = setTimeout(cb, 0);
25 }
26 };
27 m.argumentsValue((args: any[]) => {
28 const Component: any = args[0];
29 if (typeof Component !== 'object' && typeof Component !== 'function') {
30 handle(Component);
31 return args;
32 }
33 let name = Component.displayname || Component.constructor.displayName || Component.constructor.name || 'unknown';
34 if (name === 'Function' && Component.name) {
35 name = Component.name;
36 }
37 defTimes[name] = 0;
38 if (!times.hasOwnProperty(name)) {
39 times[name] = 0;
40 }
41
42 handle(Component);
43 if (Component.render) {
44 if (!Component['___debug']) {
45 Component['___debug'] = true;
46 const ov = Component.render.bind(Component);
47 Component.render = (...args: any[]) => {
48 handle(name);
49 return ov(...args);
50 };
51 }
52 }
53 return args;
54 });
55 Object.assign(React, <any>{createElement: m.getFunction()});
56 }
57}