From 15e43bd5f348e125046170cfff3ebd5f620c1065 Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Thu, 20 Jul 2017 18:58:28 +0200 Subject: [PATCH 01/32] Updating travis build and slack integration --- .travis.yml | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2d32db8..bbc9eb8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,16 +1,19 @@ sudo: false language: node_js node_js: -- '4.2' -before_deploy: 'npm run build' -deploy: - provider: npm - email: pierre.besson7+npm@gmail.com - api_key: - secure: dXLVThdNse9zbaGrmiXgNo2F+LAdvxHQsXgRnw0t/CcX3OGVDqLtCYB6WkhJcP0xWdxKxTLDhVZ6QGgwbnUSeluNO7Jzc5lkpfnWDuRvqWvO0KjAQ5qEoZm4Hk9ov8QK+3M1x3+mZE/gOr0pVWXB0P00POCG564lTFuyApi/IOU= - skip_cleanup: true - on: - branch: develop +- 6 +- node +branches: + only: + - v2.x.x + - master + - develop cache: directories: - - node_modules + - node_modules +notifications: + slack: + rooms: + secure: RQQcU2dSAzxPdYElQld3LJBZ3q83WFXrEab7BFVesWuwZCTwKiBN4v4RGDLarEUXetvmXcHUkbprIajDs/imk2ajbG8b1l4zU+4FLB8bd/+Xa3OVposUCh+P6PA3HoTa7LyLCpN0O7LcLkbyKRO3tjTpUtW05yn9IPJ9chykUNo= + on_success: change # default: always + on_failure: always # default: always From cece2c3a4e8d592fc99b52d542b8128d370178a3 Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Fri, 21 Jul 2017 10:09:45 +0200 Subject: [PATCH 02/32] Removing webpack build and dependencies --- package.json | 27 +-------------------------- 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/package.json b/package.json index e6d6683..647a673 100644 --- a/package.json +++ b/package.json @@ -40,24 +40,13 @@ }, "scripts": { "babelify": "better-npm-run babelify", - "bundle": "better-npm-run bundle", "test": "mocha src/**/__tests__/**/*.js", "test:watch": "mocha src/**/__tests__/**/*.js -w", - "build": "better-npm-run babelify && better-npm-run bundle" + "build": "better-npm-run babelify" }, "betterScripts": { "babelify": { "command": "node scripts/babelify.js" - }, - "bundle": { - "command": "webpack --progress", - "env": { - "DEV": false, - "NODE_ENV": "production", - "LIBRARY_NAME": "FocusCore", - "MINIMIFY": false, - "PACKAGE_JSON_PATH": "../" - } } }, "dependencies": { @@ -72,11 +61,9 @@ "uuid": "^2.0.1" }, "devDependencies": { - "babel": "^6.3.26", "babel-cli": "^6.4.0", "babel-core": "^6.4.0", "babel-eslint": "4.1.3", - "babel-loader": "^6.2.1", "babel-plugin-add-module-exports": "^0.1.2", "babel-plugin-runtime": "^1.0.7", "babel-plugin-transform-class-properties": "^6.4.0", @@ -90,30 +77,18 @@ "better-npm-run": "0.0.5", "chai": "^3.2.0", "chai-subset": "^1.1.0", - "css-loader": "^0.19.0", "eslint": "1.5.1", "eslint-config-focus": "0.3.0", "eslint-plugin-filenames": "0.1.1", "eslint-plugin-react": "3.5.0", "express": "^4.12.2", "extract-text-webpack-plugin": "^0.8.2", - "file-loader": "^0.8.4", "jquery": "^2.1.4", - "json-loader": "^0.5.3", "mocha": "^2.3.2", "moment": "^2.10.6", - "node-sass": "^3.3.3", "numeral": "^1.5.3", "react": "^15.2.1", "react-addons-test-utils": "^15.2.1", "react-dom": "^15.2.1", - "react-hot-loader": "^1.3.0", - "sass-loader": "^3.0.0", - "source-map-loader": "^0.1.5", - "style-loader": "^0.12.4", - "url-loader": "^0.5.6", - "webpack": "^1.12.2", - "webpack-dev-server": "^1.11.0", - "webpack-focus": "^0.11.0" } } From 9fdab49857f40b17c53b236758c47ec2e8fd3d73 Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Fri, 21 Jul 2017 10:18:24 +0200 Subject: [PATCH 03/32] Trailing comma --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 647a673..151be2f 100644 --- a/package.json +++ b/package.json @@ -89,6 +89,6 @@ "numeral": "^1.5.3", "react": "^15.2.1", "react-addons-test-utils": "^15.2.1", - "react-dom": "^15.2.1", + "react-dom": "^15.2.1" } } From ffeb631c4ec6b350d197d10f6de0cf8ddd87f4f0 Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Fri, 21 Jul 2017 11:59:54 +0200 Subject: [PATCH 04/32] Adding badges for dependencies status, correcting Travis badges --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2be4036..0125550 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,14 @@ [![Join the chat at https://gitter.im/KleeGroup/focus](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/KleeGroup/focus?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -![Build Status](https://travis-ci.org/KleeGroup/focus.svg) +[![master](https://travis-ci.org/KleeGroup/focus-core.svg?branch=master)](https://travis-ci.org/KleeGroup/focus-core) +[![develop](https://travis-ci.org/KleeGroup/focus-core.svg?branch=develop)](https://travis-ci.org/KleeGroup/focus-core) + + +[![Dependencies Status](https://david-dm.org/KleeGroup/focus-core.svg)](https://david-dm.org/KleeGroup/focus-core) +[![Dev Dependencies Status](https://david-dm.org/KleeGroup/focus-core/dev-status.svg)](https://david-dm.org/KleeGroup/focus-core?type=dev) +[![Peer Dependencies Status](https://david-dm.org/KleeGroup/focus-core/peer-status.svg)](https://david-dm.org/KleeGroup/focus-core?type=peer) + [![Package Quality](http://npm.packagequality.com/shield/focus-core.svg)](http://packagequality.com/#?package=focus-core) **Currently in dev** From c06e74dc29d824521170c007f5991a852f794b2c Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Fri, 21 Jul 2017 12:29:06 +0200 Subject: [PATCH 05/32] Correcting missing global in unit test --- test/mocha-bootload.js | 1 + 1 file changed, 1 insertion(+) diff --git a/test/mocha-bootload.js b/test/mocha-bootload.js index ca4ae6f..d2d11dc 100644 --- a/test/mocha-bootload.js +++ b/test/mocha-bootload.js @@ -19,6 +19,7 @@ const should = chai.should(); global.expect = require('chai').expect; /*eslint-enable */ +global.__DEV__ = process.env.DEV ? JSON.parse(process.env.DEV) : true; global.React = require('react'); global.ReactDOM = require('react-dom'); global.expect = chai.expect; From 9697a3699c0ba1b924e51ce8c01a005a86a9b314 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20BOULET=20KESSLER?= Date: Fri, 21 Jul 2017 16:48:58 +0200 Subject: [PATCH 06/32] Remove gitter badge --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 0125550..058814c 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,6 @@ [![NPM](https://nodei.co/npm/focus-core.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/focus-core/) -[![Join the chat at https://gitter.im/KleeGroup/focus](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/KleeGroup/focus?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - [![master](https://travis-ci.org/KleeGroup/focus-core.svg?branch=master)](https://travis-ci.org/KleeGroup/focus-core) [![develop](https://travis-ci.org/KleeGroup/focus-core.svg?branch=develop)](https://travis-ci.org/KleeGroup/focus-core) From 19589b5e3d7d4b35a274a17f7ce5911f529dc96b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20BOULETKESSLER?= Date: Tue, 4 Jul 2017 10:47:15 +0200 Subject: [PATCH 07/32] getNode returns value if empty array --- src/store/CoreStore.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/store/CoreStore.js b/src/store/CoreStore.js index 1df5ab4..188925e 100644 --- a/src/store/CoreStore.js +++ b/src/store/CoreStore.js @@ -156,7 +156,7 @@ class CoreStore extends EventEmitter { const rawData = currentStore.data.get(def); if(rawData && rawData.toJS){ const data = rawData.toJS(); - return isEmpty(data) ? undefined : data; + return data; } return rawData; } From e2fd1b0159e55b8d41950e7947c20c831a3ae80e Mon Sep 17 00:00:00 2001 From: Hartorn Date: Wed, 14 Jun 2017 13:35:45 +0200 Subject: [PATCH 08/32] Adding .gitattributes, for normalisation --- .gitattributes | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6456bda --- /dev/null +++ b/.gitattributes @@ -0,0 +1,29 @@ +# Handle line endings automatically for files detected as text +# and leave all files detected as binary untouched. +* text=auto + +# +# The above will handle all files NOT found below +# +# These files are text and should be normalized (Convert crlf => lf) +*.css text +*.js text +*.jsx text +*.json text +*.html text +*.scss text +*.txt text +*.xml text +*.yml text +*.md text +*.svg text + + +# These files are binary and should be left untouched +# (binary is a macro for -text -diff) +*.pdf binary +*.gif binary +*.ico binary +*.jpg binary +*.jpeg binary +*.png binary From c5c9d75dbf548df1a1dfeb45498f97f20dfca152 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Wed, 14 Jun 2017 13:36:44 +0200 Subject: [PATCH 09/32] Fixing advanced search store : now possible to have multiple stores, with different identifier (option) --- src/store/search/advanced-search/index.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/store/search/advanced-search/index.js b/src/store/search/advanced-search/index.js index 6e32e0e..e8c3fbd 100644 --- a/src/store/search/advanced-search/index.js +++ b/src/store/search/advanced-search/index.js @@ -7,7 +7,7 @@ const LISTENED_NODES = ['query', 'scope', 'selectedFacets', 'groupingKey', 'sort * The state should be the complete state of the page. */ class AdvancedSearchStore extends SearchStore { - constructor(conf){ + constructor(conf) { conf = conf || {}; conf.definition = { query: 'query', @@ -20,19 +20,20 @@ class AdvancedSearchStore extends SearchStore { results: 'results', totalCount: 'totalCount' }; - conf.identifier = 'ADVANCED_SEARCH'; + conf.identifier = conf.identifier || 'ADVANCED_SEARCH'; super(conf); } - emitPendingEvents(){ - if(this.pendingEvents.find(ev => LISTENED_NODES.includes(ev.name.split(':change')[0]))) { - this.emit('advanced-search-criterias:change', {status: 'update'}); + emitPendingEvents() { + if (this.pendingEvents.find(ev => LISTENED_NODES.includes(ev.name.split(':change')[0]))) { + this.emit('advanced-search-criterias:change', { status: 'update' }); } - this.pendingEvents.map((evtToEmit)=>{ - let {name, data} = evtToEmit; + this.pendingEvents.map((evtToEmit) => { + let { name, data } = evtToEmit; this.emit(name, data); }); } } -module.exports = AdvancedSearchStore; + +export default AdvancedSearchStore; From 306763204bfc1571a59d81125daeb07ea55f8f7f Mon Sep 17 00:00:00 2001 From: Hartorn Date: Wed, 14 Jun 2017 14:14:21 +0200 Subject: [PATCH 10/32] Correcting Reference Store --- src/store/reference/store.js | 44 ++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/src/store/reference/store.js b/src/store/reference/store.js index 43e1760..cfa859e 100644 --- a/src/store/reference/store.js +++ b/src/store/reference/store.js @@ -1,27 +1,37 @@ //Dependencies. -var CoreStore = require('../CoreStore'); -var buildDefinition = require('./definition'); +import CoreStore from '../CoreStore'; +import buildDefinition from './definition'; /** * Class standing for the reference store. */ class ReferenceStore extends CoreStore { + constructor(conf) { + conf = conf || {}; + conf.definition = conf.definition || buildDefinition(); + conf.identifier = conf.identifier || 'REFERENCE_LIST'; + super(newConf); + } - constructor(conf){ - conf = conf || {}; - conf.definition = conf.definition || buildDefinition(); - super(conf); - } - getReference(names){ - var refs = {}; - names.map((name)=>{ - if(this.data.has(name)){ - refs[name] = this.data.get(name); - } - }); - return {references: this.data.toJS()}; - } - setReference(){} + getReference(names) { + const refs = names.reduce((acc, name) => { + if (this.data.has(name)) { + acc[name] = this.data.get(name); + } + return acc; + }, {}); + return { references: this.refs }; + } + + getAllReference() { + return { references: this.data.toJS() }; + } + + getReferenceList(name) { + return this.data.get(name, []); + } + + setReference() { } } From d64b43821bfe1421d552fdb72c4bd5a60fed1b9b Mon Sep 17 00:00:00 2001 From: Hartorn Date: Wed, 14 Jun 2017 14:31:16 +0200 Subject: [PATCH 11/32] Fixing test unit config and import --- .../__tests__/action-builder-test.js | 60 +++++++++---------- .../validator/__tests__/number-test.js | 38 +++++------- src/util/object/__tests__/check-test.js | 18 +++--- test/mocha-bootload.js | 6 +- test/mocha.opts | 2 +- 5 files changed, 58 insertions(+), 66 deletions(-) diff --git a/src/application/__tests__/action-builder-test.js b/src/application/__tests__/action-builder-test.js index db4da53..f640dc7 100644 --- a/src/application/__tests__/action-builder-test.js +++ b/src/application/__tests__/action-builder-test.js @@ -1,42 +1,42 @@ /*global expect, it, describe*/ // __tests__/container-test.js - -const actionBuilder = require('../action-builder'); -describe('### action-builder', ()=>{ - it('Config must have a service', ()=>{ - expect(()=>actionBuilder({})) - .to.throw('You need to provide a service to call'); +import CoreStore from '../../store/CoreStore'; +import actionBuilder from '../action-builder'; +describe('### action-builder', () => { + it('Config must have a service', () => { + expect(() => actionBuilder({})) + .to.throw('You need to provide a service to call'); }); - it('Config must have a status', ()=>{ - expect(()=>actionBuilder({service: ()=>{}})) - .to.throw('You need to provide a status to your action'); + it('Config must have a status', () => { + expect(() => actionBuilder({ service: () => { } })) + .to.throw('You need to provide a status to your action'); }); - it('Config must have a node', ()=>{ - expect(()=>actionBuilder({service: ()=>{}, status: 'superStatus'})) - .to.throw('You shoud specify the store node name impacted by the action'); + it('Config must have a node', () => { + expect(() => actionBuilder({ service: () => { }, status: 'superStatus' })) + .to.throw('You shoud specify the store node name impacted by the action'); }); - it('builded action should be a function', ()=>{ - const action = actionBuilder({status: 'test', service: ()=>{}, node: 'test'}); + it('builded action should be a function', () => { + const action = actionBuilder({ status: 'test', service: () => { }, node: 'test' }); expect(action).to.be.a('function'); }); - it('Builded action call should result to a store update', (done)=>{ - const CoreStore = require('../../store/CoreStore'); + it('Builded action call should result to a store update', (done) => { const store = new CoreStore({ definition: { - name: 'name' - }}); + name: 'name' + } + }); //Creates a mock service. - const service = ()=>{ - return Promise.resolve({name: 'roberto'}); + const service = () => { + return Promise.resolve({ name: 'roberto' }); }; let nbCall = 0; - store.addNameChangeListener((e)=>{ + store.addNameChangeListener((e) => { expect('lopeez' === e.callerId); nbCall++; - if(2 === nbCall){ + if (2 === nbCall) { done(); } }); @@ -47,21 +47,21 @@ describe('### action-builder', ()=>{ callerId: 'lopez', node: 'name' }; - const action = actionBuilder(actionConf).bind({_identifier: 'champ'}); + const action = actionBuilder(actionConf).bind({ _identifier: 'champ' }); action(actionConf); }); - it('Error service shoud trigger a store error uodate', (done)=>{ - const CoreStore = require('../../store/CoreStore'); + it('Error service shoud trigger a store error uodate', (done) => { const store = new CoreStore({ definition: { - name: 'name' - }}); + name: 'name' + } + }); const lopezErrors = { lopezDavid: 'David is so powerfull...', lopezJoe: 'Jo is even more powerfull...' }; //Creates a mock service. - const service = () =>{ + const service = () => { const mockErrorResponse = { status: 422, responseJSON: { @@ -70,7 +70,7 @@ describe('### action-builder', ()=>{ }; return Promise.reject(mockErrorResponse); }; - store.addNameErrorListener(()=>{ + store.addNameErrorListener(() => { expect(store.getErrorName()).to.eql(lopezErrors); done(); }); @@ -81,7 +81,7 @@ describe('### action-builder', ()=>{ callerId: 'lopez', node: 'name' }; - const action = actionBuilder(actionConf).bind({_identifier: 'champ'}); + const action = actionBuilder(actionConf).bind({ _identifier: 'champ' }); action(actionConf); }); }); diff --git a/src/definition/validator/__tests__/number-test.js b/src/definition/validator/__tests__/number-test.js index 6a28a49..3e88576 100644 --- a/src/definition/validator/__tests__/number-test.js +++ b/src/definition/validator/__tests__/number-test.js @@ -1,42 +1,34 @@ /*global expect, describe, it*/ // __tests__/container-test.js +import numberValidation from '../number'; -describe('### validator number', ()=>{ - it('number should be valid', ()=>{ - const numberValidation = require('../number'); +describe('### validator number', () => { + it('number should be valid', () => { expect(numberValidation(1)).to.equal(true); }); - it('null should be valid', ()=>{ - const numberValidation = require('../number'); + it('null should be valid', () => { expect(numberValidation(null)).to.equal(true); }); - it('undefined should be valid', ()=>{ - const numberValidation = require('../number'); + it('undefined should be valid', () => { expect(numberValidation(undefined)).to.equal(true); }); - it('string should be invalid', ()=>{ - const numberValidation = require('../number'); + it('string should be invalid', () => { expect(numberValidation('ABCD')).to.equal(false); }); - it('string should be invalid', ()=>{ - const numberValidation = require('../number'); + it('string should be invalid', () => { expect(numberValidation('ABCD')).to.equal(false); }); - it('number min should be false when number inferior to min', ()=>{ - const numberValidation = require('../number'); - expect(numberValidation('6', {min: 7})).to.equal(false); + it('number min should be false when number inferior to min', () => { + expect(numberValidation('6', { min: 7 })).to.equal(false); }); - it('number min should be true when number superior to min', ()=>{ - const numberValidation = require('../number'); - expect(numberValidation('7', {min: 6})).to.equal(true); + it('number min should be true when number superior to min', () => { + expect(numberValidation('7', { min: 6 })).to.equal(true); }); - it('number max should be false when number superior to max', ()=>{ - const numberValidation = require('../number'); - expect(numberValidation('12', {max: 7})).to.equal(false); + it('number max should be false when number superior to max', () => { + expect(numberValidation('12', { max: 7 })).to.equal(false); }); - it('number max should be true when number inferior to max', ()=>{ - const numberValidation = require('../number'); - expect(numberValidation('7', {max: 7})).to.equal(true); + it('number max should be true when number inferior to max', () => { + expect(numberValidation('7', { max: 7 })).to.equal(true); }); }); diff --git a/src/util/object/__tests__/check-test.js b/src/util/object/__tests__/check-test.js index 73e3db2..e361fe9 100644 --- a/src/util/object/__tests__/check-test.js +++ b/src/util/object/__tests__/check-test.js @@ -1,19 +1,17 @@ /*global it, describe, expect*/ -const ArgumentInvalidException = require('../../../exception/argument-invalid-exception'); +import ArgumentInvalidException from '../../../exception/argument-invalid-exception'; +import checkObject from '../check'; -describe('### object validation', ()=>{ - it('An empty object should wokks', ()=>{ - const checkObject = require('../check'); +describe('### object validation', () => { + it('An empty object should wokks', () => { //console.log('checkObjet', checkObject); expect(checkObject('propertyName', {})).to.equal(undefined); }); - it('A string shoud be invalid', ()=>{ - const checkObject = require('../check'); - expect(()=>{checkObject('propertyName', 'aaaaa'); }).to.throw(ArgumentInvalidException, 'propertyName should be an object'); + it('A string shoud be invalid', () => { + expect(() => { checkObject('propertyName', 'aaaaa'); }).to.throw(ArgumentInvalidException, 'propertyName should be an object'); }); - it('A number shoud be invalid', ()=>{ - const checkObject = require('../check'); - expect(()=>{checkObject('propertyName', 123); }).to.throw(ArgumentInvalidException, 'propertyName should be an object'); + it('A number shoud be invalid', () => { + expect(() => { checkObject('propertyName', 123); }).to.throw(ArgumentInvalidException, 'propertyName should be an object'); }); }); diff --git a/test/mocha-bootload.js b/test/mocha-bootload.js index d2d11dc..8dc74a1 100644 --- a/test/mocha-bootload.js +++ b/test/mocha-bootload.js @@ -15,7 +15,7 @@ const chai = require('chai'); const chaiSubset = require('chai-subset'); chai.use(chaiSubset); /*eslint-disable */ -const should = chai.should(); +const should = chai.should(); global.expect = require('chai').expect; /*eslint-enable */ @@ -24,11 +24,13 @@ global.React = require('react'); global.ReactDOM = require('react-dom'); global.expect = chai.expect; global.TestUtils = require('react-addons-test-utils'); +global.__DEV__ = process.env.DEV ? JSON.parse(process.env.DEV) : true; + /*eslint-disable */ //let {shallowRenderer} = TestUtils; /*eslint-enable */ -process.on('unhandledRejection', (error)=>{ +process.on('unhandledRejection', (error) => { console.error('Unhandled Promise Rejection:'); console.error(error && error.stack || error); }); diff --git a/test/mocha.opts b/test/mocha.opts index 0b21c7e..65ed2d0 100644 --- a/test/mocha.opts +++ b/test/mocha.opts @@ -2,4 +2,4 @@ --require test/mocha-bootload --require chai --reporter spec ---ui bdd +--ui bdd \ No newline at end of file From 6126d45e34b6f2980ec1e52344ffbfcbc5b6a07d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20BOULETKESSLER?= Date: Thu, 15 Jun 2017 16:02:52 +0200 Subject: [PATCH 12/32] Fix renamed variable into reference/store.js constructor --- src/store/reference/store.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/store/reference/store.js b/src/store/reference/store.js index cfa859e..dad958d 100644 --- a/src/store/reference/store.js +++ b/src/store/reference/store.js @@ -10,7 +10,7 @@ class ReferenceStore extends CoreStore { conf = conf || {}; conf.definition = conf.definition || buildDefinition(); conf.identifier = conf.identifier || 'REFERENCE_LIST'; - super(newConf); + super(conf); } getReference(names) { From 8fcb628d5b58905f369a10a6f0713b52108e16e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20BOULETKESSLER?= Date: Thu, 15 Jun 2017 17:38:21 +0200 Subject: [PATCH 13/32] Add identifier property to the build action for reference updates --- src/reference/built-in-action.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/reference/built-in-action.js b/src/reference/built-in-action.js index c440f7c..2f21481 100644 --- a/src/reference/built-in-action.js +++ b/src/reference/built-in-action.js @@ -1,5 +1,5 @@ -var loadManyReferenceList = require('./builder').loadMany; -var dispatcher = require('../dispatcher'); +import { loadMany as loadManyReferenceList } from './builder'; +import dispatcher from '../dispatcher'; /** * Focus reference action. @@ -8,19 +8,19 @@ var dispatcher = require('../dispatcher'); */ function builtInReferenceAction(referenceNames, skipCache = false) { return () => { - if(!referenceNames) { + if (!referenceNames) { return undefined; } return Promise.all(loadManyReferenceList(referenceNames, skipCache)) - .then(function successReferenceLoading(data) { - //Rebuilt a constructed information from the map. - const reconstructedData = data.reduce((acc,item) => {acc[item.name] = item.dataList; return acc;}, {}) - dispatcher.handleViewAction({data: reconstructedData, type: 'update', subject: 'reference'}); - }, function errorReferenceLoading(err) { - dispatcher.handleViewAction({data: err, type: 'error'}); - }); + .then(function successReferenceLoading(data) { + //Rebuilt a constructed information from the map. + const reconstructedData = data.reduce((acc, item) => { acc[item.name] = item.dataList; return acc; }, {}) + // TODO : find a way to now the used identifier. + dispatcher.handleViewAction({ data: reconstructedData, type: 'update', subject: 'reference', identifier: 'REFERENCE_LIST' }); + }, function errorReferenceLoading(err) { + dispatcher.handleViewAction({ data: err, type: 'error', identifier: 'REFERENCE_LIST' }); + }); }; } - -module.exports = builtInReferenceAction; +export default builtInReferenceAction; From 9fe733b193a6abc8c68428d02fc101efe66470a2 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Fri, 16 Jun 2017 12:13:42 +0200 Subject: [PATCH 14/32] Removing Reference store identifier : Bad idea, dispatch and actions would not work anymore --- src/reference/built-in-action.js | 3 +-- src/store/reference/store.js | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/reference/built-in-action.js b/src/reference/built-in-action.js index 2f21481..1b529fe 100644 --- a/src/reference/built-in-action.js +++ b/src/reference/built-in-action.js @@ -15,8 +15,7 @@ function builtInReferenceAction(referenceNames, skipCache = false) { .then(function successReferenceLoading(data) { //Rebuilt a constructed information from the map. const reconstructedData = data.reduce((acc, item) => { acc[item.name] = item.dataList; return acc; }, {}) - // TODO : find a way to now the used identifier. - dispatcher.handleViewAction({ data: reconstructedData, type: 'update', subject: 'reference', identifier: 'REFERENCE_LIST' }); + dispatcher.handleViewAction({ data: reconstructedData, type: 'update', subject: 'reference' }); }, function errorReferenceLoading(err) { dispatcher.handleViewAction({ data: err, type: 'error', identifier: 'REFERENCE_LIST' }); }); diff --git a/src/store/reference/store.js b/src/store/reference/store.js index dad958d..c504f6b 100644 --- a/src/store/reference/store.js +++ b/src/store/reference/store.js @@ -9,7 +9,6 @@ class ReferenceStore extends CoreStore { constructor(conf) { conf = conf || {}; conf.definition = conf.definition || buildDefinition(); - conf.identifier = conf.identifier || 'REFERENCE_LIST'; super(conf); } From a5cb274ead6b7d94e2ea3f335ea51ce8614bd090 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Tue, 25 Jul 2017 14:17:14 +0200 Subject: [PATCH 15/32] Removing identifier --- src/reference/built-in-action.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/reference/built-in-action.js b/src/reference/built-in-action.js index 1b529fe..3720b72 100644 --- a/src/reference/built-in-action.js +++ b/src/reference/built-in-action.js @@ -17,7 +17,7 @@ function builtInReferenceAction(referenceNames, skipCache = false) { const reconstructedData = data.reduce((acc, item) => { acc[item.name] = item.dataList; return acc; }, {}) dispatcher.handleViewAction({ data: reconstructedData, type: 'update', subject: 'reference' }); }, function errorReferenceLoading(err) { - dispatcher.handleViewAction({ data: err, type: 'error', identifier: 'REFERENCE_LIST' }); + dispatcher.handleViewAction({ data: err, type: 'error' }); }); }; } From 8d136cbf810483873b943c7767e9c606b30ec19c Mon Sep 17 00:00:00 2001 From: Hartorn Date: Tue, 25 Jul 2017 14:19:30 +0200 Subject: [PATCH 16/32] Correcting wrong this --- src/store/reference/store.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/store/reference/store.js b/src/store/reference/store.js index c504f6b..d10d2c3 100644 --- a/src/store/reference/store.js +++ b/src/store/reference/store.js @@ -19,7 +19,7 @@ class ReferenceStore extends CoreStore { } return acc; }, {}); - return { references: this.refs }; + return { references: refs }; } getAllReference() { @@ -34,4 +34,4 @@ class ReferenceStore extends CoreStore { } -module.exports = ReferenceStore; +export default ReferenceStore; From 4cbd71b8e021fcf95e3b2b8eac9a7b9da062b55f Mon Sep 17 00:00:00 2001 From: Hartorn Date: Tue, 25 Jul 2017 15:56:59 +0200 Subject: [PATCH 17/32] CoreStore - Preventing silent name collisions --- src/store/CoreStore.js | 145 ++++++++++++++++++++++------------------- 1 file changed, 77 insertions(+), 68 deletions(-) diff --git a/src/store/CoreStore.js b/src/store/CoreStore.js index 188925e..ddc4c74 100644 --- a/src/store/CoreStore.js +++ b/src/store/CoreStore.js @@ -1,11 +1,14 @@ -//The store is an event emitter. -const EventEmitter = require('events').EventEmitter; -const assign = require('object-assign'); -const {isArray, isEmpty, isObject, isFunction} = require('lodash/lang'); -const {defer} = require('lodash/function'); -const capitalize = require('lodash/string/capitalize'); -const Immutable = require('immutable'); -const AppDispatcher = require('../dispatcher'); +import { EventEmitter } from 'events'; +import assign from 'object-assign'; +import { isArray, isEmpty, isObject, isFunction } from 'lodash/lang'; +import { defer } from 'lodash/function'; +import intersection from 'lodash/array/intersection'; +import capitalize from 'lodash/string/capitalize'; +import Immutable from 'immutable'; +import AppDispatcher from '../dispatcher'; + +const reservedNames = ["Error", "Status"]; + const _instances = []; /** @@ -31,16 +34,16 @@ class CoreStore extends EventEmitter { this.buildDefinition(); this.buildEachNodeChangeEventListener(); this.registerDispatcher(); - if(!!__DEV__){ - this._registerDevTools(); + if (!!__DEV__) { + this._registerDevTools(); } } // Get all the instances of core store. - get _instances(){ - return [..._instances]; + get _instances() { + return [..._instances]; } // register the instances saving - _registerDevTools(){ + _registerDevTools() { _instances.push(this); } /** @@ -52,32 +55,38 @@ class CoreStore extends EventEmitter { * Build the definitions for the entity (may be a subject.) * @type {object} */ - if(!this.config.definition){ + if (!this.config.definition) { throw new Error('Core Store: missing definition', this.config); } this.definition = this.config.definition; + + const properties = Object.keys(this.definition).map(elt => capitalize(elt)); + const reservedProperties = properties.reduce((acc, elt) => acc.concat(reservedNames.map(w => w + elt)), []); + if (intersection(properties, reservedProperties).length > 0) { + throw new Error(`You have a name collision into this store : you cannot use a node named Blabla and anoter named ErrorBlabla, or StatusBlabla : ${intersection(properties, reservedProperties).join(' ')} `); + } return this.definition; } /** * Get the whole value of the * @return {[type]} [description] */ - getValue(){ + getValue() { return this.data ? this.data.toJS() : {}; } /** * Getter on the identifier property. * @return {string} - Store identifier. */ - get identifier(){ + get identifier() { return this.config && this.config.identifier ? this.config.identifier : undefined; } /** Return the status of a definition. * @param {string} - The definition to load. * @returns {string} - The status of a definition. */ - getStatus(def){ - if (this.status.has(def)){ + getStatus(def) { + if (this.status.has(def)) { return this.status.get(def); } return undefined; @@ -85,9 +94,9 @@ class CoreStore extends EventEmitter { /** * Emit all events pending in the pendingEvents map. */ - emitPendingEvents(){ - this.pendingEvents.map((evtToEmit)=>{ - let {name, data} = evtToEmit; + emitPendingEvents() { + this.pendingEvents.map((evtToEmit) => { + let { name, data } = evtToEmit; this.emit(name, data); }); } @@ -97,19 +106,19 @@ class CoreStore extends EventEmitter { * @param eventName {string} - The event name. * @param data {object} - The event's associated data. */ - willEmit(eventName, data){ - this.pendingEvents = this.pendingEvents.reduce((result, current)=>{ - if(current.name !== eventName){ + willEmit(eventName, data) { + this.pendingEvents = this.pendingEvents.reduce((result, current) => { + if (current.name !== eventName) { result.push(current); } return result; - }, [{name: eventName, data: data}]); + }, [{ name: eventName, data: data }]); } /** * Clear all pending events. */ - clearPendingEvents(){ + clearPendingEvents() { this.pendingEvents = []; } /** @@ -121,74 +130,74 @@ class CoreStore extends EventEmitter { for (let definition in this.definition) { const capitalizeDefinition = capitalize(definition); //Creates the change listener - currentStore[`add${capitalizeDefinition}ChangeListener`] = function(def){ + currentStore[`add${capitalizeDefinition}ChangeListener`] = function (def) { return function (cb) { currentStore.addListener(`${def}:change`, cb); } }(definition); //Remove the change listener - currentStore[`remove${capitalizeDefinition}ChangeListener`] = function(def){ + currentStore[`remove${capitalizeDefinition}ChangeListener`] = function (def) { return function (cb) { currentStore.removeListener(`${def}:change`, cb); } }(definition); //Create an update method. //Should be named updateData to be more explicit - if(currentStore[`update${capitalizeDefinition}`] === undefined){ - currentStore[`update${capitalizeDefinition}`] = function(def){ + if (currentStore[`update${capitalizeDefinition}`] === undefined) { + currentStore[`update${capitalizeDefinition}`] = function (def) { return function (dataNode, status, informations) { const immutableNode = isFunction(dataNode) ? dataNode : Immutable.fromJS(dataNode); currentStore.data = currentStore.data.set(def, immutableNode); //Update the status on the data. currentStore.status = currentStore.status.set(def, status); - currentStore.willEmit(`${def}:change`, {property: def, status: status, informations: informations}); + currentStore.willEmit(`${def}:change`, { property: def, status: status, informations: informations }); } }(definition); } //Create a get method. - if(currentStore[`get${capitalizeDefinition}`] === undefined){ - currentStore[`get${capitalizeDefinition}`] = function(def){ + if (currentStore[`get${capitalizeDefinition}`] === undefined) { + currentStore[`get${capitalizeDefinition}`] = function (def) { return function () { const hasData = currentStore.data.has(def); - if(hasData){ + if (hasData) { const rawData = currentStore.data.get(def); - if(rawData && rawData.toJS){ - const data = rawData.toJS(); - return data; - } - return rawData; + if (rawData && rawData.toJS) { + const data = rawData.toJS(); + return data; + } + return rawData; } return undefined; }; }(definition); } //Creates the error change listener - currentStore[`add${capitalizeDefinition}ErrorListener`] = function(def){ + currentStore[`add${capitalizeDefinition}ErrorListener`] = function (def) { return function (cb) { currentStore.addListener(`${def}:error`, cb); } }(definition); //Remove the change listener - currentStore[`remove${capitalizeDefinition}ErrorListener`] = function(def){ + currentStore[`remove${capitalizeDefinition}ErrorListener`] = function (def) { return function (cb) { currentStore.removeListener(`${def}:error`, cb); } }(definition); //Create an update method. - currentStore[`updateError${capitalizeDefinition}`] = function(def){ + currentStore[`updateError${capitalizeDefinition}`] = function (def) { return function (dataNode, status, informations) { //CheckIsObject const immutableNode = Immutable[isArray(dataNode) ? "List" : "Map"](dataNode); currentStore.error = currentStore.error.set(def, immutableNode); currentStore.status = currentStore.status.set(def, status); - currentStore.willEmit(`${def}:error`, {property: def, status: status, informations: informations}); + currentStore.willEmit(`${def}:error`, { property: def, status: status, informations: informations }); } }(definition); //Create a get method. - currentStore[`getError${capitalizeDefinition}`] = function(def){ - return function(){ + currentStore[`getError${capitalizeDefinition}`] = function (def) { + return function () { const hasData = currentStore.error.has(def); return hasData ? currentStore.error.get(def).toJS() : undefined; }; @@ -196,30 +205,30 @@ class CoreStore extends EventEmitter { // status - currentStore[`add${capitalizeDefinition}StatusListener`] = function(def){ + currentStore[`add${capitalizeDefinition}StatusListener`] = function (def) { return function (cb) { currentStore.addListener(`${def}:status`, cb); } }(definition); //Remove the change listener - currentStore[`remove${capitalizeDefinition}StatusListener`] = function(def){ + currentStore[`remove${capitalizeDefinition}StatusListener`] = function (def) { return function (cb) { currentStore.removeListener(`${def}:status`, cb); } }(definition); //Create an update method. - currentStore[`updateStatus${capitalizeDefinition}`] = function(def){ + currentStore[`updateStatus${capitalizeDefinition}`] = function (def) { return function updateStatus(dataNode, status, informations) { //CheckIsObject - //console.log(`status ${JSON.stringify(status)}`); + //console.log(`status ${JSON.stringify(status) }`); const statusNode = status;//Immutable.fromJS(status); // mMaybe it is a part of the status only. currentStore.status = currentStore.status.set(def, statusNode); - currentStore.willEmit(`${def}:status`, {property: def, status: status, informations: informations}); + currentStore.willEmit(`${def}:status`, { property: def, status: status, informations: informations }); } }(definition); //Create a get method. - currentStore[`getStatus${capitalizeDefinition}`] = function(def){ - return function getStatus(){ + currentStore[`getStatus${capitalizeDefinition}`] = function (def) { + return function getStatus() { const hasData = currentStore.status.has(def); const data = hasData ? currentStore.status.get(def) : undefined; return data.toJS ? data.toJS() : data; @@ -228,14 +237,14 @@ class CoreStore extends EventEmitter { } } - delayPendingEvents(context){ + delayPendingEvents(context) { //Delay all the change emit by the store to be sure it is done after the internal store propagation and to go out of the dispatch function. - defer(()=>{ + defer(() => { context.emitPendingEvents(); context.clearPendingEvents(); }); } - _buildInformations(incomingInfos){ + _buildInformations(incomingInfos) { return { callerId: incomingInfos.action.callerId }; @@ -243,18 +252,18 @@ class CoreStore extends EventEmitter { /** * The store registrer itself on the dispatcher. */ - registerDispatcher(){ + registerDispatcher() { const currentStore = this; - this.dispatch = AppDispatcher.register(function(transferInfo) { + this.dispatch = AppDispatcher.register(function (transferInfo) { //Check if an identifier check is necessary. - if(currentStore.identifier){ + if (currentStore.identifier) { //If an identifier is needed a check is triggered. - if(!transferInfo || !transferInfo.action || !transferInfo.action.identifier || transferInfo.action.identifier !== currentStore.identifier){ + if (!transferInfo || !transferInfo.action || !transferInfo.action.identifier || transferInfo.action.identifier !== currentStore.identifier) { return; } } //currentStore.clearPendingEvents(); - if(currentStore.globalCustomHandler){ + if (currentStore.globalCustomHandler) { return currentStore.globalCustomHandler.call(currentStore, transferInfo); } @@ -265,17 +274,17 @@ class CoreStore extends EventEmitter { const otherInformations = currentStore._buildInformations(transferInfo); //Call each node handler for the matching definition's node. - for(let node in rawData){ - if(currentStore.definition[node]){ + for (let node in rawData) { + if (currentStore.definition[node]) { //Call a custom handler if this exists. - if(currentStore.customHandler && currentStore.customHandler[node] && currentStore.customHandler[node][type]){ + if (currentStore.customHandler && currentStore.customHandler[node] && currentStore.customHandler[node][type]) { currentStore.customHandler[node][type].call(currentStore, rawData[node], status[node], otherInformations); - }else { + } else { //Update the data for the given node. and emit the change/. - if(!isFunction(currentStore[`${type}${capitalize(node)}`])){ - throw new Error(`The listener you try to call is unavailable : ${type}${capitalize(node)}` ); + if (!isFunction(currentStore[`${type}${capitalize(node)}`])) { + throw new Error(`The listener you try to call is unavailable : ${type} ${capitalize(node)} `); } - currentStore[`${type}${capitalize(node)}`](rawData[node], status[node], otherInformations); + currentStore[`${type} ${capitalize(node)} `](rawData[node], status[node], otherInformations); } } } @@ -291,4 +300,4 @@ class CoreStore extends EventEmitter { this.on(eventName, cb); } } -module.exports = CoreStore; +export default CoreStore; From 64fd79c0eba35f458630fb530184b2dd0173df24 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Tue, 25 Jul 2017 17:36:10 +0200 Subject: [PATCH 18/32] Fixing nbSearchElement in nbElement + Code Style + formatting --- src/list/action-builder.js | 100 +++++++++++++++++----------------- src/list/load-action/index.js | 26 ++++----- 2 files changed, 63 insertions(+), 63 deletions(-) diff --git a/src/list/action-builder.js b/src/list/action-builder.js index 058855b..98a7c95 100644 --- a/src/list/action-builder.js +++ b/src/list/action-builder.js @@ -1,54 +1,54 @@ -let dispatcher = require('../dispatcher'); -let loadAction = require('./load-action'); +import dispatcher from '../dispatcher'; +import loadAction from './load-action'; const NB_LIST_ELEMENT = 50; - /** - * Builded search action. - * @param {object} options - The options used to build the service, it should have the following structure: - * ```javascript - * { - * identifier: string: should be 'ADVANCED_SEARCH' or 'QUICK_SEARCH' - * service:{ - * scoped: "function which launch the scope search" - * unScoped: "function whoch launch the unscoped search" - * } - * getSearchOptions a function which get the associated search store value - * nbSearchElement: number of elements to request on each search. - * } - * ``` - * @return {function} - The builded search action. - */ -module.exports = function(config){ - config = config || {}; - if(!config.identifier){ - console.warn('Your action should have an identifier'); - } - if(!config.service){ - console.warn('Your action should have a service'); - } - if(!config.getListOptions){ - console.warn('Your action should have a search options getter.'); - } - if(!config.nbSearchElement){ - config.nbElement = NB_LIST_ELEMENT; - } - return { - /** - * Build the search for the identifier scope. - * @return {function} The search function for the given identifier. - */ - load: loadAction(config), - /** - * Update the query for the identifier scope. - * @param {string} value - The query value - * @return {function} The update query function for the given identifier. - */ - updateProperties(value){ - return dispatcher.handleViewAction({ - data: value, - type: 'update', - identifier: config.identifier - }); +/** + * Builded search action. + * @param {object} options - The options used to build the service, it should have the following structure: + * ```javascript + * { + * identifier: string: should be 'ADVANCED_SEARCH' or 'QUICK_SEARCH' + * service:{ + * scoped: "function which launch the scope search" + * unScoped: "function whoch launch the unscoped search" + * } + * getSearchOptions a function which get the associated search store value + * nbElement: number of elements to request on each search. + * } + * ``` + * @return {function} - The builded search action. + */ +export default function (config) { + config = config || {}; + if (!config.identifier) { + console.warn('Your action should have an identifier'); } - }; + if (!config.service) { + console.warn('Your action should have a service'); + } + if (!config.getListOptions) { + console.warn('Your action should have a search options getter.'); + } + if (!config.nbElement) { + config.nbElement = NB_LIST_ELEMENT; + } + return { + /** + * Build the search for the identifier scope. + * @return {function} The search function for the given identifier. + */ + load: loadAction(config), + /** + * Update the query for the identifier scope. + * @param {string} value - The query value + * @return {function} The update query function for the given identifier. + */ + updateProperties(value) { + return dispatcher.handleViewAction({ + data: value, + type: 'update', + identifier: config.identifier + }); + } + }; }; diff --git a/src/list/load-action/index.js b/src/list/load-action/index.js index dbbbcca..7df7782 100644 --- a/src/list/load-action/index.js +++ b/src/list/load-action/index.js @@ -3,7 +3,7 @@ import assign from 'object-assign'; import _builder from './builder'; import _parser from './parser'; import dispatcher from '../../dispatcher'; -import {manageResponseErrors} from '../../network/error-parsing'; +import { manageResponseErrors } from '../../network/error-parsing'; /** @@ -11,7 +11,7 @@ import {manageResponseErrors} from '../../network/error-parsing'; * @param {object} config - Action configuration. * @return {function} - The generated action from the congig. */ -module.exports = function loadActionFn(config){ +export default function loadActionFn(config) { /** * Dispatch the results on the search store * @param {object} data - The data to dispatch. @@ -29,7 +29,7 @@ module.exports = function loadActionFn(config){ * @param {object} err - The error from the API call. * @return {object} - The data from the manageResponseErrors function. */ - function _errorOnCall( err){ + function _errorOnCall(err) { manageResponseErrors(err, config); //_dispatchGlobalError shoud be separated. } @@ -38,7 +38,7 @@ module.exports = function loadActionFn(config){ * Build search action. * @param {Boolean} isScroll - Is the action result from a scrolling. */ - return function listLoader(isScroll){ + return function listLoader(isScroll) { //Read search options from the accessor define in the config. // TODO: see if results should be named results. const { @@ -53,22 +53,22 @@ module.exports = function loadActionFn(config){ //Build URL data. const urlData = assign( - _builder.pagination({dataList, totalCount, isScroll, nbElement}), - _builder.orderAndSort({sortBy, sortAsc}) + _builder.pagination({ dataList, totalCount, isScroll, nbElement }), + _builder.orderAndSort({ sortBy, sortAsc }) ); //Build body data. const postData = { criteria: criteria, group: groupingKey || '' }; - config.service({urlData: urlData, data: postData}) - .then((response)=>{ - return _parser( + config.service({ urlData: urlData, data: postData }) + .then((response) => { + return _parser( response, - {isScroll, dataList} + { isScroll, dataList } ); - }) - .then(_dispatchResult) - .catch(_errorOnCall); + }) + .then(_dispatchResult) + .catch(_errorOnCall); }; }; From 6903159490021bfdabf97b556b7c672ec0146451 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Tue, 25 Jul 2017 16:04:53 +0200 Subject: [PATCH 19/32] Test - Fixing dependencies and bootload --- package.json | 39 ++++----------------------------------- test/mocha-bootload.js | 8 +------- 2 files changed, 5 insertions(+), 42 deletions(-) diff --git a/package.json b/package.json index 151be2f..29f239b 100644 --- a/package.json +++ b/package.json @@ -5,21 +5,7 @@ "main": "index.js", "babel": { "presets": [ - "stage-0", - "react", - "es2015" - ], - "plugins": [ - "transform-class-properties", - "transform-decorators-legacy", - "add-module-exports", - "transform-proto-to-assign", - [ - "transform-es2015-classes", - { - "loose": true - } - ] + "focus" ] }, "repository": { @@ -61,28 +47,11 @@ "uuid": "^2.0.1" }, "devDependencies": { - "babel-cli": "^6.4.0", - "babel-core": "^6.4.0", - "babel-eslint": "4.1.3", - "babel-plugin-add-module-exports": "^0.1.2", - "babel-plugin-runtime": "^1.0.7", - "babel-plugin-transform-class-properties": "^6.4.0", - "babel-plugin-transform-decorators-legacy": "^1.3.4", - "babel-plugin-transform-es2015-classes": "^6.5.2", - "babel-plugin-transform-proto-to-assign": "^6.5.0", - "babel-preset-es2015": "^6.3.13", - "babel-preset-react": "^6.3.13", - "babel-preset-stage-0": "^6.3.13", - "babel-runtime": "^6.3.19", - "better-npm-run": "0.0.5", + "babel-preset-focus": "0.7.0", + "better-npm-run": "0.0.15", "chai": "^3.2.0", "chai-subset": "^1.1.0", - "eslint": "1.5.1", "eslint-config-focus": "0.3.0", - "eslint-plugin-filenames": "0.1.1", - "eslint-plugin-react": "3.5.0", - "express": "^4.12.2", - "extract-text-webpack-plugin": "^0.8.2", "jquery": "^2.1.4", "mocha": "^2.3.2", "moment": "^2.10.6", @@ -91,4 +60,4 @@ "react-addons-test-utils": "^15.2.1", "react-dom": "^15.2.1" } -} +} \ No newline at end of file diff --git a/test/mocha-bootload.js b/test/mocha-bootload.js index 8dc74a1..167f807 100644 --- a/test/mocha-bootload.js +++ b/test/mocha-bootload.js @@ -1,13 +1,7 @@ //Global configuration uese for tests. require('babel-core/register')({ presets: [ - 'stage-0', - 'react', - 'es2015' - ], - plugins: [ - 'transform-class-properties', - 'transform-decorators-legacy' + 'focus' ] }); From f2ad454f838eb3258ca10fc5809c10dd9824d5ad Mon Sep 17 00:00:00 2001 From: Hartorn Date: Tue, 25 Jul 2017 17:12:46 +0200 Subject: [PATCH 20/32] Fixing error handling on multi node Fixing unit testing Formatting and code style --- .../__tests__/action-builder-test.js | 15 ++- src/application/built-in-store.js | 4 +- src/application/clear.js | 8 +- src/application/index.js | 52 ++++----- src/application/mounted-components.js | 2 +- src/dispatcher/index.js | 6 +- src/exception/argument-invalid-exception.js | 10 +- src/network/__tests__/error-parser-test.js | 38 ++++--- .../__tests__/fixture/entity-error-fixture.js | 4 +- src/network/error-parsing.js | 100 +++++++++++------- src/store/__tests__/CoreStore-test.js | 87 +++++++-------- src/util/object/__tests__/check-test.js | 4 +- src/util/object/check.js | 14 +-- tsconfig.json | 9 -- webpack.config.js | 12 --- 15 files changed, 192 insertions(+), 173 deletions(-) delete mode 100644 tsconfig.json delete mode 100644 webpack.config.js diff --git a/src/application/__tests__/action-builder-test.js b/src/application/__tests__/action-builder-test.js index f640dc7..e9bfa1d 100644 --- a/src/application/__tests__/action-builder-test.js +++ b/src/application/__tests__/action-builder-test.js @@ -1,7 +1,14 @@ /*global expect, it, describe*/ // __tests__/container-test.js -import CoreStore from '../../store/CoreStore'; + import actionBuilder from '../action-builder'; +import CoreStore from '../../store/CoreStore'; +import { init } from '../../translation'; +init({ + resStore: {}, + lng: 'fr-FR' +}); // Initialise i18n + describe('### action-builder', () => { it('Config must have a service', () => { expect(() => actionBuilder({})) @@ -16,7 +23,7 @@ describe('### action-builder', () => { expect(() => actionBuilder({ service: () => { }, status: 'superStatus' })) .to.throw('You shoud specify the store node name impacted by the action'); }); - it('builded action should be a function', () => { + it('Builded action should be a function', () => { const action = actionBuilder({ status: 'test', service: () => { }, node: 'test' }); expect(action).to.be.a('function'); }); @@ -36,7 +43,7 @@ describe('### action-builder', () => { store.addNameChangeListener((e) => { expect('lopeez' === e.callerId); nbCall++; - if (2 === nbCall) { + if (1 === nbCall) { done(); } }); @@ -50,7 +57,7 @@ describe('### action-builder', () => { const action = actionBuilder(actionConf).bind({ _identifier: 'champ' }); action(actionConf); }); - it('Error service shoud trigger a store error uodate', (done) => { + it('Error service should trigger a store error update', (done) => { const store = new CoreStore({ definition: { name: 'name' diff --git a/src/application/built-in-store.js b/src/application/built-in-store.js index 652b6b3..b8d94ec 100644 --- a/src/application/built-in-store.js +++ b/src/application/built-in-store.js @@ -1,7 +1,7 @@ -const ApplicationStore = require('../store/application'); +import ApplicationStore from '../store/application'; /** * Built the store in order to the . * @return {ApplicationStore} - An instanciated application store. */ -module.exports = new ApplicationStore(); +export default new ApplicationStore(); diff --git a/src/application/clear.js b/src/application/clear.js index fc3b458..98261b6 100644 --- a/src/application/clear.js +++ b/src/application/clear.js @@ -1,12 +1,12 @@ -const ReactDOM = require('react-dom'); -let mountedComponents = require('./mounted-components'); +import ReactDOM from 'react-dom'; +import mountedComponents from './mounted-components'; /** * Clear a react component. * @param {String} targetSelector - the component's DOM selector */ -module.exports = function clearComponent(targetSelector) { - if(mountedComponents[targetSelector]){ +export default function clearComponent(targetSelector) { + if (mountedComponents[targetSelector]) { ReactDOM.unmountComponentAtNode(document.querySelector(targetSelector)); delete mountedComponents[targetSelector]; console.info('Component ' + targetSelector + ' unmounted.'); diff --git a/src/application/index.js b/src/application/index.js index e6db9c9..54ea827 100644 --- a/src/application/index.js +++ b/src/application/index.js @@ -1,6 +1,6 @@ -const React = require('react'); -const dispatcher = require('../dispatcher'); -import {isUndefined} from 'lodash/lang'; +import React from 'react'; +import dispatcher from '../dispatcher'; +import { isUndefined } from 'lodash/lang'; import confirm from './confirm'; //Empty compoennt. const Empty = props =>
; @@ -17,16 +17,16 @@ module.exports = { * @param {string} newMode - New application mode. * @param {string} previousMode - Previous mode. */ - changeMode(newMode, previousMode){ - const mode = {newMode: newMode, previousMode: previousMode}; - dispatcher.handleViewAction({data: {mode: mode}, type: 'update'}); + changeMode(newMode, previousMode) { + const mode = { newMode: newMode, previousMode: previousMode }; + dispatcher.handleViewAction({ data: { mode: mode }, type: 'update' }); }, /** * Change application route (maybe not the wole route but a route's group.) * @param {string} newRoute - new route name. */ - changeRoute(newRoute){ - dispatcher.handleViewAction({data: {route: newRoute}, type: 'update'}); + changeRoute(newRoute) { + dispatcher.handleViewAction({ data: { route: newRoute }, type: 'update' }); }, /** * Set component to application's header. @@ -38,12 +38,12 @@ module.exports = { * @param {ReactComponent} barRight component injected in the right bar * @param {ReactComponent} EmptyComponent Empty component */ - setHeader({cartridge, summary, actions, barLeft, canDeploy, barRight, EmptyComponent = Empty}) { + setHeader({ cartridge, summary, actions, barLeft, canDeploy, barRight, EmptyComponent = Empty }) { const data = { - cartridgeComponent: cartridge || {component: EmptyComponent}, - summaryComponent: summary || {component: EmptyComponent}, - actions: actions || {primary: [], secondary: []}, - barContentLeftComponent: barLeft || {component: EmptyComponent}, + cartridgeComponent: cartridge || { component: EmptyComponent }, + summaryComponent: summary || { component: EmptyComponent }, + actions: actions || { primary: [], secondary: [] }, + barContentLeftComponent: barLeft || { component: EmptyComponent }, canDeploy: isUndefined(canDeploy) ? true : canDeploy }; @@ -51,7 +51,7 @@ module.exports = { data.barContentRightComponent = barRight; } - dispatcher.handleViewAction({data, type: 'update'}); + dispatcher.handleViewAction({ data, type: 'update' }); }, /** * Set component to application's header with only the component gived in parameter. @@ -63,40 +63,40 @@ module.exports = { * @param {ReactComponent} barRight component injected in the right bar * @param {ReactComponent} EmptyComponent Empty component */ - setPartialHeader({cartridge, summary, actions, barLeft, barRight, canDeploy}) { + setPartialHeader({ cartridge, summary, actions, barLeft, barRight, canDeploy }) { const data = { canDeploy: isUndefined(canDeploy) ? true : canDeploy }; - if(cartridge) { + if (cartridge) { data.cartridgeComponent = cartridge; } - if(summary) { + if (summary) { data.summaryComponent = summary; } - if(actions) { + if (actions) { data.actions = actions; } - if(barLeft) { + if (barLeft) { data.barContentLeftComponent = barLeft; } - if(barRight) { + if (barRight) { data.barContentRightComponent = barRight; } - dispatcher.handleViewAction({data, type: 'update'}); + dispatcher.handleViewAction({ data, type: 'update' }); }, /** * Clear the application's header. * @return {[type]} [description] */ - clearHeader(){ + clearHeader() { dispatcher.handleViewAction({ data: { - cartridgeComponent: {component: Empty}, - barContentLeftComponent: {component: Empty}, - summaryComponent: {component: Empty}, - actions: {primary: [], secondary: []} + cartridgeComponent: { component: Empty }, + barContentLeftComponent: { component: Empty }, + summaryComponent: { component: Empty }, + actions: { primary: [], secondary: [] } }, type: 'update' }); diff --git a/src/application/mounted-components.js b/src/application/mounted-components.js index 03bbfa8..0ec51ff 100644 --- a/src/application/mounted-components.js +++ b/src/application/mounted-components.js @@ -4,4 +4,4 @@ * @type {Object} */ -module.exports = {}; // Empty by default +export default {}; // Empty by default diff --git a/src/dispatcher/index.js b/src/dispatcher/index.js index 909dcaa..d664894 100644 --- a/src/dispatcher/index.js +++ b/src/dispatcher/index.js @@ -1,5 +1,5 @@ -const Dispatcher = require('flux').Dispatcher; -const assign = require('object-assign'); +import { Dispatcher } from 'flux'; +import assign from 'object-assign'; /** * Application dispatcher. @@ -30,4 +30,4 @@ const AppDispatcher = assign(new Dispatcher(), { } }); -module.exports = AppDispatcher; +export default AppDispatcher; diff --git a/src/exception/argument-invalid-exception.js b/src/exception/argument-invalid-exception.js index 6e4224c..9e51a2e 100644 --- a/src/exception/argument-invalid-exception.js +++ b/src/exception/argument-invalid-exception.js @@ -1,4 +1,4 @@ -const CustomException = require('./custom-exception'); +import CustomException from './custom-exception'; /** * Class standing for the NotImplemented exceptions. */ @@ -8,9 +8,9 @@ class ArgumentInvalidException extends CustomException { * @param {string} message - Exception message. * @param {object} options - Object to add to the exception. */ - constructor(message, options) { - super('ArgumentInvalidException', message, options); - } + constructor(message, options) { + super('ArgumentInvalidException', message, options); + } } -module.exports = ArgumentInvalidException; +export default ArgumentInvalidException; diff --git a/src/network/__tests__/error-parser-test.js b/src/network/__tests__/error-parser-test.js index d56664e..b0a0a0d 100644 --- a/src/network/__tests__/error-parser-test.js +++ b/src/network/__tests__/error-parser-test.js @@ -1,18 +1,26 @@ /* global it, describe, expect */ -import errorParsing from '../error-parsing'; -import {omit} from 'lodash/object'; -const {manageResponseErrors: errorParser} = errorParsing; -const NODE_OPTS = {node: 'field1'}; -const NODES_OPTS = {node: ['field1', 'field2']}; +import { manageResponseErrors as errorParser } from '../error-parsing'; +import { omit } from 'lodash/object'; + +const NODE_OPTS = { node: 'field1' }; +const NODES_OPTS = { node: ['field1', 'field2'] }; import errorJSONResponse from './fixture/global-and-entity-error-fixture'; import errorGlobalJSONResponse from './fixture/global-error-fixture'; import errorEntityJSONResponse from './fixture/entity-error-fixture'; -describe('# error parser ', ()=>{ - it('should return null when there is no error', ()=>{ + +import { init } from '../../translation'; +init({ + resStore: {}, + lng: 'fr-FR' +}); // Initialise i18n + + +describe('# error parser ', () => { + it('should return null when there is no error', () => { expect(errorParser({})).to.equal(null); }); - it('should return null when there is no status', ()=>{ + it('should return null when there is no status', () => { const response = { responseJSON: { ...errorGlobalJSONResponse @@ -20,7 +28,7 @@ describe('# error parser ', ()=>{ }; expect(errorParser(response, NODE_OPTS)).to.equal(null); }); - it('should return the global error when there is one', ()=>{ + it('should return the global error when there is one', () => { const response = { status: 422, responseJSON: { @@ -29,25 +37,25 @@ describe('# error parser ', ()=>{ }; expect(errorParser(response, NODE_OPTS).globals).to.eql(errorGlobalJSONResponse.globalErrors); }); - it('should return the field error when thhey are set', ()=>{ + it('should return the field error when they are set', () => { const response = { status: 422, responseJSON: errorEntityJSONResponse }; - expect(errorParser(response, NODE_OPTS)).to.eql({globals: [], fields: errorEntityJSONResponse.fieldErrors }); + expect(errorParser(response, NODE_OPTS)).to.eql({ globals: [], fields: errorEntityJSONResponse.fieldErrors }); }); - it('should return the field error when multi node ard passed', ()=>{ + it('should return the field error when multi node are passed', () => { const response = { status: 422, responseJSON: { fieldErrors: { - n1: {f11: 'f11E'}, n2: {f21: 'f21'}, n3: {f31: 'f31'} + n1: { f11: 'f11E' }, n2: { f21: 'f21' }, n3: { f31: 'f31' } } } }; - expect(errorParser(response, {node: ['n1', 'n2']})).to.eql({globals: [], fields: omit(response.responseJSON.fieldErrors, 'n3') }); + expect(errorParser(response, { node: ['n1', 'n2'] })).to.eql({ globals: [], fields: omit(response.responseJSON.fieldErrors, 'n3') }); }); - it.skip('shoud deal with field errors only when the http code is correct', ()=>{ + it.skip('shoud deal with field errors only when the http code is correct', () => { const response = { status: 1111, responseJSON: errorEntityJSONResponse diff --git a/src/network/__tests__/fixture/entity-error-fixture.js b/src/network/__tests__/fixture/entity-error-fixture.js index 17f79e2..ad9bfde 100644 --- a/src/network/__tests__/fixture/entity-error-fixture.js +++ b/src/network/__tests__/fixture/entity-error-fixture.js @@ -1,6 +1,6 @@ export default { fieldErrors: { - field1: ['Error 1'], - field2: ['Error 2', 'Error '] + field1: 'Error 1', + field2: 'Error 2' } }; diff --git a/src/network/error-parsing.js b/src/network/error-parsing.js index 719393c..f6f5ee3 100644 --- a/src/network/error-parsing.js +++ b/src/network/error-parsing.js @@ -1,6 +1,8 @@ -import message from '../message'; -import {isObject, isArray, isString} from 'lodash/lang'; -import {translate} from '../translation'; +import { isObject, isArray } from 'lodash'; +import { getAll as getDomains } from '../definition/domain/container'; + +import { addMessage } from '../message'; +import { translate } from '../translation'; /** * Define all the error types of the exceptions which are defined. * @type {object} @@ -61,11 +63,11 @@ function configure(options) { */ function _formatParameters(parameters) { let options = {}, - formatter, value; + formatter, value; for (let prop in parameters) { if (parameters.hasOwnProperty(prop)) { if (parameters[prop].domain) { - let domain = metadataBuilder.getDomains()[parameters[prop].domain]; + let domain = getDomains()[parameters[prop].domain]; formatter = domain ? domain.format : undefined; } else { formatter = undefined; @@ -85,9 +87,9 @@ function _treatGlobalMessagesPerType(messages, type) { options = _formatParameters(element.parameters); element = element.message; } - message.addMessage({ + addMessage({ type: type, - content: require('i18next-client').t(element, options), + content: translate(element, options), creationDate: Date.now() }); }); @@ -107,7 +109,7 @@ function _treatGlobalErrors(responseJSON, options) { let globalMessagesContainer = []; let messages = responseJSON; //Looping through all messages types. - allMessagesTypes.forEach((globalMessageConf)=>{ + allMessagesTypes.forEach((globalMessageConf) => { //Treat all the gloabe let msgs = messages[globalMessageConf.name]; if (msgs) { @@ -121,6 +123,22 @@ function _treatGlobalErrors(responseJSON, options) { return null; } +/** + * Treat an object of error by translating every error content. + * + * @param {object} fieldErrors an object with key for fieldName, and values as error keys in i18n. + * @returns {object} a new object, with translated error + */ +function _treatEntityDetail(fieldErrors) { + return Object.keys(fieldErrors || {}).reduce( + (res, field) => { + // No reason to have several error on the same field, taking the first one + const error = fieldErrors[field]; + res[field] = translate(error); + return res; + }, {}); +} + /** * Treat the response json of an error. * @param {object} responseJSON The json response from the server. @@ -128,25 +146,16 @@ function _treatGlobalErrors(responseJSON, options) { * @return {object} The constructed object from the error response. */ function _treatEntityExceptions(responseJSON = {}, options) { - const {node} = options; + const { node } = options; const fieldJSONError = responseJSON.fieldErrors || {}; let fieldErrors = {}; - if(isArray(node)){ - node.forEach((nd)=>{fieldErrors[nd] = fieldJSONError[nd] || null; }); - }else if(isString(node)){ - fieldErrors = fieldJSONError; - }else { - fieldErrors = fieldJSONError; + if (isArray(node)) { + node.forEach((nd) => { fieldErrors[nd] = _treatEntityDetail(fieldJSONError[nd]); }); + } else { + fieldErrors = _treatEntityDetail(fieldJSONError); } - return Object.keys(fieldErrors) - .reduce( - (res, field) => { - res[field] = translate(fieldErrors[field]); - return res; - } - , {} - ); + return fieldErrors; } /** @@ -174,12 +183,31 @@ function _treatBadRequestExceptions(responseJSON = {}, options) { case errorTypes.collection: return _treatCollectionExceptions(responseJSON, options); default: - break; + break; } } return null; } + +/** + * Treat the field errors only if the status code is right (400, 401, 422). + * + * @param {object} resErrors the errors to treat + * @param {object} opts the options for handling errors + * @returns {any} depends on the errors handled + */ +function _handleStatusError(resErrors, opts) { + switch (resErrors.status) { + case 400: + case 401: + case 422: + return _treatBadRequestExceptions(resErrors, opts); + default: + return null; + } +} + /** * Transform errors send by API to application errors. Dispatch depending on the response http code. * @param {object} response - Object whic @@ -211,7 +239,7 @@ function manageResponseErrors(response, options) { globalErrorMessages: [response.responseText] }; } - }else { + } else { responseErrors = {}; } } @@ -219,23 +247,17 @@ function manageResponseErrors(response, options) { if (responseErrors.status) { return { globals: _treatGlobalErrors(responseErrors), - fields: ((resErrors, opts) => { - switch (responseErrors.status) { - case 400: - case 401: - case 422: - return _treatBadRequestExceptions(resErrors, opts); - default: - return null; - } - return null; - })(responseErrors, options) + fields: _handleStatusError(responseErrors, options) }; } return null; } -module.exports = { - configure: configure, - manageResponseErrors: manageResponseErrors +export { + configure, + manageResponseErrors }; +export default { + configure, + manageResponseErrors +}; \ No newline at end of file diff --git a/src/store/__tests__/CoreStore-test.js b/src/store/__tests__/CoreStore-test.js index 7605773..1fb0d4c 100644 --- a/src/store/__tests__/CoreStore-test.js +++ b/src/store/__tests__/CoreStore-test.js @@ -2,100 +2,103 @@ // __tests__/container-test.js import CoreStore from '../CoreStore'; -import {handleViewAction as dispatch} from '../../dispatcher' -describe('# The core store', ()=>{ +import dispatcher from '../../dispatcher'; + +const dispatch = (data) => dispatcher.handleViewAction(data); + +describe('# The core store', () => { describe('listeners ', () => { - const testStore = new CoreStore({definition: {person: 'person', address: 'address'}}); - describe(' should create listeners functions', ()=>{ + const testStore = new CoreStore({ definition: { person: 'person', address: 'address' } }); + describe(' should create listeners functions', () => { it('should add onChange listeners', () => { expect(testStore.addPersonChangeListener).to.be.a.function; expect(testStore.addAddressnChangeListener).to.be.a.function; }); - it('should add Error listeners', ()=>{ + it('should add Error listeners', () => { expect(testStore.addPersonErrorListener).to.be.a.function; expect(testStore.addAddressErrorListener).to.be.a.function; }); - it('should add status change listeners', ()=>{ + it('should add status change listeners', () => { expect(testStore.addPersonStatusListener).to.be.a.function; expect(testStore.addAddressStatusListener).to.be.a.function; }); }); - describe(' should create remove listeners functions', ()=>{ + describe(' should create remove listeners functions', () => { it('should add onChange listeners', () => { expect(testStore.removePersonChangeListener).to.be.a.function; expect(testStore.removeAddressChangeListener).to.be.a.function; }); - it('should add Error listeners', ()=>{ + it('should add Error listeners', () => { expect(testStore.removePersonErrorListener).to.be.a.function; expect(testStore.removeAddressErrorListener).to.be.a.function; }); - it('should add status change listeners', ()=>{ + it('should add status change listeners', () => { expect(testStore.removePersonStatusListener).to.be.a.function; expect(testStore.removeAddressStatusListener).to.be.a.function; }); }); describe('Handlers should be called on dispatch', () => { it('sould call on change listener on dispatch', (done) => { - const PERSON = {nom: 'david'} + const PERSON = { nom: 'david' } const onChange = d => { - expect(testStore.getPerson()).be.deep.equal(PERSON); - testStore.removePersonChangeListener(onChange); - done(); + expect(testStore.getPerson()).be.deep.equal(PERSON); + testStore.removePersonChangeListener(onChange); + done(); } - testStore.addPersonChangeListener(onChange); - dispatch({ - data: {person: PERSON}, - type: 'update' - }) + testStore.addPersonChangeListener(onChange); + dispatch({ + data: { person: PERSON }, + type: 'update' + }) }); it('sould call on error listener on dispatch', (done) => { - const PERSON_ERROR = {nom: 'error'} + const PERSON_ERROR = { nom: 'error' } const onChange = d => { - expect(testStore.getErrorPerson()).be.deep.equal(PERSON_ERROR); - testStore.removePersonErrorListener(onChange); - done(); + expect(testStore.getErrorPerson()).be.deep.equal(PERSON_ERROR); + testStore.removePersonErrorListener(onChange); + done(); } - testStore.addPersonErrorListener(onChange); - dispatch({ - data: {person: PERSON_ERROR}, - type: 'updateError' - }) + testStore.addPersonErrorListener(onChange); + dispatch({ + data: { person: PERSON_ERROR }, + type: 'updateError' + }) }); it('sould call on status listener on dispatch', (done) => { - const PERSON_STATUS = {nom: 'status'} + const PERSON_STATUS = { nom: 'status' } const onChange = d => { - expect(testStore.getStatusPerson()).be.deep.equal(PERSON_STATUS); - testStore.removePersonStatusListener(onChange); - done(); + expect(testStore.getStatusPerson()).be.deep.equal(PERSON_STATUS); + testStore.removePersonStatusListener(onChange); + done(); } - testStore.addPersonStatusListener(onChange); - dispatch({ - data: {person: PERSON_STATUS}, - type: 'updateStatus', - status: {person: PERSON_STATUS} - }) + testStore.addPersonStatusListener(onChange); + dispatch({ + data: { person: PERSON_STATUS }, + type: 'updateStatus', + status: { person: PERSON_STATUS } + }) }); }); }); describe('getters setters', () => { - const testStore = new CoreStore({definition: {person: 'person', address: 'address'}}); - describe('should create getters functions', () =>{ + const testStore = new CoreStore({ definition: { person: 'person', address: 'address' } }); + describe('should create getters functions', () => { it('should add getData function', () => { expect(testStore.getPerson).to.be.a.function; expect(testStore.getAddress).to.be.a.function; }); - it('should add getError function', ()=>{ + it('should add getError function', () => { expect(testStore.getErrorPerson).to.be.a.function; expect(testStore.getErrorAddress).to.be.a.function; }); - it('should add getStatus function', ()=>{ + it('should add getStatus function', () => { expect(testStore.getStatusPerson).to.be.a.function; expect(testStore.getStatusAddress).to.be.a.function; }); }); - describe('should create setters functions', () =>{ + describe('should create setters functions', () => { }); }); diff --git a/src/util/object/__tests__/check-test.js b/src/util/object/__tests__/check-test.js index e361fe9..488a6a1 100644 --- a/src/util/object/__tests__/check-test.js +++ b/src/util/object/__tests__/check-test.js @@ -9,9 +9,9 @@ describe('### object validation', () => { expect(checkObject('propertyName', {})).to.equal(undefined); }); it('A string shoud be invalid', () => { - expect(() => { checkObject('propertyName', 'aaaaa'); }).to.throw(ArgumentInvalidException, 'propertyName should be an object'); + expect(() => { checkObject('propertyName', 'aaaaa'); }).to.throw(/*ArgumentInvalidException,*/ 'propertyName should be an object'); }); it('A number shoud be invalid', () => { - expect(() => { checkObject('propertyName', 123); }).to.throw(ArgumentInvalidException, 'propertyName should be an object'); + expect(() => { checkObject('propertyName', 123); }).to.throw(/*ArgumentInvalidException, */'propertyName should be an object'); }); }); diff --git a/src/util/object/check.js b/src/util/object/check.js index 729b3c2..724a9f2 100644 --- a/src/util/object/check.js +++ b/src/util/object/check.js @@ -1,6 +1,5 @@ -var ArgumentInvalidException = require( - '../../exception/argument-invalid-exception'); -var isObject = require('lodash/lang/isObject'); +import ArgumentInvalidException from '../../exception/argument-invalid-exception'; +import isObject from 'lodash/lang/isObject'; /** * Assert an object is an objet. @@ -8,8 +7,9 @@ var isObject = require('lodash/lang/isObject'); * @param {object} data - The data to validate. * @return {undefined} - Return nothing, throw an Exception if this is not valid. */ -module.exports = function(name, data) { - if (data !== undefined && !isObject(data)) { - throw new ArgumentInvalidException(`${name} should be an object`, data); - } +export default function assertIsObject(name, data) { + if (data !== undefined && !isObject(data)) { + const ex = new ArgumentInvalidException(`${name} should be an object`, data);; + throw new ArgumentInvalidException(`${name} should be an object`, data); + } }; diff --git a/tsconfig.json b/tsconfig.json deleted file mode 100644 index e23aa45..0000000 --- a/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "compilerOptions": { - "target": "es2015", - "module": "commonjs" - }, - "exclude": [ - "node_modules" - ] -} \ No newline at end of file diff --git a/webpack.config.js b/webpack.config.js deleted file mode 100644 index 66d2c8e..0000000 --- a/webpack.config.js +++ /dev/null @@ -1,12 +0,0 @@ -const configBuilder = require('webpack-focus').configBuilder; -const customConfig = { - externals: { - react: 'React', - 'react-dom': 'ReactDOM', - moment: 'moment', - jquery: 'jQuery', - numeral: 'numeral' - } -}; - -module.exports = configBuilder(customConfig); From 3895e5e4181ecd541c04a70eac239a2388bb2069 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Thu, 17 Aug 2017 16:23:55 +0200 Subject: [PATCH 21/32] Fix Critical mistake --- src/store/CoreStore.js | 606 ++++++++++++++++++++--------------------- 1 file changed, 303 insertions(+), 303 deletions(-) diff --git a/src/store/CoreStore.js b/src/store/CoreStore.js index ddc4c74..775e5c0 100644 --- a/src/store/CoreStore.js +++ b/src/store/CoreStore.js @@ -1,303 +1,303 @@ -import { EventEmitter } from 'events'; -import assign from 'object-assign'; -import { isArray, isEmpty, isObject, isFunction } from 'lodash/lang'; -import { defer } from 'lodash/function'; -import intersection from 'lodash/array/intersection'; -import capitalize from 'lodash/string/capitalize'; -import Immutable from 'immutable'; -import AppDispatcher from '../dispatcher'; - -const reservedNames = ["Error", "Status"]; - -const _instances = []; - -/** -* @class CoreStore -*/ -class CoreStore extends EventEmitter { - - /** - * Contructor of the store class. - */ - constructor(config) { - super(); - assign(this, { - config - }); - //Initialize the data as immutable map. - this.data = Immutable.Map({}); - this.status = Immutable.Map({}); - this.error = Immutable.Map({}); - this.pendingEvents = []; - this.customHandler = assign({}, config.customHandler); - //Register all gernerated methods. - this.buildDefinition(); - this.buildEachNodeChangeEventListener(); - this.registerDispatcher(); - if (!!__DEV__) { - this._registerDevTools(); - } - } - // Get all the instances of core store. - get _instances() { - return [..._instances]; - } - // register the instances saving - _registerDevTools() { - _instances.push(this); - } - /** - * Initialize the store configuration. - * @param {object} storeConfiguration - The store configuration for the initialization. - */ - buildDefinition() { - /** - * Build the definitions for the entity (may be a subject.) - * @type {object} - */ - if (!this.config.definition) { - throw new Error('Core Store: missing definition', this.config); - } - this.definition = this.config.definition; - - const properties = Object.keys(this.definition).map(elt => capitalize(elt)); - const reservedProperties = properties.reduce((acc, elt) => acc.concat(reservedNames.map(w => w + elt)), []); - if (intersection(properties, reservedProperties).length > 0) { - throw new Error(`You have a name collision into this store : you cannot use a node named Blabla and anoter named ErrorBlabla, or StatusBlabla : ${intersection(properties, reservedProperties).join(' ')} `); - } - return this.definition; - } - /** - * Get the whole value of the - * @return {[type]} [description] - */ - getValue() { - return this.data ? this.data.toJS() : {}; - } - /** - * Getter on the identifier property. - * @return {string} - Store identifier. - */ - get identifier() { - return this.config && this.config.identifier ? this.config.identifier : undefined; - } - /** Return the status of a definition. - * @param {string} - The definition to load. - * @returns {string} - The status of a definition. - */ - getStatus(def) { - if (this.status.has(def)) { - return this.status.get(def); - } - return undefined; - } - /** - * Emit all events pending in the pendingEvents map. - */ - emitPendingEvents() { - this.pendingEvents.map((evtToEmit) => { - let { name, data } = evtToEmit; - this.emit(name, data); - }); - } - - /** - * Replace the emit function with a willEmit in otder to store the changing event but send it afterwards. - * @param eventName {string} - The event name. - * @param data {object} - The event's associated data. - */ - willEmit(eventName, data) { - this.pendingEvents = this.pendingEvents.reduce((result, current) => { - if (current.name !== eventName) { - result.push(current); - } - return result; - }, [{ name: eventName, data: data }]); - } - - /** - * Clear all pending events. - */ - clearPendingEvents() { - this.pendingEvents = []; - } - /** - * Build a change listener for each property in the definition. (should be macro entities); - */ - buildEachNodeChangeEventListener() { - const currentStore = this; - //Loop through each store properties. - for (let definition in this.definition) { - const capitalizeDefinition = capitalize(definition); - //Creates the change listener - currentStore[`add${capitalizeDefinition}ChangeListener`] = function (def) { - return function (cb) { - currentStore.addListener(`${def}:change`, cb); - } - }(definition); - //Remove the change listener - currentStore[`remove${capitalizeDefinition}ChangeListener`] = function (def) { - return function (cb) { - currentStore.removeListener(`${def}:change`, cb); - } - }(definition); - //Create an update method. - //Should be named updateData to be more explicit - if (currentStore[`update${capitalizeDefinition}`] === undefined) { - currentStore[`update${capitalizeDefinition}`] = function (def) { - return function (dataNode, status, informations) { - const immutableNode = isFunction(dataNode) ? dataNode : Immutable.fromJS(dataNode); - currentStore.data = currentStore.data.set(def, immutableNode); - //Update the status on the data. - currentStore.status = currentStore.status.set(def, status); - - currentStore.willEmit(`${def}:change`, { property: def, status: status, informations: informations }); - } - }(definition); - } - - //Create a get method. - if (currentStore[`get${capitalizeDefinition}`] === undefined) { - currentStore[`get${capitalizeDefinition}`] = function (def) { - return function () { - const hasData = currentStore.data.has(def); - if (hasData) { - const rawData = currentStore.data.get(def); - if (rawData && rawData.toJS) { - const data = rawData.toJS(); - return data; - } - return rawData; - } - return undefined; - }; - }(definition); - } - //Creates the error change listener - currentStore[`add${capitalizeDefinition}ErrorListener`] = function (def) { - return function (cb) { - currentStore.addListener(`${def}:error`, cb); - } - }(definition); - //Remove the change listener - currentStore[`remove${capitalizeDefinition}ErrorListener`] = function (def) { - return function (cb) { - currentStore.removeListener(`${def}:error`, cb); - } - }(definition); - //Create an update method. - currentStore[`updateError${capitalizeDefinition}`] = function (def) { - return function (dataNode, status, informations) { - //CheckIsObject - const immutableNode = Immutable[isArray(dataNode) ? "List" : "Map"](dataNode); - currentStore.error = currentStore.error.set(def, immutableNode); - currentStore.status = currentStore.status.set(def, status); - currentStore.willEmit(`${def}:error`, { property: def, status: status, informations: informations }); - } - }(definition); - //Create a get method. - currentStore[`getError${capitalizeDefinition}`] = function (def) { - return function () { - const hasData = currentStore.error.has(def); - return hasData ? currentStore.error.get(def).toJS() : undefined; - }; - }(definition); - - - // status - currentStore[`add${capitalizeDefinition}StatusListener`] = function (def) { - return function (cb) { - currentStore.addListener(`${def}:status`, cb); - } - }(definition); - //Remove the change listener - currentStore[`remove${capitalizeDefinition}StatusListener`] = function (def) { - return function (cb) { - currentStore.removeListener(`${def}:status`, cb); - } - }(definition); - //Create an update method. - currentStore[`updateStatus${capitalizeDefinition}`] = function (def) { - return function updateStatus(dataNode, status, informations) { - //CheckIsObject - //console.log(`status ${JSON.stringify(status) }`); - const statusNode = status;//Immutable.fromJS(status); // mMaybe it is a part of the status only. - currentStore.status = currentStore.status.set(def, statusNode); - currentStore.willEmit(`${def}:status`, { property: def, status: status, informations: informations }); - } - }(definition); - //Create a get method. - currentStore[`getStatus${capitalizeDefinition}`] = function (def) { - return function getStatus() { - const hasData = currentStore.status.has(def); - const data = hasData ? currentStore.status.get(def) : undefined; - return data.toJS ? data.toJS() : data; - }; - }(definition); - } - } - - delayPendingEvents(context) { - //Delay all the change emit by the store to be sure it is done after the internal store propagation and to go out of the dispatch function. - defer(() => { - context.emitPendingEvents(); - context.clearPendingEvents(); - }); - } - _buildInformations(incomingInfos) { - return { - callerId: incomingInfos.action.callerId - }; - } - /** - * The store registrer itself on the dispatcher. - */ - registerDispatcher() { - const currentStore = this; - this.dispatch = AppDispatcher.register(function (transferInfo) { - //Check if an identifier check is necessary. - if (currentStore.identifier) { - //If an identifier is needed a check is triggered. - if (!transferInfo || !transferInfo.action || !transferInfo.action.identifier || transferInfo.action.identifier !== currentStore.identifier) { - return; - } - } - //currentStore.clearPendingEvents(); - if (currentStore.globalCustomHandler) { - return currentStore.globalCustomHandler.call(currentStore, transferInfo); - } - - //Read data from the action transfer information. - const rawData = transferInfo.action.data; - const status = transferInfo.action.status || {}; - const type = transferInfo.action.type; - const otherInformations = currentStore._buildInformations(transferInfo); - - //Call each node handler for the matching definition's node. - for (let node in rawData) { - if (currentStore.definition[node]) { - //Call a custom handler if this exists. - if (currentStore.customHandler && currentStore.customHandler[node] && currentStore.customHandler[node][type]) { - currentStore.customHandler[node][type].call(currentStore, rawData[node], status[node], otherInformations); - } else { - //Update the data for the given node. and emit the change/. - if (!isFunction(currentStore[`${type}${capitalize(node)}`])) { - throw new Error(`The listener you try to call is unavailable : ${type} ${capitalize(node)} `); - } - currentStore[`${type} ${capitalize(node)} `](rawData[node], status[node], otherInformations); - } - } - } - currentStore.delayPendingEvents(currentStore); - }); - } - /** - * Add a listener on a store event. - * @param {string} eventName - Event name. - * @param {Function} cb - CallBack to call on the event change name. - */ - addListener(eventName, cb) { - this.on(eventName, cb); - } -} -export default CoreStore; +import { EventEmitter } from 'events'; +import assign from 'object-assign'; +import { isArray, isEmpty, isObject, isFunction } from 'lodash/lang'; +import { defer } from 'lodash/function'; +import intersection from 'lodash/array/intersection'; +import capitalize from 'lodash/string/capitalize'; +import Immutable from 'immutable'; +import AppDispatcher from '../dispatcher'; + +const reservedNames = ["Error", "Status"]; + +const _instances = []; + +/** +* @class CoreStore +*/ +class CoreStore extends EventEmitter { + + /** + * Contructor of the store class. + */ + constructor(config) { + super(); + assign(this, { + config + }); + //Initialize the data as immutable map. + this.data = Immutable.Map({}); + this.status = Immutable.Map({}); + this.error = Immutable.Map({}); + this.pendingEvents = []; + this.customHandler = assign({}, config.customHandler); + //Register all gernerated methods. + this.buildDefinition(); + this.buildEachNodeChangeEventListener(); + this.registerDispatcher(); + if (!!__DEV__) { + this._registerDevTools(); + } + } + // Get all the instances of core store. + get _instances() { + return [..._instances]; + } + // register the instances saving + _registerDevTools() { + _instances.push(this); + } + /** + * Initialize the store configuration. + * @param {object} storeConfiguration - The store configuration for the initialization. + */ + buildDefinition() { + /** + * Build the definitions for the entity (may be a subject.) + * @type {object} + */ + if (!this.config.definition) { + throw new Error('Core Store: missing definition', this.config); + } + this.definition = this.config.definition; + + const properties = Object.keys(this.definition).map(elt => capitalize(elt)); + const reservedProperties = properties.reduce((acc, elt) => acc.concat(reservedNames.map(w => w + elt)), []); + if (intersection(properties, reservedProperties).length > 0) { + throw new Error(`You have a name collision into this store : you cannot use a node named Blabla and anoter named ErrorBlabla, or StatusBlabla : ${intersection(properties, reservedProperties).join(' ')} `); + } + return this.definition; + } + /** + * Get the whole value of the + * @return {[type]} [description] + */ + getValue() { + return this.data ? this.data.toJS() : {}; + } + /** + * Getter on the identifier property. + * @return {string} - Store identifier. + */ + get identifier() { + return this.config && this.config.identifier ? this.config.identifier : undefined; + } + /** Return the status of a definition. + * @param {string} - The definition to load. + * @returns {string} - The status of a definition. + */ + getStatus(def) { + if (this.status.has(def)) { + return this.status.get(def); + } + return undefined; + } + /** + * Emit all events pending in the pendingEvents map. + */ + emitPendingEvents() { + this.pendingEvents.map((evtToEmit) => { + let { name, data } = evtToEmit; + this.emit(name, data); + }); + } + + /** + * Replace the emit function with a willEmit in otder to store the changing event but send it afterwards. + * @param eventName {string} - The event name. + * @param data {object} - The event's associated data. + */ + willEmit(eventName, data) { + this.pendingEvents = this.pendingEvents.reduce((result, current) => { + if (current.name !== eventName) { + result.push(current); + } + return result; + }, [{ name: eventName, data: data }]); + } + + /** + * Clear all pending events. + */ + clearPendingEvents() { + this.pendingEvents = []; + } + /** + * Build a change listener for each property in the definition. (should be macro entities); + */ + buildEachNodeChangeEventListener() { + const currentStore = this; + //Loop through each store properties. + for (let definition in this.definition) { + const capitalizeDefinition = capitalize(definition); + //Creates the change listener + currentStore[`add${capitalizeDefinition}ChangeListener`] = function (def) { + return function (cb) { + currentStore.addListener(`${def}:change`, cb); + } + }(definition); + //Remove the change listener + currentStore[`remove${capitalizeDefinition}ChangeListener`] = function (def) { + return function (cb) { + currentStore.removeListener(`${def}:change`, cb); + } + }(definition); + //Create an update method. + //Should be named updateData to be more explicit + if (currentStore[`update${capitalizeDefinition}`] === undefined) { + currentStore[`update${capitalizeDefinition}`] = function (def) { + return function (dataNode, status, informations) { + const immutableNode = isFunction(dataNode) ? dataNode : Immutable.fromJS(dataNode); + currentStore.data = currentStore.data.set(def, immutableNode); + //Update the status on the data. + currentStore.status = currentStore.status.set(def, status); + + currentStore.willEmit(`${def}:change`, { property: def, status: status, informations: informations }); + } + }(definition); + } + + //Create a get method. + if (currentStore[`get${capitalizeDefinition}`] === undefined) { + currentStore[`get${capitalizeDefinition}`] = function (def) { + return function () { + const hasData = currentStore.data.has(def); + if (hasData) { + const rawData = currentStore.data.get(def); + if (rawData && rawData.toJS) { + const data = rawData.toJS(); + return data; + } + return rawData; + } + return undefined; + }; + }(definition); + } + //Creates the error change listener + currentStore[`add${capitalizeDefinition}ErrorListener`] = function (def) { + return function (cb) { + currentStore.addListener(`${def}:error`, cb); + } + }(definition); + //Remove the change listener + currentStore[`remove${capitalizeDefinition}ErrorListener`] = function (def) { + return function (cb) { + currentStore.removeListener(`${def}:error`, cb); + } + }(definition); + //Create an update method. + currentStore[`updateError${capitalizeDefinition}`] = function (def) { + return function (dataNode, status, informations) { + //CheckIsObject + const immutableNode = Immutable[isArray(dataNode) ? "List" : "Map"](dataNode); + currentStore.error = currentStore.error.set(def, immutableNode); + currentStore.status = currentStore.status.set(def, status); + currentStore.willEmit(`${def}:error`, { property: def, status: status, informations: informations }); + } + }(definition); + //Create a get method. + currentStore[`getError${capitalizeDefinition}`] = function (def) { + return function () { + const hasData = currentStore.error.has(def); + return hasData ? currentStore.error.get(def).toJS() : undefined; + }; + }(definition); + + + // status + currentStore[`add${capitalizeDefinition}StatusListener`] = function (def) { + return function (cb) { + currentStore.addListener(`${def}:status`, cb); + } + }(definition); + //Remove the change listener + currentStore[`remove${capitalizeDefinition}StatusListener`] = function (def) { + return function (cb) { + currentStore.removeListener(`${def}:status`, cb); + } + }(definition); + //Create an update method. + currentStore[`updateStatus${capitalizeDefinition}`] = function (def) { + return function updateStatus(dataNode, status, informations) { + //CheckIsObject + //console.log(`status ${JSON.stringify(status) }`); + const statusNode = status;//Immutable.fromJS(status); // mMaybe it is a part of the status only. + currentStore.status = currentStore.status.set(def, statusNode); + currentStore.willEmit(`${def}:status`, { property: def, status: status, informations: informations }); + } + }(definition); + //Create a get method. + currentStore[`getStatus${capitalizeDefinition}`] = function (def) { + return function getStatus() { + const hasData = currentStore.status.has(def); + const data = hasData ? currentStore.status.get(def) : undefined; + return data.toJS ? data.toJS() : data; + }; + }(definition); + } + } + + delayPendingEvents(context) { + //Delay all the change emit by the store to be sure it is done after the internal store propagation and to go out of the dispatch function. + defer(() => { + context.emitPendingEvents(); + context.clearPendingEvents(); + }); + } + _buildInformations(incomingInfos) { + return { + callerId: incomingInfos.action.callerId + }; + } + /** + * The store registrer itself on the dispatcher. + */ + registerDispatcher() { + const currentStore = this; + this.dispatch = AppDispatcher.register(function (transferInfo) { + //Check if an identifier check is necessary. + if (currentStore.identifier) { + //If an identifier is needed a check is triggered. + if (!transferInfo || !transferInfo.action || !transferInfo.action.identifier || transferInfo.action.identifier !== currentStore.identifier) { + return; + } + } + //currentStore.clearPendingEvents(); + if (currentStore.globalCustomHandler) { + return currentStore.globalCustomHandler.call(currentStore, transferInfo); + } + + //Read data from the action transfer information. + const rawData = transferInfo.action.data; + const status = transferInfo.action.status || {}; + const type = transferInfo.action.type; + const otherInformations = currentStore._buildInformations(transferInfo); + + //Call each node handler for the matching definition's node. + for (let node in rawData) { + if (currentStore.definition[node]) { + //Call a custom handler if this exists. + if (currentStore.customHandler && currentStore.customHandler[node] && currentStore.customHandler[node][type]) { + currentStore.customHandler[node][type].call(currentStore, rawData[node], status[node], otherInformations); + } else { + //Update the data for the given node. and emit the change/. + if (!isFunction(currentStore[`${type}${capitalize(node)}`])) { + throw new Error(`The listener you try to call is unavailable : ${type} ${capitalize(node)} `); + } + currentStore[`${type}${capitalize(node)}`](rawData[node], status[node], otherInformations); + } + } + } + currentStore.delayPendingEvents(currentStore); + }); + } + /** + * Add a listener on a store event. + * @param {string} eventName - Event name. + * @param {Function} cb - CallBack to call on the event change name. + */ + addListener(eventName, cb) { + this.on(eventName, cb); + } +} +export default CoreStore; From 28155211f6ef158d8a9237a9b9dac57a1f7b1475 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Thu, 17 Aug 2017 16:42:46 +0200 Subject: [PATCH 22/32] Fixing unit test + migrating to i18nnext --- jest-config.js | 15 ++++ package.json | 69 ++++++++++------ scripts/babelify.js | 82 +++++++++---------- .../__tests__/action-builder-test.js | 10 +-- .../domain/__tests__/container-test.js | 12 +-- src/definition/domain/__tests__/domainMock.js | 24 ------ .../entity/__tests__/container-test.js | 36 ++++---- .../validator/__tests__/number-test.js | 18 ++-- src/network/__tests__/error-parser-test.js | 18 ++-- src/network/error-parsing.js | 1 + src/store/__tests__/CoreStore-test.js | 53 ++++++------ src/translation/index.js | 26 +++++- src/util/object/__tests__/check-test.js | 8 +- test/mocha-bootload.js | 31 ------- test/mocha.opts | 5 -- 15 files changed, 200 insertions(+), 208 deletions(-) create mode 100644 jest-config.js delete mode 100644 src/definition/domain/__tests__/domainMock.js delete mode 100644 test/mocha-bootload.js delete mode 100644 test/mocha.opts diff --git a/jest-config.js b/jest-config.js new file mode 100644 index 0000000..187a17a --- /dev/null +++ b/jest-config.js @@ -0,0 +1,15 @@ +module.exports = { + globals: { + __DEV__: true + }, + automock: false, + unmockedModulePathPatterns: [ + '/node_modules/react', + '/node_modules/react-dom', + '/node_modules/react-addons-test-utils', + '/node_modules/fbjs', + '/node_modules/numeral', + '/node_modules/i18next', + ], + testPathIgnorePatterns: ['/node_modules/', 'fixture.js', '.history', '.localhistory', 'test-focus.jsx'] +} \ No newline at end of file diff --git a/package.json b/package.json index 29f239b..fd54a9b 100644 --- a/package.json +++ b/package.json @@ -25,39 +25,62 @@ "url": "https://github.com/KleeGroup/focus-core/issues" }, "scripts": { + "build": "better-npm-run babelify", "babelify": "better-npm-run babelify", - "test": "mocha src/**/__tests__/**/*.js", - "test:watch": "mocha src/**/__tests__/**/*.js -w", - "build": "better-npm-run babelify" + "test": "better-npm-run test", + "test:watch": "better-npm-run test-watch", + "prepublish": "npm run build", + "lint": "eslint src --ext .js,.jsx --ignore-pattern __tests__ --ignore-pattern example --ignore-pattern awesomplete", + "lint:error": "eslint src --ext .js,.jsx --ignore-pattern __tests__ --ignore-pattern example --ignore-pattern awesomplete --quiet", + "fix-lint": "eslint src/** --ext .js,.jsx --fix --ignore-pattern __tests__ --ignore-pattern example --ignore-pattern awesomplete" }, "betterScripts": { "babelify": { + "env": { + "BABEL_ENV": "production" + }, "command": "node scripts/babelify.js" + }, + "copy-sass": { + "command": "cd src && find . -name *.scss | xargs tar cvf - | tar xfp - -C ../" + }, + "test": { + "command": "jest --config jest-config.js --runInBand --no-cache", + "env": { + "BABEL_ENV": "production" + } + }, + "test-watch": { + "command": "jest --config jest-config.js --runInBand --watch ", + "env": { + "BABEL_ENV": "production" + } } }, + "peerDependencies": { + "react": "15.4.2", + "react-dom": "15.4.2" + }, "dependencies": { - "@types/flux": "^0.0.30", - "@types/node": "^6.0.38", - "flux": "^2.0.3", - "i18next-client": "^1.11.4", - "immutable": "^3.7.3", - "keymirror": "^0.1.1", - "lodash": "^3.9.1", - "object-assign": "^2.0.0", - "uuid": "^2.0.1" + "flux": "3.1.3", + "i18next": "8.4.3", + "immutable": "3.8.1", + "lodash": "3.10.1", + "object-assign": "4.1.1", + "uuid": "3.1.0" }, "devDependencies": { + "babel-jest": "20.0.3", "babel-preset-focus": "0.7.0", - "better-npm-run": "0.0.15", - "chai": "^3.2.0", - "chai-subset": "^1.1.0", - "eslint-config-focus": "0.3.0", - "jquery": "^2.1.4", - "mocha": "^2.3.2", - "moment": "^2.10.6", - "numeral": "^1.5.3", - "react": "^15.2.1", - "react-addons-test-utils": "^15.2.1", - "react-dom": "^15.2.1" + "better-npm-run": "0.1.0", + "eslint-config-focus": "git://github.com/KleeGroup/eslint-config-focus#master", + "focus-core": "2.1.1", + "i18next": "8.4.3", + "jest-cli": "20.0.4", + "jsdom": "11.1.0", + "numeral": "2.0.6", + "react": "15.4.2", + "react-addons-test-utils": "15.4.2", + "react-dom": "15.4.2" } } \ No newline at end of file diff --git a/scripts/babelify.js b/scripts/babelify.js index 7f21acd..2870241 100644 --- a/scripts/babelify.js +++ b/scripts/babelify.js @@ -1,44 +1,34 @@ -var fs = require('fs'); -var path = require('path'); -var babel = require('babel-core'); +let fs = require('fs'); +let path = require('path'); +// var babel = require('babel-core'); -var babelOptions = { - "presets": [ - "es2015", - "stage-0", - "react" - ], - "plugins": [ - "add-module-exports", - "transform-class-properties", - "transform-decorators-legacy", - "transform-proto-to-assign", - ["transform-es2015-classes", {"loose": true}] +// var babelOptions = { +// "presets": [ +// "focus" +// ], +// sourceMaps: 'inline' +// }; - ], - sourceMaps: 'inline' -}; - -var walk = function(dir) { - var files = []; - var list = fs.readdirSync(dir); - list.forEach(function(file) { +var walk = function (dir) { + let files = []; + let list = fs.readdirSync(dir); + list.forEach(function (file) { file = dir + '/' + file; - var stat = fs.statSync(file); + let stat = fs.statSync(file); if (stat && stat.isDirectory()) files = files.concat(walk(file)); else files.push(file); }); return files; }; -var filterFiles = function(files) { - return files.filter(function(file) { - return !file.match(/(example|__tests__)/) && (file.match(/\.js$/) || file.match(/\.d.ts$/)); +let filterFiles = function (files) { + return files.filter(function (file) { + return (!file.match(/(example|__tests__)/) && file.match(/\.js$/)); }); }; function ensureDirectoryExistence(filePath) { - var dirname = path.dirname(filePath); + let dirname = path.dirname(filePath); if (fs.existsSync(dirname)) { return true; } @@ -46,21 +36,23 @@ function ensureDirectoryExistence(filePath) { fs.mkdirSync(dirname); } -var files = filterFiles(walk('./src')); -files.forEach(function(file) { - if (file.match(/\.d.ts$/)) { - var newFile = file.replace('./src', '.'); - ensureDirectoryExistence(newFile); - fs.createReadStream(file).pipe(fs.createWriteStream(newFile)); - } else { - babel.transformFile(file, babelOptions, function(err, result) { - if (err) console.error(err); - var newFile = file.replace('./src', '.'); - ensureDirectoryExistence(newFile); - fs.writeFile(newFile, result.code, function(err) { - if (err) console.error(err); - console.log('Babelified ' + file); - }); - }); - } +let files = filterFiles(walk('./src')); +files.forEach(function (file) { + let newFile = file.replace('./src', '.'); + ensureDirectoryExistence(newFile); + fs.createReadStream(file).pipe(fs.createWriteStream(newFile)); + // fs.writeFile(newFile, result.code, function (err) { + // if (err) console.error(err); + // console.log('Babelified ' + file); + // }); + + // babel.transformFile(file, babelOptions, function(err, result) { + // if (err) console.error(err); + // var newFile = file.replace('./src', '.'); + // ensureDirectoryExistence(newFile); + // fs.writeFile(newFile, result.code, function(err) { + // if (err) console.error(err); + // console.log('Babelified ' + file); + // }); + // }); }); diff --git a/src/application/__tests__/action-builder-test.js b/src/application/__tests__/action-builder-test.js index e9bfa1d..f7b9b03 100644 --- a/src/application/__tests__/action-builder-test.js +++ b/src/application/__tests__/action-builder-test.js @@ -12,20 +12,20 @@ init({ describe('### action-builder', () => { it('Config must have a service', () => { expect(() => actionBuilder({})) - .to.throw('You need to provide a service to call'); + .toThrow('You need to provide a service to call'); }); it('Config must have a status', () => { expect(() => actionBuilder({ service: () => { } })) - .to.throw('You need to provide a status to your action'); + .toThrow('You need to provide a status to your action'); }); it('Config must have a node', () => { expect(() => actionBuilder({ service: () => { }, status: 'superStatus' })) - .to.throw('You shoud specify the store node name impacted by the action'); + .toThrow('You shoud specify the store node name impacted by the action'); }); it('Builded action should be a function', () => { const action = actionBuilder({ status: 'test', service: () => { }, node: 'test' }); - expect(action).to.be.a('function'); + expect(action).toBeInstanceOf(Function); }); it('Builded action call should result to a store update', (done) => { @@ -78,7 +78,7 @@ describe('### action-builder', () => { return Promise.reject(mockErrorResponse); }; store.addNameErrorListener(() => { - expect(store.getErrorName()).to.eql(lopezErrors); + expect(store.getErrorName()).toEqual(lopezErrors); done(); }); const actionConf = { diff --git a/src/definition/domain/__tests__/container-test.js b/src/definition/domain/__tests__/container-test.js index 73b2f5e..a2275f3 100644 --- a/src/definition/domain/__tests__/container-test.js +++ b/src/definition/domain/__tests__/container-test.js @@ -2,16 +2,16 @@ // __tests__/container-test.js -describe('### domain container', ()=>{ - it('domain should be empty by default', ()=>{ +describe('### domain container', () => { + it('domain should be empty by default', () => { const domainContainer = require('../container'); - expect(domainContainer.getAll()).to.deep.equal({}); + expect(domainContainer.getAll()).toEqual({}); }); - it('domain set should add a domain', ()=>{ + it('domain set should add a domain', () => { const domainContainer = require('../container'); - const doText = {name: 'DO_TEXT', type: 'string'}; + const doText = { name: 'DO_TEXT', type: 'string' }; domainContainer.set(doText); - expect(domainContainer.getAll().DO_TEXT).to.deep.equal(doText); + expect(domainContainer.getAll().DO_TEXT).toEqual(doText); }); diff --git a/src/definition/domain/__tests__/domainMock.js b/src/definition/domain/__tests__/domainMock.js deleted file mode 100644 index 90980ed..0000000 --- a/src/definition/domain/__tests__/domainMock.js +++ /dev/null @@ -1,24 +0,0 @@ -module.exports = { - "DO_TEXT": { - style: "do_text", - type: "text", - component: "PapaSinge", - validation: [{ - type: "function", - value: function() { - return false; - } - }] - }, - "DO_EMAIL": { - style: "do_email", - type: "email", - component: "PapaMail", - validation: [{ - type: "function", - value: function() { - return true; - } - }] - } -}; diff --git a/src/definition/entity/__tests__/container-test.js b/src/definition/entity/__tests__/container-test.js index 1da837f..e5ba526 100644 --- a/src/definition/entity/__tests__/container-test.js +++ b/src/definition/entity/__tests__/container-test.js @@ -3,22 +3,22 @@ const entityConfigurationMock = require('./entityConfigurationMock.json'); -describe('### entity container', ()=>{ - it('getEntityConfiguration should be empty by default', ()=>{ - const entityContainer = require('../container'); - expect(entityContainer.getEntityConfiguration()).to.deep.equal({}); - }); - it('getEntityConfiguration should sent back sent conf', ()=> { - const entityContainer = require('../container'); - entityContainer.setEntityConfiguration(entityConfigurationMock); - expect(entityContainer.getEntityConfiguration()).to.deep.equal( - entityConfigurationMock); - }); - it('Get node should trigger a warning when the props does not exists', ()=> { - const entityContainer = require('../container'); - entityContainer.setEntityConfiguration(entityConfigurationMock); - expect(()=>{ - return entityContainer.getEntityConfiguration('papa'); - }).to.throw(Error, 'Wrong definition path given, see waning for more details'); - }); +describe('### entity container', () => { + it('getEntityConfiguration should be empty by default', () => { + const entityContainer = require('../container'); + expect(entityContainer.getEntityConfiguration()).toEqual({}); + }); + it('getEntityConfiguration should sent back sent conf', () => { + const entityContainer = require('../container'); + entityContainer.setEntityConfiguration(entityConfigurationMock); + expect(entityContainer.getEntityConfiguration()).toEqual( + entityConfigurationMock); + }); + it('Get node should trigger a warning when the props does not exists', () => { + const entityContainer = require('../container'); + entityContainer.setEntityConfiguration(entityConfigurationMock); + expect(() => { + return entityContainer.getEntityConfiguration('papa'); + }).toThrow(Error, 'Wrong definition path given, see waning for more details'); + }); }); diff --git a/src/definition/validator/__tests__/number-test.js b/src/definition/validator/__tests__/number-test.js index 3e88576..85f05ea 100644 --- a/src/definition/validator/__tests__/number-test.js +++ b/src/definition/validator/__tests__/number-test.js @@ -5,30 +5,30 @@ import numberValidation from '../number'; describe('### validator number', () => { it('number should be valid', () => { - expect(numberValidation(1)).to.equal(true); + expect(numberValidation(1)).toEqual(true); }); it('null should be valid', () => { - expect(numberValidation(null)).to.equal(true); + expect(numberValidation(null)).toEqual(true); }); it('undefined should be valid', () => { - expect(numberValidation(undefined)).to.equal(true); + expect(numberValidation(undefined)).toEqual(true); }); it('string should be invalid', () => { - expect(numberValidation('ABCD')).to.equal(false); + expect(numberValidation('ABCD')).toEqual(false); }); it('string should be invalid', () => { - expect(numberValidation('ABCD')).to.equal(false); + expect(numberValidation('ABCD')).toEqual(false); }); it('number min should be false when number inferior to min', () => { - expect(numberValidation('6', { min: 7 })).to.equal(false); + expect(numberValidation('6', { min: 7 })).toEqual(false); }); it('number min should be true when number superior to min', () => { - expect(numberValidation('7', { min: 6 })).to.equal(true); + expect(numberValidation('7', { min: 6 })).toEqual(true); }); it('number max should be false when number superior to max', () => { - expect(numberValidation('12', { max: 7 })).to.equal(false); + expect(numberValidation('12', { max: 7 })).toEqual(false); }); it('number max should be true when number inferior to max', () => { - expect(numberValidation('7', { max: 7 })).to.equal(true); + expect(numberValidation('7', { max: 7 })).toEqual(true); }); }); diff --git a/src/network/__tests__/error-parser-test.js b/src/network/__tests__/error-parser-test.js index b0a0a0d..3a68a1c 100644 --- a/src/network/__tests__/error-parser-test.js +++ b/src/network/__tests__/error-parser-test.js @@ -18,7 +18,7 @@ init({ describe('# error parser ', () => { it('should return null when there is no error', () => { - expect(errorParser({})).to.equal(null); + expect(errorParser({})).toEqual(null); }); it('should return null when there is no status', () => { const response = { @@ -26,7 +26,7 @@ describe('# error parser ', () => { ...errorGlobalJSONResponse } }; - expect(errorParser(response, NODE_OPTS)).to.equal(null); + expect(errorParser(response, NODE_OPTS)).toEqual(null); }); it('should return the global error when there is one', () => { const response = { @@ -35,14 +35,14 @@ describe('# error parser ', () => { ...errorGlobalJSONResponse } }; - expect(errorParser(response, NODE_OPTS).globals).to.eql(errorGlobalJSONResponse.globalErrors); + expect(errorParser(response, NODE_OPTS).globals).toEqual(errorGlobalJSONResponse.globalErrors); }); it('should return the field error when they are set', () => { const response = { status: 422, - responseJSON: errorEntityJSONResponse + responseJSON: { ...errorEntityJSONResponse } }; - expect(errorParser(response, NODE_OPTS)).to.eql({ globals: [], fields: errorEntityJSONResponse.fieldErrors }); + expect(errorParser(response, NODE_OPTS)).toEqual({ globals: [], fields: errorEntityJSONResponse.fieldErrors }); }); it('should return the field error when multi node are passed', () => { const response = { @@ -53,14 +53,14 @@ describe('# error parser ', () => { } } }; - expect(errorParser(response, { node: ['n1', 'n2'] })).to.eql({ globals: [], fields: omit(response.responseJSON.fieldErrors, 'n3') }); + expect(errorParser(response, { node: ['n1', 'n2'] })).toEqual({ globals: [], fields: omit(response.responseJSON.fieldErrors, 'n3') }); }); - it.skip('shoud deal with field errors only when the http code is correct', () => { + it('shoud deal with field errors only when the http code is correct', () => { const response = { status: 1111, - responseJSON: errorEntityJSONResponse + responseJSON: { ...errorEntityJSONResponse } }; const filds = errorParser(response, NODE_OPTS).fields; - expect(filds).to.equal(null); + expect(filds).toEqual(null); }); }); diff --git a/src/network/error-parsing.js b/src/network/error-parsing.js index f6f5ee3..ecb1791 100644 --- a/src/network/error-parsing.js +++ b/src/network/error-parsing.js @@ -198,6 +198,7 @@ function _treatBadRequestExceptions(responseJSON = {}, options) { * @returns {any} depends on the errors handled */ function _handleStatusError(resErrors, opts) { + console.log('ici', resErrors, opts) switch (resErrors.status) { case 400: case 401: diff --git a/src/store/__tests__/CoreStore-test.js b/src/store/__tests__/CoreStore-test.js index 1fb0d4c..28de30c 100644 --- a/src/store/__tests__/CoreStore-test.js +++ b/src/store/__tests__/CoreStore-test.js @@ -8,40 +8,43 @@ const dispatch = (data) => dispatcher.handleViewAction(data); describe('# The core store', () => { describe('listeners ', () => { - const testStore = new CoreStore({ definition: { person: 'person', address: 'address' } }); + let testStore; + beforeEach(() => { + testStore = new CoreStore({ definition: { person: 'person', address: 'address' } }); + }); describe(' should create listeners functions', () => { it('should add onChange listeners', () => { - expect(testStore.addPersonChangeListener).to.be.a.function; - expect(testStore.addAddressnChangeListener).to.be.a.function; + expect(testStore.addPersonChangeListener).toBeInstanceOf(Function); + expect(testStore.addAddressChangeListener).toBeInstanceOf(Function); }); it('should add Error listeners', () => { - expect(testStore.addPersonErrorListener).to.be.a.function; - expect(testStore.addAddressErrorListener).to.be.a.function; + expect(testStore.addPersonErrorListener).toBeInstanceOf(Function); + expect(testStore.addAddressErrorListener).toBeInstanceOf(Function); }); it('should add status change listeners', () => { - expect(testStore.addPersonStatusListener).to.be.a.function; - expect(testStore.addAddressStatusListener).to.be.a.function; + expect(testStore.addPersonStatusListener).toBeInstanceOf(Function); + expect(testStore.addAddressStatusListener).toBeInstanceOf(Function); }); }); describe(' should create remove listeners functions', () => { it('should add onChange listeners', () => { - expect(testStore.removePersonChangeListener).to.be.a.function; - expect(testStore.removeAddressChangeListener).to.be.a.function; + expect(testStore.removePersonChangeListener).toBeInstanceOf(Function); + expect(testStore.removeAddressChangeListener).toBeInstanceOf(Function); }); it('should add Error listeners', () => { - expect(testStore.removePersonErrorListener).to.be.a.function; - expect(testStore.removeAddressErrorListener).to.be.a.function; + expect(testStore.removePersonErrorListener).toBeInstanceOf(Function); + expect(testStore.removeAddressErrorListener).toBeInstanceOf(Function); }); it('should add status change listeners', () => { - expect(testStore.removePersonStatusListener).to.be.a.function; - expect(testStore.removeAddressStatusListener).to.be.a.function; + expect(testStore.removePersonStatusListener).toBeInstanceOf(Function); + expect(testStore.removeAddressStatusListener).toBeInstanceOf(Function); }); }); describe('Handlers should be called on dispatch', () => { - it('sould call on change listener on dispatch', (done) => { + it('should call on change listener on dispatch', (done) => { const PERSON = { nom: 'david' } const onChange = d => { - expect(testStore.getPerson()).be.deep.equal(PERSON); + expect(testStore.getPerson()).toEqual(PERSON); testStore.removePersonChangeListener(onChange); done(); } @@ -51,10 +54,10 @@ describe('# The core store', () => { type: 'update' }) }); - it('sould call on error listener on dispatch', (done) => { + it('should call on error listener on dispatch', (done) => { const PERSON_ERROR = { nom: 'error' } const onChange = d => { - expect(testStore.getErrorPerson()).be.deep.equal(PERSON_ERROR); + expect(testStore.getErrorPerson()).toEqual(PERSON_ERROR); testStore.removePersonErrorListener(onChange); done(); } @@ -64,10 +67,10 @@ describe('# The core store', () => { type: 'updateError' }) }); - it('sould call on status listener on dispatch', (done) => { + it('should call on status listener on dispatch', (done) => { const PERSON_STATUS = { nom: 'status' } const onChange = d => { - expect(testStore.getStatusPerson()).be.deep.equal(PERSON_STATUS); + expect(testStore.getStatusPerson()).toEqual(PERSON_STATUS); testStore.removePersonStatusListener(onChange); done(); } @@ -86,16 +89,16 @@ describe('# The core store', () => { const testStore = new CoreStore({ definition: { person: 'person', address: 'address' } }); describe('should create getters functions', () => { it('should add getData function', () => { - expect(testStore.getPerson).to.be.a.function; - expect(testStore.getAddress).to.be.a.function; + expect(testStore.getPerson).toBeInstanceOf(Function); + expect(testStore.getAddress).toBeInstanceOf(Function); }); it('should add getError function', () => { - expect(testStore.getErrorPerson).to.be.a.function; - expect(testStore.getErrorAddress).to.be.a.function; + expect(testStore.getErrorPerson).toBeInstanceOf(Function); + expect(testStore.getErrorAddress).toBeInstanceOf(Function); }); it('should add getStatus function', () => { - expect(testStore.getStatusPerson).to.be.a.function; - expect(testStore.getStatusAddress).to.be.a.function; + expect(testStore.getStatusPerson).toBeInstanceOf(Function); + expect(testStore.getStatusAddress).toBeInstanceOf(Function); }); }); describe('should create setters functions', () => { diff --git a/src/translation/index.js b/src/translation/index.js index 62e6f40..44aa625 100644 --- a/src/translation/index.js +++ b/src/translation/index.js @@ -1,6 +1,24 @@ -import {t, init} from 'i18next-client'; +import i18next from 'i18next'; -export default { - translate: t, - init +const init = i18next.init.bind(i18next); +const translate = i18next.t.bind(i18next); + +function focusi18nInit(data) { + const { resStore, ...others } = data || {}; + const toInit = { ...others }; + if (resStore) { + console.warn('With new i18next version, data should be in resources, not in resStore. Please change it in the initializer.'); + toInit.resources = resStore; + } + return init(toInit); +} + + +export { + focusi18nInit as init, + translate }; +export default { + init: focusi18nInit, + translate +}; \ No newline at end of file diff --git a/src/util/object/__tests__/check-test.js b/src/util/object/__tests__/check-test.js index 488a6a1..f8f3beb 100644 --- a/src/util/object/__tests__/check-test.js +++ b/src/util/object/__tests__/check-test.js @@ -1,17 +1,17 @@ /*global it, describe, expect*/ -import ArgumentInvalidException from '../../../exception/argument-invalid-exception'; +// import ArgumentInvalidException from '../../../exception/argument-invalid-exception'; import checkObject from '../check'; describe('### object validation', () => { it('An empty object should wokks', () => { //console.log('checkObjet', checkObject); - expect(checkObject('propertyName', {})).to.equal(undefined); + expect(checkObject('propertyName', {})).toEqual(undefined); }); it('A string shoud be invalid', () => { - expect(() => { checkObject('propertyName', 'aaaaa'); }).to.throw(/*ArgumentInvalidException,*/ 'propertyName should be an object'); + expect(() => { checkObject('propertyName', 'aaaaa'); }).toThrow(/*ArgumentInvalidException,*/ 'propertyName should be an object'); }); it('A number shoud be invalid', () => { - expect(() => { checkObject('propertyName', 123); }).to.throw(/*ArgumentInvalidException, */'propertyName should be an object'); + expect(() => { checkObject('propertyName', 123); }).toThrow(/*ArgumentInvalidException,*/ 'propertyName should be an object'); }); }); diff --git a/test/mocha-bootload.js b/test/mocha-bootload.js deleted file mode 100644 index 167f807..0000000 --- a/test/mocha-bootload.js +++ /dev/null @@ -1,31 +0,0 @@ -//Global configuration uese for tests. -require('babel-core/register')({ - presets: [ - 'focus' - ] -}); - -const chai = require('chai'); -const chaiSubset = require('chai-subset'); -chai.use(chaiSubset); -/*eslint-disable */ -const should = chai.should(); -global.expect = require('chai').expect; -/*eslint-enable */ - -global.__DEV__ = process.env.DEV ? JSON.parse(process.env.DEV) : true; -global.React = require('react'); -global.ReactDOM = require('react-dom'); -global.expect = chai.expect; -global.TestUtils = require('react-addons-test-utils'); -global.__DEV__ = process.env.DEV ? JSON.parse(process.env.DEV) : true; - -/*eslint-disable */ -//let {shallowRenderer} = TestUtils; -/*eslint-enable */ - -process.on('unhandledRejection', (error) => { - console.error('Unhandled Promise Rejection:'); - console.error(error && error.stack || error); -}); -console.log('Test: bootload done'); diff --git a/test/mocha.opts b/test/mocha.opts deleted file mode 100644 index 65ed2d0..0000000 --- a/test/mocha.opts +++ /dev/null @@ -1,5 +0,0 @@ ---compilers js:babel-core/register ---require test/mocha-bootload ---require chai ---reporter spec ---ui bdd \ No newline at end of file From d4cfbff94f3d2758679b44e3d05a3e8742ab3b46 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Fri, 18 Aug 2017 11:33:22 +0200 Subject: [PATCH 23/32] Moving numeral to dependencies, updating init and format function --- package.json | 3 +-- src/definition/formatter/number.js | 31 +++++++++++++++++++----------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index fd54a9b..2821c0e 100644 --- a/package.json +++ b/package.json @@ -66,6 +66,7 @@ "i18next": "8.4.3", "immutable": "3.8.1", "lodash": "3.10.1", + "numeral": "2.0.6", "object-assign": "4.1.1", "uuid": "3.1.0" }, @@ -75,10 +76,8 @@ "better-npm-run": "0.1.0", "eslint-config-focus": "git://github.com/KleeGroup/eslint-config-focus#master", "focus-core": "2.1.1", - "i18next": "8.4.3", "jest-cli": "20.0.4", "jsdom": "11.1.0", - "numeral": "2.0.6", "react": "15.4.2", "react-addons-test-utils": "15.4.2", "react-dom": "15.4.2" diff --git a/src/definition/formatter/number.js b/src/definition/formatter/number.js index 5365b78..7e1d01f 100644 --- a/src/definition/formatter/number.js +++ b/src/definition/formatter/number.js @@ -1,12 +1,7 @@ import numeral from 'numeral'; - +// see http://numeraljs.com const DEFAULT_FORMAT = '0,0'; -//TODO change numeral lib and regroup initializers -function language(key, conf) { - return numeral.language(key, conf); -}; - /** * Format a number using a given format. * @param {number} number - The number to format. @@ -14,11 +9,25 @@ function language(key, conf) { * @return {string} - The formated number. */ function format(number, format) { - format = format || DEFAULT_FORMAT; return numeral(number).format(format); -}; +} -module.exports = { - format, - language +/** + * Initialize numeral locale and default format + * + * @param {any} { format = DEFAULT_FORMAT, locale = 'fr' } + */ +function init({ format = DEFAULT_FORMAT, locale = 'fr' }) { + numeral.locale(locale); + numeral.defaultFormat(format); +} + +export default { + init, + format }; + +export { + init, + format +}; \ No newline at end of file From 8638609fccbf5857e13c3333e6ea46e486cc6280 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Fri, 18 Aug 2017 12:02:28 +0200 Subject: [PATCH 24/32] Fixing missing keyMirror dependency --- src/store/reference/definition.js | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/store/reference/definition.js b/src/store/reference/definition.js index 3cca80f..eadadf0 100644 --- a/src/store/reference/definition.js +++ b/src/store/reference/definition.js @@ -1,20 +1,21 @@ -var refConfigAccessor = require('../../reference/config'); -var keyMirror = require('keymirror'); -var isEmpty = require('lodash/lang/isEmpty'); +import refConfigAccessor from '../../reference/config'; +import isEmpty from 'lodash/lang/isEmpty'; /** * Build the reference definition from the keys registered into the definitions. * @returns {object} - The reference definition. */ -function buildReferenceDefinition(){ - //Read the current configuration in the reference config. - var referenceConf = refConfigAccessor.get(); - //Warn the user if empty. - if(!referenceConf || isEmpty(referenceConf)){ - console.warn('You did not set any reference list in the reference configuration, see Focus.reference.config.set.'); - } - //Build an object from the keys. - return keyMirror(referenceConf); +function buildReferenceDefinition() { + //Read the current configuration in the reference config. + let referenceConf = refConfigAccessor.get(); + //Warn the user if empty. + if (!referenceConf || isEmpty(referenceConf)) { + console.warn('You did not set any reference list in the reference configuration, see Focus.reference.config.set.'); + } + //Build an object from the keys. + return Object.keys(referenceConf).reduce((acc, elt) => { + acc[elt] = elt; + return acc; + }, {}); } - -module.exports = buildReferenceDefinition; +export default buildReferenceDefinition; From 2c45a8012e29cb7856043ccd3f46992c6939af22 Mon Sep 17 00:00:00 2001 From: Hartorn Date: Fri, 18 Aug 2017 14:24:17 +0200 Subject: [PATCH 25/32] Updating lodash import, changing require to import --- .gitignore | 1 + src/application/action-builder.js | 286 +++++++++--------- src/application/index.js | 4 +- src/application/render.js | 15 +- src/component/builder.js | 14 +- src/component/types.js | 18 +- src/definition/check-domains.js | 12 +- src/definition/domain/container.js | 24 +- .../entity/__tests__/container-test.js | 2 +- src/definition/entity/builder.js | 14 +- src/definition/entity/container.js | 20 +- src/definition/validator/number.js | 11 +- src/definition/validator/string-length.js | 3 +- src/definition/validator/validate.js | 15 +- src/exception/argument-null-exception.js | 6 +- src/exception/dependency-exception.js | 6 +- src/exception/focus-exception.js | 10 +- src/exception/not-implemented-exception.js | 6 +- src/list/load-action/builder.js | 20 +- src/message/built-in-store.js | 2 +- src/message/index.js | 69 +++-- src/network/__tests__/error-parser-test.js | 2 +- src/network/built-in-store.js | 2 +- src/network/config.js | 25 +- src/network/error-parsing.js | 4 +- src/network/fetch.js | 36 +-- src/reference/built-in-store.js | 2 +- src/reference/config.js | 44 +-- src/search/action-builder.js | 56 ++-- src/search/built-in-store.js | 4 +- src/search/index.js | 3 +- src/search/search-action/index.js | 48 +-- src/site-description/builder.js | 197 ++++++------ src/site-description/index.js | 14 +- src/site-description/reader.js | 151 ++++----- src/store/CoreStore.js | 63 ++-- src/store/application/store.js | 38 +-- src/store/list/index.js | 24 +- src/store/message/store.js | 142 ++++----- src/store/request/store.js | 170 +++++------ src/store/search/quick-search/index.js | 16 +- src/store/search/search-store.js | 4 +- src/store/user/store.js | 14 +- src/user/built-in-store.js | 2 +- src/user/index.js | 26 +- src/util/object/checkIsNotNull.js | 15 +- src/util/url/builder.js | 32 +- src/util/url/processor.js | 6 +- 48 files changed, 861 insertions(+), 837 deletions(-) diff --git a/.gitignore b/.gitignore index 73b849f..9778278 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ dist /user /util index.js +.history \ No newline at end of file diff --git a/src/application/action-builder.js b/src/application/action-builder.js index 563d275..6d8eb6e 100644 --- a/src/application/action-builder.js +++ b/src/application/action-builder.js @@ -1,143 +1,143 @@ -import dispatcher from '../dispatcher'; -import {manageResponseErrors} from '../network/error-parsing'; -import {isArray} from 'lodash/lang'; -import {identity} from 'lodash/utility'; - -/** - * Method call before the service. - * @param {Object} config - The action builder config. - */ -function _preServiceCall({node, type, preStatus, callerId, shouldDumpStoreOnActionCall}, payload){ - //There is a problem if the node is empty. //Node should be an array - let data = {}; - let status = {}; - const STATUS = {name: preStatus, isLoading: true}; - type = shouldDumpStoreOnActionCall ? 'update' : 'updateStatus'; - // When there is a multi node update it should be an array. - if(isArray(node)){ - node.forEach((nd)=>{ - data[nd] = shouldDumpStoreOnActionCall ? null : (payload && payload[nd]) || null; - status[nd] = STATUS; - }); - }else{ - data[node] = shouldDumpStoreOnActionCall ? null : (payload || null); - status[node] = STATUS; - } - //Dispatch store cleaning. - dispatcher.handleViewAction({data, type, status, callerId}); -} -/** - * Method call after the service call. - * @param {Object} config - Action builder config. - * @param {object} json - The data return from the service call. - */ -function _dispatchServiceResponse({node, type, status, callerId}, json){ - const isMultiNode = isArray(node); - const data = isMultiNode ? json : {[node]: json}; - const postStatus = {name: status, isLoading: false}; - let newStatus = {}; - if(isMultiNode){ - node.forEach((nd)=>{newStatus[nd] = postStatus; }); - }else { - newStatus[node] = postStatus; - } - dispatcher.handleServerAction({ - data, - type, - status: newStatus, - callerId - }); -} -/** - * The main objective of this function is to cancel the loading state on all the nodes concerned by the service call. - */ -function _dispatchFieldErrors({node, callerId}, errorResult){ - const isMultiNode = isArray(node); - const data = {}; - if(isMultiNode){ - node.forEach((nd) => { - data[nd] = (errorResult || {})[nd] || null; - }); - } else { - data[node] = errorResult; - } - - const errorStatus = { - name: 'error', - isLoading: false - }; - let newStatus = {}; - if(isMultiNode){ - node.forEach((nd) => { - newStatus[nd] = errorStatus; - }); - } else { - newStatus[node] = errorStatus; - } - dispatcher.handleServerAction({ - data, - type: 'updateError', - status: newStatus, - callerId - }); -} - -function _dispatchGlobalErrors(conf , errors){ - //console.warn('NOT IMPLEMENTED', conf, errors); -} - -/** - * Method call when there is an error. - * @param {object} config - The action builder configuration. - * @param {object} err - The error from the API call. - * @return {object} - The data from the manageResponseErrors function. - */ -function _errorOnCall(config, err){ - const errorResult = manageResponseErrors(err, config); - _dispatchGlobalErrors(config, errorResult.globals); - _dispatchFieldErrors(config, errorResult.fields); -} - -/** - * Action builder function. - * @param {object} config - The action builder configuration should contain: - * - type(:string) - Is the action an update, a load, a save. - * - preStatus(:string) The status to dispatch before the calling. - * - service(:function) The service to call for the action. Should return a Promise. - * - status(:string)} The status after the action. - * @return {function} - The build action from the configuration. This action dispatch the preStatus, call the service and dispatch the result from the server. - */ -export default function actionBuilder(config = {}){ - config.type = config.type || 'update'; - config.preStatus = config.preStatus || 'loading'; - config.shouldDumpStoreOnActionCall = config.shouldDumpStoreOnActionCall || false; - if(!config.service){ - throw new Error('You need to provide a service to call'); - } - if(!config.status){ - throw new Error('You need to provide a status to your action'); - } - if(!config.node){ - throw new Error('You shoud specify the store node name impacted by the action'); - } - return function actionBuilderFn(payload, context) { - context = context || this; - const conf = { - callerId: context._identifier, - postService: identity, ...config - }; - const {postService} = conf; - _preServiceCall(conf, payload); - return conf.service(payload).then(postService).then((jsonData)=>{ - return _dispatchServiceResponse(conf, jsonData); - }, (err) => { - _errorOnCall(conf, err); - }); - }; -}; - -export { - _errorOnCall as errorOnCall, - _dispatchServiceResponse as dispatchServiceResponse, - _preServiceCall as preServiceCall - }; +import dispatcher from '../dispatcher'; +import { manageResponseErrors } from '../network/error-parsing'; +import isArray from 'lodash/lang/isArray'; +import identity from 'lodash/utility/identity'; + +/** + * Method call before the service. + * @param {Object} config - The action builder config. + */ +function _preServiceCall({ node, type, preStatus, callerId, shouldDumpStoreOnActionCall }, payload) { + //There is a problem if the node is empty. //Node should be an array + let data = {}; + let status = {}; + const STATUS = { name: preStatus, isLoading: true }; + type = shouldDumpStoreOnActionCall ? 'update' : 'updateStatus'; + // When there is a multi node update it should be an array. + if (isArray(node)) { + node.forEach((nd) => { + data[nd] = shouldDumpStoreOnActionCall ? null : (payload && payload[nd]) || null; + status[nd] = STATUS; + }); + } else { + data[node] = shouldDumpStoreOnActionCall ? null : (payload || null); + status[node] = STATUS; + } + //Dispatch store cleaning. + dispatcher.handleViewAction({ data, type, status, callerId }); +} +/** + * Method call after the service call. + * @param {Object} config - Action builder config. + * @param {object} json - The data return from the service call. + */ +function _dispatchServiceResponse({ node, type, status, callerId }, json) { + const isMultiNode = isArray(node); + const data = isMultiNode ? json : { [node]: json }; + const postStatus = { name: status, isLoading: false }; + let newStatus = {}; + if (isMultiNode) { + node.forEach((nd) => { newStatus[nd] = postStatus; }); + } else { + newStatus[node] = postStatus; + } + dispatcher.handleServerAction({ + data, + type, + status: newStatus, + callerId + }); +} +/** + * The main objective of this function is to cancel the loading state on all the nodes concerned by the service call. + */ +function _dispatchFieldErrors({ node, callerId }, errorResult) { + const isMultiNode = isArray(node); + const data = {}; + if (isMultiNode) { + node.forEach((nd) => { + data[nd] = (errorResult || {})[nd] || null; + }); + } else { + data[node] = errorResult; + } + + const errorStatus = { + name: 'error', + isLoading: false + }; + let newStatus = {}; + if (isMultiNode) { + node.forEach((nd) => { + newStatus[nd] = errorStatus; + }); + } else { + newStatus[node] = errorStatus; + } + dispatcher.handleServerAction({ + data, + type: 'updateError', + status: newStatus, + callerId + }); +} + +function _dispatchGlobalErrors(conf, errors) { + //console.warn('NOT IMPLEMENTED', conf, errors); +} + +/** + * Method call when there is an error. + * @param {object} config - The action builder configuration. + * @param {object} err - The error from the API call. + * @return {object} - The data from the manageResponseErrors function. + */ +function _errorOnCall(config, err) { + const errorResult = manageResponseErrors(err, config); + _dispatchGlobalErrors(config, errorResult.globals); + _dispatchFieldErrors(config, errorResult.fields); +} + +/** + * Action builder function. + * @param {object} config - The action builder configuration should contain: + * - type(:string) - Is the action an update, a load, a save. + * - preStatus(:string) The status to dispatch before the calling. + * - service(:function) The service to call for the action. Should return a Promise. + * - status(:string)} The status after the action. + * @return {function} - The build action from the configuration. This action dispatch the preStatus, call the service and dispatch the result from the server. + */ +export default function actionBuilder(config = {}) { + config.type = config.type || 'update'; + config.preStatus = config.preStatus || 'loading'; + config.shouldDumpStoreOnActionCall = config.shouldDumpStoreOnActionCall || false; + if (!config.service) { + throw new Error('You need to provide a service to call'); + } + if (!config.status) { + throw new Error('You need to provide a status to your action'); + } + if (!config.node) { + throw new Error('You shoud specify the store node name impacted by the action'); + } + return function actionBuilderFn(payload, context) { + context = context || this; + const conf = { + callerId: context._identifier, + postService: identity, ...config + }; + const { postService } = conf; + _preServiceCall(conf, payload); + return conf.service(payload).then(postService).then((jsonData) => { + return _dispatchServiceResponse(conf, jsonData); + }, (err) => { + _errorOnCall(conf, err); + }); + }; +} + +export { + _errorOnCall as errorOnCall, + _dispatchServiceResponse as dispatchServiceResponse, + _preServiceCall as preServiceCall +}; diff --git a/src/application/index.js b/src/application/index.js index 54ea827..8ed7180 100644 --- a/src/application/index.js +++ b/src/application/index.js @@ -1,9 +1,9 @@ import React from 'react'; import dispatcher from '../dispatcher'; -import { isUndefined } from 'lodash/lang'; +import isUndefined from 'lodash/lang/isUndefined'; import confirm from './confirm'; //Empty compoennt. -const Empty = props =>
; +const Empty = props =>
; Empty.displayName = 'Empty'; module.exports = { diff --git a/src/application/render.js b/src/application/render.js index 9c0b816..1052c33 100644 --- a/src/application/render.js +++ b/src/application/render.js @@ -1,10 +1,9 @@ /*global document*/ //dependencies -const React = require('react'); -const ReactDOM = require('react-dom'); -const keys = require('lodash/object/keys'); -const mountedComponents = require('./mounted-components'); -const clearComponent = require('./clear'); +import React from 'react'; +import ReactDOM from 'react-dom'; +import mountedComponents from './mounted-components'; +import clearComponent from './clear'; /** * Render a react component in a DOM selector. @@ -12,12 +11,12 @@ const clearComponent = require('./clear'); * @param {string} selector - A selector on a DOM node. * @param {object} options - Options for the component rendering. */ -module.exports = function renderComponent(component, selector, options){ +module.exports = function renderComponent(component, selector, options) { options = options || {}; // Clear a potential previously mounted component clearComponent(selector); const targetDOMContainer = document.querySelector(selector); - if(!targetDOMContainer){ + if (!targetDOMContainer) { throw new Error(`You are trying to render a component in a DOM element which is not existing, your selector is ${selector}`); } // Render the component @@ -27,7 +26,7 @@ module.exports = function renderComponent(component, selector, options){ ); //Save the fact that a component is mounted. mountedComponents[selector] = mountedComponent; - console.info('Mounted components : ', keys(mountedComponents)); + console.info('Mounted components : ', Object.keys(mountedComponents)); return mountedComponent; }; /* diff --git a/src/component/builder.js b/src/component/builder.js index 54831a3..45e10e3 100644 --- a/src/component/builder.js +++ b/src/component/builder.js @@ -1,5 +1,5 @@ -const React = require('react'); -const assign = require('object-assign'); +import React from 'react'; +import assign from 'object-assign'; //var isObject = require('lodash/lang/isObject'); //var isFunction = require('lodash/lang/isFunction'); @@ -9,11 +9,11 @@ const assign = require('object-assign'); * @param {Boolean} isMixinOnly - define if the component is a mixin only. * @return {object} - {component} the built react component. */ -function createComponent(mixin, isMixinOnly){ - if (isMixinOnly){ +function createComponent(mixin, isMixinOnly) { + if (isMixinOnly) { return null; } - return {component: React.createClass(mixin)}; + return { component: React.createClass(mixin) }; } /** @@ -22,9 +22,9 @@ function createComponent(mixin, isMixinOnly){ * @param {boolean} isMixinOnly - Bolean to set . * @return {object} {mixin: 'the component mixin', component: 'the react instanciated component'} */ -module.exports = function builder(componentMixin, isMixinOnly){ +module.exports = function builder(componentMixin, isMixinOnly) { return assign( - {mixin: componentMixin}, + { mixin: componentMixin }, createComponent(componentMixin, isMixinOnly) ); }; diff --git a/src/component/types.js b/src/component/types.js index 8906be7..33bc340 100644 --- a/src/component/types.js +++ b/src/component/types.js @@ -1,7 +1,7 @@ //Dependencies. -const React = require('react'); -const isString = require('lodash/lang/isString'); -const isArray = require('lodash/lang/isArray'); +import React from 'react'; +import isString from 'lodash/lang/isString'; +import isArray from 'lodash/lang/isArray'; /** * Expose a React type validation for the component properties validation. @@ -10,25 +10,25 @@ const isArray = require('lodash/lang/isArray'); * @param {boolean} isRequired - Defines if the props is mandatory. * @return {object} The corresponding react type. */ -module.exports = function types(type, isRequired){ +module.exports = function types(type, isRequired) { const isStringType = isString(type); - if(!isStringType && !isArray(type)){ + if (!isStringType && !isArray(type)) { throw new Error('The type should be a string or an array'); } //Container for the propTypes. let propTypeToReturn; //Array case. - if(isStringType){ + if (isStringType) { propTypeToReturn = React.PropTypes[type]; - }else { + } else { propTypeToReturn = React.PropTypes.oneOfType( type.map( - (t)=>{ + (t) => { return React.PropTypes[t]; })); } //Mandatory case - if(isRequired){ + if (isRequired) { propTypeToReturn = propTypeToReturn.isRequired; } return propTypeToReturn; diff --git a/src/definition/check-domains.js b/src/definition/check-domains.js index ba1687a..9cd5fb4 100644 --- a/src/definition/check-domains.js +++ b/src/definition/check-domains.js @@ -1,7 +1,9 @@ -const keys = require('lodash/object/keys'); -let {intersection, uniq, difference} = require('lodash/array'); +import keys from 'lodash/object/keys'; +import intersection from 'lodash/array/intersection'; +import uniq from 'lodash/array/uniq'; +import difference from 'lodash/array/difference'; -module.exports = function checkDomain(entityDef, domains){ +module.exports = function checkDomain(entityDef, domains) { domains = keys(domains); let arr = []; for (let node in entityDef) { @@ -14,11 +16,11 @@ module.exports = function checkDomain(entityDef, domains){ console.info('Entity definitions domains: ', appDomains); console.info('Domains with a definition', domains); const missingDomains = difference(appDomains, intersection(appDomains, domains)); - if(0 < missingDomains.length){ + if (0 < missingDomains.length) { console.warn('Missing domain\'s definition', missingDomains); } const useLessDomains = difference(domains, intersection(appDomains, domains)); - if(0 < useLessDomains){ + if (0 < useLessDomains) { console.warn('Useless domain definition', useLessDomains); } console.info('####################################################################'); diff --git a/src/definition/domain/container.js b/src/definition/domain/container.js index 97785ab..4c5a9bd 100644 --- a/src/definition/domain/container.js +++ b/src/definition/domain/container.js @@ -1,10 +1,10 @@ //Dependencies. -const Immutable = require('immutable'); -const isObject = require('lodash/lang/isObject'); -const isString = require('lodash/lang/isString'); +import Immutable from 'immutable'; +import isObject from 'lodash/lang/isObject'; +import isString from 'lodash/lang/isString'; const InvalidException = Error; -const checkIsString = require('../../util/string/check'); -const checkIsObject = require('../../util/object/check'); +import checkIsString from '../../util/string/check'; +import checkIsObject from '../../util/object/check'; /** * Container for the application domains. @@ -16,7 +16,7 @@ let domainsMap = Immutable.Map({}); * Get all domains in a js object. * @return {object} - All domains. */ -function getDomains(){ +function getDomains() { return domainsMap.toJS(); } @@ -25,8 +25,8 @@ function getDomains(){ * @param {object} newDomains - New domains to set. * à */ -function setDomains(newDomains){ - if(!isObject(newDomains)){ +function setDomains(newDomains) { + if (!isObject(newDomains)) { throw new InvalidException('newDomains should be an object', newDomains); } domainsMap = domainsMap.merge(newDomains); @@ -37,7 +37,7 @@ function setDomains(newDomains){ * Set a domain. * @param {object} domain - Object structure of the domain. */ -function setDomain(domain){ +function setDomain(domain) { checkIsObject('domain', domain); checkIsString('doamin.name', domain.name); //test domain, domain.name @@ -49,11 +49,11 @@ function setDomain(domain){ * @param {string} domainName - name of the domain. * @return {object} - The domain object. */ -function getDomain(domainName){ - if(!isString(domainName)){ +function getDomain(domainName) { + if (!isString(domainName)) { throw new InvalidException('domaiName should extists and be a string', domainName); } - if(!domainsMap.has(domainName)){ + if (!domainsMap.has(domainName)) { console.warn(`You are trying to access a non existing domain: ${domainName}`); return Immutable.Map({}); } diff --git a/src/definition/entity/__tests__/container-test.js b/src/definition/entity/__tests__/container-test.js index e5ba526..8f9d4b5 100644 --- a/src/definition/entity/__tests__/container-test.js +++ b/src/definition/entity/__tests__/container-test.js @@ -1,7 +1,7 @@ /*global expect, describe, it*/ // __tests__/container-test.js -const entityConfigurationMock = require('./entityConfigurationMock.json'); +import entityConfigurationMock from './entityConfigurationMock.json'; describe('### entity container', () => { it('getEntityConfiguration should be empty by default', () => { diff --git a/src/definition/entity/builder.js b/src/definition/entity/builder.js index b3ba9e2..f8eee56 100644 --- a/src/definition/entity/builder.js +++ b/src/definition/entity/builder.js @@ -1,15 +1,15 @@ -const Immutable = require('immutable'); -const checkIsString = require('../../util/string/check'); -const checkIsObject = require('../../util/object/check'); -const checkIsNotNull = require('../../util/object/checkIsNotNull'); +import Immutable from 'immutable'; +import checkIsString from '../../util/string/check'; +import checkIsObject from '../../util/object/check'; +import checkIsNotNull from '../../util/object/checkIsNotNull'; const SEPARATOR = '.'; /** * Pointer to the domain contaier. * @type {Object} */ -const domainContainer = require('../domain/container'); -const entityContainer = require('./container'); +import domainContainer from '../domain/container'; +import entityContainer from './container'; let computedEntityContainer = Immutable.Map({}); /* @@ -50,7 +50,7 @@ function _buildFieldInformation(fieldPath) { const fieldConf = entityContainer.getFieldConfiguration(fieldPath); const immutableFieldConf = Immutable.Map(fieldConf); //Maybe add a domain check existance - let {domain} = fieldConf; + let { domain } = fieldConf; return domainContainer.get(domain).mergeDeep(immutableFieldConf); } diff --git a/src/definition/entity/container.js b/src/definition/entity/container.js index 19c8cbc..9107017 100644 --- a/src/definition/entity/container.js +++ b/src/definition/entity/container.js @@ -1,7 +1,7 @@ //Dependencies. -const Immutable = require('immutable'); -const checkIsString = require('../../util/string/check'); -const checkIsObject = require('../../util/object/check'); +import Immutable from 'immutable'; +import checkIsString from '../../util/string/check'; +import checkIsObject from '../../util/object/check'; /** * Separator for the configuration @@ -21,9 +21,9 @@ let entitiesMap = Immutable.Map({}); * @param {object} extendedEntityConfiguration - The object to extend the config. * @return {object} - The entity configuration from a given path. */ -function getEntityConfiguration(nodePath, extendedEntityConfiguration){ +function getEntityConfiguration(nodePath, extendedEntityConfiguration) { //If a node is specified get the direct sub conf. - if(nodePath){ + if (nodePath) { return _getNode(nodePath, extendedEntityConfiguration).toJS(); } return entitiesMap.toJS(); @@ -33,7 +33,7 @@ function getEntityConfiguration(nodePath, extendedEntityConfiguration){ * Set new entities in the map or extend existing one. * @param {object} newEntities - new entities description */ -function setEntityConfiguration(newEntities){ +function setEntityConfiguration(newEntities) { checkIsObject('newEntities', newEntities); entitiesMap = entitiesMap.mergeDeep(newEntities); } @@ -45,9 +45,9 @@ function setEntityConfiguration(newEntities){ * @param {object} extendedConfiguration - The object to extend the config. * @return {object} - The node configuration. */ -function _getNode(nodePath, extendedConfiguration){ +function _getNode(nodePath, extendedConfiguration) { checkIsString('nodePath', nodePath); - if(!entitiesMap.hasIn(nodePath.split(SEPARATOR))){ + if (!entitiesMap.hasIn(nodePath.split(SEPARATOR))) { console.warn(` It seems the definition your are trying to use does not exists in the entity definitions of your project. The definition you want is ${nodePath} and the definition map is: @@ -56,7 +56,7 @@ function _getNode(nodePath, extendedConfiguration){ throw new Error('Wrong definition path given, see waning for more details'); } let conf = entitiesMap.getIn(nodePath.split(SEPARATOR)); - if(extendedConfiguration){ + if (extendedConfiguration) { checkIsObject(extendedConfiguration); conf = conf.mergeDeep(extendedConfiguration); } @@ -69,7 +69,7 @@ function _getNode(nodePath, extendedConfiguration){ * @param {object} customFieldConf - The object to extend the config. * @return {object} - The field configuration. */ -function getFieldConfiguration(fieldPath, customFieldConf){ +function getFieldConfiguration(fieldPath, customFieldConf) { return _getNode(fieldPath, customFieldConf).toJS(); } diff --git a/src/definition/validator/number.js b/src/definition/validator/number.js index 6b1e8e8..4c5543e 100644 --- a/src/definition/validator/number.js +++ b/src/definition/validator/number.js @@ -1,11 +1,14 @@ -let {isUndefined, isNull, isNaN, isNumber} = require('lodash/lang'); +import isUndefined from 'lodash/lang/isUndefined'; +import isNull from 'lodash/lang/isNull'; +import isNaN from 'lodash/lang/isNaN'; +import isNumber from 'lodash/lang/isNumber'; /* Function to validate that an input is a number. * @param {string || number} numberToValidate - Number to validate with the function. * @param {object} options = {}, Allow the caller to specify min and max values. * @return {boolean} True if the validator works. */ -module.exports = function numberValidation(numberToValidate, options = {}) { +export default function numberValidation(numberToValidate, options = {}) { if (isUndefined(numberToValidate) || isNull(numberToValidate)) { return true; } @@ -13,10 +16,10 @@ module.exports = function numberValidation(numberToValidate, options = {}) { if (isNaN(castNumberToValidate)) { return false; } - if(!isNumber(castNumberToValidate)){ + if (!isNumber(castNumberToValidate)) { return false; } let isMin = options.min !== undefined ? castNumberToValidate >= options.min : true; let isMax = options.max !== undefined ? castNumberToValidate <= options.max : true; return isMin && isMax; -}; +} diff --git a/src/definition/validator/string-length.js b/src/definition/validator/string-length.js index 60dade3..bc81c81 100644 --- a/src/definition/validator/string-length.js +++ b/src/definition/validator/string-length.js @@ -1,4 +1,5 @@ -let {isString} = require('lodash/lang'); +import isString from 'lodash/lang/isString'; + /** * Validate a string given options. * @param {string} stringToTest - The string to test. diff --git a/src/definition/validator/validate.js b/src/definition/validator/validate.js index 1d89b82..281acd8 100644 --- a/src/definition/validator/validate.js +++ b/src/definition/validator/validate.js @@ -1,13 +1,14 @@ //Dependency -import {DependencyException} from '../../exception'; +import { DependencyException } from '../../exception'; import assign from 'object-assign'; -import {translate} from '../../translation'; +import { translate } from '../../translation'; //Focus validators import emailValidation from './email'; import numberValidation from './number'; import stringLength from './string-length'; import dateValidation from './date'; -import {isNull, isUndefined} from 'lodash/lang'; +import isNull from 'lodash/lang/isNull'; +import isUndefined from 'lodash/lang/isUndefined'; /** * Validae a property given validators. @@ -50,9 +51,9 @@ function validateProperty(property, validator) { if (!property) { return void 0; } - const {value} = property; - const {options} = validator; - const isValueNullOrUndefined = isNull(value) || isUndefined(value ); + const { value } = property; + const { options } = validator; + const isValueNullOrUndefined = isNull(value) || isUndefined(value); isValid = (() => { switch (validator.type) { case 'required': @@ -99,7 +100,7 @@ function validateProperty(property, validator) { function getErrorLabel(type, fieldName, options = {}) { options = options || {}; const translationKey = options.translationKey ? options.translationKey : `domain.validation.${type}`; - const opts = {fieldName: translate(fieldName), ...options}; + const opts = { fieldName: translate(fieldName), ...options }; return translate(translationKey, opts); } diff --git a/src/exception/argument-null-exception.js b/src/exception/argument-null-exception.js index 77b2966..d833cdc 100644 --- a/src/exception/argument-null-exception.js +++ b/src/exception/argument-null-exception.js @@ -1,14 +1,14 @@ -const CustomException = require('./custom-exception'); +import CustomException from './custom-exception'; /** * Class standing for the NotImplemented exceptions. */ -class ArgumentNullException extends CustomException{ +class ArgumentNullException extends CustomException { /** * Exception constructor.. * @param message {string} - Exception message. * @param options {object} - Object to add to the exception. */ - constructor(message, options){ + constructor(message, options) { super('ArgumentNullException', message, options); } } diff --git a/src/exception/dependency-exception.js b/src/exception/dependency-exception.js index e27f06f..08e94c4 100644 --- a/src/exception/dependency-exception.js +++ b/src/exception/dependency-exception.js @@ -1,14 +1,14 @@ -const CustomException = require('./custom-exception'); +import CustomException from './custom-exception'; /** * Class standing for the NotImplemented exceptions. */ -class DependencyException extends CustomException{ +class DependencyException extends CustomException { /** * Exception constructor.. * @param message {string} - Exception message. * @param options {object} - Object to add to the exception. */ - constructor(message, options){ + constructor(message, options) { super('DependencyException', message, options); } } diff --git a/src/exception/focus-exception.js b/src/exception/focus-exception.js index ac29681..b4b151c 100644 --- a/src/exception/focus-exception.js +++ b/src/exception/focus-exception.js @@ -1,16 +1,16 @@ -const CustomException = require('./custom-exception'); +import CustomException from './custom-exception'; /** * Class standing for the FocusException exceptions. */ class FocusException extends CustomException { - /** + /** * Exception constructor.. * @param messgae {string} - Exception message. * @param options {object} - Object to add to the exception. */ - constructor(message, options) { - super('FocusException', message, options); - } + constructor(message, options) { + super('FocusException', message, options); + } } module.exports = FocusException; diff --git a/src/exception/not-implemented-exception.js b/src/exception/not-implemented-exception.js index 7768a36..f94add5 100644 --- a/src/exception/not-implemented-exception.js +++ b/src/exception/not-implemented-exception.js @@ -1,14 +1,14 @@ -const CustomException = require('./custom-exception'); +import CustomException from './custom-exception'; /** * Class standing for the NotImplemented exceptions. */ -class NotImplementedException extends CustomException{ +class NotImplementedException extends CustomException { /** * Exception constructor. * @param message {string} - Exception message. * @param options {object} - Object to add to the exception. */ - constructor(message, options){ + constructor(message, options) { super('NotImplementedException', message, options); } } diff --git a/src/list/load-action/builder.js b/src/list/load-action/builder.js index 87080f0..7699f7f 100644 --- a/src/list/load-action/builder.js +++ b/src/list/load-action/builder.js @@ -1,14 +1,14 @@ -let keys = require('lodash/object/keys'); -let isArray = require('lodash/lang/isArray'); +import keys from 'lodash/object/keys'; +import isArray from 'lodash/lang/isArray'; /** * Build sort infotmation. * @param {object} sortConf - The sort configuration. * @return {object} - The builded sort configuration. */ -function _buildOrderAndSort(sortConf){ +function _buildOrderAndSort(sortConf) { return { sortFieldName: sortConf.sortBy, - sortDesc: sortConf.sortAsc===undefined?false:!sortConf.sortAsc + sortDesc: sortConf.sortAsc === undefined ? false : !sortConf.sortAsc }; } @@ -21,14 +21,14 @@ function _buildOrderAndSort(sortConf){ * nbSearchElement (:number) - The number of elements you want to get back from the search. * @return {object} - An object with {top, skip}. */ -function _buildPagination(opts){ - let {isScroll, dataList, totalCount, nbElement} = opts; - if(isScroll){ - if(!isArray(dataList)){ +function _buildPagination(opts) { + let { isScroll, dataList, totalCount, nbElement } = opts; + if (isScroll) { + if (!isArray(dataList)) { throw new Error('The data list options sould exist and be an array') } - if(dataList.length < totalCount){ - return {top: nbElement, skip: dataList.length}; + if (dataList.length < totalCount) { + return { top: nbElement, skip: dataList.length }; } } return { diff --git a/src/message/built-in-store.js b/src/message/built-in-store.js index 8a9207c..b66ab4c 100644 --- a/src/message/built-in-store.js +++ b/src/message/built-in-store.js @@ -1,4 +1,4 @@ -const MessageStore = require('../store/message'); +import MessageStore from '../store/message'; /** * Built the store in order to the . * @return {MessageStore} - An instanciated reference store. diff --git a/src/message/index.js b/src/message/index.js index 74fdd52..50b487b 100644 --- a/src/message/index.js +++ b/src/message/index.js @@ -1,5 +1,5 @@ -var dispatcher = require('../dispatcher'); -var isString = require('lodash/lang/isString'); +import dispatcher from '../dispatcher'; +import isString from 'lodash/lang/isString'; /** * Transform the message into objet if it is a string. @@ -7,8 +7,8 @@ var isString = require('lodash/lang/isString'); * @returns {object} - The well constructed message. */ function _parseString(message) { - if(isString(message)) { - message = {content: message}; + if (isString(message)) { + message = { content: message }; } return message; } @@ -17,64 +17,63 @@ function _parseString(message) { * Add a message. * @param {object} message - The message object. */ -function addMessage(message){ - dispatcher.handleServerAction({ - data: {message: message}, - type: 'push' - }); +function addMessage(message) { + dispatcher.handleServerAction({ + data: { message: message }, + type: 'push' + }); } /** * Add an error message. * @param {object} message - The message content. */ -function addErrorMessage(message){ - message = _parseString(message); - message.type = 'error'; - addMessage(message); +function addErrorMessage(message) { + message = _parseString(message); + message.type = 'error'; + addMessage(message); } /** * Add a warning message. * @param {object} message - The message content. */ -function addWarningMessage(message){ - message = _parseString(message); - message.type = 'warning'; - addMessage(message); +function addWarningMessage(message) { + message = _parseString(message); + message.type = 'warning'; + addMessage(message); } /** * Add an information message. * @param {object} message - The message content. */ -function addInformationMessage(message){ - message = _parseString(message); - message.type = 'info'; - addMessage(message); +function addInformationMessage(message) { + message = _parseString(message); + message.type = 'info'; + addMessage(message); } /** * Add a success message. * @param {object} message - The message content. */ -function addSuccessMessage(message){ - message = _parseString(message); - message.type = 'success'; - addMessage(message); +function addSuccessMessage(message) { + message = _parseString(message); + message.type = 'success'; + addMessage(message); } -function clearMessages(){ - dispatcher.handleServerAction({data: {messages: {}}, type: 'clear'}); +function clearMessages() { + dispatcher.handleServerAction({ data: { messages: {} }, type: 'clear' }); } - module.exports = { - addMessage: addMessage, - addWarningMessage: addWarningMessage, - addInformationMessage: addInformationMessage, - addErrorMessage: addErrorMessage, - addSuccessMessage: addSuccessMessage, - clearMessages: clearMessages, - builtInStore: require('./built-in-store') + addMessage: addMessage, + addWarningMessage: addWarningMessage, + addInformationMessage: addInformationMessage, + addErrorMessage: addErrorMessage, + addSuccessMessage: addSuccessMessage, + clearMessages: clearMessages, + builtInStore: require('./built-in-store') }; diff --git a/src/network/__tests__/error-parser-test.js b/src/network/__tests__/error-parser-test.js index 3a68a1c..ea19095 100644 --- a/src/network/__tests__/error-parser-test.js +++ b/src/network/__tests__/error-parser-test.js @@ -1,6 +1,6 @@ /* global it, describe, expect */ import { manageResponseErrors as errorParser } from '../error-parsing'; -import { omit } from 'lodash/object'; +import omit from 'lodash/object/omit'; const NODE_OPTS = { node: 'field1' }; const NODES_OPTS = { node: ['field1', 'field2'] }; diff --git a/src/network/built-in-store.js b/src/network/built-in-store.js index 8c6a141..e389839 100644 --- a/src/network/built-in-store.js +++ b/src/network/built-in-store.js @@ -1,4 +1,4 @@ -const RequestStore = require('../store/request'); +import RequestStore from '../store/request'; /** * Built the store in order to the . * @return {RequestStore} - An instanciated application store. diff --git a/src/network/config.js b/src/network/config.js index 2b9c443..d357d2d 100644 --- a/src/network/config.js +++ b/src/network/config.js @@ -1,30 +1,31 @@ -let merge = require('lodash/object/merge'); -let {isObject, clone} = require('lodash/lang'); +import merge from 'lodash/object/merge'; +import isObject from 'lodash/lang/isObject'; +import clone from 'lodash/lang/clone'; /** * Configuration object. * @type {{CORS: boolean}} */ let configuration = { - CORS: true, - xhrErrors: {} + CORS: true, + xhrErrors: {} }; /** * Function which overrides the configuration. * @param conf */ -function configure(conf){ - if(isObject(conf)){ - merge(configuration, conf); - } +function configure(conf) { + if (isObject(conf)) { + merge(configuration, conf); + } } module.exports = { - configure: configure, - get(){ - return clone(configuration); - } + configure: configure, + get() { + return clone(configuration); + } }; diff --git a/src/network/error-parsing.js b/src/network/error-parsing.js index ecb1791..9c3b99b 100644 --- a/src/network/error-parsing.js +++ b/src/network/error-parsing.js @@ -1,4 +1,6 @@ -import { isObject, isArray } from 'lodash'; +import isObject from 'lodash/lang/isObject'; +import isArray from 'lodash/lang/isArray'; + import { getAll as getDomains } from '../definition/domain/container'; import { addMessage } from '../message'; diff --git a/src/network/fetch.js b/src/network/fetch.js index f2379e0..ea0b24e 100644 --- a/src/network/fetch.js +++ b/src/network/fetch.js @@ -2,11 +2,11 @@ * Dependency on the CORS module. * @type {object} */ -let createCORSRequest = require('./cors'); -let cancellablePromiseBuilder = require('./cancellable-promise-builder'); +import createCORSRequest from './cors'; +import cancellablePromiseBuilder from './cancellable-promise-builder'; let uuid = require('uuid').v4; -let dispatcher = require('../dispatcher'); -let isObject = require('lodash/lang/isObject'); +import dispatcher from '../dispatcher'; +import isObject from 'lodash/lang/isObject'; /** * Create a pending status. @@ -24,9 +24,9 @@ function createRequestStatus() { * @return {object} - The request to dispatch. */ function updateRequestStatus(request) { - if(!request || !request.id || !request.status) {return; } + if (!request || !request.id || !request.status) { return; } dispatcher.handleViewAction({ - data: {request: request}, + data: { request: request }, type: 'update' }); return request; @@ -37,21 +37,21 @@ function updateRequestStatus(request) { * @return {object} - The parsed object. */ function jsonParser(req) { - if(null === req.responseText || null === req.responseText || '' === req.responseText) { + if (null === req.responseText || null === req.responseText || '' === req.responseText) { console.warn('The response of your request was empty'); return null; } let parsedObject; try { parsedObject = JSON.parse(req.responseText); - } catch(error) { + } catch (error) { parsedObject = { globalErrors: [{ message: `${req.status} error when calling ${req.responseURL}` }] }; } - if(!isObject(parsedObject)) { + if (!isObject(parsedObject)) { //Maybe this check should read the header content-type console.warn('The response did not sent a JSON object'); } @@ -68,7 +68,7 @@ function fetch(obj, options = {}) { options.parser = options.parser || jsonParser; options.errorParser = options.errorParser || jsonParser; let config = require('./config').get(); - let request = createCORSRequest(obj.method, obj.url, {...config, ...options}); + let request = createCORSRequest(obj.method, obj.url, { ...config, ...options }); let requestStatus = createRequestStatus(); if (!request) { throw new Error('You cannot perform ajax request on other domains.'); @@ -77,24 +77,24 @@ function fetch(obj, options = {}) { return cancellablePromiseBuilder(function promiseFn(success, failure) { //Request error handler request.onerror = error => { - updateRequestStatus({id: requestStatus.id, status: 'error'}); + updateRequestStatus({ id: requestStatus.id, status: 'error' }); failure(error); }; //Request success handler request.onload = () => { let status = request.status; - if (status < 200 || status >= 300 ) { + if (status < 200 || status >= 300) { let err = options.errorParser(request); err.status = status; - if(config.xhrErrors[status]) { + if (config.xhrErrors[status]) { config.xhrErrors[status](request.response); } - updateRequestStatus({id: requestStatus.id, status: 'error'}); + updateRequestStatus({ id: requestStatus.id, status: 'error' }); return failure(err); } if (204 === status) { data = undefined; - updateRequestStatus({id: requestStatus.id, status: 'success'}); + updateRequestStatus({ id: requestStatus.id, status: 'success' }); return success(data); } let contentType = request.contentType ? request.contentType : request.getResponseHeader('content-type'); @@ -104,15 +104,15 @@ function fetch(obj, options = {}) { } else { data = request.responseText; } - updateRequestStatus({id: requestStatus.id, status: 'success'}); + updateRequestStatus({ id: requestStatus.id, status: 'success' }); return success(data); }; - updateRequestStatus({id: requestStatus.id, status: 'pending'}); + updateRequestStatus({ id: requestStatus.id, status: 'pending' }); //Execute the request. request.send(JSON.stringify(obj.data)); }, function cancelHandler() { // Promise cancel handler if (request.status === 0) { // request has not yet ended - updateRequestStatus({id: requestStatus.id, status: 'cancelled'}); + updateRequestStatus({ id: requestStatus.id, status: 'cancelled' }); request.abort(); return true; } else { // trying to abort an ended request, send a warning to the console diff --git a/src/reference/built-in-store.js b/src/reference/built-in-store.js index fa74f31..f4cbcfd 100644 --- a/src/reference/built-in-store.js +++ b/src/reference/built-in-store.js @@ -1,4 +1,4 @@ -const ReferenceStore = require('../store/reference'); +import ReferenceStore from '../store/reference'; let ref; diff --git a/src/reference/config.js b/src/reference/config.js index bbf8e6e..bf9315a 100644 --- a/src/reference/config.js +++ b/src/reference/config.js @@ -1,22 +1,22 @@ -var Immutable = require('immutable'); -var config = Immutable.Map({}); -var checkIsObject = require('../util/object/check'); -var checkIsString = require('../util/string/check'); +import Immutable from 'immutable'; +let config = Immutable.Map({}); +import checkIsObject from '../util/object/check'; +import checkIsString from '../util/string/check'; -var cacheDuration = 1000 * 60; +let cacheDuration = 1000 * 60; /** * Sets the cache duration (defaults to 1 min). */ function setCacheDuration(newDuration) { - cacheDuration = newDuration; + cacheDuration = newDuration; } /** * Gets the cache duration. */ function getCacheDuration() { - return cacheDuration; + return cacheDuration; } /** @@ -24,17 +24,17 @@ function getCacheDuration() { * @param {object} newConf - The new configuration to set. * @param {Boolean} isClearPrevious - Does the config should be reset. */ -function setConfig(newConf, isClearPrevious){ - checkIsObject(newConf); - config = isClearPrevious ? Immutable.fromJS(newConf) : config.merge(newConf); +function setConfig(newConf, isClearPrevious) { + checkIsObject(newConf); + config = isClearPrevious ? Immutable.fromJS(newConf) : config.merge(newConf); } /** * Get a configuration copy. * @returns {object} - A copy of the configuration. */ -function getConfig(){ - return config.toJS(); +function getConfig() { + return config.toJS(); } /** @@ -42,18 +42,18 @@ function getConfig(){ * @param {string} name - The key identifier of the configuration. * @returns {object} - The configuration of the list element. */ -function getConfigElement(name){ - checkIsString('name', name); - if(config.has(name)){ - return config.get(name); - } +function getConfigElement(name) { + checkIsString('name', name); + if (config.has(name)) { + return config.get(name); + } } module.exports = { - get: getConfig, - getElement: getConfigElement, - set: setConfig, - getCacheDuration, - setCacheDuration + get: getConfig, + getElement: getConfigElement, + set: setConfig, + getCacheDuration, + setCacheDuration }; diff --git a/src/search/action-builder.js b/src/search/action-builder.js index 39ad662..dd2bb05 100644 --- a/src/search/action-builder.js +++ b/src/search/action-builder.js @@ -1,8 +1,8 @@ -let dispatcher = require('../dispatcher'); -let searchAction = require('./search-action'); +import dispatcher from '../dispatcher'; +import searchAction from './search-action'; const NB_SEARCH_ELEMENT = 50; - /** +/** * Builded search action. * @param {object} options - The options used to build the service, it should have the following structure: * ```javascript @@ -18,37 +18,37 @@ const NB_SEARCH_ELEMENT = 50; * ``` * @return {function} - The builded search action. */ -module.exports = function(config){ - config = config || {}; - if(!config.identifier){ - console.warn('Your action should have an identifier'); - } - if(!config.service){ - console.warn('Your action should have a service'); - } - if(!config.getSearchOptions){ - console.warn('Your action should have a search options getter.'); - } - if(!config.nbSearchElement){ - config.nbSearchElement = NB_SEARCH_ELEMENT; - } - return { +module.exports = function(config) { + config = config || {}; + if (!config.identifier) { + console.warn('Your action should have an identifier'); + } + if (!config.service) { + console.warn('Your action should have a service'); + } + if (!config.getSearchOptions) { + console.warn('Your action should have a search options getter.'); + } + if (!config.nbSearchElement) { + config.nbSearchElement = NB_SEARCH_ELEMENT; + } + return { /** * Build the search for the identifier scope. * @return {function} The search function for the given identifier. */ - search: searchAction(config), - /** + search: searchAction(config), + /** * Update the query for the identifier scope. * @param {string} value - The query value * @return {function} The update query function for the given identifier. */ - updateProperties(value){ - return dispatcher.handleViewAction({ - data: value, - type: 'update', - identifier: config.identifier - }); - } - }; + updateProperties(value) { + return dispatcher.handleViewAction({ + data: value, + type: 'update', + identifier: config.identifier + }); + } + }; }; diff --git a/src/search/built-in-store.js b/src/search/built-in-store.js index 2f1d8e1..b094971 100644 --- a/src/search/built-in-store.js +++ b/src/search/built-in-store.js @@ -1,5 +1,5 @@ -let AdvancedSearchStore = require('../store/search/advanced-search'); -let QuickSearchStore = require('../store/search/quick-search'); +import AdvancedSearchStore from '../store/search/advanced-search'; +import QuickSearchStore from '../store/search/quick-search'; module.exports = { quickSearchStore: new QuickSearchStore(), diff --git a/src/search/index.js b/src/search/index.js index 4c00082..8cbdfba 100644 --- a/src/search/index.js +++ b/src/search/index.js @@ -1,11 +1,10 @@ -let dispatcher = require('../dispatcher'); module.exports = { builtInStore: require('./built-in-store'), /** * Action builder */ actionBuilder: require('./action-builder'), - log(){ + log() { let builtInStore = require('./built-in-store'); console.info('---------------------------'); console.info('QuickSearch', builtInStore.quickSearchStore.value); diff --git a/src/search/search-action/index.js b/src/search/search-action/index.js index 937bb07..8d2e399 100644 --- a/src/search/search-action/index.js +++ b/src/search/search-action/index.js @@ -1,10 +1,10 @@ //Dependencies. import assign from 'object-assign'; -import {isObject} from 'lodash/lang'; +import isObject from 'lodash/lang/isObject'; import _builder from './builder'; import _parser from './parser'; import dispatcher from '../../dispatcher'; -import {manageResponseErrors} from '../../network/error-parsing'; +import { manageResponseErrors } from '../../network/error-parsing'; import isString from 'lodash/lang/isString'; const ALL = 'ALL'; @@ -15,7 +15,7 @@ const STAR = '*'; * @param {object} config - Action configuration. * @return {function} - The generated action from the congig. */ -module.exports = function searchActionBuilder(config){ +module.exports = function searchActionBuilder(config) { /** * Dispatch the results on the search store * @param {object} data - The data to dispatch. @@ -27,14 +27,14 @@ module.exports = function searchActionBuilder(config){ identifier: config.identifier }); }; - const parser = config.parser && isObject(config.parser) ? {..._parser, ...config.parser} : _parser; + const parser = config.parser && isObject(config.parser) ? { ..._parser, ...config.parser } : _parser; /** * Method call when there is an error. * @param {object} config - The action builder configuration. * @param {object} err - The error from the API call. * @return {object} - The data from the manageResponseErrors function. */ - function _errorOnCall(err){ + function _errorOnCall(err) { manageResponseErrors(err, config); //_dispatchGlobalError shoud be separated. } @@ -52,7 +52,7 @@ module.exports = function searchActionBuilder(config){ * * @param {Boolean} isScroll - Is the action result from a scrolling. */ - return function searchAction(isScroll){ + return function searchAction(isScroll) { //Read search options from the accessor define in the config. let { scope, query, selectedFacets, @@ -64,39 +64,39 @@ module.exports = function searchActionBuilder(config){ //Number of element to search on each search. const nbSearchElement = config.nbSearchElement; //Process the query if empty. - if(!query || '' === query){ + if (!query || '' === query) { query = STAR; } //Build URL data. const urlData = assign( - _builder.pagination({results, totalCount, isScroll, nbSearchElement}), - _builder.orderAndSort({sortBy, sortAsc}) + _builder.pagination({ results, totalCount, isScroll, nbSearchElement }), + _builder.orderAndSort({ sortBy, sortAsc }) ); //Build body data. const postData = { ...otherProps, - criteria: {query, scope}, + criteria: { query, scope }, facets: selectedFacets ? _builder.facets(selectedFacets) : {}, group: groupingKey || '' }; //Different call depending on the scope. - if(isString(scope) && scope.toUpperCase() === ALL) { + if (isString(scope) && scope.toUpperCase() === ALL) { //Call the search action. - config.service.unscoped({urlData: urlData, data: postData}) - .then(parser.unscopedResponse) - .then(_dispatchResult) - .catch(_errorOnCall); + config.service.unscoped({ urlData: urlData, data: postData }) + .then(parser.unscopedResponse) + .then(_dispatchResult) + .catch(_errorOnCall); } else { //The component which call the serice should be know if it has all the data. - config.service.scoped({urlData: urlData, data: postData}) - .then((response)=>{ - return parser.scopedResponse( - response, - {isScroll, scope, results} - ); - }) - .then(_dispatchResult) - .catch(_errorOnCall); + config.service.scoped({ urlData: urlData, data: postData }) + .then((response) => { + return parser.scopedResponse( + response, + { isScroll, scope, results } + ); + }) + .then(_dispatchResult) + .catch(_errorOnCall); } }; }; diff --git a/src/site-description/builder.js b/src/site-description/builder.js index 89ce814..9bbe087 100644 --- a/src/site-description/builder.js +++ b/src/site-description/builder.js @@ -1,8 +1,9 @@ -let {find, some} = require('lodash/collection'); -let clone = require('lodash/lang/clone'); +import clone from 'lodash/lang/clone'; +import find from 'lodash/collection/find'; +import some from 'lodash/collection/some'; -let userHelper = require('../user'); -let siteDescriptionReader = require('./reader'); +import userHelper from '../user'; +import siteDescriptionReader from './reader'; //Container for the site description and routes. let siteDescription, routes = {}, siteStructure = {}; @@ -10,83 +11,83 @@ const EMPTY = ''; //Process the name of function _processName(pfx, eltDescName) { - if (pfx === undefined || pfx === null) { - pfx = EMPTY; - } - if (eltDescName === undefined || eltDescName === null) { - return pfx; - } - if (pfx === EMPTY) { - return eltDescName; - } - return pfx + '.' + eltDescName; + if (pfx === undefined || pfx === null) { + pfx = EMPTY; + } + if (eltDescName === undefined || eltDescName === null) { + return pfx; + } + if (pfx === EMPTY) { + return eltDescName; + } + return pfx + '.' + eltDescName; } //Process the deaders element of the site description element. function _processHeaders(siteDesc, prefix) { if (!siteDesc.headers) { - return; + return; } //console.log('headers', siteDesc.headers, 'prefix', prefix); - var headers = siteDesc.headers; - var isInSiteStructure = false; - if(siteDescriptionReader.checkParams(siteDesc.requiredParams)){ - isInSiteStructure = true; + let headers = siteDesc.headers; + let isInSiteStructure = false; + if (siteDescriptionReader.checkParams(siteDesc.requiredParams)) { + isInSiteStructure = true; } - for (var i in headers) { - _processElement(headers[i], prefix, {isInSiteStructure: isInSiteStructure}); + for (let i in headers) { + _processElement(headers[i], prefix, { isInSiteStructure: isInSiteStructure }); } - } +} - //Process the pages element of the site description. - function _processPages(siteDesc, prefix) { +//Process the pages element of the site description. +function _processPages(siteDesc, prefix) { if (siteDesc.pages !== undefined && siteDesc.pages !== null) { - //console.log('pages', siteDesc.pages, 'prefix', prefix); + //console.log('pages', siteDesc.pages, 'prefix', prefix); - for (var i in siteDesc.pages) { - _processElement(siteDesc.pages[i], prefix); - } + for (let i in siteDesc.pages) { + _processElement(siteDesc.pages[i], prefix); + } } - } +} //Process the route part of the site description element. function _processRoute(siteDesc, prefix, options) { - options = options || {}; - //if (siteDesc.roles !== undefined && siteDesc.url !== undefined) - //console.log('route', siteDesc.url, 'prefix', prefix); + options = options || {}; + //if (siteDesc.roles !== undefined && siteDesc.url !== undefined) + //console.log('route', siteDesc.url, 'prefix', prefix); if (userHelper.hasRole(siteDesc.roles)) { - var route = { - roles: siteDesc.roles, - name: prefix, - route: siteDesc.url, - regex: routeToRegExp(siteDesc.url), - requiredParams: siteDesc.requiredParams - }; - //Call the Backbone.history.handlers.... - //console.log('*****************'); - //console.log('ROute name: ',route.route); - //console.log('Route handler name : ', findRouteName(route.route.substring(1))); - routes[findRouteName(route.route.substring(1))] = route; - if(options.isInSiteStructure){ - siteStructure[prefix] = route; - } + let route = { + roles: siteDesc.roles, + name: prefix, + route: siteDesc.url, + regex: routeToRegExp(siteDesc.url), + requiredParams: siteDesc.requiredParams + }; + //Call the Backbone.history.handlers.... + //console.log('*****************'); + //console.log('ROute name: ',route.route); + //console.log('Route handler name : ', findRouteName(route.route.substring(1))); + routes[findRouteName(route.route.substring(1))] = route; + if (options.isInSiteStructure) { + siteStructure[prefix] = route; + } } } function _processElement(siteDescElt, prefix, options) { - options = options || {}; - if (!siteDescElt) { - console.warn('The siteDescription does not exists', siteDescElt); - return; - } - var pfx = _processName(prefix, siteDescElt.name); - //if(siteDescriptionReader.checkParams(siteDescElt.requiredParams)){ - _processHeaders(siteDescElt, pfx); - //} - _processPages(siteDescElt, pfx); - _processRoute(siteDescElt, pfx, options); + options = options || {}; + if (!siteDescElt) { + console.warn('The siteDescription does not exists', siteDescElt); + return; + } + let pfx = _processName(prefix, siteDescElt.name); + //if(siteDescriptionReader.checkParams(siteDescElt.requiredParams)){ + _processHeaders(siteDescElt, pfx); + //} + _processPages(siteDescElt, pfx); + _processRoute(siteDescElt, pfx, options); } @@ -94,46 +95,46 @@ function _processElement(siteDescElt, prefix, options) { // _routeToTest_ : Route to test. // *return* : The handler route name. function findRouteName(routeToTest) { - if(!window.Backbone){ + if (!window.Backbone) { throw new Error('Dependency: Backbone is missing.'); } - var handlers = window.Backbone.history.handlers; + let handlers = window.Backbone.history.handlers; //console.log('handlers', ) - var h = find(handlers, function(handler){ - return handler.route.test(routeToTest); + let h = find(handlers, function (handler) { + return handler.route.test(routeToTest); }); - if(h !== undefined){ - return h.route.toString(); + if (h !== undefined) { + return h.route.toString(); } - return some(handlers, function(handler) { - if (handler.route.test(routeToTest)) { - return handler.route.toString(); - } + return some(handlers, function (handler) { + if (handler.route.test(routeToTest)) { + return handler.route.toString(); + } }); - } +} - //Convert a route to regexp +//Convert a route to regexp const optionalParam = /\((.*?)\)/g; const namedParam = /(\(\?)?:\w+/g; const splatParam = /\*\w+/g; const escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; function routeToRegExp(route) { route = route.replace(escapeRegExp, '\\$&') - .replace(optionalParam, '(?:$1)?') - .replace(namedParam, function(match, optional) { - return optional ? match : '([^/?]+)'; - }) - .replace(splatParam, '([^?]*?)'); + .replace(optionalParam, '(?:$1)?') + .replace(namedParam, function (match, optional) { + return optional ? match : '([^/?]+)'; + }) + .replace(splatParam, '([^?]*?)'); return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); } - //Get the siteDescription. +//Get the siteDescription. function getSiteDescription() { return clone(siteDescription); } - //Get all the application routes from the siteDescription. +//Get all the application routes from the siteDescription. function getRoute(routeName) { return clone(routes[routeName]); } @@ -145,32 +146,32 @@ function getSiteStructure() { return clone(siteStructure); } //Process the siteDescription if necessary. -function processSiteDescription(options){ - options = options || {}; - if(!siteDescriptionReader.isProcessed() || options.isForceProcess){ - siteDescription = siteDescriptionReader.getSite(); - regenerateRoutes(); - return siteDescription; - } - return false; +function processSiteDescription(options) { + options = options || {}; + if (!siteDescriptionReader.isProcessed() || options.isForceProcess) { + siteDescription = siteDescriptionReader.getSite(); + regenerateRoutes(); + return siteDescription; + } + return false; } //Regenerate the application routes. function regenerateRoutes() { - //Clean all previous registered routes. - routes = {}; - siteStructure = {}; - //Process the new routes. - _processElement(siteDescription); + //Clean all previous registered routes. + routes = {}; + siteStructure = {}; + //Process the new routes. + _processElement(siteDescription); } module.exports = { - getRoute: getRoute, - getRoutes: getRoutes, - getSiteDescription: getSiteDescription, - regenerateRoutes: regenerateRoutes, - getSiteStructure: getSiteStructure, - processSiteDescription: processSiteDescription, - findRouteName: findRouteName, - routeToRegExp: routeToRegExp + getRoute: getRoute, + getRoutes: getRoutes, + getSiteDescription: getSiteDescription, + regenerateRoutes: regenerateRoutes, + getSiteStructure: getSiteStructure, + processSiteDescription: processSiteDescription, + findRouteName: findRouteName, + routeToRegExp: routeToRegExp }; diff --git a/src/site-description/index.js b/src/site-description/index.js index 5d8915f..4a7bac3 100644 --- a/src/site-description/index.js +++ b/src/site-description/index.js @@ -1,15 +1,15 @@ -let _builder = require('./builder'); +import _builder from './builder'; /** * @description Get th site structure processed with the user roles. * @return {object} - The user site structure. */ -function getUserSiteStructure(){ - //Seems wiered looking like a ci - return _builder.getSiteStructure(); +function getUserSiteStructure() { + //Seems wiered looking like a ci + return _builder.getSiteStructure(); } module.exports = { - builder: _builder, - reader: require('./reader'), - getUserSiteStructure: getUserSiteStructure + builder: _builder, + reader: require('./reader'), + getUserSiteStructure: getUserSiteStructure }; diff --git a/src/site-description/reader.js b/src/site-description/reader.js index b3c0f54..5e508fa 100644 --- a/src/site-description/reader.js +++ b/src/site-description/reader.js @@ -1,97 +1,104 @@ let ArgumentNullException = require('../exception').ArgumentNullException; let ArgumentInvalidException = require('../exception').ArgumentInvalidException; -let {isObject, isFunction, isArray, isEqual, clone} = require('lodash/lang'); -let contains = require('lodash/collection/contains'); -let intersection = require('lodash/array/intersection'); -let keys = require('lodash/object/keys'); + +import isObject from 'lodash/lang/isObject'; +import isFunction from 'lodash/lang/isFunction'; +import isArray from 'lodash/lang/isArray'; +import isEqual from 'lodash/lang/isEqual'; +import clone from 'lodash/lang/clone'; + + +import contains from 'lodash/collection/contains'; +import intersection from 'lodash/array/intersection'; +import keys from 'lodash/object/keys'; //Module page. let siteDescriptionStructure, - siteDescriptionParams, - isProcess = false; + siteDescriptionParams, + isProcess = false; - //Get the site process - var getSite = function getSite() { +//Get the site process +let getSite = function getSite() { isProcess = true; - if(!isFunction(siteDescriptionStructure)){ - console.warn('You are trying to call getSite before it was correctly initialized...'); + if (!isFunction(siteDescriptionStructure)) { + console.warn('You are trying to call getSite before it was correctly initialized...'); } return siteDescriptionStructure(siteDescriptionParams); - }; +}; //Define the application site description. //The siteDescription must be a function which return an object with the following structure: // `{headers: [{name: "NameOfTheModule", url: "#nameOftheModule/:param, roles:['CHIEF', 'MASTER']", headers: [[{name: "NameOfTheModule", url: "#nameOftheModule/:param, roles:['CHIEF', 'MASTER']", headers: []}]]}]}` -var defineSite = function defineSite(siteDescription) { - if (!isObject(siteDescription)) { - throw new ArgumentNullException('SiteDescription must be an object', siteDescription); - } - if (!isObject(siteDescription.params)) { - throw new ArgumentNullException('SiteDescription.params must be an object', siteDescription); - } - if (!isFunction(siteDescription.value)) { - throw new ArgumentNullException('SiteDescription.value must be a function', siteDescription); - } - siteDescriptionParams = siteDescription.params || {}; - siteDescriptionStructure = siteDescription.value; - return getSite(); +let defineSite = function defineSite(siteDescription) { + if (!isObject(siteDescription)) { + throw new ArgumentNullException('SiteDescription must be an object', siteDescription); + } + if (!isObject(siteDescription.params)) { + throw new ArgumentNullException('SiteDescription.params must be an object', siteDescription); + } + if (!isFunction(siteDescription.value)) { + throw new ArgumentNullException('SiteDescription.value must be a function', siteDescription); + } + siteDescriptionParams = siteDescription.params || {}; + siteDescriptionStructure = siteDescription.value; + return getSite(); }; //param must be a {name: 'paramName', value: 'paramValue'} object. let defineParam = function defineParamSiteDescriptionHelper(param) { - if (param === undefined) { - throw new ArgumentNullException('You cannot set an undefined param.', param); - } - //console.log("Debug", param.name, siteDescriptionParams,siteDescriptionParams['codePays']); - if (siteDescriptionParams[param.name] === undefined) { - throw new ArgumentNullException('The parameter you try to define has not been anticipated by the siteDescription', { - param: param, - siteParams: siteDescriptionParams - }); - } - if (siteDescriptionParams[param.name].value === param.value && isEqual(siteDescriptionParams[param.name].title, param.title)) { - console.info('No changes on param', param); - return false; - } - siteDescriptionParams[param.name] = { - value: param.value, - title: param.title, - isDefine: true - }; - isProcess = false; - return true; + if (param === undefined) { + throw new ArgumentNullException('You cannot set an undefined param.', param); + } + //console.log("Debug", param.name, siteDescriptionParams,siteDescriptionParams['codePays']); + if (siteDescriptionParams[param.name] === undefined) { + throw new ArgumentNullException('The parameter you try to define has not been anticipated by the siteDescription', { + param: param, + siteParams: siteDescriptionParams + }); + } + if (siteDescriptionParams[param.name].value === param.value && isEqual(siteDescriptionParams[param.name].title, param.title)) { + console.info('No changes on param', param); + return false; + } + siteDescriptionParams[param.name] = { + value: param.value, + title: param.title, + isDefine: true + }; + isProcess = false; + return true; }; //Check if the params is define in the params list. -var checkParams = function checkParams(paramsArray) { - if (typeof paramsArray === 'undefined') { - return true; - } - if (isArray(paramsArray)) { - throw new ArgumentInvalidException('The paramsArray must be an array'); - } - if (intersection(keys(siteDescriptionParams), paramsArray).length !== paramsArray.length) { - return false; - } - for (var prop in siteDescriptionParams) { - if (contains(paramsArray, prop) && !siteDescriptionParams[prop].isDefine) { - return false; +let checkParams = function checkParams(paramsArray) { + if (typeof paramsArray === 'undefined') { + return true; + } + if (isArray(paramsArray)) { + throw new ArgumentInvalidException('The paramsArray must be an array'); + } + if (intersection(keys(siteDescriptionParams), paramsArray).length !== paramsArray.length) { + return false; } - } - return true; + for (let prop in siteDescriptionParams) { + if (contains(paramsArray, prop) && !siteDescriptionParams[prop].isDefine) { + return false; + } + } + return true; }; -var siteDescriptionHelper = { - defineSite: defineSite, - defineParam: defineParam, - getSite: getSite, - getParams: function () { - return clone(siteDescriptionParams); - }, - checkParams: checkParams, - isProcessed: function isProcessed() { - return isProcess; - } - }; +let siteDescriptionHelper = { + defineSite: defineSite, + defineParam: defineParam, + getSite: getSite, + getParams: function () { + return clone(siteDescriptionParams); + }, + checkParams: checkParams, + isProcessed: function isProcessed() { + return isProcess; + } +}; module.exports = siteDescriptionHelper; diff --git a/src/store/CoreStore.js b/src/store/CoreStore.js index 775e5c0..77b1498 100644 --- a/src/store/CoreStore.js +++ b/src/store/CoreStore.js @@ -1,13 +1,18 @@ +/* eslint-disable filenames/match-regex */ import { EventEmitter } from 'events'; import assign from 'object-assign'; -import { isArray, isEmpty, isObject, isFunction } from 'lodash/lang'; -import { defer } from 'lodash/function'; + +import isArray from 'lodash/lang/isArray'; +import isFunction from 'lodash/lang/isFunction'; + +import defer from 'lodash/function/defer'; + import intersection from 'lodash/array/intersection'; import capitalize from 'lodash/string/capitalize'; import Immutable from 'immutable'; import AppDispatcher from '../dispatcher'; -const reservedNames = ["Error", "Status"]; +const reservedNames = ['Error', 'Status']; const _instances = []; @@ -34,7 +39,7 @@ class CoreStore extends EventEmitter { this.buildDefinition(); this.buildEachNodeChangeEventListener(); this.registerDispatcher(); - if (!!__DEV__) { + if (__DEV__) { this._registerDevTools(); } } @@ -130,21 +135,21 @@ class CoreStore extends EventEmitter { for (let definition in this.definition) { const capitalizeDefinition = capitalize(definition); //Creates the change listener - currentStore[`add${capitalizeDefinition}ChangeListener`] = function (def) { + currentStore[`add${capitalizeDefinition}ChangeListener`] = (function (def) { return function (cb) { currentStore.addListener(`${def}:change`, cb); } - }(definition); + }(definition)); //Remove the change listener - currentStore[`remove${capitalizeDefinition}ChangeListener`] = function (def) { + currentStore[`remove${capitalizeDefinition}ChangeListener`] = (function (def) { return function (cb) { currentStore.removeListener(`${def}:change`, cb); } - }(definition); + }(definition)); //Create an update method. //Should be named updateData to be more explicit if (currentStore[`update${capitalizeDefinition}`] === undefined) { - currentStore[`update${capitalizeDefinition}`] = function (def) { + currentStore[`update${capitalizeDefinition}`] = (function (def) { return function (dataNode, status, informations) { const immutableNode = isFunction(dataNode) ? dataNode : Immutable.fromJS(dataNode); currentStore.data = currentStore.data.set(def, immutableNode); @@ -153,12 +158,12 @@ class CoreStore extends EventEmitter { currentStore.willEmit(`${def}:change`, { property: def, status: status, informations: informations }); } - }(definition); + }(definition)); } //Create a get method. if (currentStore[`get${capitalizeDefinition}`] === undefined) { - currentStore[`get${capitalizeDefinition}`] = function (def) { + currentStore[`get${capitalizeDefinition}`] = (function (def) { return function () { const hasData = currentStore.data.has(def); if (hasData) { @@ -171,53 +176,53 @@ class CoreStore extends EventEmitter { } return undefined; }; - }(definition); + }(definition)); } //Creates the error change listener - currentStore[`add${capitalizeDefinition}ErrorListener`] = function (def) { + currentStore[`add${capitalizeDefinition}ErrorListener`] = (function (def) { return function (cb) { currentStore.addListener(`${def}:error`, cb); } - }(definition); + }(definition)); //Remove the change listener - currentStore[`remove${capitalizeDefinition}ErrorListener`] = function (def) { + currentStore[`remove${capitalizeDefinition}ErrorListener`] = (function (def) { return function (cb) { currentStore.removeListener(`${def}:error`, cb); } - }(definition); + }(definition)); //Create an update method. - currentStore[`updateError${capitalizeDefinition}`] = function (def) { + currentStore[`updateError${capitalizeDefinition}`] = (function (def) { return function (dataNode, status, informations) { //CheckIsObject - const immutableNode = Immutable[isArray(dataNode) ? "List" : "Map"](dataNode); + const immutableNode = Immutable[isArray(dataNode) ? 'List' : 'Map'](dataNode); currentStore.error = currentStore.error.set(def, immutableNode); currentStore.status = currentStore.status.set(def, status); currentStore.willEmit(`${def}:error`, { property: def, status: status, informations: informations }); } - }(definition); + }(definition)); //Create a get method. - currentStore[`getError${capitalizeDefinition}`] = function (def) { + currentStore[`getError${capitalizeDefinition}`] = (function (def) { return function () { const hasData = currentStore.error.has(def); return hasData ? currentStore.error.get(def).toJS() : undefined; }; - }(definition); + }(definition)); // status - currentStore[`add${capitalizeDefinition}StatusListener`] = function (def) { + currentStore[`add${capitalizeDefinition}StatusListener`] = (function (def) { return function (cb) { currentStore.addListener(`${def}:status`, cb); } - }(definition); + }(definition)); //Remove the change listener - currentStore[`remove${capitalizeDefinition}StatusListener`] = function (def) { + currentStore[`remove${capitalizeDefinition}StatusListener`] = (function (def) { return function (cb) { currentStore.removeListener(`${def}:status`, cb); } - }(definition); + }(definition)); //Create an update method. - currentStore[`updateStatus${capitalizeDefinition}`] = function (def) { + currentStore[`updateStatus${capitalizeDefinition}`] = (function (def) { return function updateStatus(dataNode, status, informations) { //CheckIsObject //console.log(`status ${JSON.stringify(status) }`); @@ -225,15 +230,15 @@ class CoreStore extends EventEmitter { currentStore.status = currentStore.status.set(def, statusNode); currentStore.willEmit(`${def}:status`, { property: def, status: status, informations: informations }); } - }(definition); + }(definition)); //Create a get method. - currentStore[`getStatus${capitalizeDefinition}`] = function (def) { + currentStore[`getStatus${capitalizeDefinition}`] = (function (def) { return function getStatus() { const hasData = currentStore.status.has(def); const data = hasData ? currentStore.status.get(def) : undefined; return data.toJS ? data.toJS() : data; }; - }(definition); + }(definition)); } } diff --git a/src/store/application/store.js b/src/store/application/store.js index ef5f204..9281345 100644 --- a/src/store/application/store.js +++ b/src/store/application/store.js @@ -1,30 +1,30 @@ //Dependencies. -var CoreStore = require('../CoreStore'); -var getDefinition = require('./definition'); -var Immutable = require('immutable'); +import CoreStore from '../CoreStore'; +import getDefinition from './definition'; +import Immutable from 'immutable'; /** * Class standing for the cartridge store. */ class ApplicationStore extends CoreStore { - constructor(conf){ - conf = conf || {}; - conf.definition = conf.definition || getDefinition(); - super(conf); - } - /** + constructor(conf) { + conf = conf || {}; + conf.definition = conf.definition || getDefinition(); + super(conf); + } + /** * Update the mode value. * @param {object} dataNode - The value of the data. */ - updateMode(dataNode){ - var modeData = this.data.has('mode') ? this.data.get('mode') : Immutable.fromJS({}); - var newModeValue = modeData.has(dataNode.newMode)? (modeData.get(dataNode.newMode) + 1) : 1; - //Add a check to not have a negative mode, but it should not happen. - var previousModeValue = modeData.has(dataNode.previousMode)? (modeData.get(dataNode.previousMode) - 1) : 0; - this.data = this.data.set('mode', - modeData.set(dataNode.newMode, newModeValue).set(dataNode.previousMode, previousModeValue) - ); - this.willEmit('mode:change'); - } + updateMode(dataNode) { + let modeData = this.data.has('mode') ? this.data.get('mode') : Immutable.fromJS({}); + let newModeValue = modeData.has(dataNode.newMode)? (modeData.get(dataNode.newMode) + 1) : 1; + //Add a check to not have a negative mode, but it should not happen. + let previousModeValue = modeData.has(dataNode.previousMode)? (modeData.get(dataNode.previousMode) - 1) : 0; + this.data = this.data.set('mode', + modeData.set(dataNode.newMode, newModeValue).set(dataNode.previousMode, previousModeValue) + ); + this.willEmit('mode:change'); + } } module.exports = ApplicationStore; diff --git a/src/store/list/index.js b/src/store/list/index.js index 996b3bd..c42a169 100644 --- a/src/store/list/index.js +++ b/src/store/list/index.js @@ -1,4 +1,4 @@ -let CoreStore = require('../CoreStore'); +import CoreStore from '../CoreStore'; /** * Store definition. * @type {Object} @@ -16,19 +16,19 @@ const DEFINITION = { * Class standing for all list information. * The list has almost the same data as the search store but instead of the facets, it can have a . */ -class ListStore extends CoreStore{ - constructor(conf){ - conf = conf || {}; - if(!conf.identifier){ - throw new Error( - ` +class ListStore extends CoreStore { + constructor(conf) { + conf = conf || {}; + if (!conf.identifier) { + throw new Error( + ` The identifier is necessary, maybe it should be the name of the entity which is in the List. Your code should look like let myListStore = new ListStore({identifier: 'myEntityList'}) or something like that. ` - ); - } - conf.definition = DEFINITION; - super(conf); - } + ); + } + conf.definition = DEFINITION; + super(conf); + } } module.exports = ListStore; diff --git a/src/store/message/store.js b/src/store/message/store.js index f9db3ea..779b42e 100644 --- a/src/store/message/store.js +++ b/src/store/message/store.js @@ -1,113 +1,113 @@ //Dependencies. -var CoreStore = require('../CoreStore'); -var getDefinition = require('./definition'); -var uuid = require('uuid').v4; +import CoreStore from '../CoreStore'; +import getDefinition from './definition'; +let uuid = require('uuid').v4; const PUSH = 'push'; const CLEAR = 'clear'; -var AppDispatcher = require('../../dispatcher'); +import AppDispatcher from '../../dispatcher'; /** * Class standing for the cartridge store. */ class MessageStore extends CoreStore { - /** + /** * Add a listener on the global change on the search store. * @param {object} conf - The configuration of the message store. */ - constructor(conf){ - conf = conf || {}; - conf.definition = conf.definition || getDefinition(); - super(conf); - } - /** + constructor(conf) { + conf = conf || {}; + conf.definition = conf.definition || getDefinition(); + super(conf); + } + /** * Get a message from its identifier. * @param {string} messageId - The message identifier. * @returns {object} - The requested message. */ - getMessage(messageId){ - if(!this.data.has(messageId)){ - return undefined; - } - var message = this.data.get(messageId); - if(!message.isAck){ - this.deleteMessage(messageId); + getMessage(messageId) { + if (!this.data.has(messageId)) { + return undefined; + } + let message = this.data.get(messageId); + if (!message.isAck) { + this.deleteMessage(messageId); + } + return message; } - return message; - } - /** + /** * Delete a message given its id. * @param {string} messageId - The message identifier. */ - deleteMessage(messageId){ - if(this.data.has(messageId)){ - this.data = this.data.delete(messageId); + deleteMessage(messageId) { + if (this.data.has(messageId)) { + this.data = this.data.delete(messageId); + } } - } - /** + /** * Add a listener on the global change on the search store. * @param {object} message - The message to add. */ - pushMessage(message){ - message.id = `${uuid()}`; - this.data = this.data.set(message.id, message); - this.emit(PUSH, message.id); - } - /** + pushMessage(message) { + message.id = `${uuid()}`; + this.data = this.data.set(message.id, message); + this.emit(PUSH, message.id); + } + /** * Clear all messages in the stack. */ - clearMessages(){ - this.data = this.data.clear(); - this.emit(CLEAR); - } - /** + clearMessages() { + this.data = this.data.clear(); + this.emit(CLEAR); + } + /** * Add a listener on the global change on the search store. * @param {function} cb - The callback to call when a message is pushed. */ - addPushedMessageListener(cb){ - this.addListener(PUSH, cb); - } - /** + addPushedMessageListener(cb) { + this.addListener(PUSH, cb); + } + /** * Remove a listener on the global change on the search store. * @param {function} cb - The callback to called when a message is pushed. */ - removePushedMessageListener(cb){ - this.removeListener(PUSH, cb); - } + removePushedMessageListener(cb) { + this.removeListener(PUSH, cb); + } - /** + /** * Add a listener on the global change on the search store. * @param {function} cb - The callback to call when a message is pushed. */ - addClearMessagesListener(cb){ - this.addListener(CLEAR, cb); - } - /** + addClearMessagesListener(cb) { + this.addListener(CLEAR, cb); + } + /** * Remove a listener on the global change on the search store. * @param {function} cb - The callback to called when a message is pushed. */ - removeClearMessagesListener(cb){ - this.removeListener(CLEAR, cb); - } - registerDispatcher(){ - var currentStore = this; - this.dispatch = AppDispatcher.register(function(transferInfo) { - var rawData = transferInfo.action.data; - var type = transferInfo.action.type; + removeClearMessagesListener(cb) { + this.removeListener(CLEAR, cb); + } + registerDispatcher() { + let currentStore = this; + this.dispatch = AppDispatcher.register(function(transferInfo) { + let rawData = transferInfo.action.data; + let type = transferInfo.action.type; - switch (type) { - case 'push': - if(rawData.message){ - currentStore.pushMessage(rawData.message); - } - break; - case 'clear': - if(rawData.messages){ - currentStore.clearMessages(); - } - break; - } - }); - } + switch (type) { + case 'push': + if (rawData.message) { + currentStore.pushMessage(rawData.message); + } + break; + case 'clear': + if (rawData.messages) { + currentStore.clearMessages(); + } + break; + } + }); + } } module.exports = MessageStore; diff --git a/src/store/request/store.js b/src/store/request/store.js index 31b7c24..1c62da9 100644 --- a/src/store/request/store.js +++ b/src/store/request/store.js @@ -1,126 +1,126 @@ //Dependencies. -var Immutable = require('immutable'); -var CoreStore = require('../CoreStore'); -var getDefinition = require('./definition'); -var uuid = require('uuid').v4; +import Immutable from 'immutable'; +import CoreStore from '../CoreStore'; +import getDefinition from './definition'; +let uuid = require('uuid').v4; const CLEAR = 'clear'; const UPDATE = 'update'; -var AppDispatcher = require('../../dispatcher'); +import AppDispatcher from '../../dispatcher'; /** * Class standing for the cartridge store. */ class RequestStore extends CoreStore { - /** + /** * Add a listener on the global change on the search store. * @param {object} conf - The configuration of the request store. */ - constructor(conf){ - conf = conf || {}; - conf.definition = conf.definition || getDefinition(); - super(conf); - this.pending = Immutable.Map({}); - this.success = Immutable.Map({}); - this.error = Immutable.Map({}); - this.cancelled = Immutable.Map({}); - } - /** + constructor(conf) { + conf = conf || {}; + conf.definition = conf.definition || getDefinition(); + super(conf); + this.pending = Immutable.Map({}); + this.success = Immutable.Map({}); + this.error = Immutable.Map({}); + this.cancelled = Immutable.Map({}); + } + /** * Get a message from its identifier. * @param {string} messageId - The message identifier. * @returns {object} - The requested message. */ - getRequest(requestId){ - if(!this.data.has(requestId)){ - return undefined; + getRequest(requestId) { + if (!this.data.has(requestId)) { + return undefined; + } + return this.data.get(requestId); } - return this.data.get(requestId); - } - /** + /** * Get the requests by type * @return {object} An object with the total of request by type. */ - getRequests(){ - return { - 'pending': this.pending.size, - 'cancelled': this.cancelled.size, - 'success': this.success.size, - 'error': this.error.size, - 'total': this.pending.size + this.cancelled.size + this.success.size + this.error.size - }; - } - /** + getRequests() { + return { + pending: this.pending.size, + cancelled: this.cancelled.size, + success: this.success.size, + error: this.error.size, + total: this.pending.size + this.cancelled.size + this.success.size + this.error.size + }; + } + /** * Add a listener on the global change on the search store. * @param {object} message - The message to add. */ - updateRequest(request){ - request.id = request.id || `${uuid()}`; - //If the status is supported - if(this.definition[request.status]){ - //Update the associated collection - this[request.status] = this[request.status].set(request.id, request); - //Remove the associated request from pending - if(request.status !== 'pending' && this.pending.has(request.id)){ - this.pending = this.pending.delete(request.id); - } + updateRequest(request) { + request.id = request.id || `${uuid()}`; + //If the status is supported + if (this.definition[request.status]) { + //Update the associated collection + this[request.status] = this[request.status].set(request.id, request); + //Remove the associated request from pending + if (request.status !== 'pending' && this.pending.has(request.id)) { + this.pending = this.pending.delete(request.id); + } + } + this.emit(UPDATE, request.id); } - this.emit(UPDATE, request.id); - } - /** + /** * Clear all messages in the stack. */ - clearRequests(){ - this.data = this.data.clear(); - this.emit(CLEAR); - } - /** + clearRequests() { + this.data = this.data.clear(); + this.emit(CLEAR); + } + /** * Add a listener on the global change on the search store. * @param {function} cb - The callback to call when a message is pushed. */ - addUpdateRequestListener(cb){ - this.addListener(UPDATE, cb); - } - /** + addUpdateRequestListener(cb) { + this.addListener(UPDATE, cb); + } + /** * Remove a listener on the global change on the search store. * @param {function} cb - The callback to called when a message is pushed. */ - removeUpdateRequestListener(cb){ - this.removeListener(UPDATE, cb); - } + removeUpdateRequestListener(cb) { + this.removeListener(UPDATE, cb); + } - /** + /** * Add a listener on the global change on the search store. * @param {function} cb - The callback to call when a message is pushed. */ - addClearRequestsListener(cb){ - this.addListener(CLEAR, cb); - } - /** + addClearRequestsListener(cb) { + this.addListener(CLEAR, cb); + } + /** * Remove a listener on the global change on the search store. * @param {function} cb - The callback to called when a message is pushed. */ - removeClearRequestsListener(cb){ - this.removeListener(CLEAR, cb); - } - registerDispatcher(){ - var currentStore = this; - this.dispatch = AppDispatcher.register(function(transferInfo) { - var rawData = transferInfo.action.data; - var type = transferInfo.action.type; - if(!rawData || !rawData.request){return;} - switch (type) { - case 'update': - if(rawData.request){ - currentStore.updateRequest(rawData.request); - } - break; - case 'clear': - if(rawData.request){ - currentStore.clearRequests(); - } - break; - } - }); - } + removeClearRequestsListener(cb) { + this.removeListener(CLEAR, cb); + } + registerDispatcher() { + let currentStore = this; + this.dispatch = AppDispatcher.register(function(transferInfo) { + let rawData = transferInfo.action.data; + let type = transferInfo.action.type; + if (!rawData || !rawData.request) {return;} + switch (type) { + case 'update': + if (rawData.request) { + currentStore.updateRequest(rawData.request); + } + break; + case 'clear': + if (rawData.request) { + currentStore.clearRequests(); + } + break; + } + }); + } } module.exports = RequestStore; diff --git a/src/store/search/quick-search/index.js b/src/store/search/quick-search/index.js index e074de2..8b5ee87 100644 --- a/src/store/search/quick-search/index.js +++ b/src/store/search/quick-search/index.js @@ -1,4 +1,4 @@ -let SearchStore = require('../search-store'); +import SearchStore from '../search-store'; const LISTENED_NODES = ['query', 'scope']; @@ -6,8 +6,8 @@ const LISTENED_NODES = ['query', 'scope']; * Class standing for all advanced search information. * The state should be the complete state of the page. */ -class QuickSearchStore extends SearchStore{ - constructor(conf){ +class QuickSearchStore extends SearchStore { + constructor(conf) { conf = conf || {}; conf.definition = { query: 'query', @@ -20,12 +20,12 @@ class QuickSearchStore extends SearchStore{ super(conf); } - emitPendingEvents(){ - if(this.pendingEvents.find(ev => LISTENED_NODES.includes(ev.name.split(':change')[0]))) { - this.emit('quick-search-criterias:change', {status: 'update'}); + emitPendingEvents() { + if (this.pendingEvents.find(ev => LISTENED_NODES.includes(ev.name.split(':change')[0]))) { + this.emit('quick-search-criterias:change', { status: 'update' }); } - this.pendingEvents.map((evtToEmit)=>{ - let {name, data} = evtToEmit; + this.pendingEvents.map((evtToEmit) => { + let { name, data } = evtToEmit; this.emit(name, data); }); } diff --git a/src/store/search/search-store.js b/src/store/search/search-store.js index 97eea52..e098a9e 100644 --- a/src/store/search/search-store.js +++ b/src/store/search/search-store.js @@ -1,9 +1,9 @@ -let CoreStore = require('../CoreStore'); +import CoreStore from '../CoreStore'; /** * Class standing for all advanced search information. * The state should be the complete state of the page. */ -class SearchStore extends CoreStore{ +class SearchStore extends CoreStore { getValue() { return this.data.toJS(); } diff --git a/src/store/user/store.js b/src/store/user/store.js index be5eda2..55d300e 100644 --- a/src/store/user/store.js +++ b/src/store/user/store.js @@ -1,15 +1,15 @@ //Dependencies. -var CoreStore = require('../CoreStore'); -var buildDefinition = require('./definition'); +import CoreStore from '../CoreStore'; +import buildDefinition from './definition'; /** * Class standing for the user store. */ class UserStore extends CoreStore { - constructor(conf){ - conf = conf || {}; - conf.definition = conf.definition || buildDefinition(); - super(conf); - } + constructor(conf) { + conf = conf || {}; + conf.definition = conf.definition || buildDefinition(); + super(conf); + } } diff --git a/src/user/built-in-store.js b/src/user/built-in-store.js index e6aeb97..00634b6 100644 --- a/src/user/built-in-store.js +++ b/src/user/built-in-store.js @@ -1,2 +1,2 @@ -var UserStore = require('../store/user'); +import UserStore from '../store/user'; module.exports = new UserStore(); diff --git a/src/user/index.js b/src/user/index.js index 8f0041d..a76606d 100644 --- a/src/user/index.js +++ b/src/user/index.js @@ -1,15 +1,15 @@ -const userBuiltInStore = require('./built-in-store'); -const isArray = require('lodash/lang/isArray'); -const intersection = require('lodash/array/intersection'); -const dispatcher = require('../dispatcher'); +import userBuiltInStore from './built-in-store'; +import isArray from 'lodash/lang/isArray'; +import intersection from 'lodash/array/intersection'; +import dispatcher from '../dispatcher'; /** * Set the a node in the store. * @param {string} name node name * @param {string} value node value to be set */ -function _setUserNode(name, value){ - dispatcher.handleViewAction({data: {[name]: value}, type: 'update'}); +function _setUserNode(name, value) { + dispatcher.handleViewAction({ data: { [name]: value }, type: 'update' }); } module.exports = { builtInStore: userBuiltInStore, @@ -18,7 +18,7 @@ module.exports = { * @param {string | array} role - Check if the user has one or many roles. * @return {Boolean} - True if the user has at least on of the givent roles. */ - hasRole(role){ + hasRole(role) { role = isArray(role) ? role : [role]; return 0 < intersection(role, userBuiltInStore.getRoles()).length; }, @@ -26,42 +26,42 @@ module.exports = { * Set the user roles. * @param {array} roles - User role list. */ - setRoles(roles){ + setRoles(roles) { _setUserNode('roles', roles); }, /** * Get the user roles. * @return {array} - The user role list. */ - getRoles(){ + getRoles() { return userBuiltInStore.getRoles(); }, /** * Set the user profile. * @param {object} profile User profile. */ - setProfile(profile){ + setProfile(profile) { _setUserNode('profile', profile); }, /** * Get the user profile. * @return {object} profile User profile. */ - getProfile(){ + getProfile() { return userBuiltInStore.getProfile(); }, /** * Set user profile. * @param {object} login - user login. */ - setLogin(login){ + setLogin(login) { _setUserNode('login', login); }, /** * Get the user login. * @return {object} - The user login. */ - getLogin(){ + getLogin() { return userBuiltInStore.getLogin(); } }; diff --git a/src/util/object/checkIsNotNull.js b/src/util/object/checkIsNotNull.js index cf68a79..0a44bad 100644 --- a/src/util/object/checkIsNotNull.js +++ b/src/util/object/checkIsNotNull.js @@ -1,5 +1,8 @@ -var ArgumentNullException = require('../../exception/argument-null-exception'); -var {isNull, isUndefined} = require('lodash/lang'); +/* eslint-disable filenames/match-regex */ +import ArgumentNullException from '../../exception/argument-null-exception'; + +import isUndefined from 'lodash/lang/isUndefined'; +import isNull from 'lodash/lang/isNull'; /** * Assert an object is an objet. @@ -8,8 +11,8 @@ var {isNull, isUndefined} = require('lodash/lang'); * @returns {undefined} - Return nothing, throw an Exception if this is not valid. * @example var objToTest = { papa : "singe"}; isNull('objToTest', objToTest); */ -module.exports = function(name, data) { - if (isNull(data) || isUndefined(data)) { - throw new ArgumentNullException(`${name} should be defined`); - } +module.exports = function (name, data) { + if (isNull(data) || isUndefined(data)) { + throw new ArgumentNullException(`${name} should be defined`); + } }; diff --git a/src/util/url/builder.js b/src/util/url/builder.js index 7938d3f..a5bdf68 100644 --- a/src/util/url/builder.js +++ b/src/util/url/builder.js @@ -1,24 +1,24 @@ -var urlProcessor = require('./processor'); +import urlProcessor from './processor'; /* * @module config/server/url-builder * @param url - url with params such as http://url/entity/${id} * @param method - HTTP verb {GET, POST, PUT, DELETE} * @return {function} */ -module.exports = function(url, method){ - /** - * Function returns by the module. - * @param {object} param - urlData: The JSON data to inject in the URL, data: The JSON data to give to the request. - * @return {function} returns a function which takes the URL as parameters. - */ - return function generateUrl(param){ - if (param == undefined) { - param = {}; - } - return { - url: urlProcessor(url, param.urlData), - method: method, - data: param.data || param.bodyData +module.exports = function (url, method) { + /** + * Function returns by the module. + * @param {object} param - urlData: The JSON data to inject in the URL, data: The JSON data to give to the request. + * @return {function} returns a function which takes the URL as parameters. + */ + return function generateUrl(param) { + if (param == undefined) { + param = {}; + } + return { + url: urlProcessor(url, param.urlData), + method: method, + data: param.data || param.bodyData + }; }; - }; }; diff --git a/src/util/url/processor.js b/src/util/url/processor.js index 500d690..98cc72c 100644 --- a/src/util/url/processor.js +++ b/src/util/url/processor.js @@ -1,7 +1,7 @@ -var compile = require('lodash/string/template'); +import compile from 'lodash/string/template'; /** * Process an url in order to build them. */ -module.exports = function(url, data){ - return compile(url)(data); +module.exports = function (url, data) { + return compile(url)(data); }; From 492ab2eedbb13a331cc47a51168bcd40aed5fb5c Mon Sep 17 00:00:00 2001 From: Hartorn Date: Fri, 18 Aug 2017 18:10:52 +0200 Subject: [PATCH 26/32] Fixing module.exports and require --- src/application/index.js | 211 ++++++++++-------- src/application/render.js | 10 +- src/component/builder.js | 6 +- src/component/index.js | 16 +- src/component/types.js | 4 +- src/definition/check-domains.js | 4 +- .../domain/__tests__/container-test.js | 3 +- src/definition/domain/container.js | 9 +- src/definition/domain/index.js | 14 +- .../entity/__tests__/container-test.js | 7 +- src/definition/entity/builder.js | 11 +- src/definition/entity/container.js | 14 +- src/definition/entity/index.js | 16 +- src/definition/formatter/index.js | 12 +- src/definition/index.js | 28 ++- src/definition/validator/date.js | 10 +- src/definition/validator/email.js | 4 +- src/definition/validator/index.js | 28 ++- src/definition/validator/string-length.js | 4 +- src/exception/argument-invalid-exception.js | 2 +- src/exception/argument-null-exception.js | 2 +- src/exception/custom-exception.js | 22 +- src/exception/dependency-exception.js | 2 +- src/exception/focus-exception.js | 2 +- src/exception/index.js | 32 ++- src/exception/not-implemented-exception.js | 2 +- src/index.js | 94 ++++---- src/list/index.js | 16 +- src/list/load-action/builder.js | 16 +- src/list/load-action/parser.js | 8 +- src/message/built-in-store.js | 2 +- src/message/index.js | 26 ++- src/network/built-in-store.js | 2 +- src/network/cancellable-promise-builder.js | 10 +- src/network/config.js | 16 +- src/network/cors.js | 16 +- src/network/fetch.js | 9 +- src/network/index.js | 32 ++- src/reference/builder.js | 43 ++-- src/reference/built-in-store.js | 4 +- src/reference/config.js | 10 +- src/reference/index.js | 22 +- src/search/action-builder.js | 12 +- src/search/built-in-store.js | 14 +- src/search/index.js | 24 +- src/search/search-action/builder.js | 51 +++-- src/search/search-action/index.js | 4 +- src/search/search-action/parser.js | 14 +- src/site-description/builder.js | 29 ++- src/site-description/index.js | 20 +- src/site-description/reader.js | 5 +- src/store/application/definition.js | 10 +- src/store/application/index.js | 3 +- src/store/application/store.js | 6 +- src/store/index.js | 38 +++- src/store/list/index.js | 2 +- src/store/message/definition.js | 10 +- src/store/message/index.js | 3 +- src/store/message/store.js | 6 +- src/store/reference/index.js | 3 +- src/store/request/definition.js | 16 +- src/store/request/index.js | 3 +- src/store/request/store.js | 10 +- src/store/search/index.js | 16 +- src/store/search/quick-search/index.js | 2 +- src/store/search/search-store.js | 2 +- src/store/user/definition.js | 12 +- src/store/user/index.js | 3 +- src/store/user/store.js | 2 +- src/user/built-in-store.js | 2 +- src/user/index.js | 118 +++++----- src/user/login/definition.js | 2 +- src/user/login/index.js | 12 +- src/user/profile/definition.js | 18 +- src/user/profile/index.js | 12 +- src/util/index.js | 20 +- src/util/object/checkIsNotNull.js | 4 +- src/util/object/index.js | 16 +- src/util/string/check.js | 15 +- src/util/string/index.js | 12 +- src/util/url/builder.js | 4 +- src/util/url/index.js | 16 +- src/util/url/processor.js | 4 +- 83 files changed, 843 insertions(+), 533 deletions(-) diff --git a/src/application/index.js b/src/application/index.js index 8ed7180..cbafd13 100644 --- a/src/application/index.js +++ b/src/application/index.js @@ -2,104 +2,133 @@ import React from 'react'; import dispatcher from '../dispatcher'; import isUndefined from 'lodash/lang/isUndefined'; import confirm from './confirm'; + +import render from './render'; +import builtInStore from './built-in-store'; +import actionBuilder from './action-builder'; +import mountedComponents from './mounted-components'; +import clear from './clear'; + //Empty compoennt. const Empty = props =>
; Empty.displayName = 'Empty'; -module.exports = { - render: require('./render'), - builtInStore: require('./built-in-store'), - actionBuilder: require('./action-builder'), - clear: require('./clear'), - mountedComponents: require('./mounted-components'), - /** - * Change application mode. - * @param {string} newMode - New application mode. - * @param {string} previousMode - Previous mode. - */ - changeMode(newMode, previousMode) { - const mode = { newMode: newMode, previousMode: previousMode }; - dispatcher.handleViewAction({ data: { mode: mode }, type: 'update' }); - }, - /** - * Change application route (maybe not the wole route but a route's group.) - * @param {string} newRoute - new route name. - */ - changeRoute(newRoute) { - dispatcher.handleViewAction({ data: { route: newRoute }, type: 'update' }); - }, - /** - * Set component to application's header. - * @param {ReactComponent} cartridge component injected in the cartridge - * @param {ReactComponent} summary component injected in the summary bar - * @param {ReactComponent} actions arrays of cartridge actions - * @param {ReactComponent} barLeft component injected in the left bar - * @param {ReactComponent} canDeploy indicates wether the cartridge can deploy or not - * @param {ReactComponent} barRight component injected in the right bar - * @param {ReactComponent} EmptyComponent Empty component - */ - setHeader({ cartridge, summary, actions, barLeft, canDeploy, barRight, EmptyComponent = Empty }) { - const data = { - cartridgeComponent: cartridge || { component: EmptyComponent }, - summaryComponent: summary || { component: EmptyComponent }, - actions: actions || { primary: [], secondary: [] }, - barContentLeftComponent: barLeft || { component: EmptyComponent }, - canDeploy: isUndefined(canDeploy) ? true : canDeploy - }; +/** + * Change application mode. + * @param {string} newMode - New application mode. + * @param {string} previousMode - Previous mode. + */ +const changeMode = (newMode, previousMode) => { + const mode = { newMode: newMode, previousMode: previousMode }; + dispatcher.handleViewAction({ data: { mode: mode }, type: 'update' }); +}; - if (barRight) { - data.barContentRightComponent = barRight; - } +/** + * Change application route (maybe not the wole route but a route's group.) + * @param {string} newRoute - new route name. + */ +const changeRoute = (newRoute) => { + dispatcher.handleViewAction({ data: { route: newRoute }, type: 'update' }); +}; +/** + * Set component to application's header. + * @param {ReactComponent} cartridge component injected in the cartridge + * @param {ReactComponent} summary component injected in the summary bar + * @param {ReactComponent} actions arrays of cartridge actions + * @param {ReactComponent} barLeft component injected in the left bar + * @param {ReactComponent} canDeploy indicates wether the cartridge can deploy or not + * @param {ReactComponent} barRight component injected in the right bar + * @param {ReactComponent} EmptyComponent Empty component + */ +const setHeader = ({ cartridge, summary, actions, barLeft, canDeploy, barRight, EmptyComponent = Empty }) => { + const data = { + cartridgeComponent: cartridge || { component: EmptyComponent }, + summaryComponent: summary || { component: EmptyComponent }, + actions: actions || { primary: [], secondary: [] }, + barContentLeftComponent: barLeft || { component: EmptyComponent }, + canDeploy: isUndefined(canDeploy) ? true : canDeploy + }; + + if (barRight) { + data.barContentRightComponent = barRight; + } + + dispatcher.handleViewAction({ data, type: 'update' }); +}; +/** + * Set component to application's header with only the component gived in parameter. + * @param {ReactComponent} cartridge component injected in the cartridge + * @param {ReactComponent} summary component injected in the summary bar + * @param {ReactComponent} actions arrays of cartridge actions + * @param {ReactComponent} barLeft component injected in the left bar + * @param {ReactComponent} canDeploy indicates wether the cartridge can deploy or not + * @param {ReactComponent} barRight component injected in the right bar + * @param {ReactComponent} EmptyComponent Empty component + */ +const setPartialHeader = ({ cartridge, summary, actions, barLeft, barRight, canDeploy }) => { + const data = { + canDeploy: isUndefined(canDeploy) ? true : canDeploy + }; - dispatcher.handleViewAction({ data, type: 'update' }); - }, - /** - * Set component to application's header with only the component gived in parameter. - * @param {ReactComponent} cartridge component injected in the cartridge - * @param {ReactComponent} summary component injected in the summary bar - * @param {ReactComponent} actions arrays of cartridge actions - * @param {ReactComponent} barLeft component injected in the left bar - * @param {ReactComponent} canDeploy indicates wether the cartridge can deploy or not - * @param {ReactComponent} barRight component injected in the right bar - * @param {ReactComponent} EmptyComponent Empty component - */ - setPartialHeader({ cartridge, summary, actions, barLeft, barRight, canDeploy }) { - const data = { - canDeploy: isUndefined(canDeploy) ? true : canDeploy - }; + if (cartridge) { + data.cartridgeComponent = cartridge; + } + if (summary) { + data.summaryComponent = summary; + } + if (actions) { + data.actions = actions; + } + if (barLeft) { + data.barContentLeftComponent = barLeft; + } + if (barRight) { + data.barContentRightComponent = barRight; + } - if (cartridge) { - data.cartridgeComponent = cartridge; - } - if (summary) { - data.summaryComponent = summary; - } - if (actions) { - data.actions = actions; - } - if (barLeft) { - data.barContentLeftComponent = barLeft; - } - if (barRight) { - data.barContentRightComponent = barRight; - } + dispatcher.handleViewAction({ data, type: 'update' }); +}; +/** + * Clear the application's header. + * @return {[type]} [description] + */ +const clearHeader = () => { + dispatcher.handleViewAction({ + data: { + cartridgeComponent: { component: Empty }, + barContentLeftComponent: { component: Empty }, + summaryComponent: { component: Empty }, + actions: { primary: [], secondary: [] } + }, + type: 'update' + }); +}; + + +export { + render, + builtInStore, + actionBuilder, + clear, + mountedComponents, + changeMode, + changeRoute, + setHeader, + setPartialHeader, + clearHeader, + confirm +}; - dispatcher.handleViewAction({ data, type: 'update' }); - }, - /** - * Clear the application's header. - * @return {[type]} [description] - */ - clearHeader() { - dispatcher.handleViewAction({ - data: { - cartridgeComponent: { component: Empty }, - barContentLeftComponent: { component: Empty }, - summaryComponent: { component: Empty }, - actions: { primary: [], secondary: [] } - }, - type: 'update' - }); - }, +export default { + render, + builtInStore, + actionBuilder, + clear, + mountedComponents, + changeMode, + changeRoute, + setHeader, + setPartialHeader, + clearHeader, confirm }; diff --git a/src/application/render.js b/src/application/render.js index 1052c33..2699608 100644 --- a/src/application/render.js +++ b/src/application/render.js @@ -11,7 +11,7 @@ import clearComponent from './clear'; * @param {string} selector - A selector on a DOM node. * @param {object} options - Options for the component rendering. */ -module.exports = function renderComponent(component, selector, options) { +export default function renderComponent(component, selector, options) { options = options || {}; // Clear a potential previously mounted component clearComponent(selector); @@ -28,10 +28,4 @@ module.exports = function renderComponent(component, selector, options) { mountedComponents[selector] = mountedComponent; console.info('Mounted components : ', Object.keys(mountedComponents)); return mountedComponent; -}; -/* -Exemple -var render = Focus.application.render; -var MyComponent = require('./my-component'); -render(MyComponent, 'div.component-container', {props: {id: '12'}}); -*/ +} diff --git a/src/component/builder.js b/src/component/builder.js index 45e10e3..2344a38 100644 --- a/src/component/builder.js +++ b/src/component/builder.js @@ -1,7 +1,5 @@ import React from 'react'; import assign from 'object-assign'; -//var isObject = require('lodash/lang/isObject'); -//var isFunction = require('lodash/lang/isFunction'); /** * Create a component with a mixin except id the component is mixin only. @@ -22,9 +20,9 @@ function createComponent(mixin, isMixinOnly) { * @param {boolean} isMixinOnly - Bolean to set . * @return {object} {mixin: 'the component mixin', component: 'the react instanciated component'} */ -module.exports = function builder(componentMixin, isMixinOnly) { +export default function builder(componentMixin, isMixinOnly) { return assign( { mixin: componentMixin }, createComponent(componentMixin, isMixinOnly) ); -}; +} diff --git a/src/component/index.js b/src/component/index.js index 3fabe93..f14dcf3 100644 --- a/src/component/index.js +++ b/src/component/index.js @@ -1,4 +1,12 @@ -module.exports = { - builder: require('./builder'), - types: require('./types') -}; +import builder from './builder'; +import types from './types'; + +export { + builder, + types +} + +export default { + builder, + types +} \ No newline at end of file diff --git a/src/component/types.js b/src/component/types.js index 33bc340..ba69f51 100644 --- a/src/component/types.js +++ b/src/component/types.js @@ -10,7 +10,7 @@ import isArray from 'lodash/lang/isArray'; * @param {boolean} isRequired - Defines if the props is mandatory. * @return {object} The corresponding react type. */ -module.exports = function types(type, isRequired) { +export default function types(type, isRequired) { const isStringType = isString(type); if (!isStringType && !isArray(type)) { throw new Error('The type should be a string or an array'); @@ -32,4 +32,4 @@ module.exports = function types(type, isRequired) { propTypeToReturn = propTypeToReturn.isRequired; } return propTypeToReturn; -}; +} diff --git a/src/definition/check-domains.js b/src/definition/check-domains.js index 9cd5fb4..d13a96a 100644 --- a/src/definition/check-domains.js +++ b/src/definition/check-domains.js @@ -3,7 +3,7 @@ import intersection from 'lodash/array/intersection'; import uniq from 'lodash/array/uniq'; import difference from 'lodash/array/difference'; -module.exports = function checkDomain(entityDef, domains) { +export default function checkDomain(entityDef, domains) { domains = keys(domains); let arr = []; for (let node in entityDef) { @@ -24,4 +24,4 @@ module.exports = function checkDomain(entityDef, domains) { console.warn('Useless domain definition', useLessDomains); } console.info('####################################################################'); -}; +} diff --git a/src/definition/domain/__tests__/container-test.js b/src/definition/domain/__tests__/container-test.js index a2275f3..f2708f0 100644 --- a/src/definition/domain/__tests__/container-test.js +++ b/src/definition/domain/__tests__/container-test.js @@ -1,14 +1,13 @@ /*global expect, it, describe*/ // __tests__/container-test.js +import domainContainer from '../container'; describe('### domain container', () => { it('domain should be empty by default', () => { - const domainContainer = require('../container'); expect(domainContainer.getAll()).toEqual({}); }); it('domain set should add a domain', () => { - const domainContainer = require('../container'); const doText = { name: 'DO_TEXT', type: 'string' }; domainContainer.set(doText); expect(domainContainer.getAll().DO_TEXT).toEqual(doText); diff --git a/src/definition/domain/container.js b/src/definition/domain/container.js index 4c5a9bd..bca2123 100644 --- a/src/definition/domain/container.js +++ b/src/definition/domain/container.js @@ -60,9 +60,16 @@ function getDomain(domainName) { return domainsMap.get(domainName); } -module.exports = { +export default { getAll: getDomains, setAll: setDomains, set: setDomain, get: getDomain }; + +export { + getDomains as getAll, + setDomains as setAll, + setDomain as set, + getDomain as get +}; \ No newline at end of file diff --git a/src/definition/domain/index.js b/src/definition/domain/index.js index 6e308e0..885dab5 100644 --- a/src/definition/domain/index.js +++ b/src/definition/domain/index.js @@ -1,7 +1,9 @@ -/** - * Application domain gestion. - * @type {Object} - */ -module.exports = { - container: require('./container') +import container from './container'; + +export { + container +}; + +export default { + container }; diff --git a/src/definition/entity/__tests__/container-test.js b/src/definition/entity/__tests__/container-test.js index 8f9d4b5..0f50fe7 100644 --- a/src/definition/entity/__tests__/container-test.js +++ b/src/definition/entity/__tests__/container-test.js @@ -2,20 +2,17 @@ // __tests__/container-test.js import entityConfigurationMock from './entityConfigurationMock.json'; +import entityContainer from '../container'; describe('### entity container', () => { it('getEntityConfiguration should be empty by default', () => { - const entityContainer = require('../container'); expect(entityContainer.getEntityConfiguration()).toEqual({}); }); it('getEntityConfiguration should sent back sent conf', () => { - const entityContainer = require('../container'); entityContainer.setEntityConfiguration(entityConfigurationMock); - expect(entityContainer.getEntityConfiguration()).toEqual( - entityConfigurationMock); + expect(entityContainer.getEntityConfiguration()).toEqual(entityConfigurationMock); }); it('Get node should trigger a warning when the props does not exists', () => { - const entityContainer = require('../container'); entityContainer.setEntityConfiguration(entityConfigurationMock); expect(() => { return entityContainer.getEntityConfiguration('papa'); diff --git a/src/definition/entity/builder.js b/src/definition/entity/builder.js index f8eee56..b1b9655 100644 --- a/src/definition/entity/builder.js +++ b/src/definition/entity/builder.js @@ -86,8 +86,13 @@ function getFieldInformations(fieldName, complementaryInformation) { return _buildFieldInformation(fieldPath).mergeDeep(complementaryInformation).toJS(); } +export { + getEntityInformations, + getFieldInformations +}; -module.exports = { - getEntityInformations: getEntityInformations, - getFieldInformations: getFieldInformations +export default { + getEntityInformations, + getFieldInformations }; + diff --git a/src/definition/entity/container.js b/src/definition/entity/container.js index 9107017..4c51f2c 100644 --- a/src/definition/entity/container.js +++ b/src/definition/entity/container.js @@ -74,8 +74,14 @@ function getFieldConfiguration(fieldPath, customFieldConf) { } -module.exports = { - getEntityConfiguration: getEntityConfiguration, - setEntityConfiguration: setEntityConfiguration, - getFieldConfiguration: getFieldConfiguration +export default { + getEntityConfiguration, + setEntityConfiguration, + getFieldConfiguration +}; + +export { + getEntityConfiguration, + setEntityConfiguration, + getFieldConfiguration }; diff --git a/src/definition/entity/index.js b/src/definition/entity/index.js index befc4b9..d2e14b1 100644 --- a/src/definition/entity/index.js +++ b/src/definition/entity/index.js @@ -1,4 +1,12 @@ -module.exports = { - builder: require('./builder'), - container: require('./container') -}; +import builder from './builder'; +import container from './container'; + +export { + builder, + container +} + +export default { + builder, + container +} \ No newline at end of file diff --git a/src/definition/formatter/index.js b/src/definition/formatter/index.js index de67605..4876e6c 100644 --- a/src/definition/formatter/index.js +++ b/src/definition/formatter/index.js @@ -1,3 +1,9 @@ -module.exports = { - number: require('./number') -}; +import number from './number'; + +export { + number +} + +export default { + number +} \ No newline at end of file diff --git a/src/definition/index.js b/src/definition/index.js index 40f44d7..956ed26 100644 --- a/src/definition/index.js +++ b/src/definition/index.js @@ -1,7 +1,21 @@ -module.exports = { - domain: require('./domain'), - entity: require('./entity'), - validator: require('./validator'), - formatter: require('./formatter'), - checkDomains: require('./check-domains') -}; +import domain from './domain'; +import entity from './entity'; +import validator from './validator'; +import formatter from './formatter'; +import checkDomains from './check-domains'; + +export { + domain, + entity, + validator, + formatter, + checkDomains +} + +export default { + domain, + entity, + validator, + formatter, + checkDomains +} \ No newline at end of file diff --git a/src/definition/validator/date.js b/src/definition/validator/date.js index 2b7d781..4210a1d 100644 --- a/src/definition/validator/date.js +++ b/src/definition/validator/date.js @@ -1,13 +1,11 @@ +import moment from 'moment'; + /** * Validate a date. * @param {string | date} dateToValidate - The date to validate. * @param {object} options - The validator options. * @return {boolean} - True if the date is valide , false otherwise. */ -module.exports = function dateValidation(dateToValidate, options) { - const moment = require('moment'); - if(!moment){ - console.warn('Moment library is not a part of your project, please download it : http://momentjs.com/'); - } +export default function dateValidation(dateToValidate, options) { return moment(dateToValidate, options).isValid(); -}; +} \ No newline at end of file diff --git a/src/definition/validator/email.js b/src/definition/validator/email.js index 523654d..f106298 100644 --- a/src/definition/validator/email.js +++ b/src/definition/validator/email.js @@ -5,6 +5,6 @@ const EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+ * @param {string} emailToValidate - The email to validate. * @return {boolean} - True if the email is valide , false otherwise. */ -module.exports = function emailValidation(emailToValidate) { +export default function emailValidation(emailToValidate) { return EMAIL_REGEX.test(emailToValidate); -}; +} diff --git a/src/definition/validator/index.js b/src/definition/validator/index.js index e3c9381..54978c1 100644 --- a/src/definition/validator/index.js +++ b/src/definition/validator/index.js @@ -1,7 +1,21 @@ -module.exports = { - date: require('./date'), - email: require('./email'), - number: require('./number'), - stringLength: require('./string-length'), - validate: require('./validate') -}; +import date from './date'; +import email from './email'; +import number from './number'; +import stringLength from './string-length'; +import validate from './validate'; + +export { + date, + email, + number, + stringLength, + validate +} + +export default { + date, + email, + number, + stringLength, + validate +} \ No newline at end of file diff --git a/src/definition/validator/string-length.js b/src/definition/validator/string-length.js index bc81c81..b378d32 100644 --- a/src/definition/validator/string-length.js +++ b/src/definition/validator/string-length.js @@ -6,7 +6,7 @@ import isString from 'lodash/lang/isString'; * @param {object} options - Validators options, supports minLength and maxLength both optionals. * @return {boolean} - True if the string is valid , false otherwise. */ -module.exports = function stringLength(stringToTest, options = {}) { +export default function stringLength(stringToTest, options = {}) { if (!isString(stringToTest)) { return false; } @@ -14,4 +14,4 @@ module.exports = function stringLength(stringToTest, options = {}) { const isMinLength = options.minLength !== undefined ? stringToTest.length >= options.minLength : true; const isMaxLength = options.maxLength !== undefined ? stringToTest.length <= options.maxLength : true; return isMinLength && isMaxLength; -}; +} diff --git a/src/exception/argument-invalid-exception.js b/src/exception/argument-invalid-exception.js index 9e51a2e..511cb88 100644 --- a/src/exception/argument-invalid-exception.js +++ b/src/exception/argument-invalid-exception.js @@ -3,7 +3,7 @@ import CustomException from './custom-exception'; * Class standing for the NotImplemented exceptions. */ class ArgumentInvalidException extends CustomException { - /** + /** * Exception constructor. * @param {string} message - Exception message. * @param {object} options - Object to add to the exception. diff --git a/src/exception/argument-null-exception.js b/src/exception/argument-null-exception.js index d833cdc..f33a564 100644 --- a/src/exception/argument-null-exception.js +++ b/src/exception/argument-null-exception.js @@ -13,4 +13,4 @@ class ArgumentNullException extends CustomException { } } -module.exports = ArgumentNullException; +export default ArgumentNullException; diff --git a/src/exception/custom-exception.js b/src/exception/custom-exception.js index 49f1b2c..0e05030 100644 --- a/src/exception/custom-exception.js +++ b/src/exception/custom-exception.js @@ -2,12 +2,12 @@ * Classe standing for custom exception. * @see https://gist.github.com/daliwali/09ca19032ab192524dc6 */ -class CustomException extends Error{ - constructor(name, message, options){ +class CustomException extends Error { + constructor(name, message, options) { super(); - if (Error.hasOwnProperty('captureStackTrace')){ + if (Error.hasOwnProperty('captureStackTrace')) { Error.captureStackTrace(this, this.constructor); - } else{ + } else { Object.defineProperty(this, 'stack', { value: (new Error()).stack }); @@ -17,25 +17,23 @@ class CustomException extends Error{ }); this.options = options; } - get name () { + get name() { return this.constructor.name; } /** * Log the exception in the js console. */ - log(){ + log() { console.error('name', this.name, 'message', this.message, 'options', this.options); } /** * Jsonify the exception. * @return {object} - The json exception. */ - toJSON(){ - const {name, message, options} = this; - return {name, message, options}; + toJSON() { + const { name, message, options } = this; + return { name, message, options }; } } - - -module.exports = CustomException; +export default CustomException; diff --git a/src/exception/dependency-exception.js b/src/exception/dependency-exception.js index 08e94c4..8df1d2e 100644 --- a/src/exception/dependency-exception.js +++ b/src/exception/dependency-exception.js @@ -13,4 +13,4 @@ class DependencyException extends CustomException { } } -module.exports = DependencyException; +export default DependencyException; diff --git a/src/exception/focus-exception.js b/src/exception/focus-exception.js index b4b151c..06cea40 100644 --- a/src/exception/focus-exception.js +++ b/src/exception/focus-exception.js @@ -13,4 +13,4 @@ class FocusException extends CustomException { } } -module.exports = FocusException; +export default FocusException; diff --git a/src/exception/index.js b/src/exception/index.js index 8e5c0f4..1908b7d 100644 --- a/src/exception/index.js +++ b/src/exception/index.js @@ -1,8 +1,24 @@ -module.exports = { - ArgumentInvalidException: require('./argument-invalid-exception'), - ArgumentNullException: require('./argument-null-exception'), - CustomException: require('./custom-exception'), - DependencyException: require('./dependency-exception'), - FocusException: require('./focus-exception'), - NotImplementedException: require('./not-implemented-exception') -}; +import ArgumentInvalidException from './argument-invalid-exception'; +import ArgumentNullException from './argument-null-exception'; +import CustomException from './custom-exception'; +import DependencyException from './dependency-exception'; +import FocusException from './focus-exception'; +import NotImplementedException from './not-implemented-exception'; + +export { + ArgumentInvalidException, + ArgumentNullException, + CustomException, + DependencyException, + FocusException, + NotImplementedException +} + +export default { + ArgumentInvalidException, + ArgumentNullException, + CustomException, + DependencyException, + FocusException, + NotImplementedException +} \ No newline at end of file diff --git a/src/exception/not-implemented-exception.js b/src/exception/not-implemented-exception.js index f94add5..c9fab02 100644 --- a/src/exception/not-implemented-exception.js +++ b/src/exception/not-implemented-exception.js @@ -13,4 +13,4 @@ class NotImplementedException extends CustomException { } } -module.exports = NotImplementedException; +export default NotImplementedException; diff --git a/src/index.js b/src/index.js index 4adb58b..26527b3 100644 --- a/src/index.js +++ b/src/index.js @@ -1,45 +1,59 @@ //http://www.ascii-fr.com/Generateur-de-texte.html +import application from './application'; +import history from './history'; +import component from './component'; +import definition from './definition'; +import dispatcher from './dispatcher'; +import list from './list'; +import exception from './exception'; +import network from './network'; +import router from './router'; +import reference from './reference'; +import search from './search'; +import siteDescription from './site-description'; +import store from './store'; +import util from './util'; +import user from './user'; +import translation from './translation'; +import message from './message'; -const infos = require(`${__PACKAGE_JSON_PATH__}/package.json`); +export default { + application, + history, + component, + definition, + dispatcher, + list, + exception, + network, + router, + reference, + search, + siteDescription, + store, + util, + user, + translation, + message +}; -console.log( - ` - FOCUS CORE - version: ${infos.version} - focus: ${infos.homepage} - documentation: ${infos.documentation} - issues: ${infos.bugs.url} - ` -); -/** -* Focus library. -* This file requires all submodules. -* @type {Object} -*/ -module.exports = { - application: require('./application'), - history: require('./history'), - component: require('./component'), - definition: require('./definition'), - dispatcher: require('./dispatcher'), - list: require('./list'), - exception: require('./exception'), - network: require('./network'), - router: require('./router'), - reference: require('./reference'), - search: require('./search'), - siteDescription: require('./site-description'), - store: require('./store'), - util: require('./util'), - user: require('./user'), - translation: require('./translation'), - message: require('./message'), - VERSION: infos.version, - AUTHOR: infos.author, - DOCUMENTATION(){ - console.log(`documentation: ${infos.documentation}`); - console.log(`repository: ${infos.repository.url}`); - console.log(`issues: ${infos.bugs.url}`); - } +export { + application, + history, + component, + definition, + dispatcher, + list, + exception, + network, + router, + reference, + search, + siteDescription, + store, + util, + user, + translation, + message }; diff --git a/src/list/index.js b/src/list/index.js index 971e022..bb5a18e 100644 --- a/src/list/index.js +++ b/src/list/index.js @@ -1,4 +1,12 @@ -module.exports = { - actionBuilder: require('./action-builder'), - loadAction: require('./load-action') -}; +import actionBuilder from './action-builder'; +import loadAction from './load-action'; + +export { + actionBuilder, + loadAction +} + +export default { + actionBuilder, + loadAction +} \ No newline at end of file diff --git a/src/list/load-action/builder.js b/src/list/load-action/builder.js index 7699f7f..881c1bd 100644 --- a/src/list/load-action/builder.js +++ b/src/list/load-action/builder.js @@ -1,18 +1,16 @@ -import keys from 'lodash/object/keys'; import isArray from 'lodash/lang/isArray'; /** * Build sort infotmation. * @param {object} sortConf - The sort configuration. * @return {object} - The builded sort configuration. */ -function _buildOrderAndSort(sortConf) { +function orderAndSort(sortConf) { return { sortFieldName: sortConf.sortBy, sortDesc: sortConf.sortAsc === undefined ? false : !sortConf.sortAsc }; } - /** * Build the pagination configuration given the options. * @param {object} opts - The pagination options should be : @@ -21,7 +19,7 @@ function _buildOrderAndSort(sortConf) { * nbSearchElement (:number) - The number of elements you want to get back from the search. * @return {object} - An object with {top, skip}. */ -function _buildPagination(opts) { +function pagination(opts) { let { isScroll, dataList, totalCount, nbElement } = opts; if (isScroll) { if (!isArray(dataList)) { @@ -37,7 +35,11 @@ function _buildPagination(opts) { } } -module.exports = { - pagination: _buildPagination, - orderAndSort: _buildOrderAndSort +export { + pagination, + orderAndSort }; +export default { + pagination, + orderAndSort +}; \ No newline at end of file diff --git a/src/list/load-action/parser.js b/src/list/load-action/parser.js index 7a6d003..4a829f4 100644 --- a/src/list/load-action/parser.js +++ b/src/list/load-action/parser.js @@ -1,11 +1,11 @@ //Requirements -module.exports = (data, context) => { - let {dataList, totalCount, ...otherProps} = data; - if(context.isScroll){ +export default (data, context) => { + let { dataList, totalCount, ...otherProps } = data; + if (context.isScroll) { dataList = [...context.dataList, ...data.dataList]; } - if ((dataList.length === 0) && (totalCount > 0)){ + if ((dataList.length === 0) && (totalCount > 0)) { throw new Error('totalCount must be equal to zero when no data are returned!!'); } return ({ diff --git a/src/message/built-in-store.js b/src/message/built-in-store.js index b66ab4c..0774037 100644 --- a/src/message/built-in-store.js +++ b/src/message/built-in-store.js @@ -3,4 +3,4 @@ import MessageStore from '../store/message'; * Built the store in order to the . * @return {MessageStore} - An instanciated reference store. */ -module.exports = new MessageStore(); +export default new MessageStore(); diff --git a/src/message/index.js b/src/message/index.js index 50b487b..c8c5a72 100644 --- a/src/message/index.js +++ b/src/message/index.js @@ -1,5 +1,6 @@ import dispatcher from '../dispatcher'; import isString from 'lodash/lang/isString'; +import builtInStore from './built-in-store'; /** * Transform the message into objet if it is a string. @@ -67,13 +68,22 @@ function clearMessages() { dispatcher.handleServerAction({ data: { messages: {} }, type: 'clear' }); } +export { + addMessage, + addWarningMessage, + addInformationMessage, + addErrorMessage, + addSuccessMessage, + clearMessages, + builtInStore +}; -module.exports = { - addMessage: addMessage, - addWarningMessage: addWarningMessage, - addInformationMessage: addInformationMessage, - addErrorMessage: addErrorMessage, - addSuccessMessage: addSuccessMessage, - clearMessages: clearMessages, - builtInStore: require('./built-in-store') +export default { + addMessage, + addWarningMessage, + addInformationMessage, + addErrorMessage, + addSuccessMessage, + clearMessages, + builtInStore }; diff --git a/src/network/built-in-store.js b/src/network/built-in-store.js index e389839..add27bb 100644 --- a/src/network/built-in-store.js +++ b/src/network/built-in-store.js @@ -3,4 +3,4 @@ import RequestStore from '../store/request'; * Built the store in order to the . * @return {RequestStore} - An instanciated application store. */ -module.exports = new RequestStore(); +export default new RequestStore(); diff --git a/src/network/cancellable-promise-builder.js b/src/network/cancellable-promise-builder.js index 36eeda5..e894ce9 100644 --- a/src/network/cancellable-promise-builder.js +++ b/src/network/cancellable-promise-builder.js @@ -4,7 +4,7 @@ * @returns {boolean} the check result */ function isFunction(functionToCheck) { - var getType = {}; + let getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } @@ -21,18 +21,18 @@ function cancellablePromiseBuilder(promiseFn, cancelHandler) { if (cancelHandler && !isFunction(cancelHandler)) { throw new Error(`Cancel handler ${cancelHandler} is not a function.`); } - var p = new Promise(promiseFn); + let p = new Promise(promiseFn); p.cancel = function cancelCurrentPromise() { - if(cancelHandler) { // cancel handler exists, call it + if (cancelHandler) { // cancel handler exists, call it cancelHandler.call(this, arguments); } else { // cancel handler does not exist but was called, send a warning console.warn('Cancel() called on a CancellablePromise but no cancel handler function was provided at object creation.', this); } }; - p.isCancellable = function() { + p.isCancellable = function () { return cancelHandler !== undefined; }; return p; } -module.exports = cancellablePromiseBuilder; \ No newline at end of file +export default cancellablePromiseBuilder; \ No newline at end of file diff --git a/src/network/config.js b/src/network/config.js index d357d2d..585d7d9 100644 --- a/src/network/config.js +++ b/src/network/config.js @@ -22,10 +22,16 @@ function configure(conf) { } +const get = () => { + return clone(configuration); +} -module.exports = { - configure: configure, - get() { - return clone(configuration); - } +export { + configure, + get +}; + +export default { + configure, + get }; diff --git a/src/network/cors.js b/src/network/cors.js index 6cde54d..6e68284 100644 --- a/src/network/cors.js +++ b/src/network/cors.js @@ -12,10 +12,10 @@ const ArgumentInvalidException = Error; * @param {object} options - The cors options. * @returns {XMLHttpRequest} - The CORS http request. */ -module.exports = function createCORSRequest(method, url, options = {}) { +export default function createCORSRequest(method, url, options = {}) { const isCORS = options.isCORS || false; const noContentType = options.noContentType || false; - + if (typeof method !== 'string') { throw new ArgumentInvalidException('The method should be a string in GET/POST/PUT/DELETE', method); } @@ -35,29 +35,29 @@ module.exports = function createCORSRequest(method, url, options = {}) { } else if (typeof XDomainRequest !== 'undefined') { // XDomainRequest for IE. xhr = new XDomainRequest(); - xhr.onprogress = () => {}; // Needs to be set to get it work on IE9 :/ - xhr.ontimeout = () => {}; // Needs to be set to get it work on IE9 :/ + xhr.onprogress = () => { }; // Needs to be set to get it work on IE9 :/ + xhr.ontimeout = () => { }; // Needs to be set to get it work on IE9 :/ xhr.open(method, url); } else { // CORS not supported. xhr = null; } } - + const headers = options.headers || {}; // Setting 'Content-Type' header only if not in options // Also handling noContentType options - if(!noContentType && !headers['Content-Type']){ + if (!noContentType && !headers['Content-Type']) { if (xhr.setRequestHeader) { xhr.setRequestHeader('Content-Type', 'application/json'); } } // Adding the other headers - for(let prop in headers) { + for (let prop in headers) { if (xhr.setRequestHeader) { xhr.setRequestHeader(prop, headers[prop]); } } return xhr; -}; +} diff --git a/src/network/fetch.js b/src/network/fetch.js index ea0b24e..3227ab6 100644 --- a/src/network/fetch.js +++ b/src/network/fetch.js @@ -4,9 +4,10 @@ */ import createCORSRequest from './cors'; import cancellablePromiseBuilder from './cancellable-promise-builder'; -let uuid = require('uuid').v4; +import { v4 as uuid } from 'uuid'; import dispatcher from '../dispatcher'; import isObject from 'lodash/lang/isObject'; +import { get as configGetter } from './config'; /** * Create a pending status. @@ -67,7 +68,7 @@ function jsonParser(req) { function fetch(obj, options = {}) { options.parser = options.parser || jsonParser; options.errorParser = options.errorParser || jsonParser; - let config = require('./config').get(); + let config = configGetter(); let request = createCORSRequest(obj.method, obj.url, { ...config, ...options }); let requestStatus = createRequestStatus(); if (!request) { @@ -92,13 +93,13 @@ function fetch(obj, options = {}) { updateRequestStatus({ id: requestStatus.id, status: 'error' }); return failure(err); } + let data; if (204 === status) { data = undefined; updateRequestStatus({ id: requestStatus.id, status: 'success' }); return success(data); } let contentType = request.contentType ? request.contentType : request.getResponseHeader('content-type'); - let data; if (contentType && contentType.indexOf('application/json') !== -1) { data = options.parser(request); } else { @@ -122,4 +123,4 @@ function fetch(obj, options = {}) { }); } -module.exports = fetch; +export default fetch; diff --git a/src/network/index.js b/src/network/index.js index fea4b5a..f3468a0 100644 --- a/src/network/index.js +++ b/src/network/index.js @@ -1,8 +1,24 @@ -module.exports = { - cors: require('./cors'), - fetch: require('./fetch'), - cancellablePromiseBuilder: require('./cancellable-promise-builder'), - builtInStore: require('./built-in-store'), - config: require('./config'), - errorParsing: require('./error-parsing') -}; +import cors from './cors'; +import fetch from './fetch'; +import cancellablePromiseBuilder from './cancellable-promise-builder'; +import builtInStore from './built-in-store'; +import config from './config'; +import errorParsing from './error-parsing'; + +export default { + cors, + fetch, + cancellablePromiseBuilder, + builtInStore, + config, + errorParsing +} + +export { + cors, + fetch, + cancellablePromiseBuilder, + builtInStore, + config, + errorParsing +} diff --git a/src/reference/builder.js b/src/reference/builder.js index 9675911..92ed746 100755 --- a/src/reference/builder.js +++ b/src/reference/builder.js @@ -1,5 +1,5 @@ /*global Promise, _*/ -'use strict'; + /* Filename: helpers/reference_helper.js */ //Dependency gestion depending on the fact that we are in the browser or in node. @@ -7,14 +7,14 @@ import fetch from '../network/fetch'; import checkIsString from '../util/string/check'; //Container for the list and -import {getElement, getCacheDuration} from './config'; +import { getElement, getCacheDuration } from './config'; let cache = {}; const promiseWaiting = []; function _deletePromiseWaiting(name) { const indexPrm = promiseWaiting.indexOf(name); - if(indexPrm !== -1) { + if (indexPrm !== -1) { promiseWaiting.splice(indexPrm, 1); } } @@ -26,7 +26,7 @@ function _getTimeStamp() { * Serve the data from the cache. */ function _cacheData(key, value) { - cache[key] = {timeStamp: _getTimeStamp(), value: value}; + cache[key] = { timeStamp: _getTimeStamp(), value: value }; _deletePromiseWaiting(key); return value; } @@ -51,38 +51,38 @@ function loadList(listDesc) { function loadListByName(listName, args, skipCache = false) { checkIsString('listName', listName); const configurationElement = getElement(listName); - if (typeof configurationElement !== `function`) { + if (typeof configurationElement !== 'function') { throw new Error(`You are trying to load the reference list: ${listName} which does not have a list configure.`); } let now = _getTimeStamp(); - if(cache[listName] && (now - cache[listName].timeStamp) < getCacheDuration() && !skipCache) { + if (cache[listName] && (now - cache[listName].timeStamp) < getCacheDuration() && !skipCache) { _deletePromiseWaiting(listName); //console.info('data served from cache', listName, cache[listName].value); return Promise.resolve(cache[listName].value); } //Call the service, the service must return a promise. return configurationElement(args) - .then((data) => { - return _cacheData(listName, data) - }); + .then((data) => { + return _cacheData(listName, data) + }); } //Load many lists by their names. `refHelper.loadMany(['list1', 'list2']).then(success, error)` // Return an array of many promises for all the given lists. // Be carefull, if there is a problem for one list, the error callback is called. function loadMany(names, skipCache = false) { - if(names === undefined){ + if (names === undefined) { return []; } - if(!Array.isArray(names)){ + if (!Array.isArray(names)) { throw new Error('LoadMany is expecting an array.'); } return names.reduce((acc, name) => { - if(promiseWaiting.indexOf(name) !== -1){ + if (promiseWaiting.indexOf(name) !== -1) { return acc; } promiseWaiting.push(name); - return acc.concat([loadListByName(name, null, skipCache).then(dataList => ({name, dataList: dataList}))]); + return acc.concat([loadListByName(name, null, skipCache).then(dataList => ({ name, dataList: dataList }))]); }, []); } /** @@ -98,9 +98,16 @@ function getAutoCompleteServiceQuery(listName) { }; } -module.exports = { - loadListByName: loadListByName, - loadList: loadList, - loadMany: loadMany, - getAutoCompleteServiceQuery: getAutoCompleteServiceQuery +export { + loadListByName, + loadList, + loadMany, + getAutoCompleteServiceQuery +}; + +export default { + loadListByName, + loadList, + loadMany, + getAutoCompleteServiceQuery }; diff --git a/src/reference/built-in-store.js b/src/reference/built-in-store.js index f4cbcfd..2c4a464 100644 --- a/src/reference/built-in-store.js +++ b/src/reference/built-in-store.js @@ -6,9 +6,9 @@ let ref; * Built the store in order to the . * @return {ReferenceStore} - An instanciated reference store. */ -module.exports = function () { +export default function () { if (!ref) { ref = new ReferenceStore(); } return ref; -}; +} diff --git a/src/reference/config.js b/src/reference/config.js index bf9315a..af5be38 100644 --- a/src/reference/config.js +++ b/src/reference/config.js @@ -49,11 +49,19 @@ function getConfigElement(name) { } } +export { + getConfig as get, + getConfigElement as getElement, + setConfig as set, + getCacheDuration, + setCacheDuration +}; -module.exports = { +export default { get: getConfig, getElement: getConfigElement, set: setConfig, getCacheDuration, setCacheDuration + }; diff --git a/src/reference/index.js b/src/reference/index.js index 7987af7..83c7647 100644 --- a/src/reference/index.js +++ b/src/reference/index.js @@ -1,6 +1,18 @@ -module.exports = { - config: require('./config'), - builder: require('./builder'), - builtInAction: require('./built-in-action'), - storeGetter: require('./built-in-store') +import config from './config'; +import builder from './builder'; +import builtInAction from './built-in-action'; +import storeGetter from './built-in-store'; + +export { + config, + builder, + builtInAction, + storeGetter }; + +export default { + config, + builder, + builtInAction, + storeGetter +}; \ No newline at end of file diff --git a/src/search/action-builder.js b/src/search/action-builder.js index dd2bb05..b63ae14 100644 --- a/src/search/action-builder.js +++ b/src/search/action-builder.js @@ -18,7 +18,7 @@ const NB_SEARCH_ELEMENT = 50; * ``` * @return {function} - The builded search action. */ -module.exports = function(config) { +export default function (config) { config = config || {}; if (!config.identifier) { console.warn('Your action should have an identifier'); @@ -33,10 +33,10 @@ module.exports = function(config) { config.nbSearchElement = NB_SEARCH_ELEMENT; } return { - /** - * Build the search for the identifier scope. - * @return {function} The search function for the given identifier. - */ + /** + * Build the search for the identifier scope. + * @return {function} The search function for the given identifier. + */ search: searchAction(config), /** * Update the query for the identifier scope. @@ -51,4 +51,4 @@ module.exports = function(config) { }); } }; -}; +} diff --git a/src/search/built-in-store.js b/src/search/built-in-store.js index b094971..cd27af8 100644 --- a/src/search/built-in-store.js +++ b/src/search/built-in-store.js @@ -1,7 +1,15 @@ import AdvancedSearchStore from '../store/search/advanced-search'; import QuickSearchStore from '../store/search/quick-search'; -module.exports = { - quickSearchStore: new QuickSearchStore(), - advancedSearchStore: new AdvancedSearchStore() +const quickSearchStore = new QuickSearchStore(); +const advancedSearchStore = new AdvancedSearchStore(); + +export { + advancedSearchStore, + quickSearchStore }; + +export default { + advancedSearchStore, + quickSearchStore +}; \ No newline at end of file diff --git a/src/search/index.js b/src/search/index.js index 8cbdfba..bbbe1d8 100644 --- a/src/search/index.js +++ b/src/search/index.js @@ -1,14 +1,12 @@ -module.exports = { - builtInStore: require('./built-in-store'), - /** - * Action builder - */ - actionBuilder: require('./action-builder'), - log() { - let builtInStore = require('./built-in-store'); - console.info('---------------------------'); - console.info('QuickSearch', builtInStore.quickSearchStore.value); - console.info('AdvancedSearch', builtInStore.advancedSearchStore.value); - console.info('---------------------------'); - } +import builtInStore from './built-in-store'; +import actionBuilder from './action-builder'; + +export { + builtInStore, + actionBuilder }; + +export default { + builtInStore, + actionBuilder +}; \ No newline at end of file diff --git a/src/search/search-action/builder.js b/src/search/search-action/builder.js index 3a6a194..7f3d7da 100644 --- a/src/search/search-action/builder.js +++ b/src/search/search-action/builder.js @@ -28,37 +28,42 @@ const _buildFacets = facets => { */ const _buildOrderAndSort = sortConf => { return { - sortFieldName: sortConf.sortBy, - sortDesc: sortConf.sortAsc === undefined?false:!sortConf.sortAsc + sortFieldName: sortConf.sortBy, + sortDesc: sortConf.sortAsc === undefined ? false : !sortConf.sortAsc } }; - const _buildPagination = opts => { const resultsKeys = keys(opts.results); - if(opts.isScroll && resultsKeys.length === 1){ - const key = resultsKeys[0]; - const previousRes = opts.results[key]; - if(previousRes.length < opts.totalCount){ - return { - top: opts.nbSearchElement, - skip: previousRes.length - }; - //Else should not be called. - console.warn('This should not happen.') - }; + if (opts.isScroll && resultsKeys.length === 1) { + const key = resultsKeys[0]; + const previousRes = opts.results[key]; + if (previousRes.length < opts.totalCount) { + return { + top: opts.nbSearchElement, + skip: previousRes.length + }; + } else { + //Else should not be called. + console.warn('This should not happen.') + } } else { - return { - skip: 0, - top: opts.nbSearchElement || 0 - } + return { + skip: 0, + top: opts.nbSearchElement || 0 + } } }; - -module.exports = { - pagination: _buildPagination, - orderAndSort: _buildOrderAndSort, - facets: _buildFacets +export { + _buildPagination as pagination, + _buildOrderAndSort as orderAndSort, + _buildFacets as facets }; + +export default { + pagination: _buildPagination, + orderAndSort: _buildOrderAndSort, + facets: _buildFacets +}; \ No newline at end of file diff --git a/src/search/search-action/index.js b/src/search/search-action/index.js index 8d2e399..cabfc9c 100644 --- a/src/search/search-action/index.js +++ b/src/search/search-action/index.js @@ -15,7 +15,7 @@ const STAR = '*'; * @param {object} config - Action configuration. * @return {function} - The generated action from the congig. */ -module.exports = function searchActionBuilder(config) { +export default function searchActionBuilder(config) { /** * Dispatch the results on the search store * @param {object} data - The data to dispatch. @@ -99,4 +99,4 @@ module.exports = function searchActionBuilder(config) { .catch(_errorOnCall); } }; -}; +} diff --git a/src/search/search-action/parser.js b/src/search/search-action/parser.js index 0103533..96e6a4a 100644 --- a/src/search/search-action/parser.js +++ b/src/search/search-action/parser.js @@ -65,7 +65,7 @@ const _parseFacets = (serverFacets) => { const facetItemName = serverFacetItemPopertyNames[0]; const facetItemValue = serverFacetItem[facetItemName]; // The facet content is now an array instead of an object to preserve sorting. - facetData.push( { + facetData.push({ label: facetItemName, count: facetItemValue }); @@ -87,21 +87,25 @@ const _parseUnscopedResponse = (data) => { const _parseScopedResponse = (data, context) => { //Scroll can only happen when there is an ungroupSearch - if(context.isScroll){ + if (context.isScroll) { let resultsKeys = keys(context.results); let key = resultsKeys[0]; //Concat previous data with incoming data. data.list = [...context.results[key], ...data.list]; } return ({ - results: data.groups || {[context.scope]: data.list}, + results: data.groups || { [context.scope]: data.list }, facets: _parseFacets(data.facets), totalCount: data.totalCount }); }; - -module.exports = { +export default { unscopedResponse: _parseUnscopedResponse, scopedResponse: _parseScopedResponse }; + +export { + _parseUnscopedResponse as unscopedResponse, + _parseScopedResponse as scopedResponse +}; \ No newline at end of file diff --git a/src/site-description/builder.js b/src/site-description/builder.js index 9bbe087..f9bc52a 100644 --- a/src/site-description/builder.js +++ b/src/site-description/builder.js @@ -165,13 +165,24 @@ function regenerateRoutes() { _processElement(siteDescription); } -module.exports = { - getRoute: getRoute, - getRoutes: getRoutes, - getSiteDescription: getSiteDescription, - regenerateRoutes: regenerateRoutes, - getSiteStructure: getSiteStructure, - processSiteDescription: processSiteDescription, - findRouteName: findRouteName, - routeToRegExp: routeToRegExp +export { + getRoute, + getRoutes, + getSiteDescription, + regenerateRoutes, + getSiteStructure, + processSiteDescription, + findRouteName, + routeToRegExp +}; + +export default { + getRoute, + getRoutes, + getSiteDescription, + regenerateRoutes, + getSiteStructure, + processSiteDescription, + findRouteName, + routeToRegExp }; diff --git a/src/site-description/index.js b/src/site-description/index.js index 4a7bac3..1c23753 100644 --- a/src/site-description/index.js +++ b/src/site-description/index.js @@ -1,15 +1,23 @@ -import _builder from './builder'; +import builder from './builder'; +import reader from './reader'; + /** * @description Get th site structure processed with the user roles. * @return {object} - The user site structure. */ function getUserSiteStructure() { //Seems wiered looking like a ci - return _builder.getSiteStructure(); + return builder.getSiteStructure(); } -module.exports = { - builder: _builder, - reader: require('./reader'), - getUserSiteStructure: getUserSiteStructure +export { + builder, + reader, + getUserSiteStructure }; + +export default { + builder, + reader, + getUserSiteStructure +}; \ No newline at end of file diff --git a/src/site-description/reader.js b/src/site-description/reader.js index 5e508fa..4874a8e 100644 --- a/src/site-description/reader.js +++ b/src/site-description/reader.js @@ -1,5 +1,4 @@ -let ArgumentNullException = require('../exception').ArgumentNullException; -let ArgumentInvalidException = require('../exception').ArgumentInvalidException; +import { ArgumentNullException, ArgumentInvalidException } from '../exception'; import isObject from 'lodash/lang/isObject'; import isFunction from 'lodash/lang/isFunction'; @@ -101,4 +100,4 @@ let siteDescriptionHelper = { } }; -module.exports = siteDescriptionHelper; +export default siteDescriptionHelper; diff --git a/src/store/application/definition.js b/src/store/application/definition.js index 51759b7..4e98c9d 100644 --- a/src/store/application/definition.js +++ b/src/store/application/definition.js @@ -2,10 +2,10 @@ * Build the cartridge store definition. * @return {object} - The cartridge component. */ -module.exports = () => { +export default () => { return ['summaryComponent', 'barContentLeftComponent', 'barContentRightComponent', 'cartridgeComponent', 'actions', 'mode', 'route', 'confirmConfig', 'canDeploy'] - .reduce((def, node) => { - def[node] = node; - return def; - }, {}); + .reduce((def, node) => { + def[node] = node; + return def; + }, {}); }; diff --git a/src/store/application/index.js b/src/store/application/index.js index e60766b..3fc7b5f 100644 --- a/src/store/application/index.js +++ b/src/store/application/index.js @@ -1 +1,2 @@ -module.exports = require('./store'); +import ApplicationStore from './store'; +export default ApplicationStore; diff --git a/src/store/application/store.js b/src/store/application/store.js index 9281345..bb4b84a 100644 --- a/src/store/application/store.js +++ b/src/store/application/store.js @@ -17,9 +17,9 @@ class ApplicationStore extends CoreStore { */ updateMode(dataNode) { let modeData = this.data.has('mode') ? this.data.get('mode') : Immutable.fromJS({}); - let newModeValue = modeData.has(dataNode.newMode)? (modeData.get(dataNode.newMode) + 1) : 1; + let newModeValue = modeData.has(dataNode.newMode) ? (modeData.get(dataNode.newMode) + 1) : 1; //Add a check to not have a negative mode, but it should not happen. - let previousModeValue = modeData.has(dataNode.previousMode)? (modeData.get(dataNode.previousMode) - 1) : 0; + let previousModeValue = modeData.has(dataNode.previousMode) ? (modeData.get(dataNode.previousMode) - 1) : 0; this.data = this.data.set('mode', modeData.set(dataNode.newMode, newModeValue).set(dataNode.previousMode, previousModeValue) ); @@ -27,4 +27,4 @@ class ApplicationStore extends CoreStore { } } -module.exports = ApplicationStore; +export default ApplicationStore; diff --git a/src/store/index.js b/src/store/index.js index 1158e6e..3c35847 100644 --- a/src/store/index.js +++ b/src/store/index.js @@ -1,10 +1,30 @@ -module.exports = { - CoreStore: require('./CoreStore'), - MessageStore: require('./message'), - ApplicationStore: require('./application'), - ListStore: require('./list'), - SearchStore: require('./search'), - ReferenceStore: require('./reference'), - UserStore: require('./user'), - RequestStore: require('./request') +import CoreStore from './CoreStore'; +import MessageStore from './message'; +import ApplicationStore from './application'; +import ListStore from './list'; +import SearchStore from './search'; +import ReferenceStore from './reference'; +import UserStore from './user'; +import RequestStore from './request'; + +export { + CoreStore, + MessageStore, + ApplicationStore, + ListStore, + SearchStore, + ReferenceStore, + UserStore, + RequestStore +}; + +export default { + CoreStore, + MessageStore, + ApplicationStore, + ListStore, + SearchStore, + ReferenceStore, + UserStore, + RequestStore }; diff --git a/src/store/list/index.js b/src/store/list/index.js index c42a169..4942af0 100644 --- a/src/store/list/index.js +++ b/src/store/list/index.js @@ -31,4 +31,4 @@ class ListStore extends CoreStore { super(conf); } } -module.exports = ListStore; +export default ListStore; diff --git a/src/store/message/definition.js b/src/store/message/definition.js index af4708a..48f1fd4 100644 --- a/src/store/message/definition.js +++ b/src/store/message/definition.js @@ -2,8 +2,8 @@ * Build the cartridge store definition. * @return {object} - The error store component. */ -module.exports = function(){ - return { - 'messages': 'messages' - }; -}; +export default function () { + return { + messages: 'messages' + }; +} diff --git a/src/store/message/index.js b/src/store/message/index.js index e60766b..338be2d 100644 --- a/src/store/message/index.js +++ b/src/store/message/index.js @@ -1 +1,2 @@ -module.exports = require('./store'); +import MessageStore from './store'; +export default MessageStore; diff --git a/src/store/message/store.js b/src/store/message/store.js index 779b42e..dab5212 100644 --- a/src/store/message/store.js +++ b/src/store/message/store.js @@ -1,7 +1,7 @@ //Dependencies. import CoreStore from '../CoreStore'; import getDefinition from './definition'; -let uuid = require('uuid').v4; +import { v4 as uuid } from 'uuid'; const PUSH = 'push'; const CLEAR = 'clear'; import AppDispatcher from '../../dispatcher'; @@ -90,7 +90,7 @@ class MessageStore extends CoreStore { } registerDispatcher() { let currentStore = this; - this.dispatch = AppDispatcher.register(function(transferInfo) { + this.dispatch = AppDispatcher.register(function (transferInfo) { let rawData = transferInfo.action.data; let type = transferInfo.action.type; @@ -110,4 +110,4 @@ class MessageStore extends CoreStore { } } -module.exports = MessageStore; +export default MessageStore; diff --git a/src/store/reference/index.js b/src/store/reference/index.js index e60766b..df6b8d1 100644 --- a/src/store/reference/index.js +++ b/src/store/reference/index.js @@ -1 +1,2 @@ -module.exports = require('./store'); +import ReferenceStore from './store'; +export default ReferenceStore; \ No newline at end of file diff --git a/src/store/request/definition.js b/src/store/request/definition.js index b48e637..db13994 100644 --- a/src/store/request/definition.js +++ b/src/store/request/definition.js @@ -2,11 +2,11 @@ * Build the cartridge store definition. * @return {object} - The error store component. */ -module.exports = function(){ - return { - 'error': 'error', - 'success': 'success', - 'pending': 'pending', - 'cancelled': 'cancelled' - }; -}; +export default function () { + return { + error: 'error', + success: 'success', + pending: 'pending', + cancelled: 'cancelled' + }; +} diff --git a/src/store/request/index.js b/src/store/request/index.js index e60766b..287da31 100644 --- a/src/store/request/index.js +++ b/src/store/request/index.js @@ -1 +1,2 @@ -module.exports = require('./store'); +import RequestStore from './store'; +export default RequestStore; \ No newline at end of file diff --git a/src/store/request/store.js b/src/store/request/store.js index 1c62da9..95ca8ae 100644 --- a/src/store/request/store.js +++ b/src/store/request/store.js @@ -2,10 +2,10 @@ import Immutable from 'immutable'; import CoreStore from '../CoreStore'; import getDefinition from './definition'; -let uuid = require('uuid').v4; +import { v4 as uuid } from 'uuid'; const CLEAR = 'clear'; const UPDATE = 'update'; -import AppDispatcher from '../../dispatcher'; +import AppDispatcher from '../../dispatcher'; /** * Class standing for the cartridge store. @@ -103,10 +103,10 @@ class RequestStore extends CoreStore { } registerDispatcher() { let currentStore = this; - this.dispatch = AppDispatcher.register(function(transferInfo) { + this.dispatch = AppDispatcher.register(function (transferInfo) { let rawData = transferInfo.action.data; let type = transferInfo.action.type; - if (!rawData || !rawData.request) {return;} + if (!rawData || !rawData.request) { return; } switch (type) { case 'update': if (rawData.request) { @@ -123,4 +123,4 @@ class RequestStore extends CoreStore { } } -module.exports = RequestStore; +export default RequestStore; diff --git a/src/store/search/index.js b/src/store/search/index.js index 60c05aa..9d444d5 100644 --- a/src/store/search/index.js +++ b/src/store/search/index.js @@ -1,4 +1,12 @@ -module.exports = { - QuickSearch: require('./quick-search'), - AdvancedSearch: require('./advanced-search') -}; +import QuickSearch from './quick-search'; +import AdvancedSearch from './advanced-search'; + +export { + QuickSearch, + AdvancedSearch +} + +export default { + QuickSearch, + AdvancedSearch +} \ No newline at end of file diff --git a/src/store/search/quick-search/index.js b/src/store/search/quick-search/index.js index 8b5ee87..dda1209 100644 --- a/src/store/search/quick-search/index.js +++ b/src/store/search/quick-search/index.js @@ -31,4 +31,4 @@ class QuickSearchStore extends SearchStore { } } -module.exports = QuickSearchStore; +export default QuickSearchStore; diff --git a/src/store/search/search-store.js b/src/store/search/search-store.js index e098a9e..342654b 100644 --- a/src/store/search/search-store.js +++ b/src/store/search/search-store.js @@ -9,4 +9,4 @@ class SearchStore extends CoreStore { } } -module.exports = SearchStore; +export default SearchStore; diff --git a/src/store/user/definition.js b/src/store/user/definition.js index e16d6b8..0cf844e 100644 --- a/src/store/user/definition.js +++ b/src/store/user/definition.js @@ -2,10 +2,10 @@ * Build the user store definition from the login and profile. * @return {[type]} [description] */ -module.exports = function(){ +export default function () { return { - login: 'login', - profile: 'profile', - roles: 'roles' - }; -}; + login: 'login', + profile: 'profile', + roles: 'roles' + }; +} diff --git a/src/store/user/index.js b/src/store/user/index.js index e60766b..1d81a3e 100644 --- a/src/store/user/index.js +++ b/src/store/user/index.js @@ -1 +1,2 @@ -module.exports = require('./store'); +import UserStore from './store'; +export default UserStore; diff --git a/src/store/user/store.js b/src/store/user/store.js index 55d300e..3d80857 100644 --- a/src/store/user/store.js +++ b/src/store/user/store.js @@ -13,4 +13,4 @@ class UserStore extends CoreStore { } -module.exports = UserStore; +export default UserStore; diff --git a/src/user/built-in-store.js b/src/user/built-in-store.js index 00634b6..cf93cb2 100644 --- a/src/user/built-in-store.js +++ b/src/user/built-in-store.js @@ -1,2 +1,2 @@ import UserStore from '../store/user'; -module.exports = new UserStore(); +export default new UserStore(); diff --git a/src/user/index.js b/src/user/index.js index a76606d..19cc823 100644 --- a/src/user/index.js +++ b/src/user/index.js @@ -11,57 +11,75 @@ import dispatcher from '../dispatcher'; function _setUserNode(name, value) { dispatcher.handleViewAction({ data: { [name]: value }, type: 'update' }); } -module.exports = { - builtInStore: userBuiltInStore, - /** - * Check if a user has the givent role or roles. - * @param {string | array} role - Check if the user has one or many roles. - * @return {Boolean} - True if the user has at least on of the givent roles. - */ - hasRole(role) { - role = isArray(role) ? role : [role]; - return 0 < intersection(role, userBuiltInStore.getRoles()).length; - }, - /** +/** +* Check if a user has the givent role or roles. +* @param {string | array} role - Check if the user has one or many roles. +* @return {Boolean} - True if the user has at least on of the givent roles. +*/ +function hasRole(role) { + role = isArray(role) ? role : [role]; + return 0 < intersection(role, userBuiltInStore.getRoles()).length; +} +/** * Set the user roles. * @param {array} roles - User role list. */ - setRoles(roles) { - _setUserNode('roles', roles); - }, - /** - * Get the user roles. - * @return {array} - The user role list. - */ - getRoles() { - return userBuiltInStore.getRoles(); - }, - /** - * Set the user profile. - * @param {object} profile User profile. - */ - setProfile(profile) { - _setUserNode('profile', profile); - }, - /** - * Get the user profile. - * @return {object} profile User profile. - */ - getProfile() { - return userBuiltInStore.getProfile(); - }, - /** - * Set user profile. - * @param {object} login - user login. - */ - setLogin(login) { - _setUserNode('login', login); - }, - /** - * Get the user login. - * @return {object} - The user login. - */ - getLogin() { - return userBuiltInStore.getLogin(); - } +function setRoles(roles) { + _setUserNode('roles', roles); +} +/** +* Get the user roles. +* @return {array} - The user role list. +*/ +function getRoles() { + return userBuiltInStore.getRoles(); +} +/** +* Set the user profile. +* @param {object} profile User profile. +*/ +function setProfile(profile) { + _setUserNode('profile', profile); +} +/** +* Get the user profile. +* @return {object} profile User profile. +*/ +function getProfile() { + return userBuiltInStore.getProfile(); +} +/** +* Set user profile. +* @param {object} login - user login. +*/ +function setLogin(login) { + _setUserNode('login', login); +} +/** +* Get the user login. +* @return {object} - The user login. +*/ +function getLogin() { + return userBuiltInStore.getLogin(); +} +export default { + builtInStore: userBuiltInStore, + hasRole, + setRoles, + getRoles, + setProfile, + getProfile, + setLogin, + getLogin +}; + +export { + userBuiltInStore as builtInStore, + hasRole, + setRoles, + getRoles, + setProfile, + getProfile, + setLogin, + getLogin }; diff --git a/src/user/login/definition.js b/src/user/login/definition.js index 4093367..b7f9d7b 100644 --- a/src/user/login/definition.js +++ b/src/user/login/definition.js @@ -1,4 +1,4 @@ -module.exports = { +export default { login: 'login', password: 'password' }; diff --git a/src/user/login/index.js b/src/user/login/index.js index 686b4b3..5bc3899 100644 --- a/src/user/login/index.js +++ b/src/user/login/index.js @@ -1,3 +1,9 @@ -module.exports = { - definition: require('./definition') -}; +import definition from './definition'; + +export default { + definition +} + +export { + definition +} \ No newline at end of file diff --git a/src/user/profile/definition.js b/src/user/profile/definition.js index 7c762d3..cbf4d2c 100644 --- a/src/user/profile/definition.js +++ b/src/user/profile/definition.js @@ -1,10 +1,10 @@ -module.exports = { - id: 'id', - provider: 'provider', - displayName: 'displayName', - culture: 'culture', - email: 'email', - photo: 'photo', - firstName: 'firstName', - lastName: 'lastName' +export default { + id: 'id', + provider: 'provider', + displayName: 'displayName', + culture: 'culture', + email: 'email', + photo: 'photo', + firstName: 'firstName', + lastName: 'lastName' }; diff --git a/src/user/profile/index.js b/src/user/profile/index.js index 686b4b3..abfd406 100644 --- a/src/user/profile/index.js +++ b/src/user/profile/index.js @@ -1,3 +1,9 @@ -module.exports = { - definition: require('./definition') -}; +import definition from './definition'; + +export { + definition +} + +export default { + definition +} \ No newline at end of file diff --git a/src/util/index.js b/src/util/index.js index 0c826c9..818869b 100644 --- a/src/util/index.js +++ b/src/util/index.js @@ -1,5 +1,15 @@ -module.exports = { - string: require('./string'), - object: require('./object'), - url: require('./url') -}; +import string from './string'; +import object from './object'; +import url from './url'; + +export { + string, + object, + url +} + +export default { + string, + object, + url +} \ No newline at end of file diff --git a/src/util/object/checkIsNotNull.js b/src/util/object/checkIsNotNull.js index 0a44bad..e095d14 100644 --- a/src/util/object/checkIsNotNull.js +++ b/src/util/object/checkIsNotNull.js @@ -11,8 +11,8 @@ import isNull from 'lodash/lang/isNull'; * @returns {undefined} - Return nothing, throw an Exception if this is not valid. * @example var objToTest = { papa : "singe"}; isNull('objToTest', objToTest); */ -module.exports = function (name, data) { +export default function (name, data) { if (isNull(data) || isUndefined(data)) { throw new ArgumentNullException(`${name} should be defined`); } -}; +} diff --git a/src/util/object/index.js b/src/util/object/index.js index 7d7fb0f..24aaf0e 100644 --- a/src/util/object/index.js +++ b/src/util/object/index.js @@ -1,4 +1,12 @@ -module.exports = { - check: require('./check'), - checkIsNotNull: require('./checkIsNotNull') -}; +import check from './check'; +import checkIsNotNull from './checkIsNotNull'; + +export { + check, + checkIsNotNull +} + +export default { + check, + checkIsNotNull +} \ No newline at end of file diff --git a/src/util/string/check.js b/src/util/string/check.js index bc2cac5..0e6de20 100644 --- a/src/util/string/check.js +++ b/src/util/string/check.js @@ -1,6 +1,5 @@ -var ArgumentInvalidException = require( - '../../exception/argument-invalid-exception'); -var isString = require('lodash/lang/isString'); +import ArgumentInvalidException from '../../exception/argument-invalid-exception'; +import isString from 'lodash/lang/isString'; /** * Assert an object is an objet. @@ -8,8 +7,8 @@ var isString = require('lodash/lang/isString'); * @param {string} data - The data to validate. * @return {undefined} - Return nothing, throw an Exception if this is not valid. */ -module.exports = function(name, data) { - if (!isString(data)) { - throw new ArgumentInvalidException(`${name} should be a string`, data); - } -}; +export default function (name, data) { + if (!isString(data)) { + throw new ArgumentInvalidException(`${name} should be a string`, data); + } +} diff --git a/src/util/string/index.js b/src/util/string/index.js index 2f01a3e..fa445cb 100644 --- a/src/util/string/index.js +++ b/src/util/string/index.js @@ -1,3 +1,9 @@ -module.exports = { - check: require('./check') -}; +import check from './check'; + +export { + check +} + +export default { + check +} \ No newline at end of file diff --git a/src/util/url/builder.js b/src/util/url/builder.js index a5bdf68..09381e5 100644 --- a/src/util/url/builder.js +++ b/src/util/url/builder.js @@ -5,7 +5,7 @@ import urlProcessor from './processor'; * @param method - HTTP verb {GET, POST, PUT, DELETE} * @return {function} */ -module.exports = function (url, method) { +export default function (url, method) { /** * Function returns by the module. * @param {object} param - urlData: The JSON data to inject in the URL, data: The JSON data to give to the request. @@ -21,4 +21,4 @@ module.exports = function (url, method) { data: param.data || param.bodyData }; }; -}; +} diff --git a/src/util/url/index.js b/src/util/url/index.js index d56863f..55614bb 100644 --- a/src/util/url/index.js +++ b/src/util/url/index.js @@ -1,4 +1,12 @@ -module.exports = { - builder: require('./builder'), - preprocessor: require('./processor') -}; +import builder from './builder'; +import preprocessor from './processor'; + +export { + builder, + preprocessor +} + +export default { + builder, + preprocessor +} \ No newline at end of file diff --git a/src/util/url/processor.js b/src/util/url/processor.js index 98cc72c..a813bf0 100644 --- a/src/util/url/processor.js +++ b/src/util/url/processor.js @@ -2,6 +2,6 @@ import compile from 'lodash/string/template'; /** * Process an url in order to build them. */ -module.exports = function (url, data) { +export default function (url, data) { return compile(url)(data); -}; +} From ace131beca997b2c9738eb695b574867cf538562 Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Mon, 11 Sep 2017 10:44:09 +0200 Subject: [PATCH 27/32] Updating dependencies, fixing package.json --- package.json | 30 ++++++++++++++---------------- src/network/error-parsing.js | 1 - 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/package.json b/package.json index 2821c0e..3f38cdd 100644 --- a/package.json +++ b/package.json @@ -26,34 +26,33 @@ }, "scripts": { "build": "better-npm-run babelify", - "babelify": "better-npm-run babelify", "test": "better-npm-run test", "test:watch": "better-npm-run test-watch", - "prepublish": "npm run build", + "prepare": "npm run build", "lint": "eslint src --ext .js,.jsx --ignore-pattern __tests__ --ignore-pattern example --ignore-pattern awesomplete", "lint:error": "eslint src --ext .js,.jsx --ignore-pattern __tests__ --ignore-pattern example --ignore-pattern awesomplete --quiet", - "fix-lint": "eslint src/** --ext .js,.jsx --fix --ignore-pattern __tests__ --ignore-pattern example --ignore-pattern awesomplete" + "fix-lint": "eslint src/** --ext .js,.jsx --fix --ignore-pattern __tests__ --ignore-pattern example --ignore-pattern awesomplete" }, "betterScripts": { "babelify": { "env": { - "BABEL_ENV": "production" + "BABEL_ENV": "production", + "LEGACY_EXPORTS": "true" }, "command": "node scripts/babelify.js" }, - "copy-sass": { - "command": "cd src && find . -name *.scss | xargs tar cvf - | tar xfp - -C ../" - }, "test": { "command": "jest --config jest-config.js --runInBand --no-cache", "env": { - "BABEL_ENV": "production" + "BABEL_ENV": "production", + "LEGACY_EXPORTS": "true" } }, "test-watch": { "command": "jest --config jest-config.js --runInBand --watch ", "env": { - "BABEL_ENV": "production" + "BABEL_ENV": "production", + "LEGACY_EXPORTS": "true" } } }, @@ -63,7 +62,7 @@ }, "dependencies": { "flux": "3.1.3", - "i18next": "8.4.3", + "i18next": "9.0.0", "immutable": "3.8.1", "lodash": "3.10.1", "numeral": "2.0.6", @@ -71,13 +70,12 @@ "uuid": "3.1.0" }, "devDependencies": { - "babel-jest": "20.0.3", - "babel-preset-focus": "0.7.0", + "babel-jest": "21.0.2", + "babel-preset-focus": "1.0.0-beta1", "better-npm-run": "0.1.0", - "eslint-config-focus": "git://github.com/KleeGroup/eslint-config-focus#master", - "focus-core": "2.1.1", - "jest-cli": "20.0.4", - "jsdom": "11.1.0", + "eslint-config-focus": "0.6.0", + "jest-cli": "21.0.2", + "jsdom": "11.2.0", "react": "15.4.2", "react-addons-test-utils": "15.4.2", "react-dom": "15.4.2" diff --git a/src/network/error-parsing.js b/src/network/error-parsing.js index 9c3b99b..2d3d9d1 100644 --- a/src/network/error-parsing.js +++ b/src/network/error-parsing.js @@ -200,7 +200,6 @@ function _treatBadRequestExceptions(responseJSON = {}, options) { * @returns {any} depends on the errors handled */ function _handleStatusError(resErrors, opts) { - console.log('ici', resErrors, opts) switch (resErrors.status) { case 400: case 401: From bb1e91781df4cc6b8874621311113e78e128f7ce Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Mon, 11 Sep 2017 10:49:33 +0200 Subject: [PATCH 28/32] Updating version to 2.2.0-beta1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 3f38cdd..3705310 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "focus-core", - "version": "2.1.1", + "version": "2.2.0-beta1", "description": "Focus library core part.", "main": "index.js", "babel": { From 53e7bd7e0c69cef18e441838ea6ee30737c45894 Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Mon, 11 Sep 2017 11:09:39 +0200 Subject: [PATCH 29/32] Fixing moment and numeral as peer dependencies --- package.json | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 3705310..c965375 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "focus-core", - "version": "2.2.0-beta1", + "version": "2.2.0-beta2", "description": "Focus library core part.", "main": "index.js", "babel": { @@ -57,6 +57,8 @@ } }, "peerDependencies": { + "moment": "2.18.1", + "numeral": "2.0.6", "react": "15.4.2", "react-dom": "15.4.2" }, @@ -65,7 +67,6 @@ "i18next": "9.0.0", "immutable": "3.8.1", "lodash": "3.10.1", - "numeral": "2.0.6", "object-assign": "4.1.1", "uuid": "3.1.0" }, @@ -76,6 +77,8 @@ "eslint-config-focus": "0.6.0", "jest-cli": "21.0.2", "jsdom": "11.2.0", + "moment": "2.18.1", + "numeral": "2.0.6", "react": "15.4.2", "react-addons-test-utils": "15.4.2", "react-dom": "15.4.2" From 893443b0b26fb313d7900005601e839050465d2f Mon Sep 17 00:00:00 2001 From: Hartorn Date: Fri, 16 Jun 2017 12:11:31 +0200 Subject: [PATCH 30/32] Application Store : mode should be only 0 or 1 (not 2, -1, ...) --- src/store/application/store.js | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/store/application/store.js b/src/store/application/store.js index bb4b84a..c2b5405 100644 --- a/src/store/application/store.js +++ b/src/store/application/store.js @@ -12,19 +12,16 @@ class ApplicationStore extends CoreStore { super(conf); } /** - * Update the mode value. - * @param {object} dataNode - The value of the data. - */ + * Update the mode value. + * @param {object} dataNode - The value of the data. + */ updateMode(dataNode) { - let modeData = this.data.has('mode') ? this.data.get('mode') : Immutable.fromJS({}); - let newModeValue = modeData.has(dataNode.newMode) ? (modeData.get(dataNode.newMode) + 1) : 1; - //Add a check to not have a negative mode, but it should not happen. - let previousModeValue = modeData.has(dataNode.previousMode) ? (modeData.get(dataNode.previousMode) - 1) : 0; - this.data = this.data.set('mode', - modeData.set(dataNode.newMode, newModeValue).set(dataNode.previousMode, previousModeValue) - ); + const modeData = (this.data.has('mode') ? this.data.get('mode') : Immutable.fromJS({})) + .set(dataNode.newMode, 1) + .set(dataNode.previousMode, 0); + this.data = this.data.set('mode', modeData); this.willEmit('mode:change'); } } -export default ApplicationStore; +export default ApplicationStore; \ No newline at end of file From 1911976641dae0b47741258bc13872f91a47c7fc Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Mon, 11 Sep 2017 17:09:23 +0200 Subject: [PATCH 31/32] Fixing export for history --- src/history/index.js | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/history/index.js b/src/history/index.js index f9a918e..fe3fde9 100644 --- a/src/history/index.js +++ b/src/history/index.js @@ -1,29 +1,43 @@ let _navigate, _back, _start; // Define the navigation functions depending on backbone or react-router -export const setNavigationFunctions = (navigate, back, start) => { +const setNavigationFunctions = (navigate, back, start) => { _navigate = navigate; _back = back; _start = start; } -export const navigate = (...args) => { - if(!_navigate) { +const navigate = (...args) => { + if (!_navigate) { throw new Error('react-router or backbone URL Navigation was badly given in the setNavigationFunctions()') } _navigate(...args); } -export const back = (...args) => { - if(!_back){ +const back = (...args) => { + if (!_back) { throw new Error('react-router or backbone Previous Page Navigation was badly given in the setNavigationFunctions()') } _back(...args); } -export const start = (...args) => { - if(!_start) { +const start = (...args) => { + if (!_start) { throw new Error('Backbone start router was badly given in the setNavigationFunctions()') } _start(...args); } + +export { + setNavigationFunctions, + navigate, + back, + start +} + +export default { + setNavigationFunctions, + navigate, + back, + start +} \ No newline at end of file From ae1a227088f23925ad2117c8236ec11e72c0790d Mon Sep 17 00:00:00 2001 From: Bazire Houssin Date: Mon, 11 Sep 2017 17:12:22 +0200 Subject: [PATCH 32/32] Updating versions for release 2.2.0-beta3 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index c965375..b85eb2a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "focus-core", - "version": "2.2.0-beta2", + "version": "2.2.0-beta3", "description": "Focus library core part.", "main": "index.js", "babel": {