main
js 75 lines 2 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 // This flips color using ANSI, then sets a color styling, then resets.
12 const badgeFormat = '\x1b[0m\x1b[7m%c%s\x1b[0m%c';
13 // Same badge styling as DevTools.
14 const badgeStyle =
15 // We use a fixed background if light-dark is not supported, otherwise
16 // we use a transparent background.
17 'background: #e6e6e6;' +
18 'background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));' +
19 'color: #000000;' +
20 'color: light-dark(#000000, #ffffff);' +
21 'border-radius: 2px';
22 const resetStyle = '';
23 const pad = ' ';
24
25 const bind = Function.prototype.bind;
26
27 export function bindToConsole(
28 methodName: string,
29 args: Array<any>,
30 badgeName: string,
31 ): () => any {
32 let offset = 0;
33 switch (methodName) {
34 case 'dir':
35 case 'dirxml':
36 case 'groupEnd':
37 case 'table': {
38 // These methods cannot be colorized because they don't take a formatting string.
39 // $FlowFixMe[incompatible-type]
40 return bind.apply(console[methodName], [console].concat(args)); // eslint-disable-line react-internal/no-production-logging
41 }
42 case 'assert': {
43 // assert takes formatting options as the second argument.
44 offset = 1;
45 }
46 }
47
48 const newArgs = args.slice(0);
49 if (typeof newArgs[offset] === 'string') {
50 newArgs.splice(
51 offset,
52 1,
53 badgeFormat + ' ' + newArgs[offset],
54 badgeStyle,
55 pad + badgeName + pad,
56 resetStyle,
57 );
58 } else {
59 newArgs.splice(
60 offset,
61 0,
62 badgeFormat,
63 badgeStyle,
64 pad + badgeName + pad,
65 resetStyle,
66 );
67 }
68
69 // The "this" binding in the "bind";
70 newArgs.unshift(console);
71
72 // $FlowFixMe[incompatible-type]
73 // $FlowFixMe[invalid-computed-prop]
74 return bind.apply(console[methodName], newArgs); // eslint-disable-line react-internal/no-production-logging
75 }