Add no-console eslint rule (#1890)

* Add no-console eslint rule

* Remove unused test
This commit is contained in:
Charles Bochet 2023-10-05 21:16:02 +02:00 committed by GitHub
parent 922f8eca0e
commit 07450df1a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 69 additions and 212 deletions

View File

@ -24,6 +24,12 @@ module.exports = {
jest: true,
},
overrides: [
{
files: ['*.stories.tsx', '*.test.ts'],
rules: {
'no-console': 'off',
}
},
{
files: ['*.js', '*.jsx', '*.ts', '*.tsx'],
rules: {
@ -96,5 +102,6 @@ module.exports = {
},
],
"@typescript-eslint/consistent-type-imports": ["error", { "prefer": "no-type-imports" }],
'no-console': ['error', { allow: ['group', 'groupCollapsed', 'groupEnd'] }],
}
};

View File

@ -15,6 +15,7 @@ import { createUploadLink } from 'apollo-upload-client';
import { renewToken } from '@/auth/services/AuthService';
import { AuthTokenPair } from '~/generated/graphql';
import { assertNotNull } from '~/utils/assert';
import { logDebug } from '~/utils/logDebug';
import { ApolloManager } from '../types/apolloManager.interface';
import { loggerLink } from '../utils';
@ -105,7 +106,7 @@ export class ApolloFactory<TCacheShape> implements ApolloManager<TCacheShape> {
}
default:
if (isDebugMode) {
console.warn(
logDebug(
`[GraphQL error]: Message: ${
graphQLError.message
}, Location: ${
@ -121,7 +122,7 @@ export class ApolloFactory<TCacheShape> implements ApolloManager<TCacheShape> {
if (networkError) {
if (isDebugMode) {
console.warn(`[Network error]: ${networkError}`);
logDebug(`[Network error]: ${networkError}`);
}
onNetworkError?.(networkError);
}

View File

@ -1,5 +1,8 @@
import { ApolloLink, gql, Operation } from '@apollo/client';
import { logDebug } from '~/utils/logDebug';
import { logError } from '~/utils/logError';
import formatTitle from './format-title';
const getGroup = (collapsed: boolean) =>
@ -36,10 +39,10 @@ export const loggerLink = (getSchemaName: (operation: Operation) => string) =>
console.groupCollapsed(...titleArgs);
if (variables && Object.keys(variables).length !== 0) {
console.log('VARIABLES', variables);
logDebug('VARIABLES', variables);
}
console.log('QUERY', query);
logDebug('QUERY', query);
console.groupEnd();
@ -64,7 +67,7 @@ export const loggerLink = (getSchemaName: (operation: Operation) => string) =>
if (errors) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
errors.forEach((err: any) => {
console.log(
logDebug(
`%c${err.message}`,
// eslint-disable-next-line twenty/no-hardcoded-colors
'color: #F51818; font-weight: lighter',
@ -72,29 +75,29 @@ export const loggerLink = (getSchemaName: (operation: Operation) => string) =>
});
}
console.log('HEADERS: ', headers);
logDebug('HEADERS: ', headers);
if (variables && Object.keys(variables).length !== 0) {
console.log('VARIABLES', variables);
logDebug('VARIABLES', variables);
}
console.log('QUERY', query);
logDebug('QUERY', query);
if (result.data) {
console.log('RESULT', result.data);
logDebug('RESULT', result.data);
}
if (errors) {
console.log('ERRORS', errors);
logDebug('ERRORS', errors);
}
console.groupEnd();
} catch {
// this may happen if console group is not supported
console.log(
logDebug(
`${operationType} ${schemaName}::${queryName} (in ${time} ms)`,
);
if (errors) {
console.error(errors);
logError(errors);
}
}

View File

@ -9,6 +9,7 @@ import { entityFieldsFamilyState } from '@/ui/field/states/entityFieldsFamilySta
import { isThemeColor } from '@/ui/theme/utils/castStringAsThemeColor';
import { Pipeline } from '~/generated/graphql';
import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
import { logError } from '~/utils/logError';
import { companyProgressesFamilyState } from '../states/companyProgressesFamilyState';
import {
@ -98,7 +99,7 @@ export const useUpdateCompanyBoard = () =>
const newBoardColumns: BoardColumnDefinition[] =
orderedPipelineStages?.map((pipelineStage) => {
if (!isThemeColor(pipelineStage.color)) {
console.warn(
logError(
`Color ${pipelineStage.color} is not recognized in useUpdateCompanyBoard.`,
);
}

View File

@ -2,6 +2,7 @@ import { useEffect } from 'react';
import { useRecoilSnapshot, useRecoilValue } from 'recoil';
import { isDebugModeState } from '@/client-config/states/isDebugModeState';
import { logDebug } from '~/utils/logDebug';
const formatTitle = (stateName: string) => {
const headerCss = [
@ -33,9 +34,9 @@ export const RecoilDebugObserverEffect = () => {
console.groupCollapsed(...titleArgs);
console.log('STATE', loadable.state);
logDebug('STATE', loadable.state);
console.log('CONTENTS', loadable.contents);
logDebug('CONTENTS', loadable.contents);
console.groupEnd();
}

View File

@ -8,6 +8,7 @@ import { EntityForSelect } from '@/ui/input/relation-picker/types/EntityForSelec
import { RelationPickerHotkeyScope } from '@/ui/input/relation-picker/types/RelationPickerHotkeyScope';
import { useSnackBar } from '@/ui/snack-bar/hooks/useSnackBar';
import { ViewBarDropdownButton } from '@/ui/view-bar/components/ViewBarDropdownButton';
import { logError } from '~/utils/logError';
export const PipelineAddButton = () => {
const { enqueueSnackBar } = useSnackBar();
@ -30,9 +31,7 @@ export const PipelineAddButton = () => {
},
);
console.error(
'There was a problem with the company selection, please retry.',
);
logError('There was a problem with the company selection, please retry.');
return;
}
@ -44,7 +43,7 @@ export const PipelineAddButton = () => {
},
);
console.error('There was a problem with the pipeline stage selection.');
logError('There was a problem with the pipeline stage selection.');
return;
}
closeDropdown();

View File

@ -8,6 +8,7 @@ import { currentUserState } from '@/auth/states/currentUserState';
import { TextInputSettings } from '@/ui/input/text/components/TextInputSettings';
import { GET_CURRENT_USER } from '@/users/graphql/queries/getCurrentUser';
import { useUpdateUserMutation } from '~/generated/graphql';
import { logError } from '~/utils/logError';
const StyledComboInputContainer = styled.div`
display: flex;
@ -63,7 +64,7 @@ export const NameFields = ({
}
}
} catch (error) {
console.error(error);
logError(error);
}
}, 500);

View File

@ -8,6 +8,7 @@ import { currentUserState } from '@/auth/states/currentUserState';
import { TextInputSettings } from '@/ui/input/text/components/TextInputSettings';
import { GET_CURRENT_USER } from '@/users/graphql/queries/getCurrentUser';
import { useUpdateWorkspaceMutation } from '~/generated/graphql';
import { logError } from '~/utils/logError';
const StyledComboInputContainer = styled.div`
display: flex;
@ -55,7 +56,7 @@ export const NameField = ({ autoSave = true, onNameUpdate }: OwnProps) => {
throw errors;
}
} catch (error) {
console.error(error);
logError(error);
}
}, 500),
[updateWorkspace],

View File

@ -3,7 +3,7 @@ import { Meta } from '@storybook/react';
import { ModalWrapper } from '@/spreadsheet-import/components/ModalWrapper';
import { Providers } from '@/spreadsheet-import/components/Providers';
import { MatchColumnsStep } from '@/spreadsheet-import/steps/components/MatchColumnsStep/MatchColumnsStep';
import { mockRsiValues } from '@/spreadsheet-import/tests/mockRsiValues';
import { mockRsiValues } from '@/spreadsheet-import/tests/mockRsiValues.test';
const meta: Meta<typeof MatchColumnsStep> = {
title: 'Modules/SpreadsheetImport/MatchColumnsStep',

View File

@ -6,7 +6,7 @@ import { SelectHeaderStep } from '@/spreadsheet-import/steps/components/SelectHe
import {
headerSelectionTableFields,
mockRsiValues,
} from '@/spreadsheet-import/tests/mockRsiValues';
} from '@/spreadsheet-import/tests/mockRsiValues.test';
const meta: Meta<typeof SelectHeaderStep> = {
title: 'Modules/SpreadsheetImport/SelectHeaderStep',

View File

@ -3,7 +3,7 @@ import { Meta } from '@storybook/react';
import { ModalWrapper } from '@/spreadsheet-import/components/ModalWrapper';
import { Providers } from '@/spreadsheet-import/components/Providers';
import { SelectSheetStep } from '@/spreadsheet-import/steps/components/SelectSheetStep/SelectSheetStep';
import { mockRsiValues } from '@/spreadsheet-import/tests/mockRsiValues';
import { mockRsiValues } from '@/spreadsheet-import/tests/mockRsiValues.test';
const meta: Meta<typeof SelectSheetStep> = {
title: 'Modules/SpreadsheetImport/SelectSheetStep',

View File

@ -3,7 +3,7 @@ import { Meta } from '@storybook/react';
import { ModalWrapper } from '@/spreadsheet-import/components/ModalWrapper';
import { Providers } from '@/spreadsheet-import/components/Providers';
import { UploadStep } from '@/spreadsheet-import/steps/components/UploadStep/UploadStep';
import { mockRsiValues } from '@/spreadsheet-import/tests/mockRsiValues';
import { mockRsiValues } from '@/spreadsheet-import/tests/mockRsiValues.test';
const meta: Meta<typeof UploadStep> = {
title: 'Modules/SpreadsheetImport/UploadStep',

View File

@ -6,7 +6,7 @@ import { ValidationStep } from '@/spreadsheet-import/steps/components/Validation
import {
editableTableInitialData,
mockRsiValues,
} from '@/spreadsheet-import/tests/mockRsiValues';
} from '@/spreadsheet-import/tests/mockRsiValues.test';
const meta: Meta<typeof ValidationStep> = {
title: 'Modules/SpreadsheetImport/ValidationStep',

View File

@ -1,171 +0,0 @@
import { defaultSpreadsheetImportProps } from '@/spreadsheet-import/provider/components/SpreadsheetImport';
import { Fields, SpreadsheetOptions } from '@/spreadsheet-import/types';
const fields = [
{
icon: null,
label: 'Name',
key: 'name',
alternateMatches: ['first name', 'first'],
fieldType: {
type: 'input',
},
example: 'Stephanie',
validations: [
{
rule: 'required',
errorMessage: 'Name is required',
},
],
},
{
icon: null,
label: 'Surname',
key: 'surname',
alternateMatches: ['second name', 'last name', 'last'],
fieldType: {
type: 'input',
},
example: 'McDonald',
validations: [
{
rule: 'unique',
errorMessage: 'Last name must be unique',
level: 'info',
},
],
description: 'Family / Last name',
},
{
icon: null,
label: 'Age',
key: 'age',
alternateMatches: ['years'],
fieldType: {
type: 'input',
},
example: '23',
validations: [
{
rule: 'regex',
value: '^\\d+$',
errorMessage: 'Age must be a number',
level: 'warning',
},
],
},
{
icon: null,
label: 'Team',
key: 'team',
alternateMatches: ['department'],
fieldType: {
type: 'select',
options: [
{ label: 'Team One', value: 'one' },
{ label: 'Team Two', value: 'two' },
],
},
example: 'Team one',
validations: [
{
rule: 'required',
errorMessage: 'Team is required',
},
],
},
{
icon: null,
label: 'Is manager',
key: 'is_manager',
alternateMatches: ['manages'],
fieldType: {
type: 'checkbox',
booleanMatches: {},
},
example: 'true',
},
] as Fields<string>;
const mockComponentBehaviourForTypes = <T extends string>(
props: SpreadsheetOptions<T>,
) => props;
export const mockRsiValues = mockComponentBehaviourForTypes({
...defaultSpreadsheetImportProps,
fields: fields,
onSubmit: async (data) => {
console.log(data.all.map((value) => value));
},
isOpen: true,
onClose: () => {
console.log('onClose');
},
uploadStepHook: async (data) => {
await new Promise((resolve) => {
setTimeout(() => resolve(data), 4000);
});
return data;
},
selectHeaderStepHook: async (hData, data) => {
await new Promise((resolve) => {
setTimeout(
() =>
resolve({
headerValues: hData,
data,
}),
4000,
);
});
return {
headerValues: hData,
data,
};
},
// Runs after column matching and on entry change, more performant
matchColumnsStepHook: async (data) => {
await new Promise((resolve) => {
setTimeout(() => resolve(data), 4000);
});
return data;
},
});
export const editableTableInitialData = [
{
name: 'Hello',
surname: 'Hello',
age: '123123',
team: 'one',
is_manager: true,
},
{
name: 'Hello',
surname: 'Hello',
age: '12312zsas3',
team: 'two',
is_manager: true,
},
{
name: 'Whooaasdasdawdawdawdiouasdiuasdisdhasd',
surname: 'Hello',
age: '123123',
team: undefined,
is_manager: false,
},
{
name: 'Goodbye',
surname: 'Goodbye',
age: '111',
team: 'two',
is_manager: true,
},
];
export const headerSelectionTableFields = [
['text', 'num', 'select', 'bool'],
['Hello', '123', 'one', 'true'],
['Hello', '123', 'one', 'true'],
['Hello', '123', 'one', 'true'],
];

View File

@ -17,6 +17,7 @@ import { usePreviousHotkeyScope } from '@/ui/utilities/hotkey/hooks/usePreviousH
import { useScopedHotkeys } from '@/ui/utilities/hotkey/hooks/useScopedHotkeys';
import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
import { useRecoilScopedState } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopedState';
import { logError } from '~/utils/logError';
import { BoardColumnContext } from '../contexts/BoardColumnContext';
import { useBoardColumns } from '../hooks/useBoardColumns';
@ -65,9 +66,7 @@ export const BoardColumnMenu = ({
},
);
console.error(
'There was a problem with the company selection, please retry.',
);
logError('There was a problem with the company selection, please retry.');
return;
}

View File

@ -19,6 +19,7 @@ import {
PipelineStage,
useUpdateOnePipelineProgressStageMutation,
} from '~/generated/graphql';
import { logError } from '~/utils/logError';
import { useCurrentCardSelected } from '../hooks/useCurrentCardSelected';
import { useSetCardSelected } from '../hooks/useSetCardSelected';
@ -126,7 +127,7 @@ export const EntityBoard = ({
);
}
} catch (e) {
console.error(e);
logError(e);
}
},
[boardColumns, updatePipelineProgressStageInDB, updateBoardCardIds],

View File

@ -3,6 +3,7 @@ import { PersonChip } from '@/people/components/PersonChip';
import { Entity } from '@/ui/input/relation-picker/types/EntityTypeForSelect';
import { UserChip } from '@/users/components/UserChip';
import { getLogoUrlFromDomainName } from '~/utils';
import { logError } from '~/utils/logError';
import { useRelationField } from '../../hooks/useRelationField';
@ -42,7 +43,7 @@ export const RelationFieldDisplay = () => {
);
}
default:
console.warn(
logError(
`Unknown relation type: "${fieldDefinition.metadata.relationType}"
in RelationFieldDisplay`,
);

View File

@ -2,6 +2,7 @@ import { CompanyChip } from '@/companies/components/CompanyChip';
import { PersonChip } from '@/people/components/PersonChip';
import { Entity } from '@/ui/input/relation-picker/types/EntityTypeForSelect';
import { getLogoUrlFromDomainName } from '~/utils';
import { logError } from '~/utils/logError';
type OwnProps = {
entityType: Entity;
@ -36,7 +37,7 @@ export const ChipDisplay = ({
);
}
default:
console.warn(
logError(
`Unknown relation type: "${entityType}" in DoubleTextChipDisplay`,
);
return <> </>;

View File

@ -1,6 +1,8 @@
import { Profiler } from 'react';
import { Interaction } from 'scheduler/tracing';
import { logDebug } from '~/utils/logDebug';
type OwnProps = {
id: string;
children: React.ReactNode;
@ -16,7 +18,7 @@ export const TimingProfiler = ({ id, children }: OwnProps) => {
commitTime: number,
interactions: Set<Interaction>,
) => {
console.debug(
logDebug(
'TimingProfiler',
JSON.stringify(
{

View File

@ -1,6 +1,8 @@
import { Hotkey } from 'react-hotkeys-hook/dist/types';
import { useRecoilCallback } from 'recoil';
import { logDebug } from '~/utils/logDebug';
import { internalHotkeysEnabledScopesState } from '../states/internal/internalHotkeysEnabledScopesState';
const DEBUG_HOTKEY_SCOPE = true;
@ -27,7 +29,7 @@ export const useScopedHotkeyCallback = () =>
if (!currentHotkeyScopes.includes(scope)) {
if (DEBUG_HOTKEY_SCOPE) {
console.debug(
logDebug(
`%cI can't call hotkey (${
hotkeysEvent.keys
}) because I'm in scope [${scope}] and the active scopes are : [${currentHotkeyScopes.join(
@ -41,7 +43,7 @@ export const useScopedHotkeyCallback = () =>
}
if (DEBUG_HOTKEY_SCOPE) {
console.debug(
logDebug(
`%cI can call hotkey (${
hotkeysEvent.keys
}) because I'm in scope [${scope}] and the active scopes are : [${currentHotkeyScopes.join(

View File

@ -1,28 +1,30 @@
import { logError } from './logError';
const DEBUG_MODE = false;
export const canBeCastAsIntegerOrNull = (
probableNumberOrNull: string | undefined | number | null,
): probableNumberOrNull is number | null => {
if (probableNumberOrNull === undefined) {
if (DEBUG_MODE) console.log('probableNumberOrNull === undefined');
if (DEBUG_MODE) logError('probableNumberOrNull === undefined');
return false;
}
if (typeof probableNumberOrNull === 'number') {
if (DEBUG_MODE) console.log('typeof probableNumberOrNull === "number"');
if (DEBUG_MODE) logError('typeof probableNumberOrNull === "number"');
return Number.isInteger(probableNumberOrNull);
}
if (probableNumberOrNull === null) {
if (DEBUG_MODE) console.log('probableNumberOrNull === null');
if (DEBUG_MODE) logError('probableNumberOrNull === null');
return true;
}
if (probableNumberOrNull === '') {
if (DEBUG_MODE) console.log('probableNumberOrNull === ""');
if (DEBUG_MODE) logError('probableNumberOrNull === ""');
return true;
}
@ -31,12 +33,12 @@ export const canBeCastAsIntegerOrNull = (
const stringAsNumber = +probableNumberOrNull;
if (isNaN(stringAsNumber)) {
if (DEBUG_MODE) console.log('isNaN(stringAsNumber)');
if (DEBUG_MODE) logError('isNaN(stringAsNumber)');
return false;
}
if (Number.isInteger(stringAsNumber)) {
if (DEBUG_MODE) console.log('Number.isInteger(stringAsNumber)');
if (DEBUG_MODE) logError('Number.isInteger(stringAsNumber)');
return true;
}

View File

@ -0,0 +1,4 @@
/* eslint-disable no-console */
export const logDebug = (message: any, ...optionalParams: any[]) => {
console.debug(message, optionalParams);
};

View File

@ -1,3 +1,4 @@
/* eslint-disable no-console */
export const logError = (message: any) => {
console.error(message);
};

View File

@ -1,3 +1,4 @@
/* eslint-disable no-console */
import afterFrame from 'afterframe';
export const measureTotalFrameLoad = (id: string) => {