Skip to content

Commit

Permalink
format string tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lunaruan committed May 13, 2022
1 parent 2c8a145 commit 46ac276
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
21 changes: 21 additions & 0 deletions packages/react-devtools-shared/src/__tests__/utils-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,5 +189,26 @@ describe('utils', () => {
]);
expect(formatWithStyles(['%%c%c'], 'color: gray')).toEqual(['%%c%c']);
});

it('should format non string inputs as the first argument', () => {
expect(formatWithStyles([{foo: 'bar'}])).toEqual([{foo: 'bar'}]);
expect(formatWithStyles([[1, 2, 3]])).toEqual([[1, 2, 3]]);
expect(formatWithStyles([{foo: 'bar'}], 'color: gray')).toEqual([
'%c%o',
'color: gray',
{foo: 'bar'},
]);
expect(formatWithStyles([[1, 2, 3]], 'color: gray')).toEqual([
'%c%o',
'color: gray',
[1, 2, 3],
]);
expect(formatWithStyles([{foo: 'bar'}, 'hi'], 'color: gray')).toEqual([
'%c%o %s',
'color: gray',
{foo: 'bar'},
'hi',
]);
});
});
});
5 changes: 2 additions & 3 deletions packages/react-devtools-shared/src/backend/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,17 +181,16 @@ export function formatWithStyles(
inputArgs === undefined ||
inputArgs === null ||
inputArgs.length === 0 ||
typeof inputArgs[0] !== 'string' ||
// Matches any of %c but not %%c
inputArgs[0].match(/([^%]|^)(%c)/g) ||
(typeof inputArgs[0] === 'string' && inputArgs[0].match(/([^%]|^)(%c)/g)) ||
style === undefined
) {
return inputArgs;
}

// Matches any of %(o|O|d|i|s|f), but not %%(o|O|d|i|s|f)
const REGEXP = /([^%]|^)((%%)*)(%([oOdisf]))/g;
if (inputArgs[0].match(REGEXP)) {
if (typeof inputArgs[0] === 'string' && inputArgs[0].match(REGEXP)) {
return [`%c${inputArgs[0]}`, style, ...inputArgs.slice(1)];
} else {
const firstArg = inputArgs.reduce((formatStr, elem, i) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/react-devtools-shared/src/hook.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,17 +180,17 @@ export function installHook(target: any): DevToolsHook | null {
inputArgs === undefined ||
inputArgs === null ||
inputArgs.length === 0 ||
typeof inputArgs[0] !== 'string' ||
// Matches any of %c but not %%c
inputArgs[0].match(/([^%]|^)(%c)/g) ||
(typeof inputArgs[0] === 'string' &&
inputArgs[0].match(/([^%]|^)(%c)/g)) ||
style === undefined
) {
return inputArgs;
}

// Matches any of %(o|O|d|i|s|f), but not %%(o|O|d|i|s|f)
const REGEXP = /([^%]|^)((%%)*)(%([oOdisf]))/g;
if (inputArgs[0].match(REGEXP)) {
if (typeof inputArgs[0] === 'string' && inputArgs[0].match(REGEXP)) {
return [`%c${inputArgs[0]}`, style, ...inputArgs.slice(1)];
} else {
const firstArg = inputArgs.reduce((formatStr, elem, i) => {
Expand Down

0 comments on commit 46ac276

Please sign in to comment.