main
js 74 lines 1.91 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @flow
8 */
9
10 // Keep in sync with ReactServerConsoleConfig
11 const badgeFormat = '%c%s%c';
12 // Same badge styling as DevTools.
13 const badgeStyle =
14 // We use a fixed background if light-dark is not supported, otherwise
15 // we use a transparent background.
16 'background: #e6e6e6;' +
17 'background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));' +
18 'color: #000000;' +
19 'color: light-dark(#000000, #ffffff);' +
20 'border-radius: 2px';
21 const resetStyle = '';
22 const pad = ' ';
23
24 const bind = Function.prototype.bind;
25
26 export function bindToConsole(
27 methodName: string,
28 args: Array<any>,
29 badgeName: string,
30 ): () => any {
31 let offset = 0;
32 switch (methodName) {
33 case 'dir':
34 case 'dirxml':
35 case 'groupEnd':
36 case 'table': {
37 // These methods cannot be colorized because they don't take a formatting string.
38 // $FlowFixMe[incompatible-type]
39 return bind.apply(console[methodName], [console].concat(args)); // eslint-disable-line react-internal/no-production-logging
40 }
41 case 'assert': {
42 // assert takes formatting options as the second argument.
43 offset = 1;
44 }
45 }
46
47 const newArgs = args.slice(0);
48 if (typeof newArgs[offset] === 'string') {
49 newArgs.splice(
50 offset,
51 1,
52 badgeFormat + ' ' + newArgs[offset],
53 badgeStyle,
54 pad + badgeName + pad,
55 resetStyle,
56 );
57 } else {
58 newArgs.splice(
59 offset,
60 0,
61 badgeFormat,
62 badgeStyle,
63 pad + badgeName + pad,
64 resetStyle,
65 );
66 }
67
68 // The "this" binding in the "bind";
69 newArgs.unshift(console);
70
71 // $FlowFixMe[incompatible-type]
72 // $FlowFixMe[invalid-computed-prop]
73 return bind.apply(console[methodName], newArgs); // eslint-disable-line react-internal/no-production-logging
74 }