Cleanup old code

This commit is contained in:
Alexandre Bodin 2019-07-22 17:08:29 +02:00
parent e9ae95292e
commit 85762551aa
7 changed files with 22 additions and 426 deletions

View File

@ -1,87 +0,0 @@
// TODO: to remove
const _ = require('lodash');
/**
* Retrieve the path of each API
* @param {Object}} data
* @returns {Array} Array of API path ['plugins.upload.file', 'plugins.users-permissions.user', ...]
*/
const getApis = data =>
Object.keys(data).reduce((acc, curr) => {
if (data[curr].fields) {
return acc.concat([curr]);
}
if (curr === 'plugins') {
Object.keys(data[curr]).forEach(plugin => {
Object.keys(data[curr][plugin]).forEach(api => {
acc = acc.concat([`${curr}.${plugin}.${api}`]);
});
});
}
return acc;
}, []);
/**
* Retrieve all the fields from an api
* @param {Object} data
* @param {Array} apis
* @returns {Array} Array composed of fields path for instance : [['plugins.users-permissions.user.fields.username', 'plugins.users-permissions.user.fields.email', 'plugins.users-permissions.user.fields.password'], [...]]
*/
const getApisKeys = (data, apis) =>
apis.map(apiPath => {
const fields = Object.keys(_.get(data.models, apiPath.concat(['fields'])));
return fields.map(field => `${apiPath.join('.')}.fields.${field}`);
});
/**
* Same as above but only for the relations since it's custom
*/
const getApisUploadRelations = (data, sameArray) =>
sameArray.map(apiPath => {
const relationPath = [...apiPath, 'relations'];
const relationsObject = _.get(data.models, relationPath, {});
const relations = Object.keys(relationsObject).filter(relationName => {
return (
_.get(data.models, [...relationPath, relationName, 'plugin']) ===
'upload'
);
});
return relations.map(
relation => `${apiPath.join('.')}.editDisplay.availableFields.${relation}`
);
});
/**
*
* @param {String} attrPath
* @returns {Array}
*/
const getEditDisplayAvailableFieldsPath = attrPath => [
..._.take(attrPath, attrPath.length - 2),
'editDisplay',
'availableFields',
attrPath[attrPath.length - 1],
];
const getEditDisplayDisplayedField = attrPath => [
..._.take(attrPath, attrPath.length - 2),
'editDisplay',
'displayedField',
];
const getEditDisplayFieldsPath = attrPath => [
..._.take(attrPath, attrPath.length - 2),
'editDisplay',
'fields',
];
module.exports = {
getApis,
getApisKeys,
getApisUploadRelations,
getEditDisplayAvailableFieldsPath,
getEditDisplayDisplayedField,
getEditDisplayFieldsPath,
};

View File

@ -3,6 +3,7 @@
const _ = require('lodash');
const pluralize = require('pluralize');
const storeUtils = require('./utils/store');
const { pickSchemaFields } = require('./utils/schema');
const uidToStoreKey = ({ uid, source }) => {
const sourceKey = source ? `${source}.${uid}` : uid;
@ -52,9 +53,9 @@ module.exports = {
},
formatContentTypeSchema(contentType) {
const { associations, schema, allAttributes } = contentType;
const { associations, allAttributes } = contentType;
return {
...schema,
...pickSchemaFields(contentType),
attributes: Object.keys(allAttributes).reduce((acc, key) => {
const attr = allAttributes[key];
const assoc = associations.find(assoc => assoc.alias === key);

View File

@ -1,6 +1,7 @@
'use strict';
const storeUtils = require('./utils/store');
const { pickSchemaFields } = require('./utils/schema');
const uidToStoreKey = uid => `groups::${uid}`;
@ -31,9 +32,9 @@ module.exports = {
},
formatGroupSchema(group) {
const { associations, schema, allAttributes } = group;
const { associations, allAttributes } = group;
return {
...schema,
...pickSchemaFields(group),
attributes: Object.keys(allAttributes).reduce((acc, key) => {
const attr = allAttributes[key];
const assoc = associations.find(assoc => assoc.alias === key);

View File

@ -0,0 +1,9 @@
'use strict';
const _ = require('lodash');
const pickSchemaFields = model => _.pick(model, []);
module.exports = {
pickSchemaFields,
};

View File

@ -1,253 +0,0 @@
// This file contains all the methods required to get the number of inputs
// that will be displayed in the content manager edit view.
// Since we want to keep the shape of the layout when we remove a field from
// the content type builder form builder we duplicated this file already used in the content manager.
const { findIndex, pullAt, range } = require('lodash');
const { List } = require('immutable');
class Manager {
constructor(state, list, keys, index, layout) {
this.state = state;
this.keys = keys.split('.');
this.layout = layout;
this.list = list;
this.index = index;
this.arrayOfEndLineElements = this.getLinesBound();
this.attrToRemoveInfos = this.attrToRemoveInfos();
}
/**
* Retrieve the bootstrap col index, name and type of a field
* @param {Number} index
* @returns {Object}
*/
getAttrInfos(index) {
const name = this.getAttrName(index);
const appearance = this.layout.getIn([name, 'appearance']);
const type = appearance !== '' && appearance !== undefined ? appearance : this.getType(name);
const bootstrapCol = this.getBootStrapCol(type);
const infos = {
bootstrapCol,
index,
name,
type,
};
return infos;
}
/**
* Returns the number of divs to add to a row so each row is complete.
* @param {Number} number
* @returns {Array} Array of bootstrap cols to add to make a row of size 12.
*/
getColsToAdd(number) {
let ret;
switch(number) {
case 12:
ret = [];
break;
case 9:
ret = ['__col-md-3__', '__col-md-6__'];
break;
case 8:
ret = ['__col-md-4__', '__col-md-4__'];
break;
case 4:
ret = ['__col-md-4__'];
break;
case 6:
ret = ['__col-md-6__'];
break;
default:
ret = ['__col-md-3__'];
}
const random = Math.floor(Math.random() * 1000);
const random1 = Math.floor(Math.random() * 1000);
return ret.map((v, i) => {
if (i === 0) {
return `${v}${random}`;
}
return `${v}${random1}`;
});
}
/**
* Retrieve a field default bootstrap col
* NOTE: will change if we add the customisation of an input's width
* @param {String} type
* @returns {Number}
*/
getBootStrapCol(type) {
switch(type) {
case 'checkbox':
case 'boolean':
case 'date':
case 'decimal':
case 'float':
case 'integer':
case 'biginteger':
case 'number':
return 4;
case 'json':
case 'wysiwyg':
case 'WYSIWYG':
return 12;
default:
return 6;
}
}
getElementsOnALine(itemsToPull, arr = this.list) {
const array = List.isList(arr) ? arr.toJS() : arr;
return pullAt(array, itemsToPull);
}
/**
* Retrieve the field to remove infos
* @returns {Object}
*/
attrToRemoveInfos() {
return this.getAttrInfos(this.index);
}
/**
*
* Retrieve the last element of each bootstrap line
* @returns {Array}
*/
getLinesBound() { // NOTE: doesn't work for the last element if the line is not full!
const array = [];
let sum = 0;
this.list.forEach((item, i) => {
let { bootstrapCol, index, name, type } = this.getAttrInfos(i);
if (!type && name.includes('__col')) {
bootstrapCol = parseInt(name.split('__')[1].split('-')[2], 10);
}
sum += bootstrapCol;
if (sum === 12 || bootstrapCol === 12) {
const isFullSize = bootstrapCol === 12;
array.push({ name, index, isFullSize });
sum = 0;
}
if (sum > 12) {
sum = 0;
}
if (i < this.list.size - 1) {
let { bootstrapCol: nextBootstrapCol, name: nextName, type: nextType } = this.getAttrInfos(i + 1);
if (!nextType && nextName.includes('__col')) {
nextBootstrapCol = parseInt(nextName.split('__')[1].split('-')[2], 10);
}
if (sum + nextBootstrapCol > 12) {
const isFullSize = bootstrapCol === 12;
array.push({ name, index, isFullSize });
sum = 0;
}
}
});
return array;
}
/**
*
* Retrieve the field's type depending on its name
* @param {String} itemName
* @returns {String}
*/
getType(itemName) {
return this.state
.getIn(['schema', 'models', ...this.keys, 'availableFields', itemName, 'type']);
}
/**
* Retrieve a field name depending on its index
* @param {Number} itemIndex
* @returns {String}
*/
getAttrName(itemIndex){
return this.state
.getIn(['schema', 'models', ...this.keys, 'fields', itemIndex]);
}
/**
* Retrieve the line bootstrap col sum
* @param {Number} leftBound
* @param {Number} rightBound
* @returns {Number}
*/
getLineSize(elements) {
return elements.reduce((acc, current) => {
const appearance = this.layout.getIn([current, 'appearance']);
const type = appearance !== '' && appearance !== undefined ? appearance : this.getType(current);
const col = current.includes('__col') ? parseInt(current.split('__')[1].split('-')[2], 10) : this.getBootStrapCol(type);
return acc += col;
}, 0);
}
/**
*
* @param {Bool} dir sup or min
* @param {Number} pivot the center
* @returns {Object} the first sup or last sup
*/
getBound(dir, pivot = this.index) {
let result = {};
let hasResult = false;
this.arrayOfEndLineElements.forEach(item => {
const rightBondCond = findIndex(this.arrayOfEndLineElements, ['index', pivot]) !== -1 ? item.index < pivot : item.index <= pivot;
const cond = dir === true ? item.index >= pivot && !hasResult : rightBondCond;
if (cond) {
hasResult = true;
result = dir === true ? item : { name: this.list.get(item.index + 1), index: item.index + 1, isFullSize: false };
}
});
return result;
}
getLayout() {
let newList = this.list;
let sum = 0;
this.arrayOfEndLineElements.forEach((item, i) => {
const firstLineItem = i === 0 ? 0 : this.arrayOfEndLineElements[i - 1].index +1;
const lastLineItem = item.index + 1;
const lineRange = firstLineItem === lastLineItem ? [firstLineItem] : range(firstLineItem, lastLineItem);
const lineItems = this.getElementsOnALine(lineRange);
const lineSize = this.getLineSize(lineItems);
if (lineSize < 10 && i < this.arrayOfEndLineElements.length - 1) {
const colsToAdd = this.getColsToAdd(12 - lineSize);
newList = newList.insert(lastLineItem + sum, colsToAdd[0]);
if (colsToAdd.length > 1) {
newList = newList.insert(lastLineItem + sum, colsToAdd[1]);
}
sum += 1;
}
});
return newList;
}
}
module.exports = Manager;

View File

@ -1,66 +1,3 @@
const { List } = require('immutable');
const { flattenDeep, get, range } = require('lodash');
const Manager = require('./Manager');
const stateUpdater = (obj, array, keys) => obj.updateIn(['modifiedSchema', 'models', ...keys.split('.'), 'fields'], () => array);
const createManager = (obj, array, keys, dropIndex, layout) => new Manager(stateUpdater(obj, array, keys), array, keys, dropIndex, layout);
const getElementsOnALine = (manager, line, list) => {
const firstElIndex = line === 0 ? 0 : manager.arrayOfEndLineElements[line - 1].index + 1;
const lastElIndex = get(manager.arrayOfEndLineElements[line], 'index', list.size -1) + 1;
const elements = manager.getElementsOnALine(range(firstElIndex, lastElIndex));
return { elements, lastElIndex };
};
const createArrayOfLastEls = (manager, list) => {
const { name, index, bootstrapCol } = manager.getAttrInfos(list.size - 1);
const isFullSize = bootstrapCol === 12;
return manager.arrayOfEndLineElements.concat({ name, index, isFullSize });
};
const removeColsLine = (manager, list) => {
let addedElsToRemove = [];
const arrayOfEndLineElements = createArrayOfLastEls(manager, list);
arrayOfEndLineElements.forEach((item, i) => {
if (i < arrayOfEndLineElements.length) {
const firstElementOnLine = i === 0 ? 0 : arrayOfEndLineElements[i - 1].index + 1;
const lastElementOnLine = arrayOfEndLineElements[i].index;
const rangeIndex = range(firstElementOnLine, lastElementOnLine + 1);
const elementsOnLine = manager.getElementsOnALine(rangeIndex)
.filter(name => !name.includes('__col'));
if (elementsOnLine.length === 0) {
addedElsToRemove = addedElsToRemove.concat(rangeIndex);
}
}
});
return list.filter((item, index) => {
const indexToKeep = addedElsToRemove.indexOf(index) === -1;
return indexToKeep;
});
};
const reorderList = (manager, list) => {
const array = createArrayOfLastEls(manager, list);
const lines = [];
array.forEach((item, i) => {
const { elements } = getElementsOnALine(manager, i, list);
lines.push(elements);
});
const reordered = lines
.reduce((acc, curr) => {
const line = curr.sort((a) => a.includes('__col-md'));
return acc.concat(line);
}, [])
.filter(a => a !== undefined);
return List(flattenDeep(reordered));
};
const escapeNewlines = (content = '', placeholder = '\n') => {
return content.replace(/[\r\n]+/g, placeholder);
};
@ -71,25 +8,17 @@ const deepTrimObject = attribute => {
}
if (typeof attribute === 'object') {
return Object.entries(attribute)
.reduce((acc, [key, value]) => {
const trimmedObject = deepTrimObject(value);
return Object.entries(attribute).reduce((acc, [key, value]) => {
const trimmedObject = deepTrimObject(value);
return { ...acc, [key]: trimmedObject };
}, {});
return { ...acc, [key]: trimmedObject };
}, {});
}
return typeof attribute === 'string'
? attribute.trim()
: attribute;
}
return typeof attribute === 'string' ? attribute.trim() : attribute;
};
module.exports = {
createArrayOfLastEls,
createManager,
getElementsOnALine,
removeColsLine,
reorderList,
escapeNewlines,
deepTrimObject
deepTrimObject,
};

View File

@ -51,7 +51,6 @@ module.exports = function(strapi) {
throw new Error(`Group ${key} is missing a collectionName attribute`);
return Object.assign(group, {
schema: _.clone(group),
globalId: group.globalId || _.upperFirst(_.camelCase(`group_${key}`)),
});
});
@ -62,7 +61,6 @@ module.exports = function(strapi) {
let model = strapi.api[key].models[index];
Object.assign(model, {
schema: _.clone(model),
apiName: key,
globalId: model.globalId || _.upperFirst(_.camelCase(index)),
collectionName: model.collectionName || `${index}`.toLocaleLowerCase(),
@ -129,7 +127,6 @@ module.exports = function(strapi) {
let model = strapi.admin.models[key];
Object.assign(model, {
schema: _.clone(model),
identity: model.identity || _.upperFirst(key),
globalId: model.globalId || _.upperFirst(_.camelCase(`admin-${key}`)),
connection:
@ -158,7 +155,6 @@ module.exports = function(strapi) {
let model = plugin.models[key];
Object.assign(model, {
schema: _.clone(model),
collectionName:
model.collectionName || `${pluginName}_${key}`.toLowerCase(),
globalId: