appxigon-react
Version:
Appxigon implementation on React JS
275 lines (237 loc) • 12.2 kB
JavaScript
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _lodash = require('lodash');
var _superagent = require('superagent');
var _superagent2 = _interopRequireDefault(_superagent);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _redux = require('redux');
var _reactRedux = require('react-redux');
var _actions = require('./redux/actions');
var Actions = _interopRequireWildcard(_actions);
var _itemTypes = require('./item-types');
var _itemTypes2 = _interopRequireDefault(_itemTypes);
var _utils = require('./lib/utils');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // item.js
// wrapper component for leaf-level element
// a switcher for required item type
// e.g.: form / display widget items
// Default item type is 'input.text'
var Item = function (_React$Component) {
_inherits(Item, _React$Component);
function Item(props) {
_classCallCheck(this, Item);
var _this = _possibleConstructorReturn(this, (Item.__proto__ || Object.getPrototypeOf(Item)).call(this, props));
_this.state = {
id: _this.props.id,
schema: _this.props.schema,
classes: (0, _lodash.get)(_this.props, 'AXGClasses.item', ''),
showCondition: (0, _lodash.get)(_this.props, 'schema.show', true),
show: (0, _lodash.get)(_this.props, 'schema.show', true),
account: _this.props.account,
data: (0, _lodash.get)(_this.props, 'schema.data.fallback'),
title: (0, _utils._t)((0, _lodash.get)(_this.props, 'schema.title', _this.props.id))
};
return _this;
}
_createClass(Item, [{
key: 'fetchData',
value: function fetchData() {
var component = this;
var dataSrc = (0, _lodash.get)(this.state, 'schema.data');
console.info('item: ' + this.props.AXGKey + ' -> fetchData from: ' + JSON.stringify(dataSrc));
// this.mockFetchData()
if (dataSrc) {
var endpoint = (0, _lodash.get)(dataSrc, 'endpoint');
var endpointTransform = (0, _lodash.get)(dataSrc, 'transform');
var method = (0, _lodash.get)(dataSrc, 'method', 'POST');
var requestMap = (0, _lodash.get)(dataSrc, 'request-map');
var responseMap = (0, _lodash.get)(dataSrc, 'response-map');
var canCall = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'CONNECT'].includes(method);
endpoint = (0, _utils.transformUrl)(endpoint, endpointTransform, component.props.appxigonState);
if (requestMap && method.toUpperCase() === 'GET') {
endpoint = endpoint + '?' + (0, _utils.requestMapToQueryString)(requestMap, component.props.appxigonState);
}
console.info('_ item: calling: ' + endpoint);
canCall && _superagent2.default[method.toLocaleLowerCase()](endpoint).set('Accept', 'application/json').set('token', (0, _utils.getAuthToken)()).end(function (err, res) {
if (res) {
// console.log(`res.body: ${JSON.stringify(res.body)}`)
component.setState({
// data: get(res.body, 'data')
data: res.body
});
}
if (err) {
console.log('ITEM: error: ' + JSON.stringify(err));
component.setState({
data: { error: "Can't load data from server ..." }
});
}
});
}
}
}, {
key: 'getDataFromStore',
value: function getDataFromStore(storeKey) {
// console.info(` ... storeKey: ${storeKey}`)
return (0, _lodash.get)(this.props.appxigonState, storeKey);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this2 = this;
var component = this;
var dataDef = (0, _lodash.get)(this.state, 'schema.data');
// console.info(` ... ${this.props.AXGKey}: componentWillReceiveProps`)
// console.info(` ... dataDef: ${dataDef}`)
// console.info(` ... data: ${get(nextProps.appxigonState, dataDef)}`)
if (typeof dataDef == 'string') {
component.setState({
data: (0, _lodash.get)(nextProps.appxigonState, dataDef)
});
}
// pickup dependency trigger
var dependencyKey = 'dependency.' + this.props.AXGKey;
var nextDepencyValue = (0, _lodash.get)(nextProps.appxigonState, dependencyKey, '');
if (nextDepencyValue && this.state.dependency != nextDepencyValue) {
console.log('item: ' + this.props.AXGKey + ': dependency changed');
console.info('__ item: ' + this.props.AXGKey + ': refetching data ...');
setTimeout(function () {
_this2.fetchData();
}, 2000);
// quick hack to rerun actions of the button click
// this.handleActions()
}
this.setState({
dependency: nextDepencyValue
});
}
}, {
key: 'componentWillMount',
value: function componentWillMount() {
var _this3 = this;
var component = this;
var dataDef = (0, _lodash.get)(this.state, 'schema.data');
var endpoint = (0, _lodash.get)(this.state, 'schema.data.endpoint');
var fallback = (0, _lodash.get)(this.state, 'schema.data.fallback');
// console.info(` ... ${component.props.AXGKey}: dataDef: ${dataDef}`)
// console.info(` ... typeof dataDef: ${typeof dataDef}`)
switch (typeof dataDef === 'undefined' ? 'undefined' : _typeof(dataDef)) {
case 'string':
component.setState({
data: component.getDataFromStore(dataDef)
});
break;
case 'object':
// TODO: make fetchData return data directly
if (endpoint) {
setTimeout(function () {
_this3.fetchData();
}, 200);
} else if (fallback) {
component.setState({
data: fallback
});
}
break;
default:
component.setState({
data: ''
});
}
}
}, {
key: 'render',
value: function render() {
var defaultType = 'todo-item-type';
var defaultValue = (0, _lodash.get)(this.props, 'schema.data.default');
var ItemType = _itemTypes2.default[defaultType]; // default item type
var type = (0, _lodash.get)(this.props, 'schema.type', defaultType);
// console.info(`__ type: ${type}`)
// console.log(`id / show: ${this.state.id} / ${JSON.stringify(this.state.showCondition)} ${typeof this.state.showCondition}`)
// console.log(`AXGState: ${JSON.stringify(this.props.AXGState)}`)
// _________ Show / Hide condition checking
var show = this.state.show;
var stateRefKey = '';
var stateRefVal = '';
// console.log(`showCondition: ${JSON.stringify(this.state.showCondition)}`)
if (typeof this.state.showCondition === 'boolean') {
show = this.state.showCondition;
} else if (typeof this.state.showCondition === 'string') {
// TODO: generic handling of pre-defined conditions
// account.authenticated
// REVIEW: untimely update incidentally solved by passing down props: account from root component
if (this.state.showCondition === 'account.authenticated') {
// show = localStorage.getItem('Appxigon.loginToken') !== null
show = (0, _utils.validUserLogin)();
// console.info(`Appxigon.loginToken: ${localStorage.getItem('Appxigon.loginToken')}`)
// console.info(`account.authenticated check: ${show}`)
// show = this.state.account.loginToken !== null
}
if (this.state.showCondition === 'account.rejected') {
// APOLLO-TODO: proper error condition from REDUX
show = !(0, _utils.validUserLogin)();
}
} else {
// object of conditions
// TODO: handle multiple conditions
var conditionKey = Object.keys(this.state.showCondition)[0];
var conditionVal = this.state.showCondition[conditionKey];
stateRefKey = (0, _utils.normalizeSchemaKey)(conditionKey, this.props.AXGKey);
show = (0, _lodash.get)(this.props.appxigonState, [stateRefKey]) === conditionVal ? true : false;
// console.info(` ------- show: ${this.props.AXGKey}: ${show} stateRefKey: ${stateRefKey}`)
// console.info(` ------- show: ${this.props.AXGKey}: ${show} conditionVal: ${conditionVal}`)
}
// console.info(`item: show ${this.props.AXGKey}: ${show}`)
// ---------- Get data for current item ----------
var data = this.state.data;
// var dataKey = get(this.props, 'schema.data')
// console.info(`${this.props.AXGKey}: dataKey: ${JSON.stringify(dataKey)}`)
// data:
// 1. dataKey is string
// 1a. '$ref.' -> fetch from parameters AXGState[dataKey] . (TODO: caching ?)
// -> immediate consume?
// 1b. 'some.other.key' -> get from AXGState[dataKey] (normalizedKey)
// -> only update when asked?
// 2. dataKey is object with endpoint, method, request-map, response-map, transformation etc...
// -> same as $ref ? Use hidden action.button ?
// console.log(`id / display: ${this.state.id} / ${show}`)
if (typeof _itemTypes2.default[type] !== 'undefined') {
ItemType = _itemTypes2.default[type];
}
return show && _react2.default.createElement(ItemType, {
id: this.state.id,
title: this.state.title,
schema: this.state.schema,
defaultValue: defaultValue,
data: data,
show: show,
value: this.props.value,
AXGKey: this.props.AXGKey,
AXGClasses: this.props.AXGClasses,
AXGOptions: this.props.AXGOptions,
AXGDataSource: this.props.AXGDataSource });
}
}]);
return Item;
}(_react2.default.Component);
function mapStateToProps(state) {
return {
appxigonState: state.AXGState,
appxigonAccount: state.AXGAccount
};
}
function mapDispatchToProps(dispatch) {
return {
actions: (0, _redux.bindActionCreators)(Actions, dispatch)
};
}
exports.default = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps)(Item);