Merge pull request #14017 from strapi/chore/use-eslint-config

Chore/use eslint config
This commit is contained in:
Alexandre BODIN 2022-08-11 16:19:29 +02:00 committed by GitHub
commit 2a9050d0d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1389 changed files with 7623 additions and 8108 deletions

View File

@ -7,6 +7,7 @@ examples/**
cypress/**
packages/generators/generators/lib/files/
packages/generators/app/lib/resources/files/
packages/core/admin/admin/src/plugins.js
packages/core/helper-plugin/build/**
packages/core/helper-plugin/lib/src/old/components/**
packages/core/helper-plugin/lib/src/testUtils/**

View File

@ -1,55 +1,36 @@
'use strict';
module.exports = {
extends: [
'eslint:recommended',
'prettier',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:node/recommended',
// 'plugin:jsdoc/recommended',
],
plugins: ['jsdoc'],
env: {
es6: true,
node: true,
jest: true,
},
extends: '@strapi/eslint-config/back',
globals: {
strapi: false,
},
rules: {
// 'jsdoc/require-jsdoc': [
// 'warn',
// {
// publicOnly: true,
// require: {
// ArrowFunctionExpression: true,
// ClassDeclaration: true,
// ClassExpression: true,
// FunctionDeclaration: true,
// FunctionExpression: true,
// MethodDefinition: true,
// },
// },
// ],
'node/no-unpublished-require': 'off',
'require-atomic-updates': 'off',
'no-process-exit': 'off',
strict: ['error', 'global'],
'no-return-await': 'error',
'object-shorthand': ['error', 'always', { avoidExplicitReturnArrows: true }],
'import/order': 'error',
'import/no-cycle': 'error',
'import/no-useless-path-segments': 'error',
'import/first': 'error',
'import/extensions': ['error', 'never'],
'import/newline-after-import': 'error',
'node/exports-style': ['error', 'module.exports'],
'node/no-new-require': 'error',
'node/no-path-concat': 'error',
'node/no-callback-literal': 'error',
'node/handle-callback-err': 'error',
'one-var': ['error', 'never'],
'import/no-dynamic-require': 'off',
'global-require': 'off',
'import/no-extraneous-dependencies': [
'error',
{
devDependencies: [
'packages/admin-test-utils/**/*.js',
'packages/generators/admin/**/*.js',
'scripts/**/*.js',
'**/test/**/*.js',
'**/tests/**/*.js',
'**/__tests__/**/*.js',
'**/__mocks__/**/*.js',
],
},
],
'prefer-destructuring': ['error', { AssignmentExpression: { array: false } }],
eqeqeq: 'warn',
'no-underscore-dangle': 'warn',
'no-use-before-define': 'warn',
'no-param-reassign': 'warn',
'no-continue': 'warn',
'no-process-exit': 'warn',
'no-plusplus': 'warn',
'no-loop-func': 'warn',
'guard-for-in': 'warn',
},
};

View File

@ -1,13 +1,6 @@
module.exports = {
parser: 'babel-eslint',
extends: [
'airbnb',
'eslint:recommended',
'plugin:react/recommended',
'plugin:redux-saga/recommended',
'prettier',
],
plugins: ['react', 'redux-saga', 'react-hooks', 'import', 'jsx-a11y'],
parser: '@babel/eslint-parser',
extends: ['@strapi/eslint-config/front'],
env: {
browser: true,
commonjs: true,
@ -16,11 +9,10 @@ module.exports = {
mocha: true,
},
parserOptions: {
ecmaVersion: 2018,
ecmaFeatures: {
jsx: true,
requireConfigFile: false,
babelOptions: {
presets: ['@babel/preset-react'],
},
sourceType: 'module',
},
globals: {
strapi: false,
@ -39,86 +31,12 @@ module.exports = {
},
settings: {
react: {
version: '16.5.2',
version: 'detect',
},
},
rules: {
'import/no-unresolved': 0,
'generator-star-spacing': 0,
'no-console': 0,
'require-atomic-updates': 0,
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'error',
'arrow-body-style': 0,
'arrow-parens': 0,
camelcase: 0,
'comma-dangle': 0,
'consistent-return': [
2,
{
treatUndefinedAsUnspecified: true,
},
],
'template-curly-spacing': 0,
'func-names': ['error', 'never'],
'function-paren-newline': 0,
'implicit-arrow-linebreak': 0,
'import/no-extraneous-dependencies': 0,
'import/no-named-as-default': 0,
'import/order': 2,
'import/prefer-default-export': 'off',
'jsx-a11y/click-events-have-key-events': 1,
'max-len': [
2,
{
code: 120,
ignoreComments: true,
ignoreUrls: true,
ignoreTrailingComments: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
},
],
'newline-before-return': 2,
'no-confusing-arrow': 0,
'no-else-return': 1,
'no-nested-ternary': ['error'],
'no-return-assign': 0,
'no-param-reassign': 0,
'no-plusplus': 0,
'no-shadow': 0,
'no-underscore-dangle': 0,
'no-use-before-define': ['error', { functions: false, classes: false, variables: false }],
'object-curly-newline': [2, { multiline: true, consistent: true }],
'one-var': ['error', 'never'],
'operator-linebreak': 0,
'padding-line-between-statements': [
'error',
{ blankLine: 'always', prev: '*', next: 'if' },
{ blankLine: 'any', prev: 'block-like', next: 'if' },
],
'prefer-arrow-callback': 0,
'prefer-const': 0,
'prefer-destructuring': 0,
'prefer-object-spread': 0,
'prefer-spread': 0,
'space-before-function-paren': [
'error',
{
anonymous: 'never',
named: 'never',
asyncArrow: 'always',
},
],
'react/destructuring-assignment': 0,
'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx'] }],
'react/forbid-prop-types': 0,
'react/no-unused-prop-types': 2,
'react/jsx-props-no-spreading': 0,
'react/jsx-one-expression-per-line': 0,
'react/state-in-constructor': 0,
'react/static-property-placement': 0,
'react/display-name': 0,
'react/jsx-wrap-multilines': 0,
'react/jsx-no-constructed-context-values': 'warn',
'react/jsx-no-useless-fragment': 'warn',
'react/no-unstable-nested-components': 'warn',
},
};

View File

@ -6,7 +6,7 @@ jest.mock('@actions/core');
const github = require('@actions/github');
const core = require('@actions/core');
test.each(action.BLOCKING_LABELS)('Test blocking labels %s', async label => {
test.each(action.BLOCKING_LABELS)('Test blocking labels %s', async (label) => {
github.context = {
payload: {
pull_request: {

View File

@ -7,20 +7,20 @@ async function main() {
try {
const labels = github.context.payload.pull_request?.labels ?? [];
const blockingLabels = labels.filter(label => BLOCKING_LABELS.includes(label.name));
const blockingLabels = labels.filter((label) => BLOCKING_LABELS.includes(label.name));
if (blockingLabels.length > 0) {
core.setFailed(
`The PR has been labelled with a blocking label (${blockingLabels
.map(label => label.name)
.map((label) => label.name)
.join(', ')}).`
);
return;
}
const sourceLabelCount = labels.filter(label => label.name.startsWith('source: ')).length;
const issueLabelCount = labels.filter(label => label.name.startsWith('pr: ')).length;
const sourceLabelCount = labels.filter((label) => label.name.startsWith('source: ')).length;
const issueLabelCount = labels.filter((label) => label.name.startsWith('pr: ')).length;
if (sourceLabelCount !== 1) {
core.setFailed(`The PR must have one and only one 'source:' label.`);

View File

@ -5,4 +5,5 @@ module.exports = {
tabWidth: 2,
trailingComma: 'es5',
printWidth: 100,
arrowParens: 'always',
};

View File

@ -1,7 +1,7 @@
'use strict';
module.exports = {
'404': async (/* ctx */) => {
404: async (/* ctx */) => {
// return ctx.notFound('My custom message 404');
},
};

View File

@ -1,4 +1,4 @@
module.exports = options => {
module.exports = (options) => {
return (ctx, next) => {
ctx.set('X-Strapi-Test', 'Address Middleware');
return next();

View File

@ -4,7 +4,7 @@ module.exports = createCoreService('api::address.address', {
async find(...args) {
const { results, pagination } = await super.find(...args);
results.forEach(result => {
results.forEach((result) => {
result.counter = 1;
});

View File

@ -1,4 +1,5 @@
{
"kind": "collectionType",
"collectionName": "reviews",
"info": {
"displayName": "Review",

View File

@ -1,3 +1,3 @@
module.exports = plugin => {
module.exports = (plugin) => {
return plugin;
};

View File

@ -29,7 +29,7 @@ export default {
bootstrap() {},
async registerTrads({ locales }) {
const importedTrads = await Promise.all(
locales.map(locale => {
locales.map((locale) => {
return import(
/* webpackChunkName: "[pluginId]-[request]" */ `./translations/${locale}.json`
)

View File

@ -1,5 +1,5 @@
import pluginId from '../pluginId';
const getTrad = id => `${pluginId}.${id}`;
const getTrad = (id) => `${pluginId}.${id}`;
export default getTrad;

View File

@ -4,7 +4,7 @@ module.exports = {
default: {
testConf: 1,
},
validator: config => {
validator: (config) => {
if (typeof config.testConf !== 'number') {
throw new Error('testConfig has to be a number');
}

View File

@ -2,8 +2,7 @@ import theme from './extensions/theme';
const config = {
auth: {
logo:
'https://images.unsplash.com/photo-1593642634367-d91a135587b5?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
logo: 'https://images.unsplash.com/photo-1593642634367-d91a135587b5?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
},
head: {
favicon:
@ -12,8 +11,7 @@ const config = {
},
locales: ['fr', 'de'],
menu: {
logo:
'https://images.unsplash.com/photo-1593642634367-d91a135587b5?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
logo: 'https://images.unsplash.com/photo-1593642634367-d91a135587b5?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
},
theme,
translations: {
@ -29,7 +27,7 @@ const config = {
notifications: { release: false },
};
const bootstrap = app => {
const bootstrap = (app) => {
console.log(app);
};

View File

@ -2,8 +2,7 @@ import theme from './extensions/theme';
const config = {
auth: {
logo:
'https://images.unsplash.com/photo-1593642634367-d91a135587b5?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
logo: 'https://images.unsplash.com/photo-1593642634367-d91a135587b5?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
},
head: {
favicon:
@ -12,8 +11,7 @@ const config = {
},
locales: ['fr', 'de'],
menu: {
logo:
'https://images.unsplash.com/photo-1593642634367-d91a135587b5?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
logo: 'https://images.unsplash.com/photo-1593642634367-d91a135587b5?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
},
theme,
translations: {
@ -29,7 +27,7 @@ const config = {
notifications: { release: false },
};
const bootstrap = app => {
const bootstrap = (app) => {
console.log(app);
};

View File

@ -71,6 +71,10 @@
"@babel/polyfill": "7.12.1"
},
"devDependencies": {
"@babel/core": "7.18.10",
"@babel/eslint-parser": "7.18.9",
"@babel/preset-react": "7.18.6",
"@strapi/eslint-config": "0.1.1",
"@swc/core": "1.2.224",
"@swc/jest": "0.2.22",
"@testing-library/react": "11.2.7",
@ -82,22 +86,13 @@
"chokidar": "3.5.3",
"cross-env": "7.0.3",
"dotenv": "14.2.0",
"eslint": "7.32.0",
"eslint-config-airbnb": "18.2.1",
"eslint-config-airbnb-base": "14.2.1",
"eslint-config-prettier": "6.15.0",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-jsdoc": "36.1.1",
"eslint-plugin-jsx-a11y": "6.6.1",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-react": "7.30.1",
"eslint-plugin-react-hooks": "4.6.0",
"eslint-plugin-redux-saga": "1.3.2",
"eslint": "8.21.0",
"execa": "1.0.0",
"fs-extra": "10.1.0",
"get-port": "5.1.1",
"glob": "7.2.3",
"husky": "3.1.0",
"inquirer": "8.2.4",
"istanbul": "~0.4.2",
"jest": "26.6.3",
"jest-circus": "26.6.3",
@ -110,7 +105,7 @@
"npm-run-all": "4.1.5",
"nx": "14.4.2",
"plop": "2.7.6",
"prettier": "1.19.1",
"prettier": "2.7.1",
"qs": "6.11.0",
"react-test-renderer": "17.0.2",
"request": "2.88.2",

View File

@ -1,6 +1,5 @@
'use strict';
// eslint-disable-next-line node/no-extraneous-require
const { combineReducers, createStore } = require('redux');
const reducers = {

View File

@ -25,4 +25,4 @@ global.strapi = {
global.prompt = jest.fn();
global.URL.createObjectURL = file => `http://localhost:4000/assets/${file.name}`;
global.URL.createObjectURL = (file) => `http://localhost:4000/assets/${file.name}`;

View File

@ -1,7 +1,6 @@
'use strict';
// needed for regenerator-runtime
// (ES7 generator support is required by redux-saga)
require('@babel/polyfill');
const noop = () => {};

View File

@ -24,6 +24,9 @@
"@testing-library/jest-dom": "5.16.5",
"jest-styled-components": "7.0.2"
},
"peerDependencies": {
"redux": "^4.0.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},

View File

@ -39,7 +39,7 @@ program
.option('--template <templateurl>', 'Specify a Strapi template')
.option('--ts, --typescript', 'Use TypeScript to generate the project')
.description('create a new application')
.action(directory => {
.action((directory) => {
initProject(directory, program);
})
.parse(process.argv);
@ -62,7 +62,7 @@ async function initProject(projectName, program) {
await checkInstallPath(resolve(projectName));
}
const hasDatabaseOptions = databaseOptions.some(opt => program[opt]);
const hasDatabaseOptions = databaseOptions.some((opt) => program[opt]);
if (program.quickstart && hasDatabaseOptions) {
console.error(

View File

@ -1,4 +1,5 @@
#!/usr/bin/env node
'use strict';
require('./create-strapi-app');

View File

@ -57,7 +57,9 @@ function generateApp(projectArgs, programArgs) {
}
async function initProject(projectArgs, program) {
const hasIncompatibleQuickstartOptions = incompatibleQuickstartOptions.some(opt => program[opt]);
const hasIncompatibleQuickstartOptions = incompatibleQuickstartOptions.some(
(opt) => program[opt]
);
if (program.quickstart && hasIncompatibleQuickstartOptions) {
console.error(
@ -96,7 +98,7 @@ async function initProject(projectArgs, program) {
try {
program.parse(process.argv);
} catch (err) {
if (err.exitCode && err.exitCode != 0) {
if (err.exitCode && err.exitCode !== 0) {
program.outputHelp();
}
}

View File

@ -1,4 +1,5 @@
#!/usr/bin/env node
'use strict';
require('./create-strapi-starter');

View File

@ -72,10 +72,7 @@ async function installWithLogs(path, options) {
const installPrefix = chalk.yellow('Installing dependencies:');
const loader = ora(installPrefix).start();
const logInstall = (chunk = '') => {
loader.text = `${installPrefix} ${chunk
.toString()
.split('\n')
.join(' ')}`;
loader.text = `${installPrefix} ${chunk.toString().split('\n').join(' ')}`;
};
const runner = runInstall(path, options);
@ -94,7 +91,7 @@ async function installWithLogs(path, options) {
* @param {boolean} options.useYarn Use yarn instead of npm
*/
async function getStarterInfo(starter, { useYarn } = {}) {
const isLocalStarter = ['./', '../', '/'].some(filePrefix => starter.startsWith(filePrefix));
const isLocalStarter = ['./', '../', '/'].some((filePrefix) => starter.startsWith(filePrefix));
let starterPath;
let starterParentPath;
@ -125,12 +122,8 @@ async function getStarterInfo(starter, { useYarn } = {}) {
*/
module.exports = async function buildStarter({ projectName, starter }, program) {
const hasYarnInstalled = await hasYarn();
const {
isLocalStarter,
starterPath,
starterParentPath,
starterPackageInfo,
} = await getStarterInfo(starter, { useYarn: hasYarnInstalled });
const { isLocalStarter, starterPath, starterParentPath, starterPackageInfo } =
await getStarterInfo(starter, { useYarn: hasYarnInstalled });
// Project directory
const rootPath = resolve(projectName);

View File

@ -27,12 +27,11 @@ function runApp(rootPath, { useYarn } = {}) {
stdio: 'inherit',
cwd: rootPath,
});
} else {
return execa('npm', ['run', 'develop'], {
stdio: 'inherit',
cwd: rootPath,
});
}
return execa('npm', ['run', 'develop'], {
stdio: 'inherit',
cwd: rootPath,
});
}
async function initGit(rootPath) {

View File

@ -1,4 +1,5 @@
'use strict';
const logger = require('./logger');
module.exports = function stopProcess(message) {

View File

@ -61,15 +61,15 @@ class StrapiApp {
};
}
addComponents = components => {
addComponents = (components) => {
if (Array.isArray(components)) {
components.map(compo => this.library.components.add(compo));
components.map((compo) => this.library.components.add(compo));
} else {
this.library.components.add(components);
}
};
addCorePluginMenuLink = link => {
addCorePluginMenuLink = (link) => {
const stringifiedLink = JSON.stringify(link);
invariant(link.to, `link.to should be defined for ${stringifiedLink}`);
@ -89,15 +89,15 @@ class StrapiApp {
this.menu.push(link);
};
addFields = fields => {
addFields = (fields) => {
if (Array.isArray(fields)) {
fields.map(field => this.library.fields.add(field));
fields.map((field) => this.library.fields.add(field));
} else {
this.library.fields.add(fields);
}
};
addMenuLink = link => {
addMenuLink = (link) => {
const stringifiedLink = JSON.stringify(link);
invariant(link.to, `link.to should be defined for ${stringifiedLink}`);
@ -121,14 +121,14 @@ class StrapiApp {
this.menu.push(link);
};
addMiddlewares = middlewares => {
middlewares.forEach(middleware => {
addMiddlewares = (middlewares) => {
middlewares.forEach((middleware) => {
this.middlewares.add(middleware);
});
};
addReducers = reducers => {
Object.keys(reducers).forEach(reducerName => {
addReducers = (reducers) => {
Object.keys(reducers).forEach((reducerName) => {
this.reducers.add(reducerName, reducers[reducerName]);
});
};
@ -156,13 +156,13 @@ class StrapiApp {
invariant(this.settings[sectionId], 'The section does not exist');
invariant(Array.isArray(links), 'TypeError expected links to be an array');
links.forEach(link => {
links.forEach((link) => {
this.addSettingsLink(sectionId, link);
});
};
async bootstrap() {
Object.keys(this.appPlugins).forEach(plugin => {
Object.keys(this.appPlugins).forEach((plugin) => {
const bootstrap = this.appPlugins[plugin].bootstrap;
if (bootstrap) {
@ -208,7 +208,7 @@ class StrapiApp {
if (this.customConfigurations?.locales) {
this.configurations.locales = [
'en',
...this.customConfigurations.locales?.filter(loc => loc !== 'en'),
...(this.customConfigurations.locales?.filter((loc) => loc !== 'en') || []),
];
}
@ -237,7 +237,7 @@ class StrapiApp {
}
};
createHook = name => {
createHook = (name) => {
this.hooksDict[name] = createHook();
};
@ -253,7 +253,7 @@ class StrapiApp {
this.settings[section.id] = { ...section, links: [] };
links.forEach(link => {
links.forEach((link) => {
this.addSettingsLink(section.id, link);
});
};
@ -274,12 +274,12 @@ class StrapiApp {
}
};
getPlugin = pluginId => {
getPlugin = (pluginId) => {
return this.plugins[pluginId];
};
async initialize() {
Object.keys(this.appPlugins).forEach(plugin => {
Object.keys(this.appPlugins).forEach((plugin) => {
this.appPlugins[plugin].register({
addComponents: this.addComponents,
addCorePluginMenuLink: this.addCorePluginMenuLink,
@ -319,7 +319,7 @@ class StrapiApp {
* @returns {Object} The imported admin translations
*/
async loadAdminTrads() {
const arrayOfPromises = this.configurations.locales.map(locale => {
const arrayOfPromises = this.configurations.locales.map((locale) => {
return import(/* webpackChunkName: "[request]" */ `./translations/${locale}.json`)
.then(({ default: data }) => {
return { data, locale };
@ -350,7 +350,7 @@ class StrapiApp {
const adminTranslations = await this.loadAdminTrads();
const arrayOfPromises = Object.keys(this.appPlugins)
.map(plugin => {
.map((plugin) => {
const registerTrads = this.appPlugins[plugin].registerTrads;
if (registerTrads) {
@ -359,7 +359,7 @@ class StrapiApp {
return null;
})
.filter(a => a);
.filter((a) => a);
const pluginsTrads = await Promise.all(arrayOfPromises);
const mergedTrads = pluginsTrads.reduce((acc, currentPluginTrads) => {
@ -369,7 +369,7 @@ class StrapiApp {
return acc1;
}, {});
Object.keys(pluginTrads).forEach(locale => {
Object.keys(pluginTrads).forEach((locale) => {
acc[locale] = { ...acc[locale], ...pluginTrads[locale] };
});
@ -399,7 +399,7 @@ class StrapiApp {
this.hooksDict[name].register(fn);
};
registerPlugin = pluginConf => {
registerPlugin = (pluginConf) => {
const plugin = Plugin(pluginConf);
this.plugins[plugin.pluginId] = plugin;
@ -414,7 +414,7 @@ class StrapiApp {
: this.hooksDict[name].runWaterfall(initialValue, store);
};
runHookParallel = name => this.hooksDict[name].runParallel();
runHookParallel = (name) => this.hooksDict[name].runParallel();
render() {
const store = this.createStore();

View File

@ -56,9 +56,10 @@ const AuthenticatedApp = () => {
},
]);
const shouldUpdateStrapi = useMemo(() => checkLatestStrapiVersion(strapiVersion, tag_name), [
tag_name,
]);
const shouldUpdateStrapi = useMemo(
() => checkLatestStrapiVersion(strapiVersion, tag_name),
[tag_name]
);
useEffect(() => {
if (userRoles) {
@ -77,6 +78,16 @@ const AuthenticatedApp = () => {
const shouldShowLoader = isLoading || shouldShowNotDependentQueriesLoader;
const appInfosValue = useMemo(() => {
return {
...appInfos,
latestStrapiReleaseTag: tag_name,
setUserDisplayName,
shouldUpdateStrapi,
userDisplayName,
};
}, [appInfos, tag_name, shouldUpdateStrapi, userDisplayName]);
if (shouldShowLoader) {
return <LoadingIndicatorPage />;
}
@ -87,15 +98,7 @@ const AuthenticatedApp = () => {
}
return (
<AppInfosContext.Provider
value={{
...appInfos,
latestStrapiReleaseTag: tag_name,
setUserDisplayName,
shouldUpdateStrapi,
userDisplayName,
}}
>
<AppInfosContext.Provider value={appInfosValue}>
<RBACProvider permissions={permissions} refetchPermissions={refetch}>
<PluginsInitializer />
</RBACProvider>

View File

@ -1,4 +1,5 @@
import React from 'react';
import PropTypes from 'prop-types';
import { render, waitFor } from '@testing-library/react';
import { QueryClientProvider, QueryClient } from 'react-query';
import { useGuidedTour } from '@strapi/helper-plugin';
@ -35,9 +36,19 @@ jest.mock('../utils/api', () => ({
fetchUserRoles: jest.fn(),
}));
jest.mock('../../PluginsInitializer', () => () => <div>PluginsInitializer</div>);
jest.mock('../../PluginsInitializer', () => () => {
return <div>PluginsInitializer</div>;
});
// eslint-disable-next-line react/prop-types
jest.mock('../../RBACProvider', () => ({ children }) => <div>{children}</div>);
jest.mock('../../RBACProvider', () => {
const Compo = ({ children }) => <div>{children}</div>;
Compo.propTypes = {
children: PropTypes.node.isRequired,
};
return Compo;
});
const queryClient = new QueryClient({
defaultOptions: {
@ -47,11 +58,13 @@ const queryClient = new QueryClient({
},
});
const app = (
const configurationContextValue = { showReleaseNotification: false };
const App = () => (
<ThemeToggleProvider themes={{ light: lightTheme, dark: darkTheme }}>
<Theme>
<QueryClientProvider client={queryClient}>
<ConfigurationsContext.Provider value={{ showReleaseNotification: false }}>
<ConfigurationsContext.Provider value={configurationContextValue}>
<AuthenticatedApp />
</ConfigurationsContext.Provider>
</QueryClientProvider>
@ -81,7 +94,7 @@ describe('Admin | components | AuthenticatedApp', () => {
);
fetchCurrentUserPermissions.mockImplementation(() => Promise.resolve([]));
const { container } = render(app);
const { container } = render(<App />);
expect(container.firstChild).toMatchInlineSnapshot(`
.c0 {
@ -147,7 +160,7 @@ describe('Admin | components | AuthenticatedApp', () => {
});
it('should not fetch the latest release', () => {
render(app);
render(<App />);
expect(fetchStrapiLatestRelease).not.toHaveBeenCalled();
});
@ -157,7 +170,7 @@ describe('Admin | components | AuthenticatedApp', () => {
const setGuidedTourVisibility = jest.fn();
useGuidedTour.mockImplementation(() => ({ setGuidedTourVisibility }));
render(app);
render(<App />);
await waitFor(() => expect(setGuidedTourVisibility).not.toHaveBeenCalled());
});
@ -166,7 +179,7 @@ describe('Admin | components | AuthenticatedApp', () => {
fetchUserRoles.mockImplementationOnce(() => [{ code: 'strapi-super-admin' }]);
const setGuidedTourVisibility = jest.fn();
useGuidedTour.mockImplementation(() => ({ setGuidedTourVisibility }));
render(app);
render(<App />);
await waitFor(() => expect(setGuidedTourVisibility).toHaveBeenCalledWith(true));
});

View File

@ -6,7 +6,7 @@ import packageJSON from '../../../../../package.json';
const strapiVersion = packageJSON.version;
const showUpdateNotif = !JSON.parse(localStorage.getItem('STRAPI_UPDATE_NOTIF'));
const fetchStrapiLatestRelease = async toggleNotification => {
const fetchStrapiLatestRelease = async (toggleNotification) => {
try {
const {
data: { tag_name },

View File

@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { AutoReloadOverlayBockerContext } from '@strapi/helper-plugin';
import Blocker from './Blocker';
@ -13,7 +13,7 @@ const AutoReloadOverlayBlockerProvider = ({ children }) => {
const lockAppWithAutoreload = (config = undefined) => {
setIsOpen(true);
setConfig(config);
setState(prev => ({ ...prev, start: Date.now() }));
setState((prev) => ({ ...prev, start: Date.now() }));
};
const unlockAppWithAutoreload = () => {
@ -36,7 +36,7 @@ const AutoReloadOverlayBlockerProvider = ({ children }) => {
return null;
}
setState(prev => ({ ...prev, elapsed: Math.round(Date.now() - prev.start) / 1000 }));
setState((prev) => ({ ...prev, elapsed: Math.round(Date.now() - prev.start) / 1000 }));
return null;
}, 1000);
@ -75,10 +75,12 @@ const AutoReloadOverlayBlockerProvider = ({ children }) => {
};
}
const autoReloadValue = useMemo(() => {
return { lockApp: lockApp.current, unlockApp: unlockApp.current };
}, [lockApp, unlockApp]);
return (
<AutoReloadOverlayBockerContext.Provider
value={{ lockApp: lockApp.current, unlockApp: unlockApp.current }}
>
<AutoReloadOverlayBockerContext.Provider value={autoReloadValue}>
<Blocker
displayedIcon={displayedIcon}
isOpen={isOpen}

View File

@ -1,4 +1,4 @@
import React, { useReducer, useRef } from 'react';
import React, { useMemo, useReducer, useRef } from 'react';
import PropTypes from 'prop-types';
import { ConfigurationsContext } from '../../contexts';
import reducer, { initialState } from './reducer';
@ -23,18 +23,27 @@ const ConfigurationsProvider = ({
const updateProjectSettingsRef = useRef(updateProjectSettings);
const configurationValue = useMemo(() => {
return {
logos: {
menu: { custom: menuLogo, default: defaultMenuLogo },
auth: { custom: null, default: authLogo },
},
updateProjectSettings: updateProjectSettingsRef.current,
showReleaseNotification,
showTutorials,
};
}, [
authLogo,
menuLogo,
showReleaseNotification,
showTutorials,
updateProjectSettingsRef,
defaultMenuLogo,
]);
return (
<ConfigurationsContext.Provider
value={{
logos: {
menu: { custom: menuLogo, default: defaultMenuLogo },
auth: { custom: null, default: authLogo },
},
updateProjectSettings: updateProjectSettingsRef.current,
showReleaseNotification,
showTutorials,
}}
>
<ConfigurationsContext.Provider value={configurationValue}>
{children}
</ConfigurationsContext.Provider>
);

View File

@ -12,7 +12,7 @@ const initialState = {
};
const reducer = (state = initialState, action) =>
produce(state, draftState => {
produce(state, (draftState) => {
switch (action.type) {
case 'UPDATE_PROJECT_SETTINGS': {
Object.assign(draftState, action.values);

View File

@ -19,7 +19,7 @@ const getType = (activeSectionIndex, index) => {
};
const StepperHomepage = ({ sections, currentSectionKey }) => {
const activeSectionIndex = sections.findIndex(section => section.key === currentSectionKey);
const activeSectionIndex = sections.findIndex((section) => section.key === currentSectionKey);
return (
<Box>

View File

@ -31,7 +31,7 @@ const sections = [
},
];
const App = children => (
const App = (children) => (
<ThemeProvider theme={lightTheme}>
<IntlProvider locale="en" messages={{}} textComponent="span">
{children}

View File

@ -29,12 +29,12 @@ const GuidedTourHomepage = () => {
),
}));
const enrichedSections = sections.map(section => ({
const enrichedSections = sections.map((section) => ({
isDone: Object.entries(guidedTourState[section.key]).every(([, value]) => value),
...section,
}));
const activeSection = enrichedSections.find(section => !section.isDone)?.key;
const activeSection = enrichedSections.find((section) => !section.isDone)?.key;
const handleSkip = () => {
setSkipped(true);

View File

@ -3,7 +3,7 @@ import { render, screen } from '@testing-library/react';
import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { IntlProvider } from 'react-intl';
import { useGuidedTour, TrackingContext } from '@strapi/helper-plugin';
import { useGuidedTour, TrackingProvider } from '@strapi/helper-plugin';
import { ThemeProvider, lightTheme } from '@strapi/design-system';
import GuidedTourHomepage from '../index';
@ -31,7 +31,7 @@ jest.mock('@strapi/helper-plugin', () => ({
const history = createMemoryHistory();
const App = (
<TrackingContext.Provider value={{ uuid: null, telemetryProperties: undefined }}>
<TrackingProvider>
<ThemeProvider theme={lightTheme}>
<IntlProvider locale="en" messages={{}} textComponent="span">
<Router history={history}>
@ -39,7 +39,7 @@ const App = (
</Router>
</IntlProvider>
</ThemeProvider>
</TrackingContext.Provider>
</TrackingProvider>
);
describe('GuidedTour Homepage', () => {

View File

@ -18,7 +18,7 @@ const Content = ({ id, defaultMessage }) => {
{formatMessage(
{ id, defaultMessage },
{
documentationLink: children => (
documentationLink: (children) => (
<a
target="_blank"
rel="noopener noreferrer"
@ -27,15 +27,15 @@ const Content = ({ id, defaultMessage }) => {
{children}
</a>
),
b: children => <Typography fontWeight="semiBold">{children}</Typography>,
p: children => <Typography>{children}</Typography>,
light: children => <Typography textColor="neutral600">{children}</Typography>,
ul: children => (
b: (children) => <Typography fontWeight="semiBold">{children}</Typography>,
p: (children) => <Typography>{children}</Typography>,
light: (children) => <Typography textColor="neutral600">{children}</Typography>,
ul: (children) => (
<Box paddingLeft={6}>
<ul>{children}</ul>
</Box>
),
li: children => <LiStyled>{children}</LiStyled>,
li: (children) => <LiStyled>{children}</LiStyled>,
}
)}
</Stack>

View File

@ -36,7 +36,7 @@ const Modal = ({ onClose, onSkip, children, hideSkip }) => {
spacing={8}
role="dialog"
aria-modal
onClick={e => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
>
<Flex justifyContent="flex-end">
<IconButton

View File

@ -16,10 +16,8 @@ const GuidedTourModal = () => {
setSkipped,
} = useGuidedTour();
const [isVisible, setIsVisible] = useState(currentStep);
const [
{ stepContent, sectionIndex, stepIndex, hasSectionAfter, hasStepAfter },
dispatch,
] = useReducer(reducer, initialState);
const [{ stepContent, sectionIndex, stepIndex, hasSectionAfter, hasStepAfter }, dispatch] =
useReducer(reducer, initialState);
const { trackUsage } = useTracking();
useEffect(() => {

View File

@ -10,7 +10,7 @@ export const initialState = {
};
const reducer = (state = initialState, action) =>
produce(state, draftState => {
produce(state, (draftState) => {
switch (action.type) {
case 'UPDATE_MODAL': {
draftState.stepContent = action.content;

View File

@ -1,7 +1,7 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { IntlProvider } from 'react-intl';
import { useGuidedTour, TrackingContext } from '@strapi/helper-plugin';
import { useGuidedTour, TrackingProvider } from '@strapi/helper-plugin';
import { lightTheme, darkTheme } from '@strapi/design-system';
import Theme from '../../../Theme';
import ThemeToggleProvider from '../../../ThemeToggleProvider';
@ -30,7 +30,7 @@ jest.mock('@strapi/helper-plugin', () => ({
}));
const App = (
<TrackingContext.Provider value={{ uuid: null, telemetryProperties: undefined }}>
<TrackingProvider>
<ThemeToggleProvider themes={{ light: lightTheme, dark: darkTheme }}>
<Theme>
<IntlProvider locale="en" messages={{}} defaultLocale="en" textComponent="span">
@ -38,7 +38,7 @@ const App = (
</IntlProvider>
</Theme>
</ThemeToggleProvider>
</TrackingContext.Provider>
</TrackingProvider>
);
describe('<GuidedTourModal />', () => {

View File

@ -15,7 +15,7 @@ const GuidedTour = ({ children }) => {
init
);
const setCurrentStep = step => {
const setCurrentStep = (step) => {
// if step is null it is intentional, we need to dispatch it
if (step !== null) {
const isStepAlreadyDone = get(guidedTourState, step);
@ -34,7 +34,7 @@ const GuidedTour = ({ children }) => {
});
};
const setGuidedTourVisibility = value => {
const setGuidedTourVisibility = (value) => {
dispatch({
type: 'SET_GUIDED_TOUR_VISIBILITY',
value,
@ -51,7 +51,7 @@ const GuidedTour = ({ children }) => {
});
};
const startSection = sectionName => {
const startSection = (sectionName) => {
const sectionSteps = guidedTourState[sectionName];
if (sectionSteps) {
@ -67,7 +67,7 @@ const GuidedTour = ({ children }) => {
return null;
};
const setSkipped = value => {
const setSkipped = (value) => {
persistStateToLocaleStorage.setSkipped(value);
dispatch({

View File

@ -5,14 +5,14 @@ import persistStateToLocaleStorage, {
SKIPPED,
} from './utils/persistStateToLocaleStorage';
const init = initialState => {
const init = (initialState) => {
const copyInitialState = { ...initialState };
const guidedTourLocaleStorage = persistStateToLocaleStorage.get(COMPLETED_STEPS);
const currentStepLocaleStorage = persistStateToLocaleStorage.get(CURRENT_STEP);
const skippedLocaleStorage = persistStateToLocaleStorage.get(SKIPPED);
if (guidedTourLocaleStorage) {
guidedTourLocaleStorage.forEach(step => {
guidedTourLocaleStorage.forEach((step) => {
const [sectionName, stepName] = step.split('.');
set(copyInitialState, ['guidedTourState', sectionName, stepName], true);
});

View File

@ -22,7 +22,7 @@ export const initialState = {
};
const reducer = (state = initialState, action) =>
produce(state, draftState => {
produce(state, (draftState) => {
switch (action.type) {
case 'SET_CURRENT_STEP': {
draftState.currentStep = action.step;

View File

@ -1,4 +1,4 @@
const isGuidedTourCompleted = guidedTourState =>
const isGuidedTourCompleted = (guidedTourState) =>
Object.entries(guidedTourState).every(([, section]) =>
Object.entries(section).every(([, step]) => step)
);

View File

@ -9,7 +9,7 @@ const persistStateToLocaleStorage = {
localStorage.removeItem(CURRENT_STEP);
localStorage.removeItem(COMPLETED_STEPS);
},
addCompletedStep: completedStep => {
addCompletedStep(completedStep) {
const currentSteps = parse(localStorage.getItem(COMPLETED_STEPS))?.slice() || [];
const isAlreadyStored = currentSteps.includes(completedStep);
@ -20,13 +20,13 @@ const persistStateToLocaleStorage = {
currentSteps.push(completedStep);
localStorage.setItem(COMPLETED_STEPS, stringify(currentSteps));
},
addCurrentStep: currentStep => {
addCurrentStep(currentStep) {
localStorage.setItem(CURRENT_STEP, stringify(currentStep));
},
setSkipped: value => {
setSkipped(value) {
localStorage.setItem(SKIPPED, stringify(value));
},
get: item => {
get(item) {
return parse(localStorage.getItem(item));
},
};

View File

@ -23,7 +23,7 @@ const LanguageProvider = ({ children, localeNames, messages }) => {
window.localStorage.setItem(localStorageKey, locale);
}, [locale]);
const changeLocale = locale => {
const changeLocale = (locale) => {
dispatch({
type: 'CHANGE_LOCALE',
locale,

View File

@ -1,6 +1,6 @@
import localStorageKey from './utils/localStorageKey';
const init = localeNames => {
const init = (localeNames) => {
const languageFromLocaleStorage = window.localStorage.getItem(localStorageKey);
const appLanguage = localeNames[languageFromLocaleStorage] ? languageFromLocaleStorage : 'en';

View File

@ -62,18 +62,18 @@ const LeftMenu = ({ generalSectionLinks, pluginsSectionLinks }) => {
const initials = userDisplayName
.split(' ')
.map(name => name.substring(0, 1))
.map((name) => name.substring(0, 1))
.join('')
.substring(0, 2);
const handleToggleUserLinks = () => setUserLinksVisible(prev => !prev);
const handleToggleUserLinks = () => setUserLinksVisible((prev) => !prev);
const handleLogout = () => {
auth.clearAppStorage();
handleToggleUserLinks();
};
const handleBlur = e => {
const handleBlur = (e) => {
if (
!e.currentTarget.contains(e.relatedTarget) &&
e.relatedTarget?.parentElement?.id !== 'main-nav-user-button'
@ -121,7 +121,7 @@ const LeftMenu = ({ generalSectionLinks, pluginsSectionLinks }) => {
defaultMessage: 'Plugins',
})}
>
{pluginsSectionLinks.map(link => {
{pluginsSectionLinks.map((link) => {
const Icon = link.icon;
return (
@ -140,7 +140,7 @@ const LeftMenu = ({ generalSectionLinks, pluginsSectionLinks }) => {
defaultMessage: 'General',
})}
>
{generalSectionLinks.map(link => {
{generalSectionLinks.map((link) => {
const LinkIcon = link.icon;
return (
@ -201,7 +201,7 @@ const LeftMenu = ({ generalSectionLinks, pluginsSectionLinks }) => {
</LinkUserWrapper>
)}
<NavCondense onClick={() => setCondensed(s => !s)}>
<NavCondense onClick={() => setCondensed((s) => !s)}>
{condensed
? formatMessage({
id: 'app.components.LeftMenu.expand',

View File

@ -8,7 +8,8 @@ const Notification = ({ dispatch, notification }) => {
const { formatMessage } = useIntl();
const { message, link, type, id, onClose, timeout, blockTransition } = notification;
const formattedMessage = msg => (typeof msg === 'string' ? msg : formatMessage(msg, msg.values));
const formattedMessage = (msg) =>
typeof msg === 'string' ? msg : formatMessage(msg, msg.values);
const handleClose = useCallback(() => {
if (onClose) {
onClose();
@ -66,9 +67,7 @@ const Notification = ({ dispatch, notification }) => {
defaultMessage: link.label?.defaultMessage || link.label?.id || link.label,
})}
</Link>
) : (
undefined
)
) : undefined
}
onClose={handleClose}
closeLabel="Close"

View File

@ -8,7 +8,7 @@ import reducer, { initialState } from './reducer';
const Notifications = ({ children }) => {
const [{ notifications }, dispatch] = useReducer(reducer, initialState);
const displayNotification = config => {
const displayNotification = (config) => {
dispatch({
type: 'SHOW_NOTIFICATION',
config,
@ -26,7 +26,7 @@ const Notifications = ({ children }) => {
width={`${500 / 16}rem`}
zIndex={10}
>
{notifications.map(notification => {
{notifications.map((notification) => {
return (
<Notification key={notification.id} dispatch={dispatch} notification={notification} />
);

View File

@ -8,7 +8,7 @@ const initialState = {
const notificationReducer = (state = initialState, action) =>
// eslint-disable-next-line consistent-return
produce(state, draftState => {
produce(state, (draftState) => {
switch (action.type) {
case 'SHOW_NOTIFICATION': {
draftState.notifications.push({
@ -28,7 +28,7 @@ const notificationReducer = (state = initialState, action) =>
break;
}
case 'HIDE_NOTIFICATION': {
const indexToRemove = state.notifications.findIndex(notif => notif.id === action.id);
const indexToRemove = state.notifications.findIndex((notif) => notif.id === action.id);
if (indexToRemove !== -1) {
draftState.notifications.splice(indexToRemove, 1);

View File

@ -108,7 +108,9 @@ describe('<Notifications />', () => {
expect(items).toHaveLength(1);
await act(async () => {
await new Promise(resolve => setTimeout(resolve, 2500));
await new Promise((resolve) => {
setTimeout(resolve, 2500);
});
});
const foundItems = screen.queryAllByText(/simple notif/);
@ -151,7 +153,9 @@ describe('<Notifications />', () => {
expect(items).toHaveLength(1);
await act(async () => {
await new Promise(resolve => setTimeout(resolve, 2500));
await new Promise((resolve) => {
setTimeout(resolve, 2500);
});
});
const foundItems = screen.queryAllByText(/simple notif/);

View File

@ -8,11 +8,13 @@ import reducer, { initialState } from './reducer';
const PluginsInitializer = () => {
const { plugins: appPlugins } = useStrapiApp();
const [{ plugins }, dispatch] = useReducer(reducer, initialState, () => init(appPlugins));
const setPlugin = useRef(pluginId => {
const setPlugin = useRef((pluginId) => {
dispatch({ type: 'SET_PLUGIN_READY', pluginId });
});
const hasApluginNotReady = Object.keys(plugins).some(plugin => plugins[plugin].isReady === false);
const hasApluginNotReady = Object.keys(plugins).some(
(plugin) => plugins[plugin].isReady === false
);
if (hasApluginNotReady) {
const initializers = Object.keys(plugins).reduce((acc, current) => {

View File

@ -1,4 +1,4 @@
const init = plugins => {
const init = (plugins) => {
return {
plugins: Object.keys(plugins).reduce((acc, current) => {
acc[current] = { ...plugins[current] };

View File

@ -7,7 +7,7 @@ const initialState = {
const reducer = (state = initialState, action) =>
/* eslint-disable-next-line consistent-return */
produce(state, draftState => {
produce(state, (draftState) => {
switch (action.type) {
case 'SET_PLUGIN_READY': {
set(draftState, ['plugins', action.pluginId, 'isReady'], true);

View File

@ -3,7 +3,9 @@ import { StrapiAppProvider } from '@strapi/helper-plugin';
import { render } from '@testing-library/react';
import PluginsInitializer from '../index';
jest.mock('../../../pages/Admin', () => () => <div>ADMIN</div>);
jest.mock('../../../pages/Admin', () => () => {
return <div>ADMIN</div>;
});
describe('ADMIN | COMPONENTS | PluginsInitializer', () => {
it('should not crash', () => {

View File

@ -20,7 +20,7 @@ const PrivateRoute = ({ component: Component, path, ...rest }) => {
return (
<Route
path={path}
render={props =>
render={(props) =>
auth.getToken() !== null ? (
<Component {...rest} {...props} />
) : (

View File

@ -2,7 +2,7 @@ import { RESET_STORE, SET_PERMISSIONS } from './constants';
const resetStore = () => ({ type: RESET_STORE });
const setPermissions = permissions => ({
const setPermissions = (permissions) => ({
type: SET_PERMISSIONS,
permissions,
});

View File

@ -5,7 +5,7 @@ import PropTypes from 'prop-types';
import { resetStore, setPermissions } from './actions';
const RBACProvider = ({ children, permissions, refetchPermissions }) => {
const { allPermissions } = useSelector(state => state.rbacProvider);
const { allPermissions } = useSelector((state) => state.rbacProvider);
const dispatch = useDispatch();

View File

@ -18,12 +18,12 @@ const initialState = {
const reducer = (state = initialState, action) =>
// eslint-disable-next-line consistent-return
produce(state, draftState => {
produce(state, (draftState) => {
switch (action.type) {
case SET_PERMISSIONS: {
draftState.allPermissions = action.permissions;
draftState.collectionTypesRelatedPermissions = action.permissions
.filter(perm => perm.subject)
.filter((perm) => perm.subject)
.reduce((acc, current) => {
const { subject, action } = current;

View File

@ -1,4 +1,4 @@
import { permissions } from '../../../../../../../admin-test-utils/lib/fixtures';
import { permissions } from '@strapi/admin-test-utils/lib/fixtures';
import { setPermissions, resetStore } from '../actions';
import rbacProviderReducer, { initialState } from '../reducer';

View File

@ -20,7 +20,7 @@ const getDefaultTheme = () => {
const ThemeToggleProvider = ({ children, themes }) => {
const [currentTheme, setCurrentTheme] = useState(getDefaultTheme());
const handleChangeTheme = nextTheme => {
const handleChangeTheme = (nextTheme) => {
setCurrentTheme(nextTheme);
localStorage.setItem(THEME_KEY, nextTheme);
};

View File

@ -73,7 +73,7 @@ const UpgradePlanModal = ({ onClose, isOpen }) => {
<UpgradeWrapper onClick={onClose}>
<FocusTrap onEscape={onClose}>
<UpgradeContainer
onClick={e => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
aria-labelledby="upgrade-plan"
background="neutral0"
hasRadius

View File

@ -16,7 +16,7 @@ const Filters = ({ displayedFilters }) => {
if (!isVisible) {
trackUsage('willFilterEntries');
}
setIsVisible(prev => !prev);
setIsVisible((prev) => !prev);
};
return (

View File

@ -17,7 +17,7 @@ const useAllowedAttributes = (contentType, slug) => {
const readPermissionForAttr = get(readPermissionsForSlug, ['0', 'properties', 'fields'], []);
const attributesArray = Object.keys(get(contentType, ['attributes']), {});
const allowedAttributes = attributesArray
.filter(attr => {
.filter((attr) => {
const current = get(contentType, ['attributes', attr], {});
if (!current.type) {

View File

@ -7,7 +7,7 @@ import Filters from './Filters';
const AttributeFilter = ({ contentType, slug, metadatas }) => {
const { formatMessage } = useIntl();
const allowedAttributes = useAllowedAttributes(contentType, slug);
const displayedFilters = allowedAttributes.map(name => {
const displayedFilters = allowedAttributes.map((name) => {
const attribute = contentType.attributes[name];
const { type, enum: options } = attribute;

View File

@ -8,7 +8,7 @@ import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { Wrapper, Sub } from './components';
const renderMsg = msg => <p>{msg}</p>;
const renderMsg = (msg) => <p>{msg}</p>;
const Block = ({ children, description, style, title }) => (
<div className="col-md-12">

View File

@ -40,13 +40,8 @@ const CollectionTypeFormWrapper = ({ allLayoutData, children, slug, id, origin }
const { push, replace } = useHistory();
const [{ rawQuery }] = useQueryParams();
const dispatch = useDispatch();
const {
componentsDataStructure,
contentTypeDataStructure,
data,
isLoading,
status,
} = useSelector(selectCrudReducer);
const { componentsDataStructure, contentTypeDataStructure, data, isLoading, status } =
useSelector(selectCrudReducer);
const redirectionLink = useFindRedirectionLink(slug);
const isMounted = useRef(true);
@ -65,7 +60,7 @@ const CollectionTypeFormWrapper = ({ allLayoutData, children, slug, id, origin }
}, [slug, id, isCreatingEntry, origin]);
const cleanClonedData = useCallback(
data => {
(data) => {
if (!origin) {
return data;
}
@ -81,7 +76,7 @@ const CollectionTypeFormWrapper = ({ allLayoutData, children, slug, id, origin }
[origin]
);
const cleanReceivedData = useCallback(data => {
const cleanReceivedData = useCallback((data) => {
const cleaned = removePasswordFieldsFromData(
data,
allLayoutDataRef.current.contentType,
@ -136,7 +131,7 @@ const CollectionTypeFormWrapper = ({ allLayoutData, children, slug, id, origin }
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const fetchData = async source => {
const fetchData = async (source) => {
dispatch(getData());
try {
@ -201,7 +196,7 @@ const CollectionTypeFormWrapper = ({ allLayoutData, children, slug, id, origin }
]);
const displayErrors = useCallback(
err => {
(err) => {
const errorPayload = err.response.data;
let errorMessage = get(errorPayload, ['error', 'message'], 'Bad Request');
@ -218,7 +213,7 @@ const CollectionTypeFormWrapper = ({ allLayoutData, children, slug, id, origin }
);
const onDelete = useCallback(
async trackerProperty => {
async (trackerProperty) => {
try {
trackUsageRef.current('willDeleteEntry', trackerProperty);

View File

@ -36,7 +36,7 @@ function getItemStyles(initialOffset, currentOffset, mouseOffset) {
const CustomDragLayer = () => {
const { itemType, isDragging, item, initialOffset, currentOffset, mouseOffset } = useDragLayer(
monitor => ({
(monitor) => ({
item: monitor.getItem(),
itemType: monitor.getItemType(),
initialOffset: monitor.getInitialSourceClientOffset(),

View File

@ -85,7 +85,7 @@ const RelationMultiple = ({ fieldSchema, metadatas, queryInfos, name, rowId, val
{status === 'success' && (
<>
{data?.results.map(entry => (
{data?.results.map((entry) => (
<MenuItem key={entry.id} aria-disabled>
<TypographyMaxWidth ellipsis>
<CellValue

View File

@ -36,7 +36,7 @@ const RepeatableComponentCell = ({ value, metadatas }) => {
return (
<Box {...stopPropagation}>
<SimpleMenu label={Label} size="S">
{value.map(item => (
{value.map((item) => (
<MenuItem key={item.id} aria-disabled>
<TypographyMaxWidth ellipsis>
<CellValue type={mainFieldType} value={item[mainFieldName] || item.id} />

View File

@ -1,7 +1,7 @@
import isSingleRelation from '../isSingleRelation';
describe('isSingleRelation', () => {
['oneToOne', 'manyToOne', 'oneToOneMorph'].forEach(type => {
['oneToOne', 'manyToOne', 'oneToOneMorph'].forEach((type) => {
test(`is single relation: ${type}`, () => {
expect(isSingleRelation(type)).toBeTruthy();
});

View File

@ -38,7 +38,7 @@ const TableRows = ({
return (
<Tbody>
{rows.map((data, index) => {
const isChecked = entriesToDelete.findIndex(id => id === data.id) !== -1;
const isChecked = entriesToDelete.findIndex((id) => id === data.id) !== -1;
const itemLineText = formatMessage(
{
id: 'content-manager.components.DynamicTable.row-line',
@ -51,7 +51,7 @@ const TableRows = ({
<Tr
key={data.id}
{...onRowClick({
fn: () => {
fn() {
trackUsage('willEditEntryFromList');
push({
pathname: `${pathname}/${data.id}`,
@ -170,8 +170,8 @@ TableRows.defaultProps = {
canCreate: false,
canDelete: false,
entriesToDelete: [],
onClickDelete: () => {},
onSelectRow: () => {},
onClickDelete() {},
onSelectRow() {},
rows: [],
withBulkActions: false,
withMainAction: false,

View File

@ -35,7 +35,7 @@ const DynamicTable = ({
layout,
});
const formattedHeaders = headers.displayedHeaders.map(header => {
const formattedHeaders = headers.displayedHeaders.map((header) => {
if (header.fieldSchema.type === 'relation') {
const sortFieldValue = `${header.name}.${header.metadatas.mainField.name}`;
@ -65,7 +65,7 @@ const DynamicTable = ({
searchable: false,
sortable: true,
},
cellFormatter: cellData => {
cellFormatter(cellData) {
const isPublished = !isEmpty(cellData.publishedAt);
return <State isPublished={isPublished} />;

View File

@ -120,26 +120,24 @@ const AddComponentButton = ({
}
return (
<>
<Flex justifyContent="center">
<Box style={{ cursor: isDisabled ? 'not-allowed' : 'pointer' }}>
<StyledButton type="button" onClick={onClick} disabled={isDisabled} hasError={hasError}>
<Flex>
<BoxFullHeight aria-hidden paddingRight={2}>
<StyledAddIcon $isOpen={isOpen} $hasError={hasError && !isOpen} />
</BoxFullHeight>
<Typography
variant="pi"
fontWeight="bold"
textColor={hasError && !isOpen ? 'danger600' : 'neutral500'}
>
{buttonLabel}
</Typography>
</Flex>
</StyledButton>
</Box>
</Flex>
</>
<Flex justifyContent="center">
<Box style={{ cursor: isDisabled ? 'not-allowed' : 'pointer' }}>
<StyledButton type="button" onClick={onClick} disabled={isDisabled} hasError={hasError}>
<Flex>
<BoxFullHeight aria-hidden paddingRight={2}>
<StyledAddIcon $isOpen={isOpen} $hasError={hasError && !isOpen} />
</BoxFullHeight>
<Typography
variant="pi"
fontWeight="bold"
textColor={hasError && !isOpen ? 'danger600' : 'neutral500'}
>
{buttonLabel}
</Typography>
</Flex>
</StyledButton>
</Box>
</Flex>
);
};

View File

@ -88,7 +88,7 @@ const Component = ({
const formErrorsKeys = Object.keys(formErrors);
const fieldsErrors = formErrorsKeys.filter(errorKey => {
const fieldsErrors = formErrorsKeys.filter((errorKey) => {
const errorKeysArray = errorKey.split('.');
if (`${errorKeysArray[0]}.${errorKeysArray[1]}` === `${name}.${index}`) {

View File

@ -75,7 +75,7 @@ function ComponentCard({ componentUid, intlLabel, icon, onClick }) {
ComponentCard.defaultProps = {
icon: 'dice-d6',
onClick: () => {},
onClick() {},
};
ComponentCard.propTypes = {

View File

@ -16,7 +16,7 @@ const ComponentPicker = ({ components, isOpen, onClickAddComponent }) => {
const [categoryToOpen, setCategoryToOpen] = useState('');
const dynamicComponentCategories = useMemo(() => {
const componentsWithInfo = components.map(componentUid => {
const componentsWithInfo = components.map((componentUid) => {
const { category, info } = getComponentLayout(componentUid);
return { componentUid, category, info };
@ -38,7 +38,7 @@ const ComponentPicker = ({ components, isOpen, onClickAddComponent }) => {
}, [isOpen, dynamicComponentCategories]);
const handleAddComponentToDz = useCallback(
componentUid => {
(componentUid) => {
onClickAddComponent(componentUid);
setCategoryToOpen('');
},
@ -46,7 +46,7 @@ const ComponentPicker = ({ components, isOpen, onClickAddComponent }) => {
);
const handleClickToggle = useCallback(
categoryName => {
(categoryName) => {
const nextCategoryToOpen = categoryToOpen === categoryName ? '' : categoryName;
setCategoryToOpen(nextCategoryToOpen);

View File

@ -16,7 +16,7 @@ import ComponentPicker from './components/ComponentPicker';
/* eslint-disable react/no-array-index-key */
const createCollapses = arrayLength =>
const createCollapses = (arrayLength) =>
Array.from({ length: arrayLength }).map(() => ({ isOpen: false }));
const DynamicZone = ({
@ -53,7 +53,7 @@ const DynamicZone = ({
useEffect(() => {
if (shouldOpenAddedComponent) {
setComponentsCollapses(prev =>
setComponentsCollapses((prev) =>
prev.map((collapse, index) => {
if (index === prev.length - 1) {
return { ...collapse, isOpen: true };
@ -71,10 +71,10 @@ const DynamicZone = ({
const { max = Infinity, min = -Infinity } = fieldSchema;
const dynamicZoneErrors = useMemo(() => {
return Object.keys(formErrors)
.filter(key => {
.filter((key) => {
return key === name;
})
.map(key => formErrors[key]);
.map((key) => formErrors[key]);
}, [formErrors, name]);
const dynamicZoneAvailableComponents = useMemo(() => fieldSchema.components || [], [fieldSchema]);
@ -89,7 +89,7 @@ const DynamicZone = ({
hasError && get(dynamicZoneErrors, [0, 'id'], '') === 'components.Input.error.validation.max';
const handleAddComponent = useCallback(
componentUid => {
(componentUid) => {
setIsOpen(false);
addComponentToDynamicZone(name, componentUid, hasError);
@ -100,7 +100,7 @@ const DynamicZone = ({
const handleClickOpenPicker = () => {
if (dynamicDisplayedComponentsLength < max) {
setIsOpen(prev => !prev);
setIsOpen((prev) => !prev);
} else {
toggleNotification({
type: 'info',
@ -109,8 +109,8 @@ const DynamicZone = ({
}
};
const handleToggleComponent = indexToToggle => {
setComponentsCollapses(prev =>
const handleToggleComponent = (indexToToggle) => {
setComponentsCollapses((prev) =>
prev.map(({ isOpen }, index) => {
if (index === indexToToggle) {
return { isOpen: !isOpen };
@ -123,7 +123,7 @@ const DynamicZone = ({
const handleMoveComponentDown = (name, currentIndex) => {
moveComponentDown(name, currentIndex);
setComponentsCollapses(prev => {
setComponentsCollapses((prev) => {
return prev.map(({ isOpen }, index, refArray) => {
if (index === currentIndex + 1) {
return { isOpen: refArray[currentIndex].isOpen };
@ -140,7 +140,7 @@ const DynamicZone = ({
const handleMoveComponentUp = (name, currentIndex) => {
moveComponentUp(name, currentIndex);
setComponentsCollapses(prev => {
setComponentsCollapses((prev) => {
return prev.map(({ isOpen }, index, refArray) => {
if (index === currentIndex - 1) {
return { isOpen: refArray[currentIndex].isOpen };

View File

@ -1,7 +1,7 @@
import React from 'react';
function connect(WrappedComponent, select) {
return function(props) {
return (props) => {
// eslint-disable-next-line react/prop-types
const selectors = select(props.name);

View File

@ -17,7 +17,7 @@ function useSelect(name) {
} = useCMEditViewDataManager();
const dynamicDisplayedComponents = useMemo(
() => get(modifiedData, [name], []).map(data => data.__component),
() => get(modifiedData, [name], []).map((data) => data.__component),
[modifiedData, name]
);

View File

@ -264,7 +264,7 @@ const EditViewDataManagerProvider = ({
);
const createFormData = useCallback(
data => {
(data) => {
// First we need to remove the added keys needed for the dnd
const preparedData = removeKeyInObject(cloneDeep(data), '__temp_key__');
// Then we need to apply our helper
@ -288,7 +288,7 @@ const EditViewDataManagerProvider = ({
}, [hasDraftAndPublish, shouldNotRunValidations]);
const handleSubmit = useCallback(
async e => {
async (e) => {
e.preventDefault();
let errors = {};
@ -358,8 +358,8 @@ const EditViewDataManagerProvider = ({
}, [allLayoutData, currentContentTypeLayout, isCreatingEntry, modifiedData, onPublish]);
const shouldCheckDZErrors = useCallback(
dzName => {
const doesDZHaveError = Object.keys(formErrors).some(key => key.split('.')[0] === dzName);
(dzName) => {
const doesDZHaveError = Object.keys(formErrors).some((key) => key.split('.')[0] === dzName);
const shouldCheckErrors = !isEmpty(formErrors) && doesDZHaveError;
return shouldCheckErrors;
@ -413,7 +413,7 @@ const EditViewDataManagerProvider = ({
});
}, []);
const onRemoveRelation = useCallback(keys => {
const onRemoveRelation = useCallback((keys) => {
dispatch({
type: 'REMOVE_RELATION',
keys,
@ -526,7 +526,7 @@ const EditViewDataManagerProvider = ({
EditViewDataManagerProvider.defaultProps = {
from: '/',
initialValues: null,
redirectToPreviousPage: () => {},
redirectToPreviousPage() {},
};
EditViewDataManagerProvider.propTypes = {

View File

@ -18,7 +18,7 @@ const initialState = {
const reducer = (state, action) =>
// eslint-disable-next-line consistent-return
produce(state, draftState => {
produce(state, (draftState) => {
switch (action.type) {
case 'ADD_NON_REPEATABLE_COMPONENT_TO_FIELD': {
set(

View File

@ -32,7 +32,7 @@ const cleanData = (retrievedData, currentSchema, componentsSchema) => {
}
case 'media':
if (getOtherInfos(schema, [current, 'multiple']) === true) {
cleanedData = value ? value.filter(file => !(file instanceof File)) : null;
cleanedData = value ? value.filter((file) => !(file instanceof File)) : null;
} else {
cleanedData = get(value, 0) instanceof File ? null : get(value, 'id', null);
}
@ -40,7 +40,7 @@ const cleanData = (retrievedData, currentSchema, componentsSchema) => {
case 'component':
if (isRepeatable) {
cleanedData = value
? value.map(data => {
? value.map((data) => {
const subCleanedData = recursiveCleanData(data, componentsSchema[component]);
return subCleanedData;
@ -52,7 +52,7 @@ const cleanData = (retrievedData, currentSchema, componentsSchema) => {
break;
case 'dynamiczone':
cleanedData = value.map(componentData => {
cleanedData = value.map((componentData) => {
const subCleanedData = recursiveCleanData(
componentData,
componentsSchema[componentData.__component]
@ -77,7 +77,7 @@ const cleanData = (retrievedData, currentSchema, componentsSchema) => {
export const helperCleanData = (value, key) => {
if (isArray(value)) {
return value.map(obj => (obj[key] ? obj[key] : obj));
return value.map((obj) => (obj[key] ? obj[key] : obj));
}
if (isObject(value)) {
return value[key];

View File

@ -9,12 +9,12 @@ import { translatedErrors as errorsTrads } from '@strapi/helper-plugin';
import isFieldTypeNumber from '../../../utils/isFieldTypeNumber';
yup.addMethod(yup.mixed, 'defined', function() {
return this.test('defined', errorsTrads.required, value => value !== undefined);
yup.addMethod(yup.mixed, 'defined', function () {
return this.test('defined', errorsTrads.required, (value) => value !== undefined);
});
yup.addMethod(yup.array, 'notEmptyMin', function(min) {
return this.test('notEmptyMin', errorsTrads.min, value => {
yup.addMethod(yup.array, 'notEmptyMin', function (min) {
return this.test('notEmptyMin', errorsTrads.min, (value) => {
if (isEmpty(value)) {
return true;
}
@ -23,8 +23,8 @@ yup.addMethod(yup.array, 'notEmptyMin', function(min) {
});
});
yup.addMethod(yup.string, 'isInferior', function(message, max) {
return this.test('isInferior', message, function(value) {
yup.addMethod(yup.string, 'isInferior', function (message, max) {
return this.test('isInferior', message, function (value) {
if (!value) {
return true;
}
@ -37,8 +37,8 @@ yup.addMethod(yup.string, 'isInferior', function(message, max) {
});
});
yup.addMethod(yup.string, 'isSuperior', function(message, min) {
return this.test('isSuperior', message, function(value) {
yup.addMethod(yup.string, 'isSuperior', function (message, min) {
return this.test('isSuperior', message, function (value) {
if (!value) {
return true;
}
@ -51,7 +51,7 @@ yup.addMethod(yup.string, 'isSuperior', function(message, min) {
});
});
const getAttributes = data => get(data, ['attributes'], {});
const getAttributes = (data) => get(data, ['attributes'], {});
const createYupSchema = (
model,
@ -97,7 +97,7 @@ const createYupSchema = (
if (attribute.repeatable === true) {
const { min, max, required } = attribute;
let componentSchema = yup.lazy(value => {
let componentSchema = yup.lazy((value) => {
let baseSchema = yup.array().of(componentFieldSchema);
if (min) {
@ -123,7 +123,7 @@ const createYupSchema = (
return acc;
}
const componentSchema = yup.lazy(obj => {
const componentSchema = yup.lazy((obj) => {
if (obj !== undefined) {
return attribute.required === true && !options.isDraft
? componentFieldSchema.defined()
@ -154,7 +154,7 @@ const createYupSchema = (
if (min) {
if (attribute.required) {
dynamicZoneSchema = dynamicZoneSchema
.test('min', errorsTrads.min, value => {
.test('min', errorsTrads.min, (value) => {
if (options.isCreatingEntry) {
return value && value.length >= min;
}
@ -165,7 +165,7 @@ const createYupSchema = (
return value !== null && value.length >= min;
})
.test('required', errorsTrads.required, value => {
.test('required', errorsTrads.required, (value) => {
if (options.isCreatingEntry) {
return value !== null || value !== undefined;
}
@ -180,7 +180,7 @@ const createYupSchema = (
dynamicZoneSchema = dynamicZoneSchema.notEmptyMin(min);
}
} else if (attribute.required && !options.isDraft) {
dynamicZoneSchema = dynamicZoneSchema.test('required', errorsTrads.required, value => {
dynamicZoneSchema = dynamicZoneSchema.test('required', errorsTrads.required, (value) => {
if (options.isCreatingEntry) {
return value !== null || value !== undefined;
}
@ -215,7 +215,7 @@ const createYupSchemaAttribute = (type, validations, options) => {
if (type === 'json') {
schema = yup
.mixed(errorsTrads.json)
.test('isJSON', errorsTrads.json, value => {
.test('isJSON', errorsTrads.json, (value) => {
if (value === undefined) {
return true;
}
@ -238,7 +238,7 @@ const createYupSchemaAttribute = (type, validations, options) => {
if (['number', 'integer', 'float', 'decimal'].includes(type)) {
schema = yup
.number()
.transform(cv => (isNaN(cv) ? undefined : cv))
.transform((cv) => (isNaN(cv) ? undefined : cv))
.typeError();
}
@ -250,7 +250,7 @@ const createYupSchemaAttribute = (type, validations, options) => {
schema = yup.date();
}
Object.keys(validations).forEach(validation => {
Object.keys(validations).forEach((validation) => {
const validationValue = validations[validation];
if (
@ -269,7 +269,7 @@ const createYupSchemaAttribute = (type, validations, options) => {
if (options.isCreatingEntry) {
schema = schema.required(errorsTrads.required);
} else {
schema = schema.test('required', errorsTrads.required, value => {
schema = schema.test('required', errorsTrads.required, (value) => {
// Field is not touched and the user is editing the entry
if (value === undefined && !options.isFromComponent) {
return true;

View File

@ -1,7 +1,7 @@
import React from 'react';
function connect(WrappedComponent, select) {
return function(props) {
return (props) => {
// eslint-disable-next-line react/prop-types
const selectors = select(props);

View File

@ -22,7 +22,7 @@ function useSelect({ isFromDynamicZone, name }) {
const allDynamicZoneFields = useMemo(() => {
const attributes = get(contentType, ['attributes'], {});
const dynamicZoneFields = Object.keys(attributes).filter(attrName => {
const dynamicZoneFields = Object.keys(attributes).filter((attrName) => {
return get(attributes, [attrName, 'type'], '') === 'dynamiczone';
});
@ -43,17 +43,17 @@ function useSelect({ isFromDynamicZone, name }) {
return true;
}
const includedDynamicZoneFields = allowedFields.filter(name => name === compoName[0]);
const includedDynamicZoneFields = allowedFields.filter((name) => name === compoName[0]);
if (includedDynamicZoneFields.length > 0) {
return true;
}
const relatedChildrenAllowedFields = allowedFields
.map(fieldName => {
.map((fieldName) => {
return fieldName.split('.');
})
.filter(fieldName => {
.filter((fieldName) => {
if (fieldName.length < compoName.length) {
return false;
}
@ -78,10 +78,10 @@ function useSelect({ isFromDynamicZone, name }) {
const allowedFields = isCreatingEntry ? [] : readActionAllowedFields;
const relatedChildrenAllowedFields = allowedFields
.map(fieldName => {
.map((fieldName) => {
return fieldName.split('.');
})
.filter(fieldName => {
.filter((fieldName) => {
if (fieldName.length < compoName.length) {
return false;
}

View File

@ -5,7 +5,7 @@ import { FormattedMessage } from 'react-intl';
const FormTitle = ({ description, title }) => (
<>
{!!title && <FormattedMessage id={title} />}
{!!description && <FormattedMessage id={description}>{msg => <p>{msg}</p>}</FormattedMessage>}
{!!description && <FormattedMessage id={description}>{(msg) => <p>{msg}</p>}</FormattedMessage>}
</>
);

View File

@ -13,7 +13,7 @@ const InjectionZoneList = ({ area, ...props }) => {
// TODO
return (
<ul>
{compos.map(compo => {
{compos.map((compo) => {
const component = compo.Component(props);
if (component) {

View File

@ -87,11 +87,10 @@ class InputJSON extends React.Component {
setSize = () => this.codeMirror.setSize('100%', 'auto');
getContentAtLine = line => this.codeMirror.getLine(line);
getContentAtLine = (line) => this.codeMirror.getLine(line);
getEditorOption = opt => this.codeMirror.getOption(opt);
getValue = () => this.codeMirror.getValue();
// getEditorOption = (opt) => this.codeMirror.getOption(opt);
// getValue = () => this.codeMirror.getValue();
markSelection = ({ message }) => {
let line = parseInt(message.split(':')[0].split('line ')[1], 10) - 1;
@ -142,7 +141,7 @@ class InputJSON extends React.Component {
this.timer = setTimeout(() => this.testJSON(doc.getValue()), WAIT);
};
testJSON = value => {
testJSON = (value) => {
try {
jsonlint.parse(value);
} catch (err) {
@ -189,7 +188,7 @@ InputJSON.defaultProps = {
error: undefined,
intlLabel: undefined,
labelAction: undefined,
onChange: () => {},
onChange() {},
value: null,
required: false,
};

View File

@ -1,6 +1,6 @@
/* Jison generated parser */
/* eslint-disable */
var jsonlint = (function() {
var jsonlint = (function () {
var parser = {
trace: function trace() {},
yy: {},
@ -453,7 +453,7 @@ var jsonlint = (function() {
},
};
/* Jison generated lexer */
var lexer = (function() {
var lexer = (function () {
var lexer = {
EOF: 1,
parseError: function parseError(str, hash) {
@ -463,7 +463,7 @@ var jsonlint = (function() {
throw new Error(str);
}
},
setInput: function(input) {
setInput: function (input) {
this._input = input;
this._more = this._less = this.done = false;
this.yylineno = this.yyleng = 0;
@ -472,7 +472,7 @@ var jsonlint = (function() {
this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
return this;
},
input: function() {
input: function () {
var ch = this._input[0];
this.yytext += ch;
this.yyleng++;
@ -483,34 +483,34 @@ var jsonlint = (function() {
this._input = this._input.slice(1);
return ch;
},
unput: function(ch) {
unput: function (ch) {
this._input = ch + this._input;
return this;
},
more: function() {
more: function () {
this._more = true;
return this;
},
less: function(n) {
less: function (n) {
this._input = this.match.slice(n) + this._input;
},
pastInput: function() {
pastInput: function () {
var past = this.matched.substr(0, this.matched.length - this.match.length);
return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, '');
},
upcomingInput: function() {
upcomingInput: function () {
var next = this.match;
if (next.length < 20) {
next += this._input.substr(0, 20 - next.length);
}
return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, '');
},
showPosition: function() {
showPosition: function () {
var pre = this.pastInput();
var c = new Array(pre.length + 1).join('-');
return pre + this.upcomingInput() + '\n' + c + '^';
},
next: function() {
next: function () {
if (this.done) {
return this.EOF;
}
@ -587,7 +587,7 @@ var jsonlint = (function() {
_currentRules: function _currentRules() {
return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
},
topState: function() {
topState: function () {
return this.conditionStack[this.conditionStack.length - 2];
},
pushState: function begin(condition) {
@ -669,7 +669,7 @@ var jsonlint = (function() {
})();
if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
exports.parser = jsonlint;
exports.parse = function() {
exports.parse = function () {
return jsonlint.parse.apply(jsonlint, arguments);
};
exports.main = function commonjsMain(args) {

View File

@ -174,7 +174,7 @@ const InputUID = ({
setRegenerateLabel(null);
};
const handleChange = e => {
const handleChange = (e) => {
if (e.target.value && isCreation) {
setIsCustomized(true);
}

View File

@ -1,3 +1,3 @@
const UID_REGEX = new RegExp(/^[A-Za-z0-9-_.~]*$/);
const UID_REGEX = /^[A-Za-z0-9-_.~]*$/;
export default UID_REGEX;

View File

@ -157,10 +157,10 @@ function Inputs({
return disabled;
}, [disabled, isCreatingEntry, isUserAllowedToEditField, isUserAllowedToReadField]);
const options = useMemo(() => generateOptions(fieldSchema.enum || [], isRequired), [
fieldSchema,
isRequired,
]);
const options = useMemo(
() => generateOptions(fieldSchema.enum || [], isRequired),
[fieldSchema, isRequired]
);
const { label, description, placeholder, visible } = metadatas;

View File

@ -1,7 +1,7 @@
import React from 'react';
function connect(WrappedComponent, select) {
return function(props) {
return (props) => {
// eslint-disable-next-line react/prop-types
const selectors = select(props.keys);

View File

@ -12,7 +12,7 @@ const generateOptions = (options, isRequired = false) => {
key: '__enum_option_null',
value: '',
},
...options.map(option => {
...options.map((option) => {
return {
metadatas: {
intlLabel: {

Some files were not shown because too many files have changed in this diff Show More