keep only needed utils

Signed-off-by: soupette <cyril@strapi.io>
This commit is contained in:
soupette 2021-11-09 14:06:08 +01:00
parent b416194cc9
commit f354400f6f
25 changed files with 11 additions and 859 deletions

View File

@ -1,18 +0,0 @@
// NOTE TO PLUGINS DEVELOPERS:
// If you modify this file you need to update the documentation accordingly
// Here's the file: strapi/docs/3.0.0-beta.x/guides/custom-admin.md#update-the-content-manager
// Also the strapi-generate-plugins/files/admin/src/index.js needs to be updated
// IF THE DOC IS NOT UPDATED THE PULL REQUEST WILL NOT BE MERGED
import { dateFormats as defaultDateFormats } from '@strapi/helper-plugin';
const dateFormats = {
...defaultDateFormats,
// Customise the format by uncommenting the one you wan to override it corresponds to the type of your field
// date: 'dddd, MMMM Do YYYY',
// datetime: 'dddd, MMMM Do YYYY HH:mm',
// time: 'HH:mm A',
// timestamp: 'dddd, MMMM Do YYYY HH:mm',
};
export default dateFormats;

View File

@ -1,61 +0,0 @@
import { isEmpty, isNull, isObject, toLower, toString } from 'lodash';
import moment from 'moment';
import dateFormats from './dateFormats';
const getDisplayedValue = (type, value, name) => {
switch (toLower(type)) {
case 'string':
case 'text':
case 'email':
case 'enumeration':
case 'uid':
return (value && !isEmpty(toString(value))) || name === 'id' ? toString(value) : '-';
case 'float':
case 'integer':
case 'biginteger':
case 'decimal':
return !isNull(value) ? toString(value) : '-';
case 'boolean':
return value !== null ? toString(value) : '-';
case 'date':
case 'datetime':
case 'timestamp': {
if (value == null) {
return '-';
}
const date =
value && isObject(value) && value._isAMomentObject === true ? JSON.stringify(value) : value;
return moment(date).format(dateFormats[type]);
}
case 'password':
return '••••••••';
case 'media':
case 'file':
case 'files':
return value;
case 'time': {
if (!value) {
return '-';
}
const [hour, minute, second] = value.split(':');
const timeObj = {
hour,
minute,
second,
};
const date = moment().set(timeObj);
return date.format(dateFormats.time);
}
case 'relation': {
return value;
}
default:
return '-';
}
};
export default getDisplayedValue;

View File

@ -1,10 +1,8 @@
export { default as arrayMoveItem } from './arrayMoveItem';
export { default as checkIfAttributeIsDisplayable } from './checkIfAttributeIsDisplayable';
export { default as createDefaultForm } from './createDefaultForm';
export { default as dateFormats } from './dateFormats';
export { default as formatLayoutToApi } from './formatLayoutToApi';
export { default as generatePermissionsObject } from './generatePermissionsObject';
export { default as getDisplayedValue } from './getDisplayedValue';
export { default as getFieldName } from './getFieldName';
export { default as getMaxTempKey } from './getMaxTempKey';
export { default as getRequestUrl } from './getRequestUrl';

View File

@ -36,25 +36,6 @@ export { default as NotificationsProvider } from './providers/NotificationsProvi
export { default as StrapiAppProvider } from './providers/StrapiAppProvider';
// Utils
export { default as cleanData } from './old/utils/cleanData';
export { default as difference } from './old/utils/difference';
export { default as dateFormats } from './old/utils/dateFormats';
export { default as dateToUtcTime } from './old/utils/dateToUtcTime';
export { darken } from './old/utils/colors';
export { default as getFilterType } from './old/utils/getFilterType';
export { default as getQueryParameters } from './old/utils/getQueryParameters';
export { default as validateInput } from './old/utils/inputsValidations';
export { default as request } from './old/utils/request';
export { default as storeData } from './old/utils/storeData';
export { default as templateObject } from './old/utils/templateObject';
export { default as getYupInnerErrors } from './old/utils/getYupInnerErrors';
export { default as generateFiltersFromSearch } from './old/utils/generateFiltersFromSearch';
export { default as generateSearchFromFilters } from './old/utils/generateSearchFromFilters';
export { default as generateSearchFromObject } from './old/utils/generateSearchFromObject';
// New components
export { default as CheckPagePermissions } from './components/CheckPagePermissions';
@ -116,3 +97,7 @@ export {
} from './content-manager/utils/contentManagementUtilRemoveFieldsFromData';
export { default as getFileExtension } from './utils/getFileExtension/getFileExtension';
export * from './utils/stopPropagation';
export { default as difference } from './utils/difference';
export { default as request } from './utils/request';
export { default as getYupInnerErrors } from './utils/getYupInnerErrors';

View File

@ -1,14 +0,0 @@
import { isArray, isObject } from 'lodash';
const cleanData = (value, key, secondKey) => {
if (isArray(value)) {
return value.map(obj => (obj[key] ? obj[key] : obj));
}
if (isObject(value)) {
return value[key] || value[`_${key}`] || value[secondKey] || value[`_${secondKey}`];
}
return value;
};
export default cleanData;

View File

@ -1,18 +0,0 @@
const subtractLight = (color, amount) => {
const cc = parseInt(color, 16) - amount;
let c = cc < 0 ? 0 : cc;
c = c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`;
return c;
};
export const darken = (colour, amount) => {
let color = colour.indexOf('#') >= 0 ? colour.substring(1, colour.length) : colour;
const percentage = parseInt((255 * amount) / 100, 10);
color = `#${subtractLight(color.substring(0, 2), percentage)}${subtractLight(
color.substring(2, 4),
percentage
)}${subtractLight(color.substring(4, 6), percentage)}`;
return color;
};

View File

@ -1,3 +0,0 @@
export const RESTART_ON_REMOUNT = '@@saga-injector/restart-on-remount';
export const DAEMON = '@@saga-injector/daemon';
export const ONCE_TILL_UNMOUNT = '@@saga-injector/once-till-unmount';

View File

@ -1,8 +0,0 @@
const dateFormats = {
date: 'dddd, MMMM Do YYYY',
datetime: 'dddd, MMMM Do YYYY HH:mm',
time: 'HH:mm A',
timestamp: 'dddd, MMMM Do YYYY HH:mm',
};
export default dateFormats;

View File

@ -1,5 +0,0 @@
import moment from 'moment';
const dateToUtcTime = date => moment.parseZone(date).utc();
export default dateToUtcTime;

View File

@ -1,55 +0,0 @@
/**
* Generate filters object from string
* @param {String} search
* @return {Object}
*/
const generateFiltersFromSearch = search => {
return search
.split('&')
.filter(
x =>
!x.includes('_limit') &&
!x.includes('_page') &&
!x.includes('sort') &&
!x.includes('_start') &&
!x.includes('_q=') &&
x !== ''
)
.reduce((acc, curr) => {
const [name, value] = curr.split('=');
const split = name.split('_');
let filter = `_${split[split.length - 1]}`;
if (
![
'_ne',
'_lt',
'_lte',
'_gt',
'_gte',
'_contains',
'_containss',
'_ncontains',
'_in',
'_nin',
].includes(filter)
) {
filter = '=';
}
const toSlice = filter === '=' ? split.length : split.length - 1;
acc.push({
name: split
.slice(0, toSlice)
.join('_')
.replace('?', ''),
filter,
value: decodeURIComponent(value),
});
return acc;
}, []);
};
export default generateFiltersFromSearch;

View File

@ -1,26 +0,0 @@
import { isEmpty, toString } from 'lodash';
const generateSearchFromFilters = (filters, paramsToFilter = []) => {
return Object.keys(filters)
.filter(key => !paramsToFilter.includes(key) && !isEmpty(toString(filters[key])))
.map(key => {
let ret = `${key}=${encodeURIComponent(filters[key])}`;
if (key === 'filters') {
const formattedFilters = filters[key]
.reduce((acc, curr) => {
const key = curr.filter === '=' ? curr.name : `${curr.name}${curr.filter}`;
acc.push(`${key}=${encodeURIComponent(curr.value)}`);
return acc;
}, [])
.join('&');
ret = formattedFilters;
}
return ret;
})
.join('&');
};
export default generateSearchFromFilters;

View File

@ -1,38 +0,0 @@
import { clone, set, unset } from 'lodash';
const generateSearchFromObject = params => {
const clonedParams = clone(params);
const _start = (clonedParams._page - 1) * parseInt(clonedParams._limit, 10);
set(clonedParams, '_start', _start);
unset(clonedParams, '_page');
if (clonedParams._q === '') {
unset(clonedParams, '_q');
}
const search = Object.keys(clonedParams)
.reduce((acc, current) => {
if (current !== 'filters') {
acc.push(`${current}=${clonedParams[current]}`);
} else {
const filters = clonedParams[current].reduce((acc, curr) => {
const key = curr.filter === '=' ? curr.name : `${curr.name}${curr.filter}`;
acc.push(`${key}=${curr.value}`);
return acc;
}, []);
if (filters.length > 0) {
acc.push(filters.join('&'));
}
}
return acc;
}, [])
.join('&');
return search;
};
export default generateSearchFromObject;

View File

@ -1,120 +0,0 @@
const getFilterType = type => {
switch (type) {
case 'string':
case 'text':
case 'password':
case 'email':
return [
{
id: 'components.FilterOptions.FILTER_TYPES.=',
value: '=',
},
{
id: 'components.FilterOptions.FILTER_TYPES._ne',
value: '_ne',
},
{
id: 'components.FilterOptions.FILTER_TYPES._lt',
value: '_lt',
},
{
id: 'components.FilterOptions.FILTER_TYPES._lte',
value: '_lte',
},
{
id: 'components.FilterOptions.FILTER_TYPES._gt',
value: '_gt',
},
{
id: 'components.FilterOptions.FILTER_TYPES._gte',
value: '_gte',
},
{
id: 'components.FilterOptions.FILTER_TYPES._contains',
value: '_contains',
},
{
id: 'components.FilterOptions.FILTER_TYPES._containss',
value: '_containss',
},
// These lines are commented until we support the array in the admin
// {
// id: 'components.FilterOptions.FILTER_TYPES._in',
// value: '_in',
// },
// {
// id: 'components.FilterOptions.FILTER_TYPES._nin',
// value: '_nin',
// },
];
case 'integer':
case 'biginteger':
case 'float':
case 'decimal':
case 'date':
case 'datetime':
case 'time':
case 'timestamp':
case 'timestampUpdate':
return [
{
id: 'components.FilterOptions.FILTER_TYPES.=',
value: '=',
},
{
id: 'components.FilterOptions.FILTER_TYPES._ne',
value: '_ne',
},
{
id: 'components.FilterOptions.FILTER_TYPES._lt',
value: '_lt',
},
{
id: 'components.FilterOptions.FILTER_TYPES._lte',
value: '_lte',
},
{
id: 'components.FilterOptions.FILTER_TYPES._gt',
value: '_gt',
},
{
id: 'components.FilterOptions.FILTER_TYPES._gte',
value: '_gte',
},
// FIXME: commenting these filters as I am not sure if the UI
// corresponds to the filter
// {
// id: 'components.FilterOptions.FILTER_TYPES._in',
// value: '_in',
// },
// {
// id: 'components.FilterOptions.FILTER_TYPES._nin',
// value: '_nin',
// },
];
case 'enum':
return [
{
id: 'components.FilterOptions.FILTER_TYPES.=',
value: '_contains',
},
{
id: 'components.FilterOptions.FILTER_TYPES._ne',
value: '_ncontains',
},
];
default:
return [
{
id: 'components.FilterOptions.FILTER_TYPES.=',
value: '=',
},
{
id: 'components.FilterOptions.FILTER_TYPES._ne',
value: '_ne',
},
];
}
};
export default getFilterType;

View File

@ -1,14 +0,0 @@
/* eslint-disable prefer-template */
export default (location, n) => {
const half = location.split(n + '=')[1];
if (half !== undefined) {
try {
return decodeURIComponent(half.split('&')[0]);
} catch (e) {
return null;
}
}
return null;
};

View File

@ -1,77 +0,0 @@
import { includes, mapKeys, reject } from 'lodash';
/**
* [validateInput description]
* @param {String || Number} value Input's value
* @param {Object} inputValidations
* @param {String} [type='text'] Optional: the input's type only for email
* @return {Array} Array of errors to be displayed
*/
/* eslint-disable no-useless-escape */
const validateInput = (value, inputValidations = {}, type = 'text') => {
let errors = [];
const emailRegex = new RegExp(
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
// handle i18n
const requiredError = { id: 'components.Input.error.validation.required' };
mapKeys(inputValidations, (validationValue, validationKey) => {
switch (validationKey) {
case 'max':
if (parseInt(value, 10) > validationValue) {
errors.push({ id: 'components.Input.error.validation.max' });
}
break;
case 'maxLength':
if (value && value.length > validationValue) {
errors.push({ id: 'components.Input.error.validation.maxLength' });
}
break;
case 'min':
if (parseInt(value, 10) < validationValue) {
errors.push({ id: 'components.Input.error.validation.min' });
}
break;
case 'minLength':
if (!value || value.length < validationValue) {
errors.push({ id: 'components.Input.error.validation.minLength' });
}
break;
case 'required':
if (value == null || value.length === 0) {
errors.push({ id: 'components.Input.error.validation.required' });
}
break;
case 'regex':
if (!new RegExp(validationValue).test(value)) {
errors.push({ id: 'components.Input.error.validation.regex' });
}
break;
case 'type':
if (validationValue === 'json') {
try {
value = JSON.parse(value);
} catch (err) {
errors.push({ id: 'components.Input.error.validation.json' });
}
}
break;
default:
errors = [];
}
});
if (type === 'email' && !emailRegex.test(value)) {
errors.push({ id: 'components.Input.error.validation.email' });
}
if (includes(errors, requiredError)) {
errors = reject(errors, error => error !== requiredError);
}
return errors;
};
export default validateInput;

View File

@ -1,25 +0,0 @@
const storeData = {
clear(key) {
if (localStorage) {
return localStorage.removeItem(key);
}
return null;
},
get(key) {
if (localStorage && localStorage.getItem(key)) {
return JSON.parse(localStorage.getItem(key));
}
return null;
},
set(key, value) {
if (localStorage) {
return localStorage.setItem(key, JSON.stringify(value, null, 2));
}
},
};
export default storeData;

View File

@ -1,26 +0,0 @@
import { isPlainObject, isString, isArray } from 'lodash';
const templateObject = function(obj, variables) {
// Allow values which looks like such as
// an ES6 literal string without parenthesis inside (aka function call).
const regex = /\$\{[\S]*\}/g;
const replacer = match => {
const key = match.substring(0, match.length - 1).replace('${', '');
return variables[key];
};
return Object.keys(obj).reduce((acc, key) => {
if (isPlainObject(obj[key]) || isArray(obj[key])) {
acc[key] = templateObject(obj[key], variables[key]);
} else if (isString(obj[key]) && regex.test(obj[key])) {
acc[key] = obj[key].replace(regex, replacer);
} else {
acc[key] = variables[obj[key]];
}
return acc;
}, {});
};
export default templateObject;

View File

@ -1,47 +0,0 @@
import generateFiltersFromSearch from '../generateFiltersFromSearch';
describe('HELPER PLUGIN | utils | generateFiltersFromSearch', () => {
it('should generate an array of filters', () => {
const search =
'?sort=id:ASC&bool=true&big_number_ne=1&createdAt_lt=2019-08-01T00:00:00Z&date_lte=2019-08-02T00:00:00Z&decimal_number_gt=2&enum_ne=noon&float_number_gte=3';
const expected = [
{
name: 'bool',
filter: '=',
value: 'true',
},
{
name: 'big_number',
filter: '_ne',
value: '1',
},
{
name: 'createdAt',
filter: '_lt',
value: '2019-08-01T00:00:00Z',
},
{
name: 'date',
filter: '_lte',
value: '2019-08-02T00:00:00Z',
},
{
name: 'decimal_number',
filter: '_gt',
value: '2',
},
{
name: 'enum',
filter: '_ne',
value: 'noon',
},
{
name: 'float_number',
filter: '_gte',
value: '3',
},
];
expect(generateFiltersFromSearch(search)).toEqual(expected);
});
});

View File

@ -1,59 +0,0 @@
import generateSearchFromFilters from '../generateSearchFromFilters';
describe('HELPER PLUGIN | utils | generateSearchFromFilters', () => {
it('should return a string with all the applied filters', () => {
const data = {
_limit: 10,
sort: 'id:ASC',
_page: 2,
filters: [
{
name: 'bool',
filter: '=',
value: 'true',
},
{
name: 'big_number',
filter: '_ne',
value: '1',
},
{
name: 'createdAt',
filter: '_lt',
value: '2019-08-01T00:00:00Z',
},
{
name: 'date',
filter: '_lte',
value: '2019-08-02T00:00:00Z',
},
{
name: 'decimal_number',
filter: '_gt',
value: '2',
},
{
name: 'enum',
filter: '_ne',
value: 'noon',
},
{
name: 'float_number',
filter: '_gte',
value: '3',
},
],
};
const expected =
'_limit=10&sort=id:ASC&_page=2&bool=true&big_number_ne=1&createdAt_lt=2019-08-01T00:00:00Z&date_lte=2019-08-02T00:00:00Z&decimal_number_gt=2&enum_ne=noon&float_number_gte=3';
const encoded = expected
.split('&')
.map(pair => {
const parts = pair.split('=');
return `${parts[0]}=${encodeURIComponent(parts[1])}`;
})
.join('&');
expect(generateSearchFromFilters(data)).toEqual(encoded);
});
});

View File

@ -1,44 +0,0 @@
import generateSearchFromObject from '../generateSearchFromObject';
describe('HELPER PLUGIN | utils | generateSearchFromObject', () => {
it('should return a string containing the _limit, _start and order', () => {
const search = { _page: 1, _limit: 10, sort: 'city:ASC' };
const expected = '_limit=10&sort=city:ASC&_start=0';
expect(generateSearchFromObject(search)).toEqual(expected);
});
it('should remove the _q param from the search if it is empty', () => {
const search = { _page: 1, _limit: 10, sort: 'city:ASC', _q: '' };
const expected = '_limit=10&sort=city:ASC&_start=0';
expect(generateSearchFromObject(search)).toEqual(expected);
});
it('should not add the filters if it is empty', () => {
const search = {
_page: 1,
_limit: 10,
sort: 'city:ASC',
_q: '',
filters: [],
};
const expected = '_limit=10&sort=city:ASC&_start=0';
expect(generateSearchFromObject(search)).toEqual(expected);
});
it('should handle the filters correctly', () => {
const search = {
_limit: 10,
_page: 1,
_q: '',
sort: 'city:ASC',
filters: [{ name: 'city', filter: '=', value: 'test' }],
};
const expected = '_limit=10&sort=city:ASC&city=test&_start=0';
expect(generateSearchFromObject(search)).toEqual(expected);
});
});

View File

@ -1,175 +0,0 @@
import getFilterType from '../getFilterType';
describe('HELPER PLUGIN | utils | getFilterType', () => {
describe('Text types', () => {
const expected = [
{
id: 'components.FilterOptions.FILTER_TYPES.=',
value: '=',
},
{
id: 'components.FilterOptions.FILTER_TYPES._ne',
value: '_ne',
},
{
id: 'components.FilterOptions.FILTER_TYPES._lt',
value: '_lt',
},
{
id: 'components.FilterOptions.FILTER_TYPES._lte',
value: '_lte',
},
{
id: 'components.FilterOptions.FILTER_TYPES._gt',
value: '_gt',
},
{
id: 'components.FilterOptions.FILTER_TYPES._gte',
value: '_gte',
},
{
id: 'components.FilterOptions.FILTER_TYPES._contains',
value: '_contains',
},
{
id: 'components.FilterOptions.FILTER_TYPES._containss',
value: '_containss',
},
// Commenting until we support them
// {
// id: 'components.FilterOptions.FILTER_TYPES._in',
// value: '_in',
// },
// {
// id: 'components.FilterOptions.FILTER_TYPES._nin',
// value: '_nin',
// },
];
it('should generate the expected array if type is text', () => {
const type = 'text';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is string', () => {
const type = 'string';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is password', () => {
const type = 'password';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is email', () => {
const type = 'email';
expect(getFilterType(type)).toEqual(expected);
});
});
describe('Number and timestamp types', () => {
const expected = [
{
id: 'components.FilterOptions.FILTER_TYPES.=',
value: '=',
},
{
id: 'components.FilterOptions.FILTER_TYPES._ne',
value: '_ne',
},
{
id: 'components.FilterOptions.FILTER_TYPES._lt',
value: '_lt',
},
{
id: 'components.FilterOptions.FILTER_TYPES._lte',
value: '_lte',
},
{
id: 'components.FilterOptions.FILTER_TYPES._gt',
value: '_gt',
},
{
id: 'components.FilterOptions.FILTER_TYPES._gte',
value: '_gte',
},
];
it('should generate the expected array if type is integer', () => {
const type = 'integer';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is biginteger', () => {
const type = 'biginteger';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is float', () => {
const type = 'float';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is decimal', () => {
const type = 'decimal';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is date', () => {
const type = 'date';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is datetime', () => {
const type = 'datetime';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is time', () => {
const type = 'time';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is timestamp', () => {
const type = 'timestamp';
expect(getFilterType(type)).toEqual(expected);
});
it('should generate the expected array if type is timestampUpdate', () => {
const type = 'timestampUpdate';
expect(getFilterType(type)).toEqual(expected);
});
});
describe('Other types', () => {
const expected = [
{
id: 'components.FilterOptions.FILTER_TYPES.=',
value: '=',
},
{
id: 'components.FilterOptions.FILTER_TYPES._ne',
value: '_ne',
},
];
it('should generate the expected array if type is size', () => {
const type = 'size';
expect(getFilterType(type)).toEqual(expected);
});
});
});

View File

@ -1,4 +1,6 @@
import { isEqual, transform, isObject } from 'lodash';
import isEqual from 'lodash/isEqual';
import transform from 'lodash/transform';
import isObject from 'lodash/isObject';
function difference(object, base) {
function changes(object, base) {

View File

@ -1,5 +1,5 @@
import { isEmpty, pickBy, transform } from 'lodash';
import request from '../../old/utils/request';
import request from '../request';
const findMatchingPermissions = (userPermissions, permissions) => {
return transform(

View File

@ -1,6 +1,6 @@
import 'whatwg-fetch';
import _ from 'lodash';
import auth from '../../utils/auth';
import startsWith from 'lodash/startsWith';
import auth from '../auth';
/**
* Parses the JSON returned by a network request
@ -130,7 +130,7 @@ export default function request(...args) {
}
// Add parameters to url
url = _.startsWith(url, '/') ? `${strapi.backendURL}${url}` : url;
url = startsWith(url, '/') ? `${strapi.backendURL}${url}` : url;
if (options && options.params) {
const params = formatQueryParams(options.params);