(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],2:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.AttendanceAdapter = _lib.AttendanceAdapter; window.AttendanceStatusAdapter = _lib.AttendanceStatusAdapter; },{"./lib":3}],3:[function(require,module,exports){ "use strict"; var _AdapterBase3 = _interopRequireDefault(require("../../../api/AdapterBase")); var _FormValidation = _interopRequireDefault(require("../../../api/FormValidation")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var AttendanceAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(AttendanceAdapter, _AdapterBase); var _super = _createSuper(AttendanceAdapter); function AttendanceAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, AttendanceAdapter); _this = _super.call(this, endPoint, tab, filter, orderBy); _this.photoAttendance = false; return _this; } _createClass(AttendanceAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'in_time', 'out_time', 'note']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Time-In' }, { sTitle: 'Time-Out' }, { sTitle: 'Note' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['employee', { label: 'Employee', type: 'select2', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['id', { label: 'ID', type: 'hidden' }], ['in_time', { label: 'Time-In', type: 'datetime' }], ['out_time', { label: 'Time-Out', type: 'datetime', validation: 'none' }], ['note', { label: 'Note', type: 'textarea', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }, { key: "setPhotoAttendance", value: function setPhotoAttendance(val) { this.photoAttendance = parseInt(val, 10); } }, { key: "getCustomTableParams", value: function getCustomTableParams() { var that = this; var dataTableParams = { aoColumnDefs: [{ fnRender: function fnRender(data, cell) { return that.preProcessRemoteTableData(data, cell, 2); }, aTargets: [2] }, { fnRender: function fnRender(data, cell) { return that.preProcessRemoteTableData(data, cell, 3); }, aTargets: [3] }, { fnRender: function fnRender(data, cell) { return that.preProcessRemoteTableData(data, cell, 4); }, aTargets: [4] }, { fnRender: that.getActionButtons, aTargets: [that.getDataMapping().length] }] }; return dataTableParams; } }, { key: "preProcessRemoteTableData", value: function preProcessRemoteTableData(data, cell, id) { if (id === 2) { if (cell === '0000-00-00 00:00:00' || cell === '' || cell === undefined || cell == null) { return ''; } return Date.parse(cell).toString('yyyy MMM d HH:mm'); } if (id === 3) { if (cell === '0000-00-00 00:00:00' || cell === '' || cell === undefined || cell == null) { return ''; } return Date.parse(cell).toString('MMM d HH:mm'); } if (id === 4) { if (cell !== undefined && cell !== null) { if (cell.length > 10) { return "".concat(cell.substring(0, 10), ".."); } } return cell; } } }, { key: "save", value: function save() { var validator = new _FormValidation["default"]("".concat(this.getTableName(), "_submit"), true, { ShowPopup: false, LabelErrorClass: 'error' }); if (validator.checkValues()) { var params = validator.getFormParameters(); var msg = this.doCustomValidation(params); if (msg == null) { var id = $("#".concat(this.getTableName(), "_submit #id")).val(); if (id != null && id !== undefined && id !== '') { params.id = id; } var reqJson = JSON.stringify(params); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'saveSuccessCallback'; callBackData.callBackFail = 'saveFailCallback'; this.customAction('savePunch', 'admin=attendance', reqJson, callBackData); } else { var label = $("#".concat(this.getTableName(), "Form .label")); label.html(msg); label.show(); } } } }, { key: "saveSuccessCallback", value: function saveSuccessCallback(callBackData) { this.get(callBackData); } }, { key: "saveFailCallback", value: function saveFailCallback(callBackData) { this.showMessage('Error saving attendance entry', callBackData); } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }, { key: "showPunchImages", value: function showPunchImages(id) { var reqJson = JSON.stringify({ id: id }); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'getImagesSuccessCallback'; callBackData.callBackFail = 'getImagesFailCallback'; this.customAction('getImages', 'admin=attendance', reqJson, callBackData); } }, { key: "getImagesSuccessCallback", value: function getImagesSuccessCallback(callBackData) { $('#attendnaceMapCanvasIn').remove(); $('#attendnaceCanvasInWrapper').html(''); $('#attendnaceCanvasOut').remove(); $('#attendnaceCanvasOutWrapper').html(''); $('#attendnaceCanvasPunchInTime').html(''); $('#attendnaceCanvasPunchOutTime').html(''); $('#punchInLocation').html(''); $('#punchOutLocation').html(''); $('#punchInIp').html(''); $('#punchOutIp').html(''); $('#attendnaceMapCanvasIn').remove(); $('#attendnaceMapCanvasInWrapper').html(''); $('#attendnaceMapCanvasOut').remove(); $('#attendnaceMapCanvasOutWrapper').html(''); $('#attendancePhotoModel').modal('show'); $('#attendnaceCanvasEmp').html(callBackData.employee_Name); if (callBackData.in_time) { $('#attendnaceCanvasPunchInTime').html(Date.parse(callBackData.in_time).toString('yyyy MMM d HH:mm')); } if (callBackData.image_in) { $('#attendancePhoto').show(); var myCanvas = document.getElementById('attendnaceCanvasIn'); try { var ctx = myCanvas.getContext('2d'); var img = new Image(); img.onload = function () { ctx.drawImage(img, 0, 0); // Or at whatever offset you like }; img.src = callBackData.image_in; } catch (e) { console.log(e); } } if (callBackData.out_time) { $('#attendnaceCanvasPunchOutTime').html(Date.parse(callBackData.out_time).toString('yyyy MMM d HH:mm')); } if (callBackData.image_out) { $('#attendancePhoto').show(); var _myCanvas = document.getElementById('attendnaceCanvasOut'); try { var _ctx = _myCanvas.getContext('2d'); var _img = new Image(); _img.onload = function () { _ctx.drawImage(_img, 0, 0); // Or at whatever offset you like }; _img.src = callBackData.image_out; } catch (e) { console.log(e); } } if (callBackData.map_lat) { $('#attendanceMap').show(); $('#punchInLocation').html("".concat(callBackData.map_lat, ",").concat(callBackData.map_lng)); } if (callBackData.map_out_lat) { $('#attendanceMap').show(); $('#punchOutLocation').html("".concat(callBackData.map_out_lat, ",").concat(callBackData.map_out_lng)); } if (callBackData.in_ip) { $('#punchInIp').html(callBackData.in_ip); } if (callBackData.out_ip) { $('#punchOutIp').html(callBackData.out_ip); } if (callBackData.map_snapshot) { $('#attendanceMap').show(); var _myCanvas2 = document.getElementById('attendnaceMapCanvasIn'); try { var _ctx2 = _myCanvas2.getContext('2d'); var _img2 = new Image(); _img2.onload = function () { _ctx2.drawImage(_img2, 0, 0); // Or at whatever offset you like }; _img2.src = callBackData.map_snapshot; } catch (e) { console.log(e); } } if (callBackData.map_out_snapshot) { $('#attendanceMap').show(); var _myCanvas3 = document.getElementById('attendnaceMapCanvasOut'); try { var _ctx3 = _myCanvas3.getContext('2d'); var _img3 = new Image(); _img3.onload = function () { _ctx3.drawImage(_img3, 0, 0); // Or at whatever offset you like }; _img3.src = callBackData.map_out_snapshot; } catch (e) { console.log(e); } } } }, { key: "getImagesFailCallback", value: function getImagesFailCallback(callBackData) { this.showMessage('Error', callBackData); } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var editButton = ''; var deleteButton = ''; var photoButton = ''; var html; if (this.photoAttendance === 1) { html = '
_edit__delete__photo_
'; } else { html = '
_edit__delete_
'; } html = html.replace('_photo_', photoButton); if (this.showDelete) { html = html.replace('_delete_', deleteButton); } else { html = html.replace('_delete_', ''); } if (this.showEdit) { html = html.replace('_edit_', editButton); } else { html = html.replace('_edit_', ''); } html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/time-and-attendance/attendance-time-management'; } }]); return AttendanceAdapter; }(_AdapterBase3["default"]); /* Attendance Status */ var AttendanceStatusAdapter = /*#__PURE__*/function (_AdapterBase2) { _inherits(AttendanceStatusAdapter, _AdapterBase2); var _super2 = _createSuper(AttendanceStatusAdapter); function AttendanceStatusAdapter() { _classCallCheck(this, AttendanceStatusAdapter); return _super2.apply(this, arguments); } _createClass(AttendanceStatusAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'status']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Clocked In Status' }]; } }, { key: "getFormFields", value: function getFormFields() { return []; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var html = '
'; html = html.replace(/_BASE_/g, this.baseUrl); if (data[2] == 'Not Clocked In') { html = html.replace(/_COLOR_/g, 'gray'); } else if (data[2] == 'Clocked Out') { html = html.replace(/_COLOR_/g, 'yellow'); } else if (data[2] == 'Clocked In') { html = html.replace(/_COLOR_/g, 'green'); } return html; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/time-and-attendance/attendance-time-management'; } }]); return AttendanceStatusAdapter; }(_AdapterBase3["default"]); module.exports = { AttendanceAdapter: AttendanceAdapter, AttendanceStatusAdapter: AttendanceStatusAdapter }; },{"../../../api/AdapterBase":52,"../../../api/FormValidation":56}],4:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.AttendanceGraphAdapter = _lib.AttendanceGraphAdapter; window.TimeUtilizationGraphAdapter = _lib.TimeUtilizationGraphAdapter; },{"./lib":5}],5:[function(require,module,exports){ "use strict"; var _BaseGraphAdapter3 = _interopRequireDefault(require("../../../api/BaseGraphAdapter")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /* * AttendanceGraphAdapter */ var AttendanceGraphAdapter = /*#__PURE__*/function (_BaseGraphAdapter) { _inherits(AttendanceGraphAdapter, _BaseGraphAdapter); var _super = _createSuper(AttendanceGraphAdapter); function AttendanceGraphAdapter() { _classCallCheck(this, AttendanceGraphAdapter); return _super.apply(this, arguments); } _createClass(AttendanceGraphAdapter, [{ key: "getFormFields", value: function getFormFields() { return []; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'allow-null': true, 'null-label': 'All Employees', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['start', { label: 'Start Date', type: 'date', validation: '' }], ['end', { label: 'End Date', type: 'date', validation: '' }]]; } }, { key: "get", value: function get() { this.initFieldMasterData(); this.getTimeUtilization(); } }, { key: "doCustomFilterValidation", value: function doCustomFilterValidation(params) { var $errorElement = $("#".concat(this.table, "_filter_error")); $errorElement.html(''); $errorElement.hide(); if (Date.parse(params.start).getTime() > Date.parse(params.end).getTime()) { $errorElement.html('End date should be a later date than start date'); $errorElement.show(); return false; } var dateDiff = (Date.parse(params.end).getTime() - Date.parse(params.start).getTime()) / (1000 * 60 * 60 * 24); if (dateDiff > 45 && (params.employee === undefined || params.employee == null || params.employee === 'NULL')) { $errorElement.html('Differance between start and end dates should not be more than 45 days, when creating chart for all employees'); $errorElement.show(); return false; } if (dateDiff > 90) { $errorElement.html('Differance between start and end dates should not be more than 90 days'); $errorElement.show(); return false; } return true; } }, { key: "getTimeUtilization", value: function getTimeUtilization(object, callBackData) { object = {}; if (this.filter != null && this.filter !== undefined) { if (this.filter.employee !== 'NULL') { object.employee = this.filter.employee; } object.start = this.filter.start; object.end = this.filter.end; } var reqJson = JSON.stringify(object); callBackData = callBackData === undefined || callBackData === null ? [] : callBackData; callBackData.callBackData = []; callBackData.callBackSuccess = 'getAttendanceSuccessCallBack'; callBackData.callBackFail = 'getAttendanceFailCallBack'; this.customAction('getAttendance', 'admin=charts', reqJson, callBackData); } }, { key: "getAttendanceFailCallBack", value: function getAttendanceFailCallBack(callBackData) { this.showMessage('Error Occured while getting data for chart', callBackData); } }, { key: "getAttendanceSuccessCallBack", value: function getAttendanceSuccessCallBack(callBackData) { var that = this; var filterHtml = that.getTableTopButtonHtml(); $('#tabPageAttendanceGraph svg').remove(); $('#tabPageAttendanceGraph div').remove(); var $tabPageAttendanceGraph = $('#tabPageAttendanceGraph'); $tabPageAttendanceGraph.html(''); $tabPageAttendanceGraph.html("".concat(filterHtml, "")); nv.addGraph(function () { var chart = nv.models.multiBarChart().margin({ bottom: 200 }).transitionDuration(0).reduceXTicks(true) // If 'false', every single x-axis tick label will be rendered. .rotateLabels(45) // Angle to rotate x-axis labels. .showControls(false) // Allow user to switch between 'Grouped' and 'Stacked' mode. .groupSpacing(0.1); // Distance between each group of bars. chart.yAxis.tickFormat(d3.format(',.1f')); chart.dispatch.on('stateChange', function (e) { nv.log('New State:', JSON.stringify(e)); }); chart.tooltip(function (key, x, y, e, graph) { return "

".concat(key, "

") + "

".concat(y, " on ").concat(x, "

"); }); d3.select('#tabPageAttendanceGraph svg').datum(callBackData).call(chart); return chart; }); } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/insights/analytics'; } }]); return AttendanceGraphAdapter; }(_BaseGraphAdapter3["default"]); /* * TimeUtilizationGraphAdapter */ var TimeUtilizationGraphAdapter = /*#__PURE__*/function (_BaseGraphAdapter2) { _inherits(TimeUtilizationGraphAdapter, _BaseGraphAdapter2); var _super2 = _createSuper(TimeUtilizationGraphAdapter); function TimeUtilizationGraphAdapter() { _classCallCheck(this, TimeUtilizationGraphAdapter); return _super2.apply(this, arguments); } _createClass(TimeUtilizationGraphAdapter, [{ key: "getFormFields", value: function getFormFields() { return []; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'allow-null': true, 'null-label': 'All Employees', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['start', { label: 'Start Date', type: 'date', validation: '' }], ['end', { label: 'End Date', type: 'date', validation: '' }]]; } }, { key: "get", value: function get() { this.initFieldMasterData(); this.getTimeUtilization(); } }, { key: "doCustomFilterValidation", value: function doCustomFilterValidation(params) { var $errorElement = $("#".concat(this.table, "_filter_error")); $errorElement.html(''); $errorElement.hide(); if (Date.parse(params.start).getTime() > Date.parse(params.end).getTime()) { $errorElement.html('End date should be a later date than start date'); $errorElement.show(); return false; } var dateDiff = (Date.parse(params.end).getTime() - Date.parse(params.start).getTime()) / (1000 * 60 * 60 * 24); if (dateDiff > 45 && (params.employee === undefined || params.employee == null || params.employee === 'NULL')) { $errorElement.html('Differance between start and end dates should not be more than 45 days, when creating chart for all employees'); $errorElement.show(); return false; } if (dateDiff > 90) { $errorElement.html('Differance between start and end dates should not be more than 90 days'); $errorElement.show(); return false; } return true; } }, { key: "getTimeUtilization", value: function getTimeUtilization(object, callBackData) { object = {}; if (this.filter != null && this.filter !== undefined) { if (this.filter.employee !== 'NULL') { object.employee = this.filter.employee; } object.start = this.filter.start; object.end = this.filter.end; } var reqJson = JSON.stringify(object); callBackData = callBackData === undefined || callBackData === null ? [] : callBackData; callBackData.callBackData = []; callBackData.callBackSuccess = 'getTimeUtilizationSuccessCallBack'; callBackData.callBackFail = 'getTimeUtilizationFailCallBack'; this.customAction('getTimeUtilization', 'admin=charts', reqJson, callBackData); } }, { key: "getTimeUtilizationFailCallBack", value: function getTimeUtilizationFailCallBack(callBackData) { this.showMessage('Error Occured while getting data for chart', callBackData); } }, { key: "getTimeUtilizationSuccessCallBack", value: function getTimeUtilizationSuccessCallBack(callBackData) { var that = this; var filterHtml = that.getTableTopButtonHtml(); $('#tabPageTimeUtilizationGraph svg').remove(); $('#tabPageTimeUtilizationGraph div').remove(); var $tabPageTimeUtilizationGraph = $('#tabPageTimeUtilizationGraph'); $tabPageTimeUtilizationGraph.html(''); $tabPageTimeUtilizationGraph.html("".concat(filterHtml, "")); nv.addGraph(function () { var chart = nv.models.multiBarChart().margin({ bottom: 200 }).transitionDuration(0).reduceXTicks(true) // If 'false', every single x-axis tick label will be rendered. .rotateLabels(45) // Angle to rotate x-axis labels. .showControls(true) // Allow user to switch between 'Grouped' and 'Stacked' mode. .groupSpacing(0.1); // Distance between each group of bars. chart.yAxis.tickFormat(d3.format(',.1f')); d3.select('#tabPageTimeUtilizationGraph svg').datum(callBackData).call(chart); chart.dispatch.on('stateChange', function (e) { nv.log('New State:', JSON.stringify(e)); }); chart.tooltip(function (key, x, y, e, graph) { return "

".concat(key, "

") + "

".concat(y, " on ").concat(x, "

"); }); return chart; }); } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/insights/analytics'; } }]); return TimeUtilizationGraphAdapter; }(_BaseGraphAdapter3["default"]); module.exports = { AttendanceGraphAdapter: AttendanceGraphAdapter, TimeUtilizationGraphAdapter: TimeUtilizationGraphAdapter }; },{"../../../api/BaseGraphAdapter":54}],6:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.ClientAdapter = _lib.ClientAdapter; },{"./lib":7}],7:[function(require,module,exports){ "use strict"; var _ReactModalAdapterBase = _interopRequireDefault(require("../../../api/ReactModalAdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * ClientAdapter */ var ClientAdapter = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(ClientAdapter, _ReactModalAdapterBas); var _super = _createSuper(ClientAdapter); function ClientAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, ClientAdapter); _this = _super.call(this, endPoint, tab, filter, orderBy); _this.fieldNameMap = {}; _this.hiddenFields = {}; _this.tableFields = {}; _this.formOnlyFields = {}; return _this; } _createClass(ClientAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'details', 'address', 'contact_number']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Details' }, { sTitle: 'Address' }, { sTitle: 'Contact Number' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Details', dataIndex: 'details', sorter: true }, { title: 'Address', dataIndex: 'address', sorter: true }, { title: 'Contact Number', dataIndex: 'contact_number', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { if (this.showSave) { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text' }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }], ['address', { label: 'Address', type: 'textarea', validation: 'none' }], ['contact_number', { label: 'Contact Number', type: 'text', validation: 'none' }], ['contact_email', { label: 'Contact Email', type: 'text', validation: 'none' }], ['company_url', { label: 'Company Url', type: 'text', validation: 'none' }], ['status', { label: 'Status', type: 'select', source: [['Active', 'Active'], ['Inactive', 'Inactive']] }], ['first_contact_date', { label: 'First Contact Date', type: 'date', validation: 'none' }]]; } return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'placeholder' }], ['details', { label: 'Details', type: 'placeholder', validation: 'none' }], ['address', { label: 'Address', type: 'placeholder', validation: 'none' }], ['contact_number', { label: 'Contact Number', type: 'placeholder', validation: 'none' }], ['contact_email', { label: 'Contact Email', type: 'placeholder', validation: 'none' }], ['company_url', { label: 'Company Url', type: 'placeholder', validation: 'none' }], ['status', { label: 'Status', type: 'placeholder', source: [['Active', 'Active'], ['Inactive', 'Inactive']] }], ['first_contact_date', { label: 'First Contact Date', type: 'placeholder', validation: 'none' }]]; } }, { key: "getHelpLink", value: function getHelpLink() { return 'http://blog.icehrm.com/docs/projects/'; } }]); return ClientAdapter; }(_ReactModalAdapterBase["default"]); module.exports = { ClientAdapter: ClientAdapter }; },{"../../../api/ReactModalAdapterBase":65}],8:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); var _IceDataPipe = _interopRequireDefault(require("../../../api/IceDataPipe")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function init(data) { var modJsList = {}; modJsList.tabCompanyStructure = new _lib.CompanyStructureAdapter('CompanyStructure'); modJsList.tabCompanyStructure.setObjectTypeName('Company Structure'); modJsList.tabCompanyStructure.setDataPipe(new _IceDataPipe["default"](modJsList.tabCompanyStructure)); modJsList.tabCompanyStructure.setAccess(data.permissions.CompanyStructure); modJsList.tabCompanyStructure.setCustomFields(data.customFields); modJsList.tabCompanyGraph = new _lib.CompanyGraphAdapter('CompanyStructure'); window.modJs = modJsList.tabCompanyStructure; window.modJsList = modJsList; } window.initAdminCompanyStructure = init; },{"../../../api/IceDataPipe":58,"./lib":9}],9:[function(require,module,exports){ "use strict"; var _ReactModalAdapterBase = _interopRequireDefault(require("../../../api/ReactModalAdapterBase")); var _AdapterBase2 = _interopRequireDefault(require("../../../api/AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var CompanyStructureAdapter = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(CompanyStructureAdapter, _ReactModalAdapterBas); var _super = _createSuper(CompanyStructureAdapter); function CompanyStructureAdapter() { _classCallCheck(this, CompanyStructureAdapter); return _super.apply(this, arguments); } _createClass(CompanyStructureAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'title', 'address', 'type', 'country', 'timezone', 'parent']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Address', bSortable: false }, { sTitle: 'Type' }, { sTitle: 'Country', sClass: 'center' }, { sTitle: 'Time Zone' }, { sTitle: 'Parent Structure' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'title', sorter: true }, { title: 'Address', dataIndex: 'address' }, { title: 'Type', dataIndex: 'type' }, { title: 'Country', dataIndex: 'country' }, { title: 'Time Zone', dataIndex: 'timezone' }, { title: 'Parent Structure', dataIndex: 'parent' }]; } }, { key: "getFormFields", value: function getFormFields() { return this.addCustomFields([['id', { label: 'ID', type: 'hidden', validation: '' }], ['title', { label: 'Name', type: 'text', validation: '' }], ['description', { label: 'Details', type: 'textarea', validation: '' }], ['address', { label: 'Address', type: 'textarea', validation: 'none' }], ['type', { label: 'Type', type: 'select', source: [['Company', 'Company'], ['Head Office', 'Head Office'], ['Regional Office', 'Regional Office'], ['Department', 'Department'], ['Unit', 'Unit'], ['Sub Unit', 'Sub Unit'], ['Other', 'Other']] }], ['country', { label: 'Country', type: 'select2', 'remote-source': ['Country', 'code', 'name'] }], ['timezone', { label: 'Time Zone', type: 'select2', 'allow-null': false, 'remote-source': ['Timezone', 'name', 'details', 'getTimezonesWithOffset'] }], ['parent', { label: 'Parent Structure', type: 'select', 'allow-null': true, 'remote-source': ['CompanyStructure', 'id', 'title'] }], ['heads', { label: 'Heads', type: 'select2multi', 'allow-null': true, 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]); } }, { key: "postRenderForm", value: function postRenderForm(object, $tempDomObj) { if (object === undefined || object === null || object.id === null || object.id === undefined || object.id === '') { $tempDomObj.find('#field_heads').hide(); } } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/employees/employee-information-setup'; } }]); return CompanyStructureAdapter; }(_ReactModalAdapterBase["default"]); /* * Company Graph */ var CompanyGraphAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(CompanyGraphAdapter, _AdapterBase); var _super2 = _createSuper(CompanyGraphAdapter); function CompanyGraphAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, CompanyGraphAdapter); _this = _super2.call(this, endPoint, tab, filter, orderBy); _this.nodeIdCounter = 0; return _this; } _createClass(CompanyGraphAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'title', 'address', 'type', 'country', 'timezone', 'parent']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Address', bSortable: false }, { sTitle: 'Type' }, { sTitle: 'Country', sClass: 'center' }, { sTitle: 'Time Zone' }, { sTitle: 'Parent Structure' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden', validation: '' }], ['title', { label: 'Name', type: 'text', validation: '' }], ['description', { label: 'Details', type: 'textarea', validation: '' }], ['address', { label: 'Address', type: 'textarea', validation: 'none' }], ['type', { label: 'Type', type: 'select', source: [['Company', 'Company'], ['Head Office', 'Head Office'], ['Regional Office', 'Regional Office'], ['Department', 'Department'], ['Unit', 'Unit'], ['Sub Unit', 'Sub Unit'], ['Other', 'Other']] }], ['country', { label: 'Country', type: 'select2', 'remote-source': ['Country', 'code', 'name'] }], ['timezone', { label: 'Time Zone', type: 'select2', 'allow-null': false, 'remote-source': ['Timezone', 'name', 'details', 'getTimezonesWithOffset'] }], ['parent', { label: 'Parent Structure', type: 'select', 'allow-null': true, 'remote-source': ['CompanyStructure', 'id', 'title'] }], ['heads', { label: 'Heads', type: 'select2multi', 'allow-null': true, 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }, { key: "convertToTree", value: function convertToTree(data) { var ice = {}; ice.id = -1; ice.title = ''; ice.name = ''; ice.children = []; var parent = null; var added = {}; for (var i = 0; i < data.length; i++) { data[i].name = data[i].title; if (data[i].parent != null && data[i].parent !== undefined) { parent = this.findParent(data, data[i].parent); if (parent != null) { if (parent.children === undefined || parent.children == null) { parent.children = []; } parent.children.push(data[i]); } } } for (var _i = 0; _i < data.length; _i++) { if (data[_i].parent == null || data[_i].parent === undefined) { ice.children.push(data[_i]); } } return ice; } }, { key: "findParent", value: function findParent(data, parent) { for (var i = 0; i < data.length; i++) { if (data[i].title === parent || data[i].title === parent) { return data[i]; } } return null; } }, { key: "createTable", value: function createTable(elementId) { $('#tabPageCompanyGraph').html(''); var that = this; var sourceData = this.sourceData; // this.fixCyclicParent(sourceData); var treeData = this.convertToTree(sourceData); var m = [20, 120, 20, 120]; var w = 5000 - m[1] - m[3]; var h = 1000 - m[0] - m[2]; var tree = d3.layout.tree().size([h, w]); this.diagonal = d3.svg.diagonal().projection(function (d) { return [d.y, d.x]; }); this.vis = d3.select('#tabPageCompanyGraph').append('svg:svg').attr('width', w + m[1] + m[3]).attr('height', h + m[0] + m[2]).append('svg:g').attr('transform', "translate(".concat(m[3], ",").concat(m[0], ")")); var root = treeData; root.x0 = h / 2; root.y0 = 0; function toggleAll(d) { if (d.children) { console.log(d.name); d.children.forEach(toggleAll); that.toggle(d); } } this.update(root, tree, root); } }, { key: "update", value: function update(source, tree, root) { var that = this; var duration = d3.event && d3.event.altKey ? 5000 : 500; // Compute the new tree layout. var nodes = tree.nodes(root).reverse(); // Normalize for fixed-depth. nodes.forEach(function (d) { d.y = d.depth * 180; }); // Update the nodes� var node = that.vis.selectAll('g.node').data(nodes, function (d) { return d.id || (d.id = ++that.nodeIdCounter); }); // Enter any new nodes at the parent's previous position. var nodeEnter = node.enter().append('svg:g').attr('class', 'node').attr('transform', function (d) { return "translate(".concat(source.y0, ",").concat(source.x0, ")"); }).on('click', function (d) { that.toggle(d); that.update(d, tree, root); }); nodeEnter.append('svg:circle').attr('r', 1e-6).style('fill', function (d) { return d._children ? 'lightsteelblue' : '#fff'; }); nodeEnter.append('svg:text').attr('x', function (d) { return d.children || d._children ? -10 : 10; }).attr('dy', '.35em').attr('text-anchor', function (d) { return d.children || d._children ? 'end' : 'start'; }).text(function (d) { return d.name; }).style('fill-opacity', 1e-6); // Transition nodes to their new position. var nodeUpdate = node.transition().duration(duration).attr('transform', function (d) { return "translate(".concat(d.y, ",").concat(d.x, ")"); }); nodeUpdate.select('circle').attr('r', 4.5).style('fill', function (d) { return d._children ? 'lightsteelblue' : '#fff'; }); nodeUpdate.select('text').style('fill-opacity', 1); // Transition exiting nodes to the parent's new position. var nodeExit = node.exit().transition().duration(duration).attr('transform', function (d) { return "translate(".concat(source.y, ",").concat(source.x, ")"); }).remove(); nodeExit.select('circle').attr('r', 1e-6); nodeExit.select('text').style('fill-opacity', 1e-6); // Update the links� var link = that.vis.selectAll('path.link').data(tree.links(nodes), function (d) { return d.target.id; }); // Enter any new links at the parent's previous position. link.enter().insert('svg:path', 'g').attr('class', 'link').attr('d', function (d) { var o = { x: source.x0, y: source.y0 }; return that.diagonal({ source: o, target: o }); }).transition().duration(duration).attr('d', that.diagonal); // Transition links to their new position. link.transition().duration(duration).attr('d', that.diagonal); // Transition exiting nodes to the parent's new position. link.exit().transition().duration(duration).attr('d', function (d) { var o = { x: source.x, y: source.y }; return that.diagonal({ source: o, target: o }); }).remove(); // Stash the old positions for transition. nodes.forEach(function (d) { d.x0 = d.x; d.y0 = d.y; }); } // Toggle children. }, { key: "toggle", value: function toggle(d) { if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } } }, { key: "getSourceDataById", value: function getSourceDataById(id) { for (var i = 0; i < this.sourceData.length; i++) { if (this.sourceData[i].id == id) { return this.sourceData[i]; } } return null; } }, { key: "fixCyclicParent", value: function fixCyclicParent(sourceData) { var errorMsg = ''; for (var i = 0; i < sourceData.length; i++) { var obj = sourceData[i]; var curObj = obj; var parentIdArr = {}; parentIdArr[curObj.id] = 1; while (curObj.parent != null && curObj.parent != undefined) { var parent = this.getSourceDataById(curObj.parent); if (parent == null) { break; } else if (parentIdArr[parent.id] == 1) { errorMsg = "".concat(obj.title, "'s parent structure set to ").concat(parent.title, "
"); obj.parent = null; break; } parentIdArr[parent.id] = 1; curObj = parent; } } if (errorMsg !== '') { this.showMessage('Company Structure is having a cyclic dependency', "We found a cyclic dependency due to following reasons:
".concat(errorMsg)); return false; } return true; } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/employees/employee-information-setup'; } }]); return CompanyGraphAdapter; }(_AdapterBase2["default"]); module.exports = { CompanyStructureAdapter: CompanyStructureAdapter, CompanyGraphAdapter: CompanyGraphAdapter }; },{"../../../api/AdapterBase":52,"../../../api/ReactModalAdapterBase":65}],10:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); var _IceDataPipe = _interopRequireDefault(require("../../../api/IceDataPipe")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function init(data) { var modJsList = {}; modJsList.tabCustomField = new _lib.CommonCustomFieldAdapter('CustomField', 'CustomField', {}, ''); modJsList.tabCustomField.setRemoteTable(true); modJsList.tabCustomField.setObjectTypeName('Custom Field'); modJsList.tabCustomField.setDataPipe(new _IceDataPipe["default"](modJsList.tabCustomField)); modJsList.tabCustomField.setAccess(data.permissions.CustomField); modJsList.tabCustomField.setTypes(data.types); window.modJs = modJsList.tabCustomField; window.modJsList = modJsList; } window.initAdminCustomFields = init; },{"../../../api/IceDataPipe":58,"./lib":11}],11:[function(require,module,exports){ "use strict"; var _ReactCustomFieldAdapter = _interopRequireDefault(require("../../../api/ReactCustomFieldAdapter")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * AssetTypeAdapter */ var CommonCustomFieldAdapter = /*#__PURE__*/function (_ReactCustomFieldAdap) { _inherits(CommonCustomFieldAdapter, _ReactCustomFieldAdap); var _super = _createSuper(CommonCustomFieldAdapter); function CommonCustomFieldAdapter() { _classCallCheck(this, CommonCustomFieldAdapter); return _super.apply(this, arguments); } _createClass(CommonCustomFieldAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'type', 'field_type', 'field_label', 'display', 'display_order']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Object Type' }, { sTitle: 'Field Type' }, { sTitle: 'Field Label' }, { sTitle: 'Display Status' }, { sTitle: 'Priority' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Object Type', dataIndex: 'type', sorter: true }, { title: 'Field Label', dataIndex: 'field_label' }, { title: 'Field Type', dataIndex: 'field_type' }, { title: 'Display Status', dataIndex: 'display', sorter: true }, { title: 'Priority', dataIndex: 'display_order', sorter: true }]; } }, { key: "setTypes", value: function setTypes(tables) { this.types = tables; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['field_label', { label: 'Field Label', type: 'text', validation: '' }], ['type', { label: 'Object Type', type: 'select2', source: this.types }], ['field_type', { label: 'Field Type', type: 'select', source: [['text', 'Text Field'], ['textarea', 'Text Area'], ['select', 'Select'], ['select2', 'Select2'], ['select2multi', 'Multi Select'], ['fileupload', 'File Upload'], ['date', 'Date'], ['datetime', 'Date Time'], ['time', 'Time'], ['signature', 'Signature']] }], ['field_validation', { label: 'Validation', type: 'select2', validation: 'none', sort: 'none', 'null-label': 'Required', 'allow-null': true, source: [['none', 'None'], ['number', 'Number'], ['numberOrEmpty', 'Number or Empty'], ['float', 'Decimal'], ['email', 'Email'], ['emailOrEmpty', 'Email or Empty']] }], ['field_options', { label: 'Field Options', type: 'datagroup', form: [['label', { label: 'Label', type: 'text', validation: '' }], ['value', { label: 'Value', type: 'text', validation: 'none' }]], html: '
#_delete_##_edit_##_label_#:#_value_#
', columns: [{ title: 'Label', dataIndex: 'label', key: 'label' }, { title: 'Option Value', dataIndex: 'value', key: 'value' }], validation: 'none' }], ['display_order', { label: 'Priority', type: 'text', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['type', { label: 'Object Type', type: 'select2', 'allow-null': true, source: this.types }]]; } }, { key: "forceInjectValuesBeforeSave", value: function forceInjectValuesBeforeSave(params) { var data = ['', {}]; var options = []; var optionsData; data[1].label = params.field_label; data[1].type = params.field_type; data[1].validation = params.field_validation; if (['select', 'select2', 'select2multi'].indexOf(params.field_type) >= 0) { optionsData = params.field_options === '' || params.field_options === undefined ? [] : JSON.parse(params.field_options); for (var index in optionsData) { options.push([optionsData[index].value, optionsData[index].label]); } data[1].source = options; } if (params.field_validation == null || params.field_validation === undefined) { params.field_validation = ''; } if (this.currentElement == null || this.currentElement.name == null || this.currentElement.name === '') { params.name = this.getNameFromFieldName(params.field_label); } else { params.name = this.currentElement.name; } data[0] = params.name; params.data = JSON.stringify(data); params.display = 'Form'; params.display_order = parseInt(params.display_order); if (!Number.isInteger(params.display_order)) { params.display_order = 1; } return params; } }]); return CommonCustomFieldAdapter; }(_ReactCustomFieldAdapter["default"]); module.exports = { CommonCustomFieldAdapter: CommonCustomFieldAdapter }; },{"../../../api/ReactCustomFieldAdapter":63}],12:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.DashboardAdapter = _lib.DashboardAdapter; },{"./lib":13}],13:[function(require,module,exports){ "use strict"; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _g2plot = require("@antv/g2plot"); var _reactDom = _interopRequireDefault(require("react-dom")); var _AdapterBase2 = _interopRequireDefault(require("../../../api/AdapterBase")); var _TaskList = _interopRequireDefault(require("../../../components/TaskList")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var DashboardAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(DashboardAdapter, _AdapterBase); var _super = _createSuper(DashboardAdapter); function DashboardAdapter() { _classCallCheck(this, DashboardAdapter); return _super.apply(this, arguments); } _createClass(DashboardAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return []; } }, { key: "getHeaders", value: function getHeaders() { return []; } }, { key: "getFormFields", value: function getFormFields() { return []; } }, { key: "get", value: function get(callBackData) { this.initializeReactDashboard(); } }, { key: "getInitData", value: function getInitData() { var that = this; var object = {}; var reqJson = JSON.stringify(object); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'getInitDataSuccessCallBack'; callBackData.callBackFail = 'getInitDataFailCallBack'; this.customAction('getInitData', 'admin=dashboard', reqJson, callBackData); } }, { key: "getInitDataSuccessCallBack", value: function getInitDataSuccessCallBack(data) { $('#numberOfEmployees').html("".concat(data.numberOfEmployees, " Employees")); $('#numberOfCompanyStuctures').html("".concat(data.numberOfCompanyStuctures, " Departments")); $('#numberOfUsers').html("".concat(data.numberOfUsers, " Users")); $('#numberOfProjects').html("".concat(data.numberOfProjects, " Active Projects")); $('#numberOfAttendanceLastWeek').html("".concat(data.numberOfAttendanceLastWeek, " Entries Last Week")); $('#numberOfLeaves').html("".concat(data.numberOfLeaves, " Upcoming")); $('#numberOfTimeEntries').html(data.numberOfTimeEntries); $('#numberOfCandidates').html("".concat(data.numberOfCandidates, " Candidates")); $('#numberOfJobs').html("".concat(data.numberOfJobs, " Active")); $('#numberOfCourses').html("".concat(data.numberOfCourses, " Courses")); } }, { key: "getInitDataFailCallBack", value: function getInitDataFailCallBack(callBackData) {} }, { key: "getSpinner", value: function getSpinner() { return /*#__PURE__*/_react["default"].createElement(_antd.Row, null, /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 8 }, " "), /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 8 }, /*#__PURE__*/_react["default"].createElement(_antd.Spin, { size: "large" })), /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 8 }, " ")); } }, { key: "initializeReactDashboard", value: function initializeReactDashboard() { //this.drawCompanyLeaveEntitlementChart(); this.drawOnlineOfflineEmployeeChart(); this.drawEmployeeDistributionChart(); this.buildTaskList(); } }, { key: "buildTaskList", value: function buildTaskList() { document.getElementById('TaskListWrap').style.display = 'none'; _reactDom["default"].render(this.getSpinner(), document.getElementById('TaskListLoader')); this.apiClient.get('tasks').then(function (data) { document.getElementById('TaskListWrap').style.display = 'block'; _reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(_TaskList["default"], { tasks: data.data }), document.getElementById('TaskList')); _reactDom["default"].unmountComponentAtNode(document.getElementById('TaskListLoader')); }); } }, { key: "drawEmployeeDistributionChart", value: function drawEmployeeDistributionChart() { var that = this; document.getElementById('EmployeeDistributionChart').style.display = 'none'; _reactDom["default"].render(this.getSpinner(), document.getElementById('EmployeeDistributionChartLoader')); this.apiClient.get('charts/employees-distribution').then(function (data) { var chartData = Object.keys(data.data).map(function (key) { return { type: key.charAt(0).toUpperCase() + key.slice(1), value: data.data[key] }; }); var props = { forceFit: true, title: { visible: true, text: that.gt('Employee Distribution') }, description: { visible: false, text: '' }, statistic: { visible: true, content: { value: chartData.reduce(function (acc, item) { return acc + item.value; }, 0), name: that.gt('Total') } }, legend: { visible: true, position: 'bottom-center' }, radius: 0.8, padding: 'auto', data: chartData, angleField: 'value', colorField: 'type', label: { visible: true, type: 'outer', offset: 20 } }; _reactDom["default"].unmountComponentAtNode(document.getElementById('EmployeeDistributionChartLoader')); document.getElementById('EmployeeDistributionChart').style.display = 'block'; var plot = new _g2plot.Pie(document.getElementById('EmployeeDistributionChart'), props); plot.render(); }); } }, { key: "drawOnlineOfflineEmployeeChart", value: function drawOnlineOfflineEmployeeChart() { var that = this; document.getElementById('EmployeeOnlineOfflineChart').style.display = 'none'; _reactDom["default"].render(this.getSpinner(), document.getElementById('EmployeeOnlineOfflineChartLoader')); this.apiClient.get('charts/employee-check-ins').then(function (data) { var chartData = Object.keys(data.data).map(function (key) { return { type: key, value: data.data[key] }; }); var props = { forceFit: true, title: { visible: true, text: that.gt('Employee Check-Ins') }, description: { visible: false, text: '' }, statistic: { visible: true, content: { value: chartData.reduce(function (acc, item) { return acc + item.value; }, 0), name: that.gt('Total') } }, legend: { visible: true, position: 'bottom-center' }, radius: 0.8, padding: 'auto', data: chartData, angleField: 'value', colorField: 'type' }; _reactDom["default"].unmountComponentAtNode(document.getElementById('EmployeeOnlineOfflineChartLoader')); document.getElementById('EmployeeOnlineOfflineChart').style.display = 'block'; var donutPlot = new _g2plot.Donut(document.getElementById('EmployeeOnlineOfflineChart'), props); donutPlot.render(); }); } }, { key: "drawCompanyLeaveEntitlementChart", value: function drawCompanyLeaveEntitlementChart() { var that = this; document.getElementById('CompanyLeaveEntitlementChart').style.display = 'none'; _reactDom["default"].render(this.getSpinner(), document.getElementById('CompanyLeaveEntitlementChartLoader')); this.apiClient.get('charts/company-leave-entitlement').then(function (data) { var chartData = Object.keys(data.data).map(function (key) { return { type: key, value: data.data[key] }; }); var props = { forceFit: true, title: { visible: true, text: that.gt('Company Vacation Usage') }, description: { visible: false, text: '' }, statistic: { visible: true, content: { value: chartData.reduce(function (acc, item) { return acc + item.value; }, 0), name: that.gt('Total') } }, legend: { visible: true, position: 'bottom-center' }, radius: 0.8, padding: 'auto', data: chartData, angleField: 'value', colorField: 'type' }; _reactDom["default"].unmountComponentAtNode(document.getElementById('CompanyLeaveEntitlementChartLoader')); document.getElementById('CompanyLeaveEntitlementChart').style.display = 'block'; var donutPlot = new _g2plot.Donut(document.getElementById('CompanyLeaveEntitlementChart'), props); donutPlot.render(); }); } }]); return DashboardAdapter; }(_AdapterBase2["default"]); module.exports = { DashboardAdapter: DashboardAdapter }; },{"../../../api/AdapterBase":52,"../../../components/TaskList":80,"@antv/g2plot":"@antv/g2plot","antd":"antd","react":"react","react-dom":"react-dom"}],14:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.DataImportAdapter = _lib.DataImportAdapter; window.DataImportFileAdapter = _lib.DataImportFileAdapter; },{"./lib":15}],15:[function(require,module,exports){ "use strict"; var _AdapterBase3 = _interopRequireDefault(require("../../../api/AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * DataImportAdapter */ var DataImportAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(DataImportAdapter, _AdapterBase); var _super = _createSuper(DataImportAdapter); function DataImportAdapter() { _classCallCheck(this, DataImportAdapter); return _super.apply(this, arguments); } _createClass(DataImportAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'dataType', 'details']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Data Type' }, { sTitle: 'Details' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['dataType', { label: 'Data Type', type: 'select', sort: 'none', source: [['EmployeeDataImporter', 'Employee Data'], ['AttendanceDataImporter', 'Attendance Data'], ['PayrollDataImporter', 'Payroll Data'], ['UserDataImporter', 'User Data'], ['CommonDataImporter', 'Common Data Importer']] }], ['objectType', { label: 'Object Type', type: 'select', sort: 'none', 'allow-null': true, 'null-label': 'None', source: [['LeaveStartingBalance', 'Leave Starting Balance'], ['HoliDay', 'Holidays'], ['EmployeeExpense', 'Employee Expenses'], ['Project', 'Projects'], ['EmployeeProject', 'Employee Projects'], ['EmployeeSalary', 'Employee Salary'], ['PayrollEmployee', 'Company Payroll'], ['Client', 'Clients'], ['Province', 'Provinces'], ['Industry', 'Industry'], ['Industry', 'Industry'], ['EmergencyContact', 'Emergency Contacts'], ['Ethnicity', 'Ethnicity'], ['Nationality', 'Nationality'], ['JobTitle', 'Job Titles'], ['PayFrequency', 'Pay Frequency'], ['PayrollEmployee', 'Payroll Employees'], ['SalaryComponent', 'Salary Components'], ['EmployeeSalary', 'Employee Salary'], ['CompanyStructure', 'Company Structure']] }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }], ['columns', { label: 'Columns', type: 'datagroup', form: [['name', { label: 'CSV Field Name', type: 'text', validation: '' }], ['title', { label: 'Field Title', type: 'text', validation: 'none' }], ['type', { label: 'Type', type: 'select', sort: 'none', source: [['Normal', 'Normal'], ['Reference', 'Reference']] }], ['dependOn', { label: 'Depends On', type: 'select', 'allow-null': true, 'null-label': 'N/A', source: [['EmergencyContact', 'Emergency Contacts'], ['Ethnicity', 'Ethnicity'], ['Nationality', 'Nationality'], ['JobTitle', 'JobTitle'], ['PayFrequency', 'Pay Frequency'], ['PayGrade', 'Pay Grade'], ['EmploymentStatus', 'Employment Status'], ['CompanyStructure', 'Company Structure'], ['Employee', 'Employee'], ['ImmigrationStatus', 'Immigration Status'], ['Industry', 'Industry'], ['CurrencyType', 'CurrencyType'], ['Document', 'Document'], ['Education', 'Education'], ['ExpensesCategory', 'Expenses Category'], ['ExpensesPaymentMethod', 'Expenses Payment Method'], ['ExperienceLevel', 'Experience Level'], ['Form', 'Form'], ['HiringPipeline', 'Hiring Pipeline'], ['HoliDay', 'HoliDay'], ['Language', 'Language'], ['LeaveGroup', 'Leave Group'], ['LeavePeriod', 'Leave Period'], ['LeaveRule', 'Leave Rule'], ['LeaveType', 'Leave Type'], ['OvertimeCategory', 'Overtime Category'], ['Project', 'Project'], ['Client', 'Client'], ['ReviewTemplate', 'Review Template'], ['SalaryComponent', 'Salary Component'], ['SalaryComponentType', 'Salary Component Type'], ['Skill', 'Skill'], ['Timezone', 'Timezone'], ['AssetType', 'Asset Type'], ['Benifit', 'Benifit'], ['Certification', 'Certification'], ['Country', 'Country'], ['Province', 'Province'], ['TrainingSession', 'TrainingSession'], ['User', 'User']] }], ['dependOnField', { label: 'Depends On Field', type: 'select', 'allow-null': true, 'null-label': 'N/A', source: [['id', 'id'], ['employee_id', 'employee_id'], ['name', 'name'], ['code', 'code'], ['title', 'title'], ['employee', 'employee']] }], ['idField', { label: 'Is ID Field', type: 'select', validation: '', source: [['No', 'No'], ['Yes', 'Yes']] }], ['sampleValue', { label: 'Sample Value', type: 'text' }], ['help', { label: 'Help Text', type: 'text' }]], html: '
#_name_# #_delete_##_edit_#
Title: #_title_#
Type: #_type_#
Sample: #_sampleValue_#
 #_help_#
', validation: 'none', 'custom-validate-function': function customValidateFunction(data) { var res = {}; res.params = data; res.valid = true; if (data.type === 'Reference') { if (data.dependOn === 'NULL') { res.message = 'If the type is Reference this field should referring another object'; res.valid = false; } else if (dependOnField == null || dependOnField === 'NULL') { res.message = "If the type is Reference then 'Depends On Field' can not be empty"; res.valid = false; } } else if (data.type === 'Normal') { if (data.dependOn !== 'NULL') { res.message = 'If the type is Reference this field should not refer another object'; res.valid = false; } else if (dependOnField == null || dependOnField === 'NULL') { res.message = "If the type is Reference then 'Depends On Field' should be empty"; res.valid = false; } } return res; } }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var editButton = ''; var download = ''; var deleteButton = ''; var cloneButton = ''; var html = '
_edit__download__clone__delete_
'; if (this.showAddNew) { html = html.replace('_clone_', cloneButton); } else { html = html.replace('_clone_', ''); } if (this.showDelete) { html = html.replace('_delete_', deleteButton); } else { html = html.replace('_delete_', ''); } if (this.showEdit) { html = html.replace('_edit_', editButton); } else { html = html.replace('_edit_', ''); } html = html.replace('_download_', download); html = html.replace(/_id_/g, id); html = html.replace(/_status_/g, data[6]); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "downloadTemplate", value: function downloadTemplate(id) { var params = { t: this.table, sa: 'downloadTemplate', mod: 'admin=data' }; params.req = JSON.stringify({ id: id }); var downloadUrl = modJs.getCustomActionUrl('ca', params); window.open(downloadUrl, '_blank'); } }]); return DataImportAdapter; }(_AdapterBase3["default"]); /** * DataImportFileAdapter */ var DataImportFileAdapter = /*#__PURE__*/function (_AdapterBase2) { _inherits(DataImportFileAdapter, _AdapterBase2); var _super2 = _createSuper(DataImportFileAdapter); function DataImportFileAdapter() { _classCallCheck(this, DataImportFileAdapter); return _super2.apply(this, arguments); } _createClass(DataImportFileAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'data_import_definition', 'status']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Data Import Definition' }, { sTitle: 'Status' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['data_import_definition', { label: 'Data Import Definitions', type: 'select', 'remote-source': ['DataImport', 'id', 'name'] }], ['file', { label: 'File to Import', type: 'fileupload', validation: '', filetypes: 'csv,txt' }], ['details', { label: 'Last Export Result', type: 'textarea', validation: 'none' }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var editButton = ''; var processButton = ''; var deleteButton = ''; var cloneButton = ''; var html = '
_edit__process__clone__delete_
'; if (this.showAddNew) { html = html.replace('_clone_', cloneButton); } else { html = html.replace('_clone_', ''); } if (this.showDelete) { html = html.replace('_delete_', deleteButton); } else { html = html.replace('_delete_', ''); } if (this.showEdit) { html = html.replace('_edit_', editButton); } else { html = html.replace('_edit_', ''); } if (data[3] === 'Not Processed') { html = html.replace('_process_', processButton); } else { html = html.replace('_process_', ''); } html = html.replace(/_id_/g, id); html = html.replace(/_status_/g, data[6]); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "process", value: function process(id) { var object = { id: id }; var reqJson = JSON.stringify(object); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'processSuccessCallBack'; callBackData.callBackFail = 'processFailCallBack'; this.customAction('processDataFile', 'admin=data', reqJson, callBackData); } }, { key: "processSuccessCallBack", value: function processSuccessCallBack(callBackData) { this.showMessage('Success', 'File imported successfully.'); this.get([]); } }, { key: "processFailCallBack", value: function processFailCallBack(callBackData) { this.showMessage('Error', "File import unsuccessful. Result:".concat(callBackData)); } }]); return DataImportFileAdapter; }(_AdapterBase3["default"]); module.exports = { DataImportAdapter: DataImportAdapter, DataImportFileAdapter: DataImportFileAdapter }; },{"../../../api/AdapterBase":52}],16:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.DocumentAdapter = _lib.DocumentAdapter; window.CompanyDocumentAdapter = _lib.CompanyDocumentAdapter; window.EmployeeDocumentAdapter = _lib.EmployeeDocumentAdapter; },{"./lib":17}],17:[function(require,module,exports){ "use strict"; var _AdapterBase4 = _interopRequireDefault(require("../../../api/AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * DocumentAdapter */ var DocumentAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(DocumentAdapter, _AdapterBase); var _super = _createSuper(DocumentAdapter); function DocumentAdapter() { _classCallCheck(this, DocumentAdapter); return _super.apply(this, arguments); } _createClass(DocumentAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'details']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Details' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['expire_notification', { label: 'Notify Expiry', type: 'select', source: [['Yes', 'Yes'], ['No', 'No']] }], ['expire_notification_month', { label: 'Notify Expiry Before One Month', type: 'select', source: [['Yes', 'Yes'], ['No', 'No']] }], ['expire_notification_week', { label: 'Notify Expiry Before One Week', type: 'select', source: [['Yes', 'Yes'], ['No', 'No']] }], ['expire_notification_day', { label: 'Notify Expiry Before One Day', type: 'select', source: [['Yes', 'Yes'], ['No', 'No']] }], ['share_with_employee', { label: 'Share with Employee', type: 'select', source: [['Yes', 'Yes'], ['No', 'No']] }], // [ "sign", {"label":"Require Signature","type":"select","source":[["Yes","Yes"],["No","No"]]}], // [ "sign", {"label":"Require Signature","type":"select","source":[["Yes","Yes"],["No","No"]]}], // [ "sign_label", {"label":"Signature Description","type":"textarea","validation":"none"}], ['details', { label: 'Details', type: 'textarea', validation: 'none' }]]; } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/training-and-reviews/document-management'; } }]); return DocumentAdapter; }(_AdapterBase4["default"]); /** * CompanyDocumentAdapter */ var CompanyDocumentAdapter = /*#__PURE__*/function (_AdapterBase2) { _inherits(CompanyDocumentAdapter, _AdapterBase2); var _super2 = _createSuper(CompanyDocumentAdapter); function CompanyDocumentAdapter() { _classCallCheck(this, CompanyDocumentAdapter); return _super2.apply(this, arguments); } _createClass(CompanyDocumentAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'details', 'status']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Details' }, { sTitle: 'Status' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }], ['status', { label: 'Status', type: 'select', source: [['Active', 'Active'], ['Inactive', 'Inactive'], ['Draft', 'Draft']] }], ['attachment', { label: 'Attachment', type: 'fileupload' }], ['share_departments', { label: 'Share Departments', type: 'select2multi', 'allow-null': true, 'null-label': 'All Departments', 'remote-source': ['CompanyStructure', 'id', 'title'], help: 'This document will be visible to employees from selected department. If no department is selected only Admin users can see this' }], ['share_employees', { label: 'Share Employees', type: 'select2multi', 'allow-null': true, 'null-label': 'All Employees', 'remote-source': ['Employee', 'id', 'first_name+last_name'], validation: 'none', help: 'Instead of sharing with all the employees in a department, you can share it only with specific employees' }]]; } }]); return CompanyDocumentAdapter; }(_AdapterBase4["default"]); /** * EmployeeDocumentAdapter */ var EmployeeDocumentAdapter = /*#__PURE__*/function (_AdapterBase3) { _inherits(EmployeeDocumentAdapter, _AdapterBase3); var _super3 = _createSuper(EmployeeDocumentAdapter); function EmployeeDocumentAdapter() { _classCallCheck(this, EmployeeDocumentAdapter); return _super3.apply(this, arguments); } _createClass(EmployeeDocumentAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'document', 'details', 'date_added', 'status', 'attachment']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Document' }, { sTitle: 'Details' }, { sTitle: 'Date Added' }, { sTitle: 'Status' }, { sTitle: 'Attachment', bVisible: false }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['document', { label: 'Document', type: 'select2', 'remote-source': ['Document', 'id', 'name'] }], ['date_added', { label: 'Date Added', type: 'date', validation: '' }], ['valid_until', { label: 'Valid Until', type: 'date', validation: 'none' }], ['status', { label: 'Status', type: 'select', source: [['Active', 'Active'], ['Inactive', 'Inactive'], ['Draft', 'Draft']] }], ['visible_to', { label: 'Visible To', type: 'select', source: [['Owner', 'Owner'], ['Manager', 'Manager'], ['Admin', 'Admin']] }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }], ['attachment', { label: 'Attachment', type: 'fileupload', validation: '' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var html = '
' + '' + '' + '' + '
'; html = html.replace(/_id_/g, id); html = html.replace(/_attachment_/g, data[6]); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }]); return EmployeeDocumentAdapter; }(_AdapterBase4["default"]); module.exports = { DocumentAdapter: DocumentAdapter, CompanyDocumentAdapter: CompanyDocumentAdapter, EmployeeDocumentAdapter: EmployeeDocumentAdapter }; },{"../../../api/AdapterBase":52}],18:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireWildcard(require("react")); var _antd = require("antd"); var _icons = require("@ant-design/icons"); var _TagList = _interopRequireDefault(require("../../../../components/TagList")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Search = _antd.Input.Search; var Title = _antd.Typography.Title, Text = _antd.Typography.Text; var TabPane = _antd.Tabs.TabPane; var EmployeeProfile = /*#__PURE__*/function (_React$Component) { _inherits(EmployeeProfile, _React$Component); var _super = _createSuper(EmployeeProfile); function EmployeeProfile(props) { var _this; _classCallCheck(this, EmployeeProfile); _this = _super.call(this, props); _this.state = { loading: true }; return _this; } _createClass(EmployeeProfile, [{ key: "updateProfileImage", value: function updateProfileImage() { showUploadDialog("profile_image_".concat(this.props.element.id, "_").concat(new Date().getTime()), 'Upload Profile Image', 'profile_image', this.props.element.id, "profile_image_".concat(this.props.element.id), 'function', 'reloadCurrentElement', 'image'); } }, { key: "getEditButtonJsx", value: function getEditButtonJsx() { var _this2 = this; return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, this.props.loading && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { icon: /*#__PURE__*/_react["default"].createElement(_icons.SyncOutlined, { spin: true }), color: "processing" }, this.props.adapter.gt('Edit')), !this.props.loading && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { icon: /*#__PURE__*/_react["default"].createElement(_icons.EditOutlined, null), color: "processing", onClick: function onClick() { return modJs.edit(_this2.props.element.id); } }, this.props.adapter.gt('Edit'))); } }, { key: "getTabViewEmployeeFilterButtonJsx", value: function getTabViewEmployeeFilterButtonJsx(tab) { var _this3 = this; return /*#__PURE__*/_react["default"].createElement(_antd.Tag, { icon: /*#__PURE__*/_react["default"].createElement(_icons.EditOutlined, null), color: "processing", onClick: function onClick() { switchTab(tab, { employee: _this3.props.element.id }); } }, this.props.adapter.gt('Edit')); } }, { key: "render", value: function render() { var _this4 = this; return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_antd.Row, { direction: "vertical", style: { width: '100%', padding: '10px' }, gutter: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Card, { title: this.props.adapter.gt('Employee Profile'), extra: this.getEditButtonJsx(), style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_antd.Space, { size: 'large' }, /*#__PURE__*/_react["default"].createElement(_antd.Avatar, { size: 140, src: this.props.element.image, onClick: function onClick() { return _this4.updateProfileImage(); } }), /*#__PURE__*/_react["default"].createElement(_antd.Space, { direction: 'vertical' }, /*#__PURE__*/_react["default"].createElement(Title, { level: 4 }, "".concat(this.props.element.first_name, " ").concat(this.props.element.last_name)), /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement(_icons.PhoneTwoTone, null), /*#__PURE__*/_react["default"].createElement(Text, { copyable: true }, " ".concat(this.props.element.mobile_phone || ''))), /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement(_icons.MailTwoTone, null), /*#__PURE__*/_react["default"].createElement(Text, { copyable: true }, " ".concat(this.props.element.work_email || '')))), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions, { title: "", bordered: true, style: { width: '100%', padding: '10px' } }, /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Employee Number'), span: 3 }, this.props.element.employee_id), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('ID Number'), span: 3 }, this.props.element.nic_num || ''), this.props.element.ssn_num && this.props.element.ssn_num !== '' && /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Social Security Number'), span: 3 }, this.props.element.ssn_num || '')))))), /*#__PURE__*/_react["default"].createElement(_antd.Row, { direction: "vertical", style: { width: '100%', padding: '10px' }, gutter: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Tabs, { type: "card", style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(TabPane, { tab: "Basic Information", key: "1", style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_antd.Row, { direction: "vertical", style: { width: '100%', padding: '10px' }, gutter: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Card, { title: this.props.adapter.gt('Personal Information'), extra: this.getEditButtonJsx(), style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_antd.Descriptions, { title: "", bordered: true }, /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Date of Birth') }, this.props.element.birthday || ''), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Gender') }, this.props.element.gender), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Nationality') }, this.props.element.nationality_Name), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Marital Status') }, this.props.element.marital_status), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Joined Date') }, this.props.element.joined_date), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Driving License No') }, this.props.element.driving_license || ''), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Other ID') }, this.props.element.other_id || '')))), /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Card, { title: this.props.adapter.gt('Contact Information'), extra: this.getEditButtonJsx(), style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_antd.Descriptions, { title: "", bordered: true }, /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Address'), span: 3 }, "".concat(this.props.element.address1, ", ").concat(this.props.element.address2 || '')), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('City') }, this.props.element.city), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Country') }, this.props.element.country_Name), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Postal/Zip Code') }, this.props.element.postal_code), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Home Phone'), span: 2 }, /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement(_icons.PhoneTwoTone, null), /*#__PURE__*/_react["default"].createElement(Text, { copyable: true }, " ".concat(this.props.element.home_phone || '')))), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Work Phone'), span: 2 }, /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement(_icons.PhoneTwoTone, null), /*#__PURE__*/_react["default"].createElement(Text, { copyable: true }, " ".concat(this.props.element.work_phone || '')))), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Private Email'), span: 2 }, /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement(_icons.MailTwoTone, null), /*#__PURE__*/_react["default"].createElement(Text, { copyable: true }, " ".concat(this.props.element.private_email || ''))))))), /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Card, { title: this.props.adapter.gt('Job Details'), extra: this.getEditButtonJsx(), style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_antd.Descriptions, { title: "", bordered: true }, /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Job Title'), span: 2 }, this.props.element.job_title_Name), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Employment Status') }, this.props.element.employment_status_Name), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Department') }, this.props.element.department_Name), /*#__PURE__*/_react["default"].createElement(_antd.Descriptions.Item, { label: this.props.adapter.gt('Supervisor') }, this.props.element.supervisor_Name)))))), /*#__PURE__*/_react["default"].createElement(TabPane, { tab: this.props.adapter.gt('Qualifications'), key: "2", style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_antd.Row, { style: { width: '100%', padding: '10px' }, gutter: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 6 }, /*#__PURE__*/_react["default"].createElement(_antd.Card, { title: this.props.adapter.gt('Skills'), extra: this.getTabViewEmployeeFilterButtonJsx('tabEmployeeSkill'), style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_TagList["default"], { color: "geekblue", apiClient: this.props.adapter.apiClient, url: "employees/".concat(this.props.element.id, "/skills"), extractTag: function extractTag(item) { return item.skill_id.display; } }))), /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 6 }, /*#__PURE__*/_react["default"].createElement(_antd.Card, { title: this.props.adapter.gt('Education'), extra: this.getTabViewEmployeeFilterButtonJsx('tabEmployeeEducation'), style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_TagList["default"], { color: "cyan", apiClient: this.props.adapter.apiClient, url: "employees/".concat(this.props.element.id, "/educations"), extractTag: function extractTag(item) { return item.education_id.display; } }))), /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 6 }, /*#__PURE__*/_react["default"].createElement(_antd.Card, { title: this.props.adapter.gt('Certifications'), extra: this.getTabViewEmployeeFilterButtonJsx('tabEmployeeCertification'), style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_TagList["default"], { color: "volcano", apiClient: this.props.adapter.apiClient, url: "employees/".concat(this.props.element.id, "/certifications"), extractTag: function extractTag(item) { return item.certification_id.display; } }))), /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 6 }, /*#__PURE__*/_react["default"].createElement(_antd.Card, { title: this.props.adapter.gt('Languages'), extra: this.getTabViewEmployeeFilterButtonJsx('tabEmployeeLanguage'), style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_TagList["default"], { color: "orange", apiClient: this.props.adapter.apiClient, url: "employees/".concat(this.props.element.id, "/languages"), extractTag: function extractTag(item) { return item.language_id.display; } })))))))); } }]); return EmployeeProfile; }(_react["default"].Component); var _default = EmployeeProfile; exports["default"] = _default; },{"../../../../components/TagList":79,"@ant-design/icons":"@ant-design/icons","antd":"antd","react":"react"}],19:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); var _IceDataPipe = _interopRequireDefault(require("../../../api/IceDataPipe")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } window.EmployeeAdapter = _lib.EmployeeAdapter; window.TerminatedEmployeeAdapter = _lib.TerminatedEmployeeAdapter; window.ArchivedEmployeeAdapter = _lib.ArchivedEmployeeAdapter; window.EmployeeSkillAdapter = _lib.EmployeeSkillAdapter; window.EmployeeEducationAdapter = _lib.EmployeeEducationAdapter; window.EmployeeCertificationAdapter = _lib.EmployeeCertificationAdapter; window.EmployeeLanguageAdapter = _lib.EmployeeLanguageAdapter; window.EmployeeDependentAdapter = _lib.EmployeeDependentAdapter; window.EmergencyContactAdapter = _lib.EmergencyContactAdapter; window.EmployeeImmigrationAdapter = _lib.EmployeeImmigrationAdapter; window.EmployeeSubSkillsAdapter = _lib.EmployeeSubSkillsAdapter; window.EmployeeSubEducationAdapter = _lib.EmployeeSubEducationAdapter; window.EmployeeSubCertificationAdapter = _lib.EmployeeSubCertificationAdapter; window.EmployeeSubLanguageAdapter = _lib.EmployeeSubLanguageAdapter; window.EmployeeSubDependentAdapter = _lib.EmployeeSubDependentAdapter; window.EmployeeSubEmergencyContactAdapter = _lib.EmployeeSubEmergencyContactAdapter; window.EmployeeSubDocumentAdapter = _lib.EmployeeSubDocumentAdapter; window.IceDataPipe = _IceDataPipe["default"]; },{"../../../api/IceDataPipe":58,"./lib":20}],20:[function(require,module,exports){ "use strict"; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _icons = require("@ant-design/icons"); var _AdapterBase = _interopRequireDefault(require("../../../api/AdapterBase")); var _SubAdapterBase = _interopRequireDefault(require("../../../api/SubAdapterBase")); var _ReactLegacyModalAdapterBase = _interopRequireDefault(require("../../../api/ReactLegacyModalAdapterBase")); var _ReactModalAdapterBase = _interopRequireDefault(require("../../../api/ReactModalAdapterBase")); var _EmployeeProfile = _interopRequireDefault(require("./components/EmployeeProfile")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var SubProfileEnabledAdapterBase = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(SubProfileEnabledAdapterBase, _ReactModalAdapterBas); var _super = _createSuper(SubProfileEnabledAdapterBase); function SubProfileEnabledAdapterBase() { _classCallCheck(this, SubProfileEnabledAdapterBase); return _super.apply(this, arguments); } _createClass(SubProfileEnabledAdapterBase, [{ key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }]); return SubProfileEnabledAdapterBase; }(_ReactModalAdapterBase["default"]); var EmployeeAdapter = /*#__PURE__*/function (_ReactModalAdapterBas2) { _inherits(EmployeeAdapter, _ReactModalAdapterBas2); var _super2 = _createSuper(EmployeeAdapter); function EmployeeAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, EmployeeAdapter); _this = _super2.call(this, endPoint, tab, filter, orderBy); _this.fieldNameMap = {}; _this.hiddenFields = {}; _this.tableFields = {}; _this.formOnlyFields = {}; return _this; } _createClass(EmployeeAdapter, [{ key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }, { key: "setFieldNameMap", value: function setFieldNameMap(fields) { var field; for (var i = 0; i < fields.length; i++) { field = fields[i]; this.fieldNameMap[field.name] = field; if (field.display === 'Hidden') { this.hiddenFields[field.name] = field; } else if (field.display === 'Table and Form' || field.display === 'Form') { this.tableFields[field.name] = field; } else { this.formOnlyFields[field.name] = field; } } } }, { key: "getCustomTableParams", value: function getCustomTableParams() { var that = this; return { aoColumnDefs: [{ fnRender: function fnRender(data, cell) { return that.preProcessRemoteTableData(data, cell, 1); }, aTargets: [1] }, { fnRender: that.getActionButtons, aTargets: [that.getDataMapping().length] }] }; } }, { key: "preProcessRemoteTableData", value: function preProcessRemoteTableData(data, cell, id) { if (id === 1) { var tmp = 'User Image'; return tmp.replace('_img_', cell); } return cell; } }, { key: "getTableHTMLTemplate", value: function getTableHTMLTemplate() { return '
'; } }, { key: "getTableFields", value: function getTableFields() { return ['id', 'image', 'employee_id', 'first_name', 'last_name', //'mobile_phone', 'department', //'gender', 'supervisor']; } }, { key: "getDataMapping", value: function getDataMapping() { var tableFields = this.getTableFields(); var newTableFields = []; for (var i = 0; i < tableFields.length; i++) { if ((this.hiddenFields[tableFields[i]] === undefined || this.hiddenFields[tableFields[i]] === null) && (this.formOnlyFields[tableFields[i]] === undefined || this.formOnlyFields[tableFields[i]] === null)) { newTableFields.push(tableFields[i]); } } return newTableFields; } }, { key: "getHeaders", value: function getHeaders() { var tableFields = this.getTableFields(); var headers = [{ sTitle: 'ID', bVisible: false }, { sTitle: '', bSortable: false }]; var title = ''; for (var i = 0; i < tableFields.length; i++) { if ((this.hiddenFields[tableFields[i]] === undefined || this.hiddenFields[tableFields[i]] === null) && (this.formOnlyFields[tableFields[i]] === undefined || this.formOnlyFields[tableFields[i]] === null)) { if (this.fieldNameMap[tableFields[i]] !== undefined && this.fieldNameMap[tableFields[i]] !== null) { title = this.fieldNameMap[tableFields[i]].textMapped; if (title === undefined || title === null || title === '') { headers.push({ sTitle: title }); } else if (tableFields[i] === 'gender') { headers.push({ sTitle: title, translate: true }); } else { headers.push({ sTitle: title }); } } } } return headers; } }, { key: "getTableColumns", value: function getTableColumns() { var columns = this.getDataMapping(); var headers = this.getHeaders(); var tableColumns = []; for (var i = 1; i < columns.length; i++) { tableColumns.push({ title: headers[i].sTitle, dataIndex: columns[i], sorter: true }); if (columns[i] === 'image') { tableColumns[i - 1].render = function (text, record) { return /*#__PURE__*/_react["default"].createElement(_antd.Avatar, { src: text }); }; } } return tableColumns; } }, { key: "showElement", value: function showElement(element) { this.tableContainer.current.setCurrentElement(element); } }, { key: "getTableChildComponents", value: function getTableChildComponents() { return /*#__PURE__*/_react["default"].createElement(_EmployeeProfile["default"], null); } }, { key: "getFormFields", value: function getFormFields() { var newFields = []; var tempField; var title; var fields = [['id', { label: 'ID', type: 'hidden', validation: '' }], ['employee_id', { label: 'Employee Number', type: 'text', validation: '' }], ['first_name', { label: 'First Name', type: 'text', validation: '' }], ['middle_name', { label: 'Middle Name', type: 'text', validation: 'none' }], ['last_name', { label: 'Last Name', type: 'text', validation: '' }], ['nationality', { label: 'Nationality', type: 'select2', 'remote-source': ['Nationality', 'id', 'name'] }], ['birthday', { label: 'Date of Birth', type: 'date', validation: '' }], ['gender', { label: 'Gender', type: 'select', source: [['Male', 'Male'], ['Female', 'Female'], ['Other', 'Other']] }], ['marital_status', { label: 'Marital Status', type: 'select', source: [['Married', 'Married'], ['Single', 'Single'], ['Divorced', 'Divorced'], ['Widowed', 'Widowed'], ['Other', 'Other']] }], ['ethnicity', { label: 'Ethnicity', type: 'select2', 'allow-null': true, 'remote-source': ['Ethnicity', 'id', 'name'] }], ['immigration_status', { label: 'Immigration Status', type: 'select2', 'allow-null': true, 'remote-source': ['ImmigrationStatus', 'id', 'name'] }], ['ssn_num', { label: 'SSN/NRIC', type: 'text', validation: 'none' }], ['nic_num', { label: 'NIC', type: 'text', validation: 'none' }], ['other_id', { label: 'Other ID', type: 'text', validation: 'none' }], ['driving_license', { label: 'Driving License No', type: 'text', validation: 'none' }], ['employment_status', { label: 'Employment Status', type: 'select2', 'remote-source': ['EmploymentStatus', 'id', 'name'] }], ['department', { label: 'Department', type: 'select2', 'remote-source': ['CompanyStructure', 'id', 'title'] }], ['job_title', { label: 'Job Title', type: 'select2', 'remote-source': ['JobTitle', 'id', 'name'] }], ['pay_grade', { label: 'Pay Grade', type: 'select2', 'allow-null': true, 'remote-source': ['PayGrade', 'id', 'name'] }], ['joined_date', { label: 'Joined Date', type: 'date', validation: '' }], ['confirmation_date', { label: 'Confirmation Date', type: 'date', validation: 'none' }], ['termination_date', { label: 'Termination Date', type: 'date', validation: 'none' }], ['work_station_id', { label: 'Work Station Id', type: 'text', validation: 'none' }], ['address1', { label: 'Address Line 1', type: 'text', validation: 'none' }], ['address2', { label: 'Address Line 2', type: 'text', validation: 'none' }], ['city', { label: 'City', type: 'text', validation: 'none' }], ['country', { label: 'Country', type: 'select2', 'remote-source': ['Country', 'code', 'name'] }], ['province', { label: 'State', type: 'select2', 'allow-null': true, 'remote-source': ['Province', 'id', 'name'] }], ['postal_code', { label: 'Postal/Zip Code', type: 'text', validation: 'none' }], ['home_phone', { label: 'Home Phone', type: 'text', validation: 'none' }], ['mobile_phone', { label: 'Mobile Phone', type: 'text', validation: 'none' }], ['work_phone', { label: 'Work Phone', type: 'text', validation: 'none' }], ['work_email', { label: 'Work Email', type: 'text', validation: 'emailOrEmpty' }], ['private_email', { label: 'Private Email', type: 'text', validation: 'emailOrEmpty' }], ['supervisor', { label: 'Direct Supervisor', type: 'select2', 'allow-null': true, 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['indirect_supervisors', { label: 'Indirect Supervisors', type: 'select2multi', 'allow-null': true, 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['approver1', { label: 'First Level Approver', type: 'select2', 'allow-null': true, 'null-label': 'None', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['approver2', { label: 'Second Level Approver', type: 'select2', 'allow-null': true, 'null-label': 'None', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['approver3', { label: 'Third Level Approver', type: 'select2', 'allow-null': true, 'null-label': 'None', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['notes', { label: 'Notes', type: 'datagroup', form: [['note', { label: 'Note', type: 'textarea', validation: '' }]], html: '
#_delete_##_edit_#Date: #_date_#
#_note_#
', validation: 'none', columns: [{ title: 'Note', dataIndex: 'note', key: 'note' }], 'sort-function': function sortFunction(a, b) { var t1 = Date.parse(a.date).getTime(); var t2 = Date.parse(b.date).getTime(); return t1 < t2; }, 'custom-validate-function': function customValidateFunction(data) { var res = {}; res.valid = true; data.date = new Date().toString('d-MMM-yyyy hh:mm tt'); res.params = data; return res; } }]]; for (var i = 0; i < this.customFields.length; i++) { fields.push(this.customFields[i]); } for (var _i = 0; _i < fields.length; _i++) { tempField = fields[_i]; if (this.hiddenFields[tempField[0]] === undefined || this.hiddenFields[tempField[0]] === null) { if (this.fieldNameMap[tempField[0]] !== undefined && this.fieldNameMap[tempField[0]] !== null) { title = this.fieldNameMap[tempField[0]].textMapped; tempField[1].label = title; } newFields.push(tempField); } } return newFields; } }, { key: "getMappedFields", value: function getMappedFields() { var fields = this.getFormFields(); var steps = [{ title: this.gt('Personal'), description: this.gt('Personal Information'), fields: ['id', 'employee_id', 'first_name', 'middle_name', 'last_name', 'nationality', 'birthday', 'gender', 'marital_status', 'ethnicity'] }, { title: this.gt('Identification'), description: this.gt('Personal Information'), fields: ['immigration_status', 'ssn_num', 'nic_num', 'other_id', 'driving_license'] }, { title: this.gt('Work'), description: this.gt('Work related details'), fields: ['employment_status', 'department', 'job_title', 'pay_grade', 'joined_date', 'confirmation_date', 'termination_date', 'work_station_id'] }, { title: this.gt('Contact'), description: this.gt('Contact details'), fields: ['address1', 'address2', 'city', 'country', 'province', 'postal_code', 'home_phone', 'mobile_phone', 'work_phone', 'work_email', 'private_email'] }, { title: this.gt('Report'), description: this.gt('Supervisors and reports'), fields: ['supervisor', 'indirect_supervisors', 'approver1', 'approver2', 'approver3', 'notes'] }]; if (this.customFields.length > 0) { steps.push({ title: this.gt('Other'), description: this.gt('Additional details'), fields: this.customFields.map(function (item) { return item[0]; }) }); } return this.addActualFieldsForStepModal(steps, fields); } }, { key: "getFilters", value: function getFilters() { return [['job_title', { label: 'Job Title', type: 'select2', 'allow-null': true, 'null-label': 'All Job Titles', 'remote-source': ['JobTitle', 'id', 'name'] }], ['department', { label: 'Department', type: 'select2', 'allow-null': true, 'null-label': 'All Departments', 'remote-source': ['CompanyStructure', 'id', 'title'] }], ['supervisor', { label: 'Supervisor', type: 'select2', 'allow-null': true, 'null-label': 'Anyone', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }, { key: "getTableActionButtonJsx", value: function getTableActionButtonJsx(adapter) { return function (text, record) { return /*#__PURE__*/_react["default"].createElement(_antd.Space, { size: "middle" }, /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "orange", onClick: function onClick() { return modJs.setAdminProfile(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.LoginOutlined, null), " ".concat(adapter.gt('Login As'))), adapter.hasAccess('save') && adapter.showEdit && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "green", onClick: function onClick() { return modJs.edit(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.EditOutlined, null), " ".concat(adapter.gt('Edit'))), adapter.hasAccess('element') && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "blue", onClick: function onClick() { return modJs.viewElement(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.MonitorOutlined, null), " ".concat(adapter.gt('View'))), adapter.hasAccess('delete') && adapter.showDelete && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "volcano", onClick: function onClick() { return modJs.terminateEmployee(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.DeleteOutlined, null), " ".concat(adapter.gt('Deactivate'))), adapter.hasAccess('save') && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "cyan", onClick: function onClick() { return modJs.copyRow(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.CopyOutlined, null), " ".concat(adapter.gt('Copy')))); }; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id) { var deleteBtn = ''; if (this.showDelete === false) { deleteBtn = ''; } // eslint-disable-next-line max-len var html = "
\n\n\n\n".concat(deleteBtn, "\n
"); html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://thilinah.gitbooks.io/icehrm-guide/content/employee-information-setup.html'; } }, { key: "saveSuccessItemCallback", value: function saveSuccessItemCallback(data) { this.lastSavedEmployee = data; if (this.currentId === null) { $('#createUserModel').modal('show'); } } }, { key: "closeCreateUser", value: function closeCreateUser() { $('#createUserModel').modal('hide'); } }, { key: "createUser", value: function createUser() { var data = {}; data.employee = this.lastSavedEmployee.id; data.user_level = 'Employee'; data.email = this.lastSavedEmployee.work_email; data.username = this.lastSavedEmployee.work_email.split('@')[0]; top.location.href = this.getCustomUrl("?g=admin&n=users&m=admin_Admin&action=new&object=".concat(Base64.encodeURI(JSON.stringify(data)))); } }, { key: "deleteEmployee", value: function deleteEmployee(id) { if (confirm('Are you sure you want to archive this employee? Data for this employee will be saved to an archive table. But you will not be able to covert the archived employee data into a normal employee.')) {// Archive } else { return; } var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'deleteEmployeeSuccessCallback'; callBackData.callBackFail = 'deleteEmployeeFailCallback'; this.customAction('deleteEmployee', 'admin=employees', JSON.stringify({ id: id }), callBackData); } }, { key: "deleteEmployeeSuccessCallback", value: function deleteEmployeeSuccessCallback(callBackData) { this.showMessage('Delete Success', 'Employee deleted. You can find archived information for this employee in Archived Employees tab'); this.get([]); } }, { key: "deleteEmployeeFailCallback", value: function deleteEmployeeFailCallback(callBackData) { this.showMessage('Error occurred while deleting Employee', callBackData); } }, { key: "terminateEmployee", value: function terminateEmployee(id) { if (confirm('Are you sure you want to terminate this employee contract? You will still be able to access all details of this employee.')) {// Terminate } else { return; } var params = {}; params.id = id; var reqJson = JSON.stringify(params); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'terminateEmployeeSuccessCallback'; callBackData.callBackFail = 'terminateEmployeeFailCallback'; this.customAction('terminateEmployee', 'admin=employees', reqJson, callBackData); } }, { key: "terminateEmployeeSuccessCallback", value: function terminateEmployeeSuccessCallback(callBackData) { this.showMessage('Success', 'Employee contract terminated. You can find terminated employee information under Terminated Employees menu.'); this.get([]); } }, { key: "terminateEmployeeFailCallback", value: function terminateEmployeeFailCallback(callBackData) { this.showMessage('Error occured while terminating Employee', callBackData); } }, { key: "activateEmployee", value: function activateEmployee(id) { if (confirm('Are you sure you want to re-activate this employee contract?')) {// Terminate } else { return; } var params = {}; params.id = id; var reqJson = JSON.stringify(params); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'activateEmployeeSuccessCallback'; callBackData.callBackFail = 'activateEmployeeFailCallback'; this.customAction('activateEmployee', 'admin=employees', reqJson, callBackData); } }, { key: "activateEmployeeSuccessCallback", value: function activateEmployeeSuccessCallback(callBackData) { this.showMessage('Success', 'Employee contract re-activated.'); this.get([]); } }, { key: "activateEmployeeFailCallback", value: function activateEmployeeFailCallback(callBackData) { this.showMessage('Error occurred while activating Employee', callBackData); } }, { key: "view", value: function view(id) { var that = this; this.currentId = id; var sourceMappingJson = JSON.stringify(this.getSourceMapping()); var object = { id: id, map: sourceMappingJson }; var reqJson = JSON.stringify(object); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'renderEmployee'; callBackData.callBackFail = 'viewFailCallBack'; this.customAction('get', 'modules=employees', reqJson, callBackData); } }, { key: "viewFailCallBack", value: function viewFailCallBack(callBackData) { this.showMessage('Error', 'Error Occurred while retrieving candidate'); } }, { key: "deleteProfileImage", value: function deleteProfileImage(empId) { var req = { id: empId }; var reqJson = JSON.stringify(req); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'modEmployeeDeleteProfileImageCallBack'; callBackData.callBackFail = 'modEmployeeDeleteProfileImageCallBack'; this.customAction('deleteProfileImage', 'modules=employees', reqJson, callBackData); } }, { key: "modEmployeeDeleteProfileImageCallBack", value: function modEmployeeDeleteProfileImageCallBack(data) {// top.location.href = top.location.href; } }]); return EmployeeAdapter; }(_ReactModalAdapterBase["default"]); /* * Terminated Employee */ var TerminatedEmployeeAdapter = /*#__PURE__*/function (_EmployeeAdapter) { _inherits(TerminatedEmployeeAdapter, _EmployeeAdapter); var _super3 = _createSuper(TerminatedEmployeeAdapter); function TerminatedEmployeeAdapter() { _classCallCheck(this, TerminatedEmployeeAdapter); return _super3.apply(this, arguments); } _createClass(TerminatedEmployeeAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee_id', 'first_name', 'last_name', 'mobile_phone', 'department', 'gender', 'supervisor']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID' }, { sTitle: '', bSortable: false }, { sTitle: 'Employee Number' }, { sTitle: 'First Name' }, { sTitle: 'Last Name' }, { sTitle: 'Mobile' }, { sTitle: 'Department' }, { sTitle: 'Gender' }, { sTitle: 'Supervisor' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee Number', dataIndex: 'employee_id', sorter: true }, { title: 'First Name', dataIndex: 'first_name' }, { title: 'Last Name', dataIndex: 'last_name' }, { title: 'Department', dataIndex: 'department' }, { title: 'Supervisor', dataIndex: 'supervisor' }]; } }, { key: "getFilters", value: function getFilters() { return [['job_title', { label: 'Job Title', type: 'select2', 'allow-null': true, 'null-label': 'All Job Titles', 'remote-source': ['JobTitle', 'id', 'name'] }], ['department', { label: 'Department', type: 'select2', 'allow-null': true, 'null-label': 'All Departments', 'remote-source': ['CompanyStructure', 'id', 'title'] }], ['supervisor', { label: 'Supervisor', type: 'select2', 'allow-null': true, 'null-label': 'Anyone', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id) { // eslint-disable-next-line max-len var html = "
\n\n\n\n
"; html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "download", value: function download(id) { var params = { t: 'ArchivedEmployee', sa: 'downloadArchivedEmployee', mod: 'admin=employees' }; params.req = JSON.stringify({ id: id }); var downloadUrl = modJs.getCustomActionUrl('ca', params); window.open(downloadUrl, '_blank'); } }, { key: "getTableActionButtonJsx", value: function getTableActionButtonJsx(adapter) { return function (text, record) { return /*#__PURE__*/_react["default"].createElement(_antd.Space, { size: "middle" }, /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "cyan", onClick: function onClick() { return modJs.activateEmployee(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.UndoOutlined, null), " ".concat(adapter.gt('Activate'))), adapter.hasAccess('delete') && adapter.showDelete && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "volcano", onClick: function onClick() { return modJs.deleteEmployee(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.DeleteOutlined, null), " ".concat(adapter.gt('Delete')))); }; } }]); return TerminatedEmployeeAdapter; }(EmployeeAdapter); /* * Archived Employee */ var ArchivedEmployeeAdapter = /*#__PURE__*/function (_SubProfileEnabledAda) { _inherits(ArchivedEmployeeAdapter, _SubProfileEnabledAda); var _super4 = _createSuper(ArchivedEmployeeAdapter); function ArchivedEmployeeAdapter() { _classCallCheck(this, ArchivedEmployeeAdapter); return _super4.apply(this, arguments); } _createClass(ArchivedEmployeeAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee_id', 'first_name', 'last_name', 'work_email', 'department', 'gender', 'supervisor']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID' }, { sTitle: 'Employee Number' }, { sTitle: 'First Name' }, { sTitle: 'Last Name' }, { sTitle: 'Work Email' }, { sTitle: 'Department' }, { sTitle: 'Gender' }, { sTitle: 'Supervisor' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee Number', dataIndex: 'employee_id', sorter: true }, { title: 'First Name', dataIndex: 'first_name' }, { title: 'Last Name', dataIndex: 'last_name' }, { title: 'Department', dataIndex: 'department' }, { title: 'Supervisor', dataIndex: 'supervisor' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden', validation: '' }], ['employee_id', { label: 'Employee Number', type: 'text', validation: '' }], ['first_name', { label: 'First Name', type: 'text', validation: '' }], ['middle_name', { label: 'Middle Name', type: 'text', validation: 'none' }], ['last_name', { label: 'Last Name', type: 'text', validation: '' }], ['gender', { label: 'Gender', type: 'select', source: [['Male', 'Male'], ['Female', 'Female'], ['Other', 'Other']] }], ['ssn_num', { label: 'SSN/NRIC', type: 'text', validation: 'none' }], ['nic_num', { label: 'NIC', type: 'text', validation: 'none' }], ['other_id', { label: 'Other ID', type: 'text', validation: 'none' }], ['driving_license', { label: 'Driving License No', type: 'text', validation: 'none' }], ['department', { label: 'Department', type: 'select2', 'remote-source': ['CompanyStructure', 'id', 'title'] }], ['supervisor', { label: 'Supervisor', type: 'select2', 'allow-null': true, 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }, { key: "getFilters", value: function getFilters() { return [['job_title', { label: 'Job Title', type: 'select2', 'allow-null': true, 'null-label': 'All Job Titles', 'remote-source': ['JobTitle', 'id', 'name'] }], ['department', { label: 'Department', type: 'select2', 'allow-null': true, 'null-label': 'All Departments', 'remote-source': ['CompanyStructure', 'id', 'title'] }], ['supervisor', { label: 'Supervisor', type: 'select2', 'allow-null': true, 'null-label': 'Anyone', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id) { // eslint-disable-next-line max-len var html = '
'; html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "download", value: function download(id) { var params = { t: 'ArchivedEmployee', sa: 'downloadArchivedEmployee', mod: 'admin=employees' }; params.req = JSON.stringify({ id: id }); var downloadUrl = modJs.getCustomActionUrl('ca', params); window.open(downloadUrl, '_blank'); } }, { key: "getTableActionButtonJsx", value: function getTableActionButtonJsx(adapter) { return function (text, record) { return /*#__PURE__*/_react["default"].createElement(_antd.Space, { size: "middle" }, adapter.hasAccess('element') && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "blue", onClick: function onClick() { return modJs.viewElement(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.MonitorOutlined, null), " ".concat(adapter.gt('View'))), /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "cyan", onClick: function onClick() { return modJs.download(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.CloudDownloadOutlined, null), " ".concat(adapter.gt('Download'))), adapter.hasAccess('delete') && adapter.showDelete && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "volcano", onClick: function onClick() { return modJs.deleteRow(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.DeleteOutlined, null), " ".concat(adapter.gt('Delete')))); }; } }]); return ArchivedEmployeeAdapter; }(SubProfileEnabledAdapterBase); /* * ========================================================== */ var EmployeeSkillAdapter = /*#__PURE__*/function (_ReactModalAdapterBas3) { _inherits(EmployeeSkillAdapter, _ReactModalAdapterBas3); var _super5 = _createSuper(EmployeeSkillAdapter); function EmployeeSkillAdapter() { _classCallCheck(this, EmployeeSkillAdapter); return _super5.apply(this, arguments); } _createClass(EmployeeSkillAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'skill_id', 'details']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Skill' }, { sTitle: 'Details' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee', dataIndex: 'employee', sorter: true }, { title: 'Skill', dataIndex: 'skill_id', sorter: true }, { title: 'Details', dataIndex: 'details' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['skill_id', { label: 'Skill', type: 'select2', 'allow-null': true, 'remote-source': ['Skill', 'id', 'name'] }], ['details', { label: 'Details', type: 'textarea', validation: '' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['skill_id', { label: 'Skill', type: 'select2', 'allow-null': true, 'null-label': 'All Skills', 'remote-source': ['Skill', 'id', 'name'] }]]; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }]); return EmployeeSkillAdapter; }(_ReactModalAdapterBase["default"]); /** * EmployeeEducationAdapter */ var EmployeeEducationAdapter = /*#__PURE__*/function (_SubProfileEnabledAda2) { _inherits(EmployeeEducationAdapter, _SubProfileEnabledAda2); var _super6 = _createSuper(EmployeeEducationAdapter); function EmployeeEducationAdapter() { _classCallCheck(this, EmployeeEducationAdapter); return _super6.apply(this, arguments); } _createClass(EmployeeEducationAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'education_id', 'institute', 'date_start', 'date_end']; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee', dataIndex: 'employee', sorter: true }, { title: 'Qualification', dataIndex: 'education_id', sorter: true }, { title: 'Institute', dataIndex: 'institute', sorter: true }, { title: 'Start Date', dataIndex: 'date_start', sorter: true }, { title: 'Completed On', dataIndex: 'date_end', sorter: true }]; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Qualification' }, { sTitle: 'Institute' }, { sTitle: 'Start Date' }, { sTitle: 'Completed On' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['education_id', { label: 'Qualification', type: 'select2', 'allow-null': false, 'remote-source': ['Education', 'id', 'name'] }], ['institute', { label: 'Institute', type: 'text', validation: '' }], ['date_start', { label: 'Start Date', type: 'date', validation: 'none' }], ['date_end', { label: 'Completed On', type: 'date', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['education_id', { label: 'Qualification', type: 'select2', 'allow-null': true, 'null-label': 'All Qualifications', 'remote-source': ['Education', 'id', 'name'] }]]; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }]); return EmployeeEducationAdapter; }(SubProfileEnabledAdapterBase); /** * EmployeeCertificationAdapter */ var EmployeeCertificationAdapter = /*#__PURE__*/function (_SubProfileEnabledAda3) { _inherits(EmployeeCertificationAdapter, _SubProfileEnabledAda3); var _super7 = _createSuper(EmployeeCertificationAdapter); function EmployeeCertificationAdapter() { _classCallCheck(this, EmployeeCertificationAdapter); return _super7.apply(this, arguments); } _createClass(EmployeeCertificationAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'certification_id', 'institute', 'date_start', 'date_end']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Certification' }, { sTitle: 'Institute' }, { sTitle: 'Granted On' }, { sTitle: 'Valid Thru' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee', dataIndex: 'employee', sorter: true }, { title: 'Certification', dataIndex: 'certification_id', sorter: true }, { title: 'Institute', dataIndex: 'institute', sorter: true }, { title: 'Granted On', dataIndex: 'date_start', sorter: true }, { title: 'Valid Until', dataIndex: 'date_end', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['certification_id', { label: 'Certification', type: 'select2', 'allow-null': false, 'remote-source': ['Certification', 'id', 'name'] }], ['institute', { label: 'Institute', type: 'text', validation: '' }], ['date_start', { label: 'Granted On', type: 'date', validation: 'none' }], ['date_end', { label: 'Valid Thru', type: 'date', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['certification_id', { label: 'Certification', type: 'select2', 'allow-null': true, 'null-label': 'All Certifications', 'remote-source': ['Certification', 'id', 'name'] }]]; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }]); return EmployeeCertificationAdapter; }(SubProfileEnabledAdapterBase); /** * EmployeeLanguageAdapter */ var EmployeeLanguageAdapter = /*#__PURE__*/function (_SubProfileEnabledAda4) { _inherits(EmployeeLanguageAdapter, _SubProfileEnabledAda4); var _super8 = _createSuper(EmployeeLanguageAdapter); function EmployeeLanguageAdapter() { _classCallCheck(this, EmployeeLanguageAdapter); return _super8.apply(this, arguments); } _createClass(EmployeeLanguageAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'language_id', 'reading', 'speaking', 'writing', 'understanding']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Language' }, { sTitle: 'Reading' }, { sTitle: 'Speaking' }, { sTitle: 'Writing' }, { sTitle: 'Listening' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee', dataIndex: 'employee', sorter: true }, { title: 'Language', dataIndex: 'language_id', sorter: true }, { title: 'Reading', dataIndex: 'reading', sorter: true }, { title: 'Speaking', dataIndex: 'speaking', sorter: true }, { title: 'Writing', dataIndex: 'writing', sorter: true }, { title: 'Listening', dataIndex: 'understanding', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { var compArray = [['Elementary Proficiency', 'Elementary Proficiency'], ['Limited Working Proficiency', 'Limited Working Proficiency'], ['Professional Working Proficiency', 'Professional Working Proficiency'], ['Full Professional Proficiency', 'Full Professional Proficiency'], ['Native or Bilingual Proficiency', 'Native or Bilingual Proficiency']]; return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['language_id', { label: 'Language', type: 'select2', 'allow-null': false, 'remote-source': ['Language', 'id', 'name'] }], ['reading', { label: 'Reading', type: 'select', source: compArray }], ['speaking', { label: 'Speaking', type: 'select', source: compArray }], ['writing', { label: 'Writing', type: 'select', source: compArray }], ['understanding', { label: 'Listening', type: 'select', source: compArray }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['language_id', { label: 'Language', type: 'select2', 'allow-null': true, 'null-label': 'All Languages', 'remote-source': ['Language', 'id', 'name'] }]]; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }]); return EmployeeLanguageAdapter; }(SubProfileEnabledAdapterBase); /** * EmployeeDependentAdapter */ var EmployeeDependentAdapter = /*#__PURE__*/function (_SubProfileEnabledAda5) { _inherits(EmployeeDependentAdapter, _SubProfileEnabledAda5); var _super9 = _createSuper(EmployeeDependentAdapter); function EmployeeDependentAdapter() { _classCallCheck(this, EmployeeDependentAdapter); return _super9.apply(this, arguments); } _createClass(EmployeeDependentAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'name', 'relationship', 'dob', 'id_number']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Name' }, { sTitle: 'Relationship' }, { sTitle: 'Date of Birth' }, { sTitle: 'Id Number' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee', dataIndex: 'employee', sorter: true }, { title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Relationship', dataIndex: 'relationship', sorter: true }, { title: 'Date of Birth', dataIndex: 'dob', sorter: true }, { title: 'Id Number', dataIndex: 'id_number' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['name', { label: 'Name', type: 'text', validation: '' }], ['relationship', { label: 'Relationship', type: 'select', source: [['Child', 'Child'], ['Spouse', 'Spouse'], ['Parent', 'Parent'], ['Other', 'Other']] }], ['dob', { label: 'Date of Birth', type: 'date', validation: '' }], ['id_number', { label: 'Id Number', type: 'text', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }]]; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }]); return EmployeeDependentAdapter; }(SubProfileEnabledAdapterBase); /* * EmergencyContactAdapter */ var EmergencyContactAdapter = /*#__PURE__*/function (_SubProfileEnabledAda6) { _inherits(EmergencyContactAdapter, _SubProfileEnabledAda6); var _super10 = _createSuper(EmergencyContactAdapter); function EmergencyContactAdapter() { _classCallCheck(this, EmergencyContactAdapter); return _super10.apply(this, arguments); } _createClass(EmergencyContactAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'name', 'relationship', 'home_phone', 'work_phone', 'mobile_phone']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Name' }, { sTitle: 'Relationship' }, { sTitle: 'Home Phone' }, { sTitle: 'Work Phone' }, { sTitle: 'Mobile Phone' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee', dataIndex: 'employee', sorter: true }, { title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Relationship', dataIndex: 'relationship', sorter: true }, { title: 'Home Phone', dataIndex: 'home_phone' }, { title: 'Work Phone', dataIndex: 'work_phone' }, { title: 'Mobile Phone', dataIndex: 'mobile_phone' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['name', { label: 'Name', type: 'text', validation: '' }], ['relationship', { label: 'Relationship', type: 'text', validation: 'none' }], ['home_phone', { label: 'Home Phone', type: 'text', validation: 'none' }], ['work_phone', { label: 'Work Phone', type: 'text', validation: 'none' }], ['mobile_phone', { label: 'Mobile Phone', type: 'text', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }]]; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }]); return EmergencyContactAdapter; }(SubProfileEnabledAdapterBase); /* * EmployeeImmigrationAdapter */ var EmployeeImmigrationAdapter = /*#__PURE__*/function (_SubProfileEnabledAda7) { _inherits(EmployeeImmigrationAdapter, _SubProfileEnabledAda7); var _super11 = _createSuper(EmployeeImmigrationAdapter); function EmployeeImmigrationAdapter() { _classCallCheck(this, EmployeeImmigrationAdapter); return _super11.apply(this, arguments); } _createClass(EmployeeImmigrationAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'document', 'doc_number', 'issued', 'expiry', 'status', 'details']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Document', sClass: 'columnMain' }, { sTitle: 'Number' }, { sTitle: 'Issued Date' }, { sTitle: 'Expiry Date' }, { sTitle: 'Status' }, { sTitle: 'Details' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['document', { label: 'Document', type: 'select2', source: [['Passport', 'Passport'], ['Visa', 'Visa']] }], ['doc_number', { label: 'Number', type: 'text', validation: '' }], ['issued', { label: 'Issued Date', type: 'date', validation: '' }], ['expiry', { label: 'Expiry Date', type: 'date', validation: '' }], ['status', { label: 'Status', type: 'text', validation: 'none' }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }]); return EmployeeImmigrationAdapter; }(SubProfileEnabledAdapterBase); module.exports = { EmployeeAdapter: EmployeeAdapter, TerminatedEmployeeAdapter: TerminatedEmployeeAdapter, ArchivedEmployeeAdapter: ArchivedEmployeeAdapter, EmployeeSkillAdapter: EmployeeSkillAdapter, EmployeeEducationAdapter: EmployeeEducationAdapter, EmployeeCertificationAdapter: EmployeeCertificationAdapter, EmployeeLanguageAdapter: EmployeeLanguageAdapter, EmployeeDependentAdapter: EmployeeDependentAdapter, EmergencyContactAdapter: EmergencyContactAdapter, EmployeeImmigrationAdapter: EmployeeImmigrationAdapter }; },{"../../../api/AdapterBase":52,"../../../api/ReactLegacyModalAdapterBase":64,"../../../api/ReactModalAdapterBase":65,"../../../api/SubAdapterBase":66,"./components/EmployeeProfile":18,"@ant-design/icons":"@ant-design/icons","antd":"antd","react":"react"}],21:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.FieldNameAdapter = _lib.FieldNameAdapter; },{"./lib":22}],22:[function(require,module,exports){ "use strict"; var _AdapterBase2 = _interopRequireDefault(require("../../../api/AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * FieldNameAdapter */ var FieldNameAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(FieldNameAdapter, _AdapterBase); var _super = _createSuper(FieldNameAdapter); function FieldNameAdapter() { _classCallCheck(this, FieldNameAdapter); return _super.apply(this, arguments); } _createClass(FieldNameAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'textOrig', 'textMapped', 'display']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Original Text' }, { sTitle: 'Mapped Text' }, { sTitle: 'Display Status' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['type', { label: 'Type', type: 'placeholder', validation: '' }], ['name', { label: 'Name', type: 'placeholder', validation: '' }], ['textOrig', { label: 'Original Text', type: 'placeholder', validation: '' }], ['textMapped', { label: 'Mapped Text', type: 'text', validation: '' }], ['display', { label: 'Display Status', type: 'select', source: [['Form', 'Show'], ['Hidden', 'Hidden']] }]]; } }]); return FieldNameAdapter; }(_AdapterBase2["default"]); module.exports = { FieldNameAdapter: FieldNameAdapter }; },{"../../../api/AdapterBase":52}],23:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); var _IceDataPipe = _interopRequireDefault(require("../../../api/IceDataPipe")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function init(data) { var modJsList = []; modJsList.tabJobTitle = new _lib.JobTitleAdapter('JobTitle', 'JobTitle', '', ''); modJsList.tabJobTitle.setObjectTypeName('Job Titles'); modJsList.tabJobTitle.setDataPipe(new _IceDataPipe["default"](modJsList.tabJobTitle)); modJsList.tabJobTitle.setAccess(data.permissions.JobTitle); modJsList.tabPayGrade = new _lib.PayGradeAdapter('PayGrade', 'PayGrade', '', ''); modJsList.tabPayGrade.setObjectTypeName('Pay Grades'); modJsList.tabPayGrade.setDataPipe(new _IceDataPipe["default"](modJsList.tabPayGrade)); modJsList.tabPayGrade.setAccess(data.permissions.PayGrade); modJsList.tabEmploymentStatus = new _lib.EmploymentStatusAdapter('EmploymentStatus', 'EmploymentStatus', '', ''); modJsList.tabEmploymentStatus.setObjectTypeName('Employment Status'); modJsList.tabEmploymentStatus.setDataPipe(new _IceDataPipe["default"](modJsList.tabEmploymentStatus)); modJsList.tabEmploymentStatus.setAccess(data.permissions.EmploymentStatus); window.modJs = modJsList.tabJobTitle; window.modJsList = modJsList; } window.initAdminJobs = init; },{"../../../api/IceDataPipe":58,"./lib":24}],24:[function(require,module,exports){ "use strict"; var _ReactModalAdapterBase = _interopRequireDefault(require("../../../api/ReactModalAdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * JobTitleAdapter */ var JobTitleAdapter = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(JobTitleAdapter, _ReactModalAdapterBas); var _super = _createSuper(JobTitleAdapter); function JobTitleAdapter() { _classCallCheck(this, JobTitleAdapter); return _super.apply(this, arguments); } _createClass(JobTitleAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'code', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Code' }, { sTitle: 'Name' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['code', { label: 'Job Title Code', type: 'text' }], ['name', { label: 'Job Title', type: 'text' }], ['description', { label: 'Description', type: 'textarea' }], ['specification', { label: 'Specification', type: 'textarea' }]]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Job Title Code', dataIndex: 'code', sorter: true }, { title: 'Job Title', dataIndex: 'name', sorter: true }]; } }]); return JobTitleAdapter; }(_ReactModalAdapterBase["default"]); /** * PayGradeAdapter */ var PayGradeAdapter = /*#__PURE__*/function (_ReactModalAdapterBas2) { _inherits(PayGradeAdapter, _ReactModalAdapterBas2); var _super2 = _createSuper(PayGradeAdapter); function PayGradeAdapter() { _classCallCheck(this, PayGradeAdapter); return _super2.apply(this, arguments); } _createClass(PayGradeAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'currency', 'min_salary', 'max_salary']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Currency' }, { sTitle: 'Min Salary' }, { sTitle: 'Max Salary' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Pay Grade Name', type: 'text' }], ['currency', { label: 'Currency', type: 'select2', 'remote-source': ['CurrencyType', 'code', 'name'] }], ['min_salary', { label: 'Min Salary', type: 'text', validation: 'float' }], ['max_salary', { label: 'Max Salary', type: 'text', validation: 'float' }]]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Currency', dataIndex: 'currency' }, { title: 'Min Salary', dataIndex: 'min_salary' }, { title: 'Max Salary', dataIndex: 'max_salary' }]; } }, { key: "doCustomValidation", value: function doCustomValidation(params) { try { if (parseFloat(params.min_salary) > parseFloat(params.max_salary)) { return 'Min Salary should be smaller than Max Salary'; } } catch (e) {// D/N } return null; } }]); return PayGradeAdapter; }(_ReactModalAdapterBase["default"]); /** * EmploymentStatusAdapter */ var EmploymentStatusAdapter = /*#__PURE__*/function (_ReactModalAdapterBas3) { _inherits(EmploymentStatusAdapter, _ReactModalAdapterBas3); var _super3 = _createSuper(EmploymentStatusAdapter); function EmploymentStatusAdapter() { _classCallCheck(this, EmploymentStatusAdapter); return _super3.apply(this, arguments); } _createClass(EmploymentStatusAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'description']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID' }, { sTitle: 'Name' }, { sTitle: 'Description' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Employment Status', type: 'text' }], ['description', { label: 'Description', type: 'textarea', validation: '' }]]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employment Status', dataIndex: 'name', sorter: true }, { title: 'Description', dataIndex: 'description' }]; } }]); return EmploymentStatusAdapter; }(_ReactModalAdapterBase["default"]); module.exports = { JobTitleAdapter: JobTitleAdapter, PayGradeAdapter: PayGradeAdapter, EmploymentStatusAdapter: EmploymentStatusAdapter }; },{"../../../api/ReactModalAdapterBase":65}],25:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); var _IceDataPipe = _interopRequireDefault(require("../../../api/IceDataPipe")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function init(data) { var modJsList = {}; modJsList.tabCompanyLoan = new _lib.CompanyLoanAdapter('CompanyLoan', 'CompanyLoan'); modJsList.tabCompanyLoan.setObjectTypeName('Company Loan'); modJsList.tabCompanyLoan.setDataPipe(new _IceDataPipe["default"](modJsList.tabCompanyLoan)); modJsList.tabCompanyLoan.setAccess(data.permissions.CompanyLoan); modJsList.tabEmployeeCompanyLoan = new _lib.EmployeeCompanyLoanAdapter('EmployeeCompanyLoan', 'EmployeeCompanyLoan'); modJsList.tabEmployeeCompanyLoan.setObjectTypeName('Employee Company Loan'); modJsList.tabEmployeeCompanyLoan.setDataPipe(new _IceDataPipe["default"](modJsList.tabEmployeeCompanyLoan)); modJsList.tabEmployeeCompanyLoan.setAccess(data.permissions.EmployeeCompanyLoan); window.modJs = modJsList.tabCompanyLoan; window.modJsList = modJsList; } window.initAdminLoan = init; },{"../../../api/IceDataPipe":58,"./lib":26}],26:[function(require,module,exports){ "use strict"; var _ReactModalAdapterBase = _interopRequireDefault(require("../../../api/ReactModalAdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * CompanyLoanAdapter */ var CompanyLoanAdapter = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(CompanyLoanAdapter, _ReactModalAdapterBas); var _super = _createSuper(CompanyLoanAdapter); function CompanyLoanAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, CompanyLoanAdapter); _this = _super.call(this, endPoint, tab, filter, orderBy); _this.fieldNameMap = {}; _this.hiddenFields = {}; _this.tableFields = {}; _this.formOnlyFields = {}; return _this; } _createClass(CompanyLoanAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'details']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Details' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Details', dataIndex: 'details', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { if (this.showSave) { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }]]; } return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }]]; } }]); return CompanyLoanAdapter; }(_ReactModalAdapterBase["default"]); /* * EmployeeCompanyLoanAdapter */ var EmployeeCompanyLoanAdapter = /*#__PURE__*/function (_ReactModalAdapterBas2) { _inherits(EmployeeCompanyLoanAdapter, _ReactModalAdapterBas2); var _super2 = _createSuper(EmployeeCompanyLoanAdapter); function EmployeeCompanyLoanAdapter(endPoint, tab, filter, orderBy) { var _this2; _classCallCheck(this, EmployeeCompanyLoanAdapter); _this2 = _super2.call(this, endPoint, tab, filter, orderBy); _this2.fieldNameMap = {}; _this2.hiddenFields = {}; _this2.tableFields = {}; _this2.formOnlyFields = {}; return _this2; } _createClass(EmployeeCompanyLoanAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'loan', 'start_date', 'period_months', 'currency', 'amount', 'status']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Loan Type' }, { sTitle: 'Loan Start Date' }, { sTitle: 'Loan Period (Months)' }, { sTitle: 'Currency' }, { sTitle: 'Amount' }, { sTitle: 'Status' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee', dataIndex: 'employee', sorter: true }, { title: 'Loan Type', dataIndex: 'loan', sorter: true }, { title: 'Loan Start Date', dataIndex: 'start_date', sorter: true }, { title: 'Loan Period (Months)', dataIndex: 'period_months', sorter: true }, { title: 'Currency', dataIndex: 'currency', sorter: true }, { title: 'Amount', dataIndex: 'amount', sorter: true }, { title: 'Status', dataIndex: 'status', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['loan', { label: 'Loan Type', type: 'select', 'remote-source': ['CompanyLoan', 'id', 'name'] }], ['start_date', { label: 'Loan Start Date', type: 'date', validation: '' }], ['last_installment_date', { label: 'Last Installment Date', type: 'date', validation: 'none' }], ['period_months', { label: 'Loan Period (Months)', type: 'text', validation: 'number' }], ['currency', { label: 'Currency', type: 'select2', 'remote-source': ['CurrencyType', 'id', 'name'] }], ['amount', { label: 'Loan Amount', type: 'text', validation: 'float' }], ['monthly_installment', { label: 'Monthly Installment', type: 'text', validation: 'float' }], ['status', { label: 'Status', type: 'select', source: [['Approved', 'Approved'], ['Paid', 'Paid'], ['Suspended', 'Suspended']] }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'allow-null': true, 'null-label': 'All Employees', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['loan', { label: 'Loan Type', type: 'select', 'allow-null': true, 'null-label': 'All Loan Types', 'remote-source': ['CompanyLoan', 'id', 'name'] }]]; } }]); return EmployeeCompanyLoanAdapter; }(_ReactModalAdapterBase["default"]); module.exports = { CompanyLoanAdapter: CompanyLoanAdapter, EmployeeCompanyLoanAdapter: EmployeeCompanyLoanAdapter }; },{"../../../api/ReactModalAdapterBase":65}],27:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.CountryAdapter = _lib.CountryAdapter; window.ProvinceAdapter = _lib.ProvinceAdapter; window.CurrencyTypeAdapter = _lib.CurrencyTypeAdapter; window.NationalityAdapter = _lib.NationalityAdapter; window.ImmigrationStatusAdapter = _lib.ImmigrationStatusAdapter; window.EthnicityAdapter = _lib.EthnicityAdapter; },{"./lib":28}],28:[function(require,module,exports){ "use strict"; var _AdapterBase4 = _interopRequireDefault(require("../../../api/AdapterBase")); var _IdNameAdapter4 = _interopRequireDefault(require("../../../api/IdNameAdapter")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * CountryAdapter */ var CountryAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(CountryAdapter, _AdapterBase); var _super = _createSuper(CountryAdapter); function CountryAdapter() { _classCallCheck(this, CountryAdapter); return _super.apply(this, arguments); } _createClass(CountryAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'code', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Code' }, { sTitle: 'Name' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['code', { label: 'Code', type: 'text', validation: '' }], ['name', { label: 'Name', type: 'text', validation: '' }]]; } }]); return CountryAdapter; }(_AdapterBase4["default"]); /** * ProvinceAdapter */ var ProvinceAdapter = /*#__PURE__*/function (_AdapterBase2) { _inherits(ProvinceAdapter, _AdapterBase2); var _super2 = _createSuper(ProvinceAdapter); function ProvinceAdapter() { _classCallCheck(this, ProvinceAdapter); return _super2.apply(this, arguments); } _createClass(ProvinceAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'code', 'name', 'country']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Code' }, { sTitle: 'Name' }, { sTitle: 'Country' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['code', { label: 'Code', type: 'text', validation: '' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['country', { label: 'Country', type: 'select2', 'remote-source': ['Country', 'code', 'name'] }]]; } }, { key: "getFilters", value: function getFilters() { return [['country', { label: 'Country', type: 'select2', 'remote-source': ['Country', 'code', 'name'] }]]; } }]); return ProvinceAdapter; }(_AdapterBase4["default"]); /** * CurrencyTypeAdapter */ var CurrencyTypeAdapter = /*#__PURE__*/function (_AdapterBase3) { _inherits(CurrencyTypeAdapter, _AdapterBase3); var _super3 = _createSuper(CurrencyTypeAdapter); function CurrencyTypeAdapter() { _classCallCheck(this, CurrencyTypeAdapter); return _super3.apply(this, arguments); } _createClass(CurrencyTypeAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'code', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Code' }, { sTitle: 'Name' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['code', { label: 'Code', type: 'text', validation: '' }], ['name', { label: 'Name', type: 'text', validation: '' }]]; } }]); return CurrencyTypeAdapter; }(_AdapterBase4["default"]); /** * NationalityAdapter */ var NationalityAdapter = /*#__PURE__*/function (_IdNameAdapter) { _inherits(NationalityAdapter, _IdNameAdapter); var _super4 = _createSuper(NationalityAdapter); function NationalityAdapter() { _classCallCheck(this, NationalityAdapter); return _super4.apply(this, arguments); } return NationalityAdapter; }(_IdNameAdapter4["default"]); /** * ImmigrationStatusAdapter */ var ImmigrationStatusAdapter = /*#__PURE__*/function (_IdNameAdapter2) { _inherits(ImmigrationStatusAdapter, _IdNameAdapter2); var _super5 = _createSuper(ImmigrationStatusAdapter); function ImmigrationStatusAdapter() { _classCallCheck(this, ImmigrationStatusAdapter); return _super5.apply(this, arguments); } return ImmigrationStatusAdapter; }(_IdNameAdapter4["default"]); /** * EthnicityAdapter */ var EthnicityAdapter = /*#__PURE__*/function (_IdNameAdapter3) { _inherits(EthnicityAdapter, _IdNameAdapter3); var _super6 = _createSuper(EthnicityAdapter); function EthnicityAdapter() { _classCallCheck(this, EthnicityAdapter); return _super6.apply(this, arguments); } return EthnicityAdapter; }(_IdNameAdapter4["default"]); module.exports = { CountryAdapter: CountryAdapter, ProvinceAdapter: ProvinceAdapter, CurrencyTypeAdapter: CurrencyTypeAdapter, NationalityAdapter: NationalityAdapter, ImmigrationStatusAdapter: ImmigrationStatusAdapter, EthnicityAdapter: EthnicityAdapter }; },{"../../../api/AdapterBase":52,"../../../api/IdNameAdapter":59}],29:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.ModuleAdapter = _lib.ModuleAdapter; window.UsageAdapter = _lib.UsageAdapter; },{"./lib":30}],30:[function(require,module,exports){ "use strict"; var _AdapterBase3 = _interopRequireDefault(require("../../../api/AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * ModuleAdapter */ var ModuleAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(ModuleAdapter, _AdapterBase); var _super = _createSuper(ModuleAdapter); function ModuleAdapter() { _classCallCheck(this, ModuleAdapter); return _super.apply(this, arguments); } _createClass(ModuleAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'label', 'menu', 'mod_group', 'mod_order', 'status', 'version', 'update_path']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Menu', bVisible: false }, { sTitle: 'Group' }, { sTitle: 'Order' }, { sTitle: 'Status' }, { sTitle: 'Version', bVisible: false }, { sTitle: 'Path', bVisible: false }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['label', { label: 'Label', type: 'text', validation: '' }], ['status', { label: 'Status', type: 'select', source: [['Enabled', 'Enabled'], ['Disabled', 'Disabled']] }], ['user_levels', { label: 'User Levels', type: 'select2multi', source: [['Admin', 'Admin'], ['Manager', 'Manager'], ['Employee', 'Employee']] }], ['user_roles', { label: 'Allowed User Roles', type: 'select2multi', 'remote-source': ['UserRole', 'id', 'name'] }], ['user_roles_blacklist', { label: 'Disallowed User Roles', type: 'select2multi', 'remote-source': ['UserRole', 'id', 'name'] }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { /* const nonEditableFields = {}; nonEditableFields['admin_Company Structure'] = 1; nonEditableFields.admin_Employees = 1; nonEditableFields['admin_Job Details Setup'] = 1; nonEditableFields.admin_Leaves = 1; nonEditableFields['admin_Manage Modules'] = 1; nonEditableFields.admin_Projects = 1; nonEditableFields.admin_Qualifications = 1; nonEditableFields.admin_Settings = 1; nonEditableFields.admin_Users = 1; nonEditableFields.admin_Upgrade = 1; nonEditableFields.admin_Dashboard = 1; nonEditableFields['user_Basic Information'] = 1; nonEditableFields.user_Dashboard = 1; if (nonEditableFields[`${data[3]}_${data[1]}`] === 1) { return ''; } */ var html = '
'; html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }]); return ModuleAdapter; }(_AdapterBase3["default"]); /** * UsageAdapter */ var UsageAdapter = /*#__PURE__*/function (_AdapterBase2) { _inherits(UsageAdapter, _AdapterBase2); var _super2 = _createSuper(UsageAdapter); function UsageAdapter() { _classCallCheck(this, UsageAdapter); return _super2.apply(this, arguments); } _createClass(UsageAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return []; } }, { key: "getHeaders", value: function getHeaders() { return []; } }, { key: "getFormFields", value: function getFormFields() { return []; } }, { key: "get", value: function get(callBackData) {} }, { key: "saveUsage", value: function saveUsage() { var object = {}; var arr = []; $('.module-check').each(function () { if ($(this).is(':checked')) { arr.push($(this).val()); } }); if (arr.length === 0) { alert('Please select one or more module groups'); return; } object.groups = arr.join(','); var reqJson = JSON.stringify(object); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'getInitDataSuccessCallBack'; callBackData.callBackFail = 'getInitDataFailCallBack'; this.customAction('saveUsage', 'admin=modules', reqJson, callBackData); } }, { key: "saveUsageSuccessCallBack", value: function saveUsageSuccessCallBack(data) {} }, { key: "saveUsageFailCallBack", value: function saveUsageFailCallBack(callBackData) {} }]); return UsageAdapter; }(_AdapterBase3["default"]); module.exports = { ModuleAdapter: ModuleAdapter, UsageAdapter: UsageAdapter }; },{"../../../api/AdapterBase":52}],31:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.OvertimeCategoryAdapter = _lib.OvertimeCategoryAdapter; window.EmployeeOvertimeAdminAdapter = _lib.EmployeeOvertimeAdminAdapter; },{"./lib":32}],32:[function(require,module,exports){ "use strict"; var _AdapterBase2 = _interopRequireDefault(require("../../../api/AdapterBase")); var _ApproveAdminAdapter2 = _interopRequireDefault(require("../../../api/ApproveAdminAdapter")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * OvertimeCategoryAdapter */ var OvertimeCategoryAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(OvertimeCategoryAdapter, _AdapterBase); var _super = _createSuper(OvertimeCategoryAdapter); function OvertimeCategoryAdapter() { _classCallCheck(this, OvertimeCategoryAdapter); return _super.apply(this, arguments); } _createClass(OvertimeCategoryAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }]]; } }]); return OvertimeCategoryAdapter; }(_AdapterBase2["default"]); /** * EmployeeOvertimeAdminAdapter */ var EmployeeOvertimeAdminAdapter = /*#__PURE__*/function (_ApproveAdminAdapter) { _inherits(EmployeeOvertimeAdminAdapter, _ApproveAdminAdapter); var _super2 = _createSuper(EmployeeOvertimeAdminAdapter); function EmployeeOvertimeAdminAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, EmployeeOvertimeAdminAdapter); _this = _super2.call(this, endPoint, tab, filter, orderBy); _this.itemName = 'OvertimeRequest'; _this.itemNameLower = 'overtimerequest'; _this.modulePathName = 'overtime'; return _this; } _createClass(EmployeeOvertimeAdminAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'category', 'start_time', 'end_time', 'project', 'status']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Category' }, { sTitle: 'Start Time' }, { sTitle: 'End Time' }, { sTitle: 'Project' }, { sTitle: 'Status' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['category', { label: 'Category', type: 'select2', 'allow-null': false, 'remote-source': ['OvertimeCategory', 'id', 'name'] }], ['start_time', { label: 'Start Time', type: 'datetime', validation: '' }], ['end_time', { label: 'End Time', type: 'datetime', validation: '' }], ['project', { label: 'Project', type: 'select2', 'allow-null': true, 'null=label': 'none', 'remote-source': ['Project', 'id', 'name'] }], ['notes', { label: 'Notes', type: 'textarea', validation: 'none' }]]; } }]); return EmployeeOvertimeAdminAdapter; }(_ApproveAdminAdapter2["default"]); module.exports = { OvertimeCategoryAdapter: OvertimeCategoryAdapter, EmployeeOvertimeAdminAdapter: EmployeeOvertimeAdminAdapter }; },{"../../../api/AdapterBase":52,"../../../api/ApproveAdminAdapter":53}],33:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.PaydayAdapter = _lib.PaydayAdapter; window.PayrollAdapter = _lib.PayrollAdapter; window.PayrollDataAdapter = _lib.PayrollDataAdapter; window.PayrollColumnAdapter = _lib.PayrollColumnAdapter; window.PayrollColumnTemplateAdapter = _lib.PayrollColumnTemplateAdapter; window.PayrollEmployeeAdapter = _lib.PayrollEmployeeAdapter; window.DeductionAdapter = _lib.DeductionAdapter; window.DeductionGroupAdapter = _lib.DeductionGroupAdapter; window.PayslipTemplateAdapter = _lib.PayslipTemplateAdapter; },{"./lib":34}],34:[function(require,module,exports){ "use strict"; var _AdapterBase9 = _interopRequireDefault(require("../../../api/AdapterBase")); var _TableEditAdapter2 = _interopRequireDefault(require("../../../api/TableEditAdapter")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } require('codemirror/mode/javascript/javascript'); require('codemirror/addon/edit/closebrackets'); require('codemirror/addon/display/autorefresh'); var CodeMirror = require('codemirror'); /** * PaydayAdapter */ var PaydayAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(PaydayAdapter, _AdapterBase); var _super = _createSuper(PaydayAdapter); function PaydayAdapter() { _classCallCheck(this, PaydayAdapter); return _super.apply(this, arguments); } _createClass(PaydayAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Select Pay Frequency' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['name', { label: 'Name', type: 'text', validation: '' }]]; } }, { key: "getAddNewLabel", value: function getAddNewLabel() { return 'Run Payroll'; } }, { key: "createTable", value: function createTable(elementId) { $('#payday_all').off(); _get(_getPrototypeOf(PaydayAdapter.prototype), "createTable", this).call(this, elementId); $('#payday_all').off().on('click', function () { if ($(this).is(':checked')) { $('.paydayCheck').prop('checked', true); } else { $('.paydayCheck').prop('checked', false); } }); } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var editButton = ''; var html = '
_edit_
'; html = html.replace('_edit_', editButton); html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "getActionButtonHeader", value: function getActionButtonHeader() { return { sTitle: '', sClass: 'center' }; } }]); return PaydayAdapter; }(_AdapterBase9["default"]); /** * PayrollAdapter */ var PayrollAdapter = /*#__PURE__*/function (_AdapterBase2) { _inherits(PayrollAdapter, _AdapterBase2); var _super2 = _createSuper(PayrollAdapter); function PayrollAdapter() { _classCallCheck(this, PayrollAdapter); return _super2.apply(this, arguments); } _createClass(PayrollAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'pay_period', 'department', 'date_start', 'date_end', 'status']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Pay Frequency' }, { sTitle: 'Department' }, { sTitle: 'Date Start' }, { sTitle: 'Date End' }, { sTitle: 'Status' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text' }], ['pay_period', { label: 'Pay Frequency', type: 'select', 'remote-source': ['PayFrequency', 'id', 'name'], sort: 'none' }], ['deduction_group', { label: 'Payroll Group', type: 'select', 'remote-source': ['DeductionGroup', 'id', 'name'], sort: 'none' }], ['payslipTemplate', { label: 'Payslip Template', type: 'select', 'remote-source': ['PayslipTemplate', 'id', 'name'] }], ['department', { label: 'Department', type: 'select2', 'remote-source': ['CompanyStructure', 'id', 'title'], sort: 'none' }], ['date_start', { label: 'Start Date', type: 'date', validation: '' }], ['date_end', { label: 'End Date', type: 'date', validation: '' }], // [ "column_template", {"label":"Report Column Template","type":"select","remote-source":["PayrollColumnTemplate","id","name"]}], ['columns', { label: 'Payroll Columns', type: 'select2multi', 'remote-source': ['PayrollColumn', 'id', 'name'] }], ['status', { label: 'Status', type: 'select', source: [['Draft', 'Draft'], ['Completed', 'Completed']], sort: 'none' }]]; } }, { key: "postRenderForm", value: function postRenderForm(object, $tempDomObj) { if (object != null && object !== undefined && object.id !== undefined && object.id != null) { $tempDomObj.find('#pay_period').attr('disabled', 'disabled'); $tempDomObj.find('#department').attr('disabled', 'disabled'); // $tempDomObj.find("#date_start").attr('disabled','disabled'); // $tempDomObj.find("#date_end").attr('disabled','disabled'); // $tempDomObj.find("#column_template").attr('disabled','disabled'); } } }, { key: "process", value: function process(id, status) { // eslint-disable-next-line no-global-assign modJs = modJsList.tabPayrollData; modJs.setCurrentPayroll(id); $('#Payroll').hide(); $('#PayrollData').show(); $('#PayrollDataButtons').show(); if (status === 'Completed') { $('.completeBtnTable').hide(); $('.saveBtnTable').hide(); } else { $('.completeBtnTable').show(); $('.saveBtnTable').show(); } modJs.get([]); } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var editButton = ''; var processButton = ''; var deleteButton = ''; var cloneButton = ''; var html = '
_edit__process__clone__delete_
'; if (this.showAddNew) { html = html.replace('_clone_', cloneButton); } else { html = html.replace('_clone_', ''); } if (this.showDelete) { html = html.replace('_delete_', deleteButton); } else { html = html.replace('_delete_', ''); } if (this.showEdit) { html = html.replace('_edit_', editButton); } else { html = html.replace('_edit_', ''); } html = html.replace('_process_', processButton); html = html.replace(/_id_/g, id); html = html.replace(/_status_/g, data[6]); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "get", value: function get(callBackData) { $('#PayrollData').hide(); $('#PayrollForm').hide(); $('#PayrollDataButtons').hide(); $('#Payroll').show(); modJsList.tabPayrollData.setCurrentPayroll(null); _get(_getPrototypeOf(PayrollAdapter.prototype), "get", this).call(this, callBackData); } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/payroll-and-expenses/payroll-management'; } }]); return PayrollAdapter; }(_AdapterBase9["default"]); /** * PayrollDataAdapter */ var PayrollDataAdapter = /*#__PURE__*/function (_TableEditAdapter) { _inherits(PayrollDataAdapter, _TableEditAdapter); var _super3 = _createSuper(PayrollDataAdapter); function PayrollDataAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, PayrollDataAdapter); _this = _super3.call(this, endPoint, tab, filter, orderBy); _this.cellDataUpdates = {}; _this.payrollId = null; return _this; } _createClass(PayrollDataAdapter, [{ key: "validateCellValue", value: function validateCellValue(element, evt, newValue) { modJs.addCellDataUpdate(element.data('colId'), element.data('rowId'), newValue); return true; } }, { key: "setCurrentPayroll", value: function setCurrentPayroll(val) { this.payrollId = val; } }, { key: "addAdditionalRequestData", value: function addAdditionalRequestData(type, req) { if (type === 'updateData') { req.payrollId = this.payrollId; } else if (type === 'updateAllData') { req.payrollId = this.payrollId; } else if (type === 'getAllData') { req.payrollId = this.payrollId; } return req; } }, { key: "modifyCSVHeader", value: function modifyCSVHeader(header) { header.unshift(''); return header; } }, { key: "getCSVData", value: function getCSVData() { var csv = ''; for (var i = 0; i < this.csvData.length; i++) { csv += this.csvData[i].join(','); if (i < this.csvData.length - 1) { csv += '\r\n'; } } return csv; } }, { key: "downloadPayroll", value: function downloadPayroll() { var element = document.createElement('a'); element.setAttribute('href', "data:text/plain;charset=utf-8,".concat(encodeURIComponent(this.getCSVData()))); element.setAttribute('download', "payroll_".concat(this.payrollId, ".csv")); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/payroll-and-expenses/payroll-management'; } }]); return PayrollDataAdapter; }(_TableEditAdapter2["default"]); /** * PayrollColumnAdapter */ var PayrollColumnAdapter = /*#__PURE__*/function (_AdapterBase3) { _inherits(PayrollColumnAdapter, _AdapterBase3); var _super4 = _createSuper(PayrollColumnAdapter); function PayrollColumnAdapter(endPoint, tab, filter, orderBy) { var _this2; _classCallCheck(this, PayrollColumnAdapter); _this2 = _super4.call(this, endPoint, tab, filter, orderBy); _this2.codeMirror = CodeMirror; return _this2; } _createClass(PayrollColumnAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'colorder', 'calculation_hook', 'deduction_group', 'editable', 'enabled']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Column Order' }, { sTitle: 'Calculation Method' }, { sTitle: 'Payroll Group' }, { sTitle: 'Editable' }, { sTitle: 'Enabled' }]; } }, { key: "getFormFields", value: function getFormFields() { var fucntionColumnList = ['calculation_columns', { label: 'Calculation Columns', type: 'datagroup', form: [['name', { label: 'Name', type: 'text', validation: '' }], ['column', { label: 'Column', type: 'select2', 'remote-source': ['PayrollColumn', 'id', 'name'] }]], html: '
#_delete_##_edit_#
#_renderFunction_#
', validation: 'none', render: function render(item) { var output = "Variable:".concat(item.name); return output; } }]; return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['calculation_hook', { label: 'Predefined Calculations', type: 'select2', 'allow-null': true, 'null-label': 'None', 'remote-source': ['CalculationHook', 'code', 'name'] }], ['deduction_group', { label: 'Payroll Group', type: 'select2', 'allow-null': true, 'null-label': 'Common', 'remote-source': ['DeductionGroup', 'id', 'name'] }], ['salary_components', { label: 'Salary Components', type: 'select2multi', 'remote-source': ['SalaryComponent', 'id', 'name'] }], ['deductions', { label: 'Calculation Method', type: 'select2multi', 'remote-source': ['Deduction', 'id', 'name'] }], ['add_columns', { label: 'Columns to Add', type: 'select2multi', 'remote-source': ['PayrollColumn', 'id', 'name'] }], ['sub_columns', { label: 'Columns to Subtract', type: 'select2multi', 'remote-source': ['PayrollColumn', 'id', 'name'] }], ['colorder', { label: 'Column Order', type: 'text', validation: 'number' }], ['editable', { label: 'Editable', type: 'select', source: [['Yes', 'Yes'], ['No', 'No']] }], ['enabled', { label: 'Enabled', type: 'select', source: [['Yes', 'Yes'], ['No', 'No']] }], ['default_value', { label: 'Default Value', type: 'text', validation: '' }], fucntionColumnList, ['function_type', { label: 'Function Type', type: 'select', source: [['Simple', 'Simple']] }], ['calculation_function', { label: 'Function', type: 'code', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['deduction_group', { label: 'Payroll Group', type: 'select2', 'allow-null': false, 'remote-source': ['DeductionGroup', 'id', 'name'] }]]; } }, { key: "getHelpLink", value: function getHelpLink() { return 'https://icehrm.gitbook.io/icehrm/payroll-and-expenses/payroll-management'; } }]); return PayrollColumnAdapter; }(_AdapterBase9["default"]); /** * PayrollColumnTemplateAdapter */ var PayrollColumnTemplateAdapter = /*#__PURE__*/function (_AdapterBase4) { _inherits(PayrollColumnTemplateAdapter, _AdapterBase4); var _super5 = _createSuper(PayrollColumnTemplateAdapter); function PayrollColumnTemplateAdapter() { _classCallCheck(this, PayrollColumnTemplateAdapter); return _super5.apply(this, arguments); } _createClass(PayrollColumnTemplateAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: true }, { sTitle: 'Name' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['columns', { label: 'Payroll Columns', type: 'select2multi', 'remote-source': ['PayrollColumn', 'id', 'name'] }]]; } }]); return PayrollColumnTemplateAdapter; }(_AdapterBase9["default"]); /* * PayrollEmployeeAdapter */ var PayrollEmployeeAdapter = /*#__PURE__*/function (_AdapterBase5) { _inherits(PayrollEmployeeAdapter, _AdapterBase5); var _super6 = _createSuper(PayrollEmployeeAdapter); function PayrollEmployeeAdapter() { _classCallCheck(this, PayrollEmployeeAdapter); return _super6.apply(this, arguments); } _createClass(PayrollEmployeeAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'pay_frequency', 'deduction_group', 'currency']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Pay Frequency' }, { sTitle: 'Payroll Group' }, { sTitle: 'Currency' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['pay_frequency', { label: 'Pay Frequency', type: 'select2', 'remote-source': ['PayFrequency', 'id', 'name'] }], ['currency', { label: 'Currency', type: 'select2', 'remote-source': ['CurrencyType', 'id', 'code'] }], ['deduction_group', { label: 'Payroll Group', type: 'select2', 'allow-null': true, 'null-label': 'None', 'remote-source': ['DeductionGroup', 'id', 'name'] }], ['deduction_exemptions', { label: 'Calculation Exemptions', type: 'select2multi', 'remote-source': ['Deduction', 'id', 'name'], validation: 'none' }], ['deduction_allowed', { label: 'Calculations Assigned', type: 'select2multi', 'remote-source': ['Deduction', 'id', 'name'], validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }]); return PayrollEmployeeAdapter; }(_AdapterBase9["default"]); /** * DeductionAdapter */ var DeductionAdapter = /*#__PURE__*/function (_AdapterBase6) { _inherits(DeductionAdapter, _AdapterBase6); var _super7 = _createSuper(DeductionAdapter); function DeductionAdapter() { _classCallCheck(this, DeductionAdapter); return _super7.apply(this, arguments); } _createClass(DeductionAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'deduction_group']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Payroll Group' }]; } }, { key: "getFormFields", value: function getFormFields() { var rangeAmounts = ['rangeAmounts', { label: 'Calculation Process', type: 'datagroup', form: [['lowerCondition', { label: 'Lower Limit Condition', type: 'select', source: [['No Lower Limit', 'No Lower Limit'], ['gt', 'Greater than'], ['gte', 'Greater than or Equal']] }], ['lowerLimit', { label: 'Lower Limit', type: 'text', validation: 'float' }], ['upperCondition', { label: 'Upper Limit Condition', type: 'select', source: [['No Upper Limit', 'No Upper Limit'], ['lt', 'Less than'], ['lte', 'Less than or Equal']] }], ['upperLimit', { label: 'Upper Limit', type: 'text', validation: 'float' }], ['amount', { label: 'Value', type: 'text', validation: '' }]], html: '
#_delete_##_edit_#
#_renderFunction_#
', validation: 'none', 'custom-validate-function': function customValidateFunction(data) { var res = {}; res.valid = true; if (data.lowerCondition === 'No Lower Limit') { data.lowerLimit = 0; } if (data.upperCondition === 'No Upper Limit') { data.upperLimit = 0; } res.params = data; return res; }, render: function render(item) { var output = ''; var getSymbol = function getSymbol(text) { var map = {}; map.gt = '>'; map.gte = '>='; map.lt = '<'; map.lte = '<='; return map[text]; }; if (item.lowerCondition !== 'No Lower Limit') { output += "".concat(item.lowerLimit, " ").concat(getSymbol(item.lowerCondition), " "); } if (item.upperCondition !== 'No Upper Limit') { output += ' and '; output += "".concat(getSymbol(item.upperCondition), " ").concat(item.upperLimit, " "); } if (output === '') { return "Deduction is ".concat(item.amount, " for all ranges"); } return "If salary component ".concat(output, " deduction is ").concat(item.amount); } }]; return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['componentType', { label: 'Salary Component Type', type: 'select2multi', 'allow-null': true, 'remote-source': ['SalaryComponentType', 'id', 'name'] }], ['component', { label: 'Salary Component', type: 'select2multi', 'allow-null': true, 'remote-source': ['SalaryComponent', 'id', 'name'] }], ['payrollColumn', { label: 'Payroll Report Column', type: 'select2', 'allow-null': true, 'remote-source': ['PayrollColumn', 'id', 'name'] }], rangeAmounts, ['deduction_group', { label: 'Payroll Group', type: 'select2', 'allow-null': false, 'remote-source': ['DeductionGroup', 'id', 'name'] }]]; } }]); return DeductionAdapter; }(_AdapterBase9["default"]); /* * DeductionGroupAdapter */ var DeductionGroupAdapter = /*#__PURE__*/function (_AdapterBase7) { _inherits(DeductionGroupAdapter, _AdapterBase7); var _super8 = _createSuper(DeductionGroupAdapter); function DeductionGroupAdapter() { _classCallCheck(this, DeductionGroupAdapter); return _super8.apply(this, arguments); } _createClass(DeductionGroupAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'description']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Details' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['description', { label: 'Details', type: 'textarea', validation: 'none' }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id) { var html = '
' + '' + '' + '' + '
'; html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "deletePayrollGroup", value: function deletePayrollGroup(id) { if (confirm('Are you sure you want to delete this payroll group? Deleting the payroll group will delete all the Payroll columns and Saved calculations attached to this Payroll Group')) {// Terminate } else { return; } var params = {}; params.id = id; var reqJson = JSON.stringify(params); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'deletePayrollGroupSuccessCallback'; callBackData.callBackFail = 'deletePayrollGroupFailCallback'; this.customAction('deletePayrollGroup', 'admin=payroll', reqJson, callBackData); } }, { key: "deletePayrollGroupSuccessCallback", value: function deletePayrollGroupSuccessCallback(callBackData) { this.showMessage('Success', 'Payroll Group Deleted '); this.get([]); } }, { key: "deletePayrollGroupFailCallback", value: function deletePayrollGroupFailCallback(callBackData) { this.showMessage('Error occured while deleting Payroll Group', callBackData); } }]); return DeductionGroupAdapter; }(_AdapterBase9["default"]); /* * PayslipTemplateAdapter */ var PayslipTemplateAdapter = /*#__PURE__*/function (_AdapterBase8) { _inherits(PayslipTemplateAdapter, _AdapterBase8); var _super9 = _createSuper(PayslipTemplateAdapter); function PayslipTemplateAdapter() { _classCallCheck(this, PayslipTemplateAdapter); return _super9.apply(this, arguments); } _createClass(PayslipTemplateAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }]; } }, { key: "getFormFields", value: function getFormFields() { var payslipFields = ['data', { label: 'Payslip Fields', type: 'datagroup', form: [['type', { label: 'Type', type: 'select', sort: 'none', source: [['Payroll Column', 'Payroll Column'], ['Text', 'Text'], ['Company Name', 'Company Name'], ['Company Logo', 'Company Logo'], ['Separators', 'Separators']] }], ['payrollColumn', { label: 'Payroll Column', type: 'select2', sort: 'none', 'allow-null': true, 'null-label': 'None', 'remote-source': ['PayrollColumn', 'id', 'name'] }], ['label', { label: 'Label', type: 'text', validation: 'none' }], ['text', { label: 'Text', type: 'textarea', validation: 'none' }], ['status', { label: 'Status', type: 'select', sort: 'none', source: [['Show', 'Show'], ['Hide', 'Hide']] }]], // "html":'
#_delete_##_edit_#
Type#_type_#
Label#_label_#
Text#_text_#
Font Size#_fontSize_#
Font Style#_fontStyle_#
Font Color#_fontColor_#
Status#_status_#
', html: '
#_delete_##_edit_#
#_type_# #_label_#
#_text_#
', validation: 'none', 'custom-validate-function': function customValidateFunction(data) { var res = {}; res.valid = true; if (data.type === 'Payroll Column') { if (data.payrollColumn === 'NULL') { res.valid = false; res.message = 'Please select payroll column'; } } else { data.payrollColumn = 'NULL'; } if (data.type === 'Text') { if (data.text === '') { res.valid = false; res.message = 'Text can not be empty'; } } res.params = data; return res; } }]; return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], payslipFields]; } }]); return PayslipTemplateAdapter; }(_AdapterBase9["default"]); module.exports = { PaydayAdapter: PaydayAdapter, PayrollAdapter: PayrollAdapter, PayrollDataAdapter: PayrollDataAdapter, PayrollColumnAdapter: PayrollColumnAdapter, PayrollColumnTemplateAdapter: PayrollColumnTemplateAdapter, PayrollEmployeeAdapter: PayrollEmployeeAdapter, DeductionAdapter: DeductionAdapter, DeductionGroupAdapter: DeductionGroupAdapter, PayslipTemplateAdapter: PayslipTemplateAdapter }; },{"../../../api/AdapterBase":52,"../../../api/TableEditAdapter":67,"codemirror":"codemirror","codemirror/addon/display/autorefresh":109,"codemirror/addon/edit/closebrackets":110,"codemirror/mode/javascript/javascript":112}],35:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.PermissionAdapter = _lib.PermissionAdapter; },{"./lib":36}],36:[function(require,module,exports){ "use strict"; var _AdapterBase2 = _interopRequireDefault(require("../../../api/AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * PermissionAdapter */ var PermissionAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(PermissionAdapter, _AdapterBase); var _super = _createSuper(PermissionAdapter); function PermissionAdapter() { _classCallCheck(this, PermissionAdapter); return _super.apply(this, arguments); } _createClass(PermissionAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'user_level', 'module_id', 'permission', 'value']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'User Level' }, { sTitle: 'Module' }, { sTitle: 'Permission' }, { sTitle: 'Value' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['user_level', { label: 'User Level', type: 'placeholder', validation: 'none' }], ['module_id', { label: 'Module', type: 'placeholder', 'remote-source': ['Module', 'id', 'menu+name'] }], ['permission', { label: 'Permission', type: 'placeholder', validation: 'none' }], ['value', { label: 'Value', type: 'text', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['module_id', { label: 'Module', type: 'select2', 'allow-null': true, 'null-label': 'All Modules', 'remote-source': ['Module', 'id', 'menu+name'] }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var html = '
'; html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "getMetaFieldForRendering", value: function getMetaFieldForRendering(fieldName) { if (fieldName === 'value') { return 'meta'; } return ''; } }, { key: "fillForm", value: function fillForm(object) { _get(_getPrototypeOf(PermissionAdapter.prototype), "fillForm", this).call(this, object); $('#helptext').html(object.description); } }]); return PermissionAdapter; }(_AdapterBase2["default"]); module.exports = { PermissionAdapter: PermissionAdapter }; },{"../../../api/AdapterBase":52}],37:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.ProjectAdapter = _lib.ProjectAdapter; window.EmployeeProjectAdapter = _lib.EmployeeProjectAdapter; },{"./lib":38}],38:[function(require,module,exports){ "use strict"; var _ReactModalAdapterBase = _interopRequireDefault(require("../../../api/ReactModalAdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * ProjectAdapter */ var ProjectAdapter = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(ProjectAdapter, _ReactModalAdapterBas); var _super = _createSuper(ProjectAdapter); function ProjectAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, ProjectAdapter); _this = _super.call(this, endPoint, tab, filter, orderBy); _this.fieldNameMap = {}; _this.hiddenFields = {}; _this.tableFields = {}; _this.formOnlyFields = {}; return _this; } _createClass(ProjectAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'client']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Client' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Client', dataIndex: 'client', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { if (this.showSave) { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text' }], ['client', { label: 'Client', type: 'select2', 'allow-null': true, 'remote-source': ['Client', 'id', 'name'] }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }], ['status', { label: 'Status', type: 'select', source: [['Active', 'Active'], ['On Hold', 'On Hold'], ['Completed', 'Completed'], ['Dropped', 'Dropped']] }]]; } return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'placeholder' }], ['client', { label: 'Client', type: 'placeholder', 'allow-null': true, 'remote-source': ['Client', 'id', 'name'] }], ['details', { label: 'Details', type: 'placeholder', validation: 'none' }], ['status', { label: 'Status', type: 'select', source: [['Active', 'Active'], ['On Hold', 'On Hold'], ['Completed', 'Completed'], ['Dropped', 'Dropped']] }]]; } }, { key: "getHelpLink", value: function getHelpLink() { return 'http://blog.icehrm.com/docs/projects/'; } }]); return ProjectAdapter; }(_ReactModalAdapterBase["default"]); /* * EmployeeProjectAdapter */ var EmployeeProjectAdapter = /*#__PURE__*/function (_ReactModalAdapterBas2) { _inherits(EmployeeProjectAdapter, _ReactModalAdapterBas2); var _super2 = _createSuper(EmployeeProjectAdapter); function EmployeeProjectAdapter(endPoint, tab, filter, orderBy) { var _this2; _classCallCheck(this, EmployeeProjectAdapter); _this2 = _super2.call(this, endPoint, tab, filter, orderBy); _this2.fieldNameMap = {}; _this2.hiddenFields = {}; _this2.tableFields = {}; _this2.formOnlyFields = {}; return _this2; } _createClass(EmployeeProjectAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'project']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Project' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee', dataIndex: 'employee', sorter: true }, { title: 'Project', dataIndex: 'project', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['project', { label: 'Project', type: 'select2', 'remote-source': ['Project', 'id', 'name'] }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }, { key: "getHelpLink", value: function getHelpLink() { return 'http://blog.icehrm.com/docs/projects/'; } }]); return EmployeeProjectAdapter; }(_ReactModalAdapterBase["default"]); module.exports = { ProjectAdapter: ProjectAdapter, EmployeeProjectAdapter: EmployeeProjectAdapter }; },{"../../../api/ReactModalAdapterBase":65}],39:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); var _IceDataPipe = _interopRequireDefault(require("../../../api/IceDataPipe")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function init(data) { var modJsList = []; modJsList.tabSkill = new _lib.SkillAdapter('Skill'); modJsList.tabSkill.setObjectTypeName('Skills'); modJsList.tabSkill.setDataPipe(new _IceDataPipe["default"](modJsList.tabSkill)); modJsList.tabSkill.setAccess(data.permissions.Skill); modJsList.tabEducation = new _lib.EducationAdapter('Education'); modJsList.tabEducation.setObjectTypeName('Education'); modJsList.tabEducation.setDataPipe(new _IceDataPipe["default"](modJsList.tabEducation)); modJsList.tabEducation.setAccess(data.permissions.Education); modJsList.tabCertification = new _lib.CertificationAdapter('Certification'); modJsList.tabCertification.setObjectTypeName('Education'); modJsList.tabCertification.setDataPipe(new _IceDataPipe["default"](modJsList.tabCertification)); modJsList.tabCertification.setAccess(data.permissions.Certification); modJsList.tabLanguage = new _lib.LanguageAdapter('Language'); modJsList.tabLanguage.setObjectTypeName('Language'); modJsList.tabLanguage.setDataPipe(new _IceDataPipe["default"](modJsList.tabLanguage)); modJsList.tabLanguage.setAccess(data.permissions.Language); window.modJs = modJsList.tabSkill; window.modJsList = modJsList; } window.initAdminQualifications = init; },{"../../../api/IceDataPipe":58,"./lib":40}],40:[function(require,module,exports){ "use strict"; var _AdapterBase = _interopRequireDefault(require("../../../api/AdapterBase")); var _ReactModalAdapterBase = _interopRequireDefault(require("../../../api/ReactModalAdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * SkillAdapter */ var SkillAdapter = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(SkillAdapter, _ReactModalAdapterBas); var _super = _createSuper(SkillAdapter); function SkillAdapter() { _classCallCheck(this, SkillAdapter); return _super.apply(this, arguments); } _createClass(SkillAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'description']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Description' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text' }], ['description', { label: 'Description', type: 'textarea', validation: '' }]]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Description', dataIndex: 'description' }]; } }]); return SkillAdapter; }(_ReactModalAdapterBase["default"]); /** * EducationAdapter */ var EducationAdapter = /*#__PURE__*/function (_ReactModalAdapterBas2) { _inherits(EducationAdapter, _ReactModalAdapterBas2); var _super2 = _createSuper(EducationAdapter); function EducationAdapter() { _classCallCheck(this, EducationAdapter); return _super2.apply(this, arguments); } _createClass(EducationAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'description']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Description' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text' }], ['description', { label: 'Description', type: 'textarea', validation: '' }]]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Description', dataIndex: 'description' }]; } }]); return EducationAdapter; }(_ReactModalAdapterBase["default"]); /** * CertificationAdapter */ var CertificationAdapter = /*#__PURE__*/function (_ReactModalAdapterBas3) { _inherits(CertificationAdapter, _ReactModalAdapterBas3); var _super3 = _createSuper(CertificationAdapter); function CertificationAdapter() { _classCallCheck(this, CertificationAdapter); return _super3.apply(this, arguments); } _createClass(CertificationAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'description']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Description' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text' }], ['description', { label: 'Description', type: 'textarea', validation: '' }]]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Description', dataIndex: 'description' }]; } }]); return CertificationAdapter; }(_ReactModalAdapterBase["default"]); /** * LanguageAdapter */ var LanguageAdapter = /*#__PURE__*/function (_ReactModalAdapterBas4) { _inherits(LanguageAdapter, _ReactModalAdapterBas4); var _super4 = _createSuper(LanguageAdapter); function LanguageAdapter() { _classCallCheck(this, LanguageAdapter); return _super4.apply(this, arguments); } _createClass(LanguageAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'description']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Description' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text' }], ['description', { label: 'Description', type: 'textarea', validation: '' }]]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Description', dataIndex: 'description' }]; } }]); return LanguageAdapter; }(_ReactModalAdapterBase["default"]); module.exports = { SkillAdapter: SkillAdapter, EducationAdapter: EducationAdapter, CertificationAdapter: CertificationAdapter, LanguageAdapter: LanguageAdapter }; },{"../../../api/AdapterBase":52,"../../../api/ReactModalAdapterBase":65}],41:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.ReportAdapter = _lib.ReportAdapter; window.ReportGenAdapter = _lib.ReportGenAdapter; },{"./lib":42}],42:[function(require,module,exports){ "use strict"; var _AdapterBase3 = _interopRequireDefault(require("../../../api/AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * ReportAdapter */ var ReportAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(ReportAdapter, _AdapterBase); var _super = _createSuper(ReportAdapter); function ReportAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, ReportAdapter); _this = _super.call(this, endPoint, tab, filter, orderBy); _this._construct(); return _this; } _createClass(ReportAdapter, [{ key: "_construct", value: function _construct() { this._formFileds = [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'label', validation: '' }], ['parameters', { label: 'Parameters', type: 'fieldset', validation: 'none' }]]; this.remoteFieldsExists = false; } }, { key: "_initLocalFormFields", value: function _initLocalFormFields() { this._formFileds = [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'label', validation: '' }], ['parameters', { label: 'Parameters', type: 'fieldset', validation: 'none' }]]; } }, { key: "setRemoteFieldExists", value: function setRemoteFieldExists(val) { this.remoteFieldsExists = val; } }, { key: "getDataMapping", value: function getDataMapping() { return ['id', 'icon', 'name', 'details', 'parameters']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: '', bSortable: false, sWidth: '22px' }, { sTitle: 'Name', sWidth: '30%' }, { sTitle: 'Details' }, { sTitle: 'Parameters', bVisible: false }]; } }, { key: "getFormFields", value: function getFormFields() { return this._formFileds; } }, { key: "processFormFieldsWithObject", value: function processFormFieldsWithObject(object) { var that = this; this._initLocalFormFields(); var len = this._formFileds.length; var fieldIDsToDelete = []; var fieldsToDelete = []; this.remoteFieldsExists = false; for (var i = 0; i < len; i++) { if (this._formFileds[i][1].type === 'fieldset') { var newFields = JSON.parse(object[this._formFileds[i][0]]); fieldsToDelete.push(this._formFileds[i][0]); newFields.forEach(function (entry) { that._formFileds.push(entry); if (entry[1]['remote-source'] !== undefined && entry[1]['remote-source'] != null) { that.remoteFieldsExists = true; } }); } } var tempArray = []; that._formFileds.forEach(function (entry) { if (jQuery.inArray(entry[0], fieldsToDelete) < 0) { tempArray.push(entry); } }); that._formFileds = tempArray; } }, { key: "renderForm", value: function renderForm(object) { var that = this; this.processFormFieldsWithObject(object); if (this.remoteFieldsExists) { var cb = function cb() { that.renderFormNew(object); }; this.initFieldMasterData(cb); } else { this.initFieldMasterData(); that.renderFormNew(object); } this.currentReport = object; } }, { key: "renderFormNew", value: function renderFormNew(object) { var that = this; var signatureIds = []; if (object == null || object === undefined) { this.currentId = null; } this.preRenderForm(object); var formHtml = this.templates.formTemplate; var html = ''; var fields = this.getFormFields(); for (var i = 0; i < fields.length; i++) { var metaField = this.getMetaFieldForRendering(fields[i][0]); if (metaField === '' || metaField === undefined) { html += this.renderFormField(fields[i]); } else { var metaVal = object[metaField]; if (metaVal !== '' && metaVal != null && metaVal !== undefined && metaVal.trim() !== '') { html += this.renderFormField(JSON.parse(metaVal)); } else { html += this.renderFormField(fields[i]); } } } formHtml = formHtml.replace(/_id_/g, "".concat(this.getTableName(), "_submit")); formHtml = formHtml.replace(/_fields_/g, html); var $tempDomObj; var randomFormId = this.generateRandom(14); if (!this.showFormOnPopup) { $tempDomObj = $("#".concat(this.getTableName(), "Form")); } else { $tempDomObj = $('
'); $tempDomObj.attr('id', randomFormId); } $tempDomObj.html(formHtml); $tempDomObj.find('.datefield').datepicker({ viewMode: 2 }); $tempDomObj.find('.timefield').datetimepicker({ language: 'en', pickDate: false }); $tempDomObj.find('.datetimefield').datetimepicker({ language: 'en' }); $tempDomObj.find('.colorpick').colorpicker(); // $tempDomObj.find('.select2Field').select2(); $tempDomObj.find('.select2Field').each(function () { $(this).select2().select2('val', $(this).find('option:eq(0)').val()); }); $tempDomObj.find('.select2Multi').each(function () { $(this).select2().on('change', function (e) { var parentRow = $(this).parents('.row'); var height = parentRow.find('.select2-choices').height(); parentRow.height(parseInt(height, 10)); }); }); $tempDomObj.find('.signatureField').each(function () { // $(this).data('signaturePad',new SignaturePad($(this))); signatureIds.push($(this).attr('id')); }); for (var _i = 0; _i < fields.length; _i++) { if (fields[_i][1].type === 'datagroup') { $tempDomObj.find("#".concat(fields[_i][0])).data('field', fields[_i]); } } if (this.showSave === false) { $tempDomObj.find('.saveBtn').remove(); } else { $tempDomObj.find('.saveBtn').off(); $tempDomObj.find('.saveBtn').data('modJs', this); $tempDomObj.find('.saveBtn').on('click', function () { if ($(this).data('modJs').saveSuccessItemCallback != null && $(this).data('modJs').saveSuccessItemCallback !== undefined) { $(this).data('modJs').save($(this).data('modJs').retriveItemsAfterSave(), $(this).data('modJs').saveSuccessItemCallback); } else { $(this).data('modJs').save(); } return false; }); } if (this.showCancel === false) { $tempDomObj.find('.cancelBtn').remove(); } else { $tempDomObj.find('.cancelBtn').off(); $tempDomObj.find('.cancelBtn').data('modJs', this); $tempDomObj.find('.cancelBtn').on('click', function () { $(this).data('modJs').cancel(); return false; }); } if (!this.showFormOnPopup) { $("#".concat(this.getTableName(), "Form")).show(); $("#".concat(this.getTableName())).hide(); for (var _i2 = 0; _i2 < signatureIds.length; _i2++) { $("#".concat(signatureIds[_i2])).data('signaturePad', new SignaturePad(document.getElementById(signatureIds[_i2]))); } if (object !== undefined && object != null) { this.fillForm(object); } } else { // var tHtml = $tempDomObj.wrap('
').parent().html(); // this.showMessage("Edit",tHtml,null,null,true); this.showMessage('Edit', '', null, null, true); $('#plainMessageModel .modal-body').html(''); $('#plainMessageModel .modal-body').append($tempDomObj); for (var _i3 = 0; _i3 < signatureIds.length; _i3++) { $("#".concat(signatureIds[_i3])).data('signaturePad', new SignaturePad(document.getElementById(signatureIds[_i3]))); } if (object !== undefined && object != null) { this.fillForm(object, "#".concat(randomFormId)); } } this.postRenderForm(object, $tempDomObj); } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var html = '
'; html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "addSuccessCallBack", value: function addSuccessCallBack(callBackData, serverData) { var fileName = serverData[0]; var link; if (fileName.indexOf('https:') === 0) { link = "Download Report "); } else { link = "Download Report "); } link = link.replace(/_BASE_/g, this.baseUrl); if (this.currentReport.output === 'PDF' || this.currentReport.output === 'JSON') { this.showMessage('Download Report', link); } else { if (serverData[1].length === 0) { this.showMessage('Empty Report', 'There were no data for selected filters'); return; } var tableHtml = "".concat(link, "

"); // Delete existing temp report table $('#tempReportTable').remove(); // this.showMessage("Report",tableHtml); $("#".concat(this.table)).html(tableHtml); $("#".concat(this.table)).show(); $("#".concat(this.table, "Form")).hide(); // Prepare headers var headers = []; for (var index in serverData[1]) { headers.push({ sTitle: serverData[1][index] }); } var data = serverData[2]; var dataTableParams = { oLanguage: { sLengthMenu: '_MENU_ records per page' }, aaData: data, aoColumns: headers, bSort: false, iDisplayLength: 15, iDisplayStart: 0 }; $('#tempReportTable').dataTable(dataTableParams); $('.dataTables_paginate ul').addClass('pagination'); $('.dataTables_length').hide(); $('.dataTables_filter input').addClass('form-control'); $('.dataTables_filter input').attr('placeholder', 'Search'); $('.dataTables_filter label').contents().filter(function () { return this.nodeType === 3; }).remove(); $('.tableActionButton').tooltip(); } } }, { key: "fillForm", value: function fillForm(object) { var fields = this.getFormFields(); for (var i = 0; i < fields.length; i++) { if (fields[i][1].type === 'label') { $("#".concat(this.getTableName(), "Form #").concat(fields[i][0])).html(object[fields[i][0]]); } else { $("#".concat(this.getTableName(), "Form #").concat(fields[i][0])).val(object[fields[i][0]]); } } } }]); return ReportAdapter; }(_AdapterBase3["default"]); var ReportGenAdapter = /*#__PURE__*/function (_AdapterBase2) { _inherits(ReportGenAdapter, _AdapterBase2); var _super2 = _createSuper(ReportGenAdapter); function ReportGenAdapter() { _classCallCheck(this, ReportGenAdapter); return _super2.apply(this, arguments); } _createClass(ReportGenAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }]; } }, { key: "getFormFields", value: function getFormFields() { return []; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var html = '
'; html = html.replace(/_id_/g, id); html = html.replace(/_name_/g, data[1]); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }]); return ReportGenAdapter; }(_AdapterBase3["default"]); module.exports = { ReportAdapter: ReportAdapter, ReportGenAdapter: ReportGenAdapter }; },{"../../../api/AdapterBase":52}],43:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); var _IceDataPipe = _interopRequireDefault(require("../../../api/IceDataPipe")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*window.SalaryComponentTypeAdapter = SalaryComponentTypeAdapter; window.SalaryComponentAdapter = SalaryComponentAdapter; window.EmployeeSalaryAdapter = EmployeeSalaryAdapter;*/ function init(data) { var modJsList = []; modJsList.tabSalaryComponentType = new _lib.SalaryComponentTypeAdapter('SalaryComponentType', 'SalaryComponentType'); modJsList.tabSalaryComponentType.setObjectTypeName('Salary Component Types'); modJsList.tabSalaryComponentType.setDataPipe(new _IceDataPipe["default"](modJsList.tabSalaryComponentType)); modJsList.tabSalaryComponentType.setAccess(data.permissions.SalaryComponentType); modJsList.tabSalaryComponent = new _lib.SalaryComponentAdapter('SalaryComponent', 'SalaryComponent'); modJsList.tabSalaryComponent.setObjectTypeName('Salary components'); modJsList.tabSalaryComponent.setDataPipe(new _IceDataPipe["default"](modJsList.tabSalaryComponent)); modJsList.tabSalaryComponent.setAccess(data.permissions.SalaryComponent); modJsList.tabEmployeeSalary = new _lib.EmployeeSalaryAdapter('EmployeeSalary', 'EmployeeSalary'); modJsList.tabEmployeeSalary.setObjectTypeName('Employee Salary'); modJsList.tabEmployeeSalary.setDataPipe(new _IceDataPipe["default"](modJsList.tabEmployeeSalary)); modJsList.tabEmployeeSalary.setAccess(data.permissions.EmployeeSalary); //window.modJs = modJsList.tabEmployeeSalary; window.modJs = modJsList.tabSalaryComponentType; window.modJsList = modJsList; } window.initAdminSalary = init; },{"../../../api/IceDataPipe":58,"./lib":44}],44:[function(require,module,exports){ "use strict"; var _ReactModalAdapterBase = _interopRequireDefault(require("../../../api/ReactModalAdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * SalaryComponentTypeAdapter */ var SalaryComponentTypeAdapter = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(SalaryComponentTypeAdapter, _ReactModalAdapterBas); var _super = _createSuper(SalaryComponentTypeAdapter); function SalaryComponentTypeAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, SalaryComponentTypeAdapter); _this = _super.call(this, endPoint, tab, filter, orderBy); _this.fieldNameMap = {}; _this.hiddenFields = {}; _this.tableFields = {}; _this.formOnlyFields = {}; return _this; } _createClass(SalaryComponentTypeAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'code', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Code' }, { sTitle: 'Name' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Code', dataIndex: 'code', sorter: true }, { title: 'Name', dataIndex: 'name', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['code', { label: 'Code', type: 'text', validation: '' }], ['name', { label: 'Name', type: 'text', validation: '' }]]; } }]); return SalaryComponentTypeAdapter; }(_ReactModalAdapterBase["default"]); /** * SalaryComponentAdapter */ var SalaryComponentAdapter = /*#__PURE__*/function (_ReactModalAdapterBas2) { _inherits(SalaryComponentAdapter, _ReactModalAdapterBas2); var _super2 = _createSuper(SalaryComponentAdapter); function SalaryComponentAdapter(endPoint, tab, filter, orderBy) { var _this2; _classCallCheck(this, SalaryComponentAdapter); _this2 = _super2.call(this, endPoint, tab, filter, orderBy); _this2.fieldNameMap = {}; _this2.hiddenFields = {}; _this2.tableFields = {}; _this2.formOnlyFields = {}; return _this2; } _createClass(SalaryComponentAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'componentType', 'details']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Salary Component Type' }, { sTitle: 'Details' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Salary Component Type', dataIndex: 'componentType', sorter: true }, { title: 'Details', dataIndex: 'details', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['componentType', { label: 'Salary Component Type', type: 'select2', 'remote-source': ['SalaryComponentType', 'id', 'name'] }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }]]; } }]); return SalaryComponentAdapter; }(_ReactModalAdapterBase["default"]); /* * EmployeeSalaryAdapter */ var EmployeeSalaryAdapter = /*#__PURE__*/function (_ReactModalAdapterBas3) { _inherits(EmployeeSalaryAdapter, _ReactModalAdapterBas3); var _super3 = _createSuper(EmployeeSalaryAdapter); function EmployeeSalaryAdapter(endPoint, tab, filter, orderBy) { var _this3; _classCallCheck(this, EmployeeSalaryAdapter); _this3 = _super3.call(this, endPoint, tab, filter, orderBy); _this3.fieldNameMap = {}; _this3.hiddenFields = {}; _this3.tableFields = {}; _this3.formOnlyFields = {}; return _this3; } _createClass(EmployeeSalaryAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'component', 'amount', 'details']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Salary Component' }, { sTitle: 'Amount' }, { sTitle: 'Details' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Employee', dataIndex: 'employee', sorter: true }, { title: 'Salary Component', dataIndex: 'component', sorter: true }, { title: 'Amount', dataIndex: 'amount', sorter: true }, { title: 'Details', dataIndex: 'details', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['component', { label: 'Salary Component', type: 'select2', 'remote-source': ['SalaryComponent', 'id', 'name'] }], ['amount', { label: 'Amount', type: 'text', validation: 'float' }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }]); return EmployeeSalaryAdapter; }(_ReactModalAdapterBase["default"]); module.exports = { SalaryComponentTypeAdapter: SalaryComponentTypeAdapter, SalaryComponentAdapter: SalaryComponentAdapter, EmployeeSalaryAdapter: EmployeeSalaryAdapter }; },{"../../../api/ReactModalAdapterBase":65}],45:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.SettingAdapter = _lib.SettingAdapter; },{"./lib":46}],46:[function(require,module,exports){ "use strict"; var _AdapterBase2 = _interopRequireDefault(require("../../../api/AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * SettingAdapter */ var SettingAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(SettingAdapter, _AdapterBase); var _super = _createSuper(SettingAdapter); function SettingAdapter() { _classCallCheck(this, SettingAdapter); return _super.apply(this, arguments); } _createClass(SettingAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'value', 'description']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Value' }, { sTitle: 'Details' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['value', { label: 'Value', type: 'text', validation: 'none' }]]; } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var html = '
'; html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } }, { key: "getMetaFieldForRendering", value: function getMetaFieldForRendering(fieldName) { if (fieldName === 'value') { return 'meta'; } return ''; } }, { key: "edit", value: function edit(id) { this.loadRemoteDataForSettings(); _get(_getPrototypeOf(SettingAdapter.prototype), "edit", this).call(this, id); } }, { key: "fillForm", value: function fillForm(object) { var metaField = this.getMetaFieldForRendering('value'); var metaVal = object[metaField]; var formFields = null; if (metaVal !== '' && metaVal !== undefined) { formFields = [['id', { label: 'ID', type: 'hidden' }], JSON.parse(metaVal)]; } _get(_getPrototypeOf(SettingAdapter.prototype), "fillForm", this).call(this, object, null, formFields); $('#helptext').html(object.description); } }, { key: "loadRemoteDataForSettings", value: function loadRemoteDataForSettings() { var fields = []; var field = null; fields.push(['country', { label: 'Country', type: 'select2multi', 'remote-source': ['Country', 'id', 'name'] }]); fields.push(['countryCompany', { label: 'Country', type: 'select2', 'remote-source': ['Country', 'code', 'name'] }]); fields.push(['currency', { label: 'Currency', type: 'select2multi', 'remote-source': ['CurrencyType', 'id', 'code+name'] }]); fields.push(['nationality', { label: 'Nationality', type: 'select2multi', 'remote-source': ['Nationality', 'id', 'name'] }]); fields.push(['supportedLanguage', { label: 'Value', type: 'select2', 'allow-null': false, 'remote-source': ['SupportedLanguage', 'name', 'description'] }]); for (var index in fields) { field = fields[index]; if (field[1]['remote-source'] !== undefined && field[1]['remote-source'] !== null) { var key = "".concat(field[1]['remote-source'][0], "_").concat(field[1]['remote-source'][1], "_").concat(field[1]['remote-source'][2]); this.fieldMasterDataKeys[key] = false; this.sourceMapping[field[0]] = field[1]['remote-source']; var callBackData = {}; callBackData.callBack = 'initFieldMasterDataResponse'; callBackData.callBackData = [key]; this.getFieldValues(field[1]['remote-source'], callBackData); } } } }, { key: "getHelpLink", value: function getHelpLink() { return 'http://blog.icehrm.com/docs/settings/'; } }]); return SettingAdapter; }(_AdapterBase2["default"]); module.exports = { SettingAdapter: SettingAdapter }; },{"../../../api/AdapterBase":52}],47:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.ImmigrationDocumentAdapter = _lib.ImmigrationDocumentAdapter; window.EmployeeImmigrationAdapter = _lib.EmployeeImmigrationAdapter; window.EmployeeTravelRecordAdminAdapter = _lib.EmployeeTravelRecordAdminAdapter; window.CustomFieldAdapter = _lib.CustomFieldAdapter; },{"./lib":48}],48:[function(require,module,exports){ "use strict"; var _AdapterBase3 = _interopRequireDefault(require("../../../api/AdapterBase")); var _CustomFieldAdapter = _interopRequireDefault(require("../../../api/CustomFieldAdapter")); var _ApproveAdminAdapter2 = _interopRequireDefault(require("../../../api/ApproveAdminAdapter")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * ImmigrationDocumentAdapter */ var ImmigrationDocumentAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(ImmigrationDocumentAdapter, _AdapterBase); var _super = _createSuper(ImmigrationDocumentAdapter); function ImmigrationDocumentAdapter() { _classCallCheck(this, ImmigrationDocumentAdapter); return _super.apply(this, arguments); } _createClass(ImmigrationDocumentAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'details', 'required', 'alert_on_missing', 'alert_before_expiry']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Details' }, { sTitle: 'Compulsory' }, { sTitle: 'Alert If Not Found' }, { sTitle: 'Alert Before Expiry' }]; } }, { key: "getFormFields", value: function getFormFields() { var fields = [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }], ['required', { label: 'Compulsory', type: 'select', source: [['No', 'No'], ['Yes', 'Yes']] }], ['alert_on_missing', { label: 'Alert If Not Found', type: 'select', source: [['No', 'No'], ['Yes', 'Yes']] }], ['alert_before_expiry', { label: 'Alert Before Expiry', type: 'select', source: [['No', 'No'], ['Yes', 'Yes']] }], ['alert_before_day_number', { label: 'Days for Expiry Alert', type: 'text', validation: '' }]]; for (var i = 0; i < this.customFields.length; i++) { fields.push(this.customFields[i]); } return fields; } }]); return ImmigrationDocumentAdapter; }(_AdapterBase3["default"]); /** * EmployeeImmigrationAdapter */ var EmployeeImmigrationAdapter = /*#__PURE__*/function (_AdapterBase2) { _inherits(EmployeeImmigrationAdapter, _AdapterBase2); var _super2 = _createSuper(EmployeeImmigrationAdapter); function EmployeeImmigrationAdapter() { _classCallCheck(this, EmployeeImmigrationAdapter); return _super2.apply(this, arguments); } _createClass(EmployeeImmigrationAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'document', 'documentname', 'valid_until', 'status']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Document' }, { sTitle: 'Document Id' }, { sTitle: 'Valid Until' }, { sTitle: 'Status' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['document', { label: 'Document', type: 'select2', 'remote-source': ['ImmigrationDocument', 'id', 'name'] }], ['documentname', { label: 'Document Id', type: 'text', validation: '' }], ['valid_until', { label: 'Valid Until', type: 'date', validation: 'none' }], ['status', { label: 'Status', type: 'select', source: [['Active', 'Active'], ['Inactive', 'Inactive'], ['Draft', 'Draft']] }], ['details', { label: 'Details', type: 'textarea', validation: 'none' }], ['attachment1', { label: 'Attachment 1', type: 'fileupload', validation: 'none' }], ['attachment2', { label: 'Attachment 2', type: 'fileupload', validation: 'none' }], ['attachment3', { label: 'Attachment 3', type: 'fileupload', validation: 'none' }]]; } }, { key: "getFilters", value: function getFilters() { return [['employee', { label: 'Employee', type: 'select2', 'remote-source': ['Employee', 'id', 'first_name+last_name'] }]]; } }]); return EmployeeImmigrationAdapter; }(_AdapterBase3["default"]); /** * EmployeeTravelRecordAdminAdapter */ var EmployeeTravelRecordAdminAdapter = /*#__PURE__*/function (_ApproveAdminAdapter) { _inherits(EmployeeTravelRecordAdminAdapter, _ApproveAdminAdapter); var _super3 = _createSuper(EmployeeTravelRecordAdminAdapter); function EmployeeTravelRecordAdminAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, EmployeeTravelRecordAdminAdapter); _this = _super3.call(this, endPoint, tab, filter, orderBy); _this.itemName = 'TravelRequest'; _this.itemNameLower = 'travelrequest'; _this.modulePathName = 'travel'; return _this; } _createClass(EmployeeTravelRecordAdminAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'employee', 'type', 'purpose', 'travel_from', 'travel_to', 'travel_date', 'status']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Employee' }, { sTitle: 'Travel Type' }, { sTitle: 'Purpose' }, { sTitle: 'From' }, { sTitle: 'To' }, { sTitle: 'Travel Date' }, { sTitle: 'Status' }]; } }, { key: "getFormFields", value: function getFormFields() { return this.addCustomFields([['id', { label: 'ID', type: 'hidden' }], ['employee', { label: 'Employee', type: 'select2', sort: 'none', 'allow-null': false, 'remote-source': ['Employee', 'id', 'first_name+last_name', 'getActiveSubordinateEmployees'] }], ['type', { label: 'Means of Transportation', type: 'select', source: [['Plane', 'Plane'], ['Rail', 'Rail'], ['Taxi', 'Taxi'], ['Own Vehicle', 'Own Vehicle'], ['Rented Vehicle', 'Rented Vehicle'], ['Other', 'Other']] }], ['purpose', { label: 'Purpose of Travel', type: 'textarea', validation: '' }], ['travel_from', { label: 'Travel From', type: 'text', validation: '' }], ['travel_to', { label: 'Travel To', type: 'text', validation: '' }], ['travel_date', { label: 'Travel Date', type: 'datetime', validation: '' }], ['return_date', { label: 'Return Date', type: 'datetime', validation: '' }], ['details', { label: 'Notes', type: 'textarea', validation: 'none' }], ['currency', { label: 'Currency', type: 'select2', 'allow-null': false, 'remote-source': ['CurrencyType', 'id', 'code'] }], ['funding', { label: 'Total Funding Proposed', type: 'text', validation: 'float', "default": '0.00', mask: '9{0,10}.99' }], ['attachment1', { label: 'Attachment', type: 'fileupload', validation: 'none' }], ['attachment2', { label: 'Attachment', type: 'fileupload', validation: 'none' }], ['attachment3', { label: 'Attachment', type: 'fileupload', validation: 'none' }]]); } }]); return EmployeeTravelRecordAdminAdapter; }(_ApproveAdminAdapter2["default"]); module.exports = { ImmigrationDocumentAdapter: ImmigrationDocumentAdapter, EmployeeImmigrationAdapter: EmployeeImmigrationAdapter, EmployeeTravelRecordAdminAdapter: EmployeeTravelRecordAdminAdapter, CustomFieldAdapter: _CustomFieldAdapter["default"] }; },{"../../../api/AdapterBase":52,"../../../api/ApproveAdminAdapter":53,"../../../api/CustomFieldAdapter":55}],49:[function(require,module,exports){ "use strict"; var _lib = require("./lib"); window.UserAdapter = _lib.UserAdapter; window.UserRoleAdapter = _lib.UserRoleAdapter; },{"./lib":50}],50:[function(require,module,exports){ "use strict"; var _FormValidation = _interopRequireDefault(require("../../../api/FormValidation")); var _AdapterBase2 = _interopRequireDefault(require("../../../api/AdapterBase")); var _ReactModalAdapterBase = _interopRequireDefault(require("../../../api/ReactModalAdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var UserAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(UserAdapter, _AdapterBase); var _super = _createSuper(UserAdapter); function UserAdapter() { _classCallCheck(this, UserAdapter); return _super.apply(this, arguments); } _createClass(UserAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'username', 'email', 'employee', 'user_level']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID' }, { sTitle: 'User Name' }, { sTitle: 'Authentication Email' }, { sTitle: 'Employee' }, { sTitle: 'User Level' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden', validation: '' }], ['username', { label: 'User Name', type: 'text', validation: 'username' }], ['email', { label: 'Email', type: 'text', validation: 'email' }], ['employee', { label: 'Employee', type: 'select2', 'allow-null': true, 'remote-source': ['Employee', 'id', 'first_name+last_name'] }], ['user_level', { label: 'User Level', type: 'select', source: [['Admin', 'Admin'], ['Manager', 'Manager'], ['Employee', 'Employee'], ['Restricted Admin', 'Restricted Admin'], ['Restricted Manager', 'Restricted Manager'], ['Restricted Employee', 'Restricted Employee']] }], ['user_roles', { label: 'User Roles', type: 'select2multi', 'remote-source': ['UserRole', 'id', 'name'] }], ['lang', { label: 'Language', type: 'select2', 'allow-null': true, 'remote-source': ['SupportedLanguage', 'id', 'description'] }], ['default_module', { label: 'Default Module', type: 'select2', 'null-label': 'No Default Module', 'allow-null': true, 'remote-source': ['Module', 'id', 'name', 'getUserModules'] }]]; } }, { key: "postRenderForm", value: function postRenderForm(object, $tempDomObj) { if (object == null || object === undefined) { $tempDomObj.find('#changePasswordBtn').remove(); } } }, { key: "changePassword", value: function changePassword() { $('#adminUsersModel').modal('show'); $('#adminUsersChangePwd #newpwd').val(''); $('#adminUsersChangePwd #conpwd').val(''); $('#adminUsersChangePwd_error').hide(); } }, { key: "saveUserSuccessCallBack", value: function saveUserSuccessCallBack(callBackData, serverData) { var user = callBackData[0]; if (callBackData[1]) { this.showMessage('Create User', "An email has been sent to ".concat(user.email, " with a temporary password to login to IceHrm.")); } else { this.showMessage('Create User', 'User created successfully. But there was a problem sending welcome email.'); } this.get([]); } }, { key: "saveUserFailCallBack", value: function saveUserFailCallBack(callBackData, serverData) { this.showMessage('Error', callBackData); } }, { key: "doCustomValidation", value: function doCustomValidation(params) { var msg = null; if (params.user_level !== 'Admin' && params.user_level !== 'Restricted Admin' && params.employee === 'NULL') { msg = 'For this user type, you have to assign an employee when adding or editing the user.
'; msg += " You may create a new employee through 'Admin'->'Employees' menu"; } return msg; } }, { key: "save", value: function save() { var validator = new _FormValidation["default"]("".concat(this.getTableName(), "_submit"), true, { ShowPopup: false, LabelErrorClass: 'error' }); if (validator.checkValues()) { var params = validator.getFormParameters(); var msg = this.doCustomValidation(params); if (msg == null) { var id = $("#".concat(this.getTableName(), "_submit #id")).val(); params.csrf = $("#".concat(this.getTableName(), "Form")).data('csrf'); if (id != null && id !== undefined && id !== '') { params.id = id; this.add(params, []); } else { var reqJson = JSON.stringify(params); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'saveUserSuccessCallBack'; callBackData.callBackFail = 'saveUserFailCallBack'; this.customAction('saveUser', 'admin=users', reqJson, callBackData); } } else { // $("#"+this.getTableName()+'Form .label').html(msg); // $("#"+this.getTableName()+'Form .label').show(); this.showMessage('Error Saving User', msg); } } } }, { key: "changePasswordConfirm", value: function changePasswordConfirm() { $('#adminUsersChangePwd_error').hide(); var password = $('#adminUsersChangePwd #newpwd').val(); var conPassword = $('#adminUsersChangePwd #conpwd').val(); if (conPassword !== password) { $('#adminUsersChangePwd_error').html("Passwords don't match"); $('#adminUsersChangePwd_error').show(); return; } var validatePasswordResult = this.validatePassword(password); if (validatePasswordResult != null) { $('#adminUsersChangePwd_error').html(validatePasswordResult); $('#adminUsersChangePwd_error').show(); return; } var req = { id: this.currentId, pwd: conPassword }; var reqJson = JSON.stringify(req); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'changePasswordSuccessCallBack'; callBackData.callBackFail = 'changePasswordFailCallBack'; this.customAction('changePassword', 'admin=users', reqJson, callBackData); } }, { key: "closeChangePassword", value: function closeChangePassword() { $('#adminUsersModel').modal('hide'); } }, { key: "changePasswordSuccessCallBack", value: function changePasswordSuccessCallBack(callBackData, serverData) { this.closeChangePassword(); this.showMessage('Password Change', 'Password changed successfully'); } }, { key: "changePasswordFailCallBack", value: function changePasswordFailCallBack(callBackData, serverData) { this.closeChangePassword(); this.showMessage('Error', callBackData); } }]); return UserAdapter; }(_AdapterBase2["default"]); /** * UserRoleAdapter */ var UserRoleAdapter = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(UserRoleAdapter, _ReactModalAdapterBas); var _super2 = _createSuper(UserRoleAdapter); function UserRoleAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, UserRoleAdapter); _this = _super2.call(this, endPoint, tab, filter, orderBy); _this.tables = []; return _this; } _createClass(UserRoleAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'ID', dataIndex: 'id', sorter: true }, { title: 'Name', dataIndex: 'name', sorter: true }]; } }, { key: "setTables", value: function setTables(tables) { this.tables = tables; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['additional_permissions', { label: 'Additional Permissions', type: 'datagroup', form: [['table', { label: 'Table', type: 'select2', source: this.tables }], ['permissions', { label: 'Permissions', type: 'select2multi', 'allow-null': true, source: [['get', 'List'], ['element', 'Get Details'], ['save', 'Add/Edit'], ['delete', 'Delete']] }]], columns: [{ title: 'Table', dataIndex: 'table', key: 'table' }, { title: 'Permissions', dataIndex: 'permissions', key: 'permissions' }], validation: 'none' }]]; } }]); return UserRoleAdapter; }(_ReactModalAdapterBase["default"]); module.exports = { UserAdapter: UserAdapter, UserRoleAdapter: UserRoleAdapter }; },{"../../../api/AdapterBase":52,"../../../api/FormValidation":56,"../../../api/ReactModalAdapterBase":65}],51:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /* Copyright (c) 2018 [Glacies UG, Berlin, Germany] (http://glacies.de) Developer: Thilina Hasantha (http://lk.linkedin.com/in/thilinah | https://github.com/thilinah) */ /** * RequestCache */ var MemoryStorage = /*#__PURE__*/function () { function MemoryStorage() { _classCallCheck(this, MemoryStorage); this.data = {}; } _createClass(MemoryStorage, [{ key: "getItem", value: function getItem(key) { return this.data[key]; } }, { key: "setItem", value: function setItem(key, data) { this.data[key] = data; } }, { key: "removeAllByPrefix", value: function removeAllByPrefix(prefix) { var keys = Object.keys(this.data); for (var i = 0; i < keys.length; i++) { if (keys[i].indexOf(prefix) > 0) { delete this.data[keys[i]]; } } } }]); return MemoryStorage; }(); var RequestCache = /*#__PURE__*/function () { function RequestCache(storage) { _classCallCheck(this, RequestCache); if (!storage) { this.storage = new MemoryStorage(); } else { this.storage = storage; } } _createClass(RequestCache, [{ key: "getKey", value: function getKey(url, params) { var key = "".concat(url, "|"); for (var index in params) { key += "".concat(index, "=").concat(params[index], "|"); } return key; } /* invalidateTable(table) { let key; for (let i = 0; i < this.storage.length; i++) { key = this.storage.key(i); if (key.indexOf(`t=${table}`) > 0) { this.storage.removeItem(key); } } } */ }, { key: "invalidateTable", value: function invalidateTable(table) { this.storage.removeAllByPrefix("t=".concat(table)); } }, { key: "getData", value: function getData(key) { var data = this.storage.getItem(key); if (!data) { return null; } return data; } }, { key: "setData", value: function setData(key, data) { if (data.status !== undefined && data.status != null && data.status !== 'SUCCESS') { return null; } this.storage.setItem(key, data); return data; } }]); return RequestCache; }(); var _default = RequestCache; exports["default"] = _default; },{}],52:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _IceApiClient = _interopRequireDefault(require("./IceApiClient")); var _ModuleBase2 = _interopRequireDefault(require("./ModuleBase")); var _RequestCache = _interopRequireDefault(require("../api-common/RequestCache")); var _MasterDataReader = _interopRequireDefault(require("./MasterDataReader")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var AdapterBase = /*#__PURE__*/function (_ModuleBase) { _inherits(AdapterBase, _ModuleBase); var _super = _createSuper(AdapterBase); function AdapterBase(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, AdapterBase); _this = _super.call(this); _this.moduleRelativeURL = null; _this.tableData = []; _this.sourceData = []; _this.filter = null; _this.origFilter = null; _this.orderBy = null; _this.currentElement = null; _this.initAdapter(endPoint, tab, filter, orderBy); return _this; } _createClass(AdapterBase, [{ key: "initAdapter", value: function initAdapter(endPoint, tab, filter, orderBy) { this.moduleRelativeURL = baseUrl; this.table = endPoint; if (tab === undefined || tab === null) { this.tab = endPoint; } else { this.tab = tab; } if (filter === undefined || filter === null) { this.filter = null; } else { this.filter = filter; } this.origFilter = this.filter; if (orderBy === undefined || orderBy === null) { this.orderBy = null; } else { this.orderBy = orderBy; } this.trackEvent('initAdapter', tab); this.requestCache = new _RequestCache["default"](); } }, { key: "initMasterDataReader", value: function initMasterDataReader() { this.masterDataReader = new _MasterDataReader["default"](this); } }, { key: "setupApiClient", value: function setupApiClient(token) { this.apiClient = new _IceApiClient["default"](this.apiUrl, token, window.CLIENT_BASE_URL, true); } }, { key: "setApiUrl", value: function setApiUrl(apiUrl) { this.apiUrl = apiUrl; } }, { key: "setFilter", value: function setFilter(filter) { this.filter = filter; } }, { key: "preSetFilterExternal", value: function preSetFilterExternal(filter) { this.initialFilter = filter; } }, { key: "setFilterExternal", value: function setFilterExternal(_filter) { var filter = _filter; if (filter === undefined || filter === null) { filter = this.initialFilter; } if (filter === undefined || filter === null) { return; } this.setFilter(filter); this.filtersAlreadySet = true; $("#".concat(this.getTableName(), "_resetFilters")).show(); this.currentFilterString = this.getFilterString(filter); } }, { key: "getFilter", value: function getFilter() { return this.filter; } }, { key: "setOrderBy", value: function setOrderBy(orderBy) { this.orderBy = orderBy; } }, { key: "getOrderBy", value: function getOrderBy() { return this.orderBy; } }, { key: "getFile", value: function getFile(name) { var _this2 = this; this.trackEvent('file', name); return new Promise(function (resolve, reject) { $.getJSON(_this2.moduleRelativeURL, { a: 'file', name: name }, function (data) { if (data.status === 'SUCCESS') { resolve(data.data); } else { reject(); } }).fail(function () { return reject(); }); }); } /** * @method add * @param object {Array} object data to be added to database * @param getFunctionCallBackData {Array} once a success is returned call get() function for this module with these parameters * @param _callGetFunction {Boolean} if false the get function of the module will not be called (default: true) * @param successCallback {Function} this will get called after success response */ }, { key: "add", value: function add(object, getFunctionCallBackData, callGetFunction, successCallback) { var that = this; if (callGetFunction === undefined || callGetFunction === null) { // eslint-disable-next-line no-param-reassign callGetFunction = true; } $(object).attr('a', 'add'); $(object).attr('t', this.table); that.showLoader(); this.requestCache.invalidateTable(this.table); $.post(this.moduleRelativeURL, object, function (data) { if (data.status === 'SUCCESS') { that.addSuccessCallBack(getFunctionCallBackData, data.object, callGetFunction, successCallback, that); } else { that.addFailCallBack(getFunctionCallBackData, data.object); } }, 'json').fail(function (e) { if (e.status === 403) { that.showMessage('Access Forbidden', e.responseJSON.message); } }).always(function () { that.hideLoader(); }); this.trackEvent('add', this.tab, this.table); } }, { key: "addSuccessCallBack", value: function addSuccessCallBack(callBackData, serverData, callGetFunction, successCallback, thisObject) { if (callGetFunction) { this.get(callBackData); } this.initFieldMasterData(); if (successCallback !== undefined && successCallback !== null) { successCallback.apply(thisObject, [serverData]); } this.trackEvent('addSuccess', this.tab, this.table); } }, { key: "addFailCallBack", value: function addFailCallBack(callBackData, serverData) { try { this.closePlainMessage(); } catch (e) {// No need to report } this.showMessage('Error saving', serverData); this.trackEvent('addFailed', this.tab, this.table); } }, { key: "deleteObj", value: function deleteObj(id, callBackData) { var that = this; that.showLoader(); this.requestCache.invalidateTable(this.table); $.post(this.moduleRelativeURL, { t: this.table, a: 'delete', id: id }, function (data) { if (data.status === 'SUCCESS') { that.deleteSuccessCallBack(callBackData, data.object); } else { that.deleteFailCallBack(callBackData, data.object); } }, 'json').fail(function (e) { if (e.status === 403) { that.showMessage('Access Forbidden', e.responseJSON.message); } }).always(function () { that.hideLoader(); }); this.trackEvent('delete', this.tab, this.table); } // eslint-disable-next-line no-unused-vars }, { key: "deleteSuccessCallBack", value: function deleteSuccessCallBack(callBackData, serverData) { this.get(callBackData); this.clearDeleteParams(); } }, { key: "deleteFailCallBack", value: function deleteFailCallBack(callBackData, serverData) { this.clearDeleteParams(); this.showMessage('Error Occurred while Deleting Item', serverData); } }, { key: "get", value: function get(callBackData) { var that = this; if (this.getRemoteTable()) { this.createTableServer(this.getTableName()); $("#".concat(this.getTableName(), "Form")).hide(); $("#".concat(this.getTableName())).show(); return; } var sourceMappingJson = JSON.stringify(this.getSourceMapping()); var filterJson = ''; if (this.getFilter() !== null) { filterJson = JSON.stringify(this.getFilter()); } var orderBy = ''; if (this.getOrderBy() !== null) { orderBy = this.getOrderBy(); } sourceMappingJson = this.fixJSON(sourceMappingJson); filterJson = this.fixJSON(filterJson); that.showLoader(); $.post(this.moduleRelativeURL, { t: this.table, a: 'get', sm: sourceMappingJson, ft: filterJson, ob: orderBy }, function (data) { if (data.status === 'SUCCESS') { that.getSuccessCallBack(callBackData, data.object); } else { that.getFailCallBack(callBackData, data.object); } }, 'json').fail(function (e) { if (e.status === 403) { that.showMessage('Access Forbidden', e.responseJSON.message); } }).always(function () { that.hideLoader(); }); that.initFieldMasterData(); this.trackEvent('get', this.tab, this.table); // var url = this.getDataUrl(); // console.log(url); } }, { key: "getDataUrl", value: function getDataUrl(_columns) { var sourceMappingJson = JSON.stringify(this.getSourceMapping()); var columns = JSON.stringify(_columns); var filterJson = ''; if (this.getFilter() !== null) { filterJson = JSON.stringify(this.getFilter()); } var orderBy = ''; if (this.getOrderBy() !== null) { orderBy = this.getOrderBy(); } var url = this.moduleRelativeURL.replace('service.php', 'data.php'); url = "".concat(url, "?t=").concat(this.table); url = "".concat(url, "&sm=").concat(this.fixJSON(sourceMappingJson)); url = "".concat(url, "&cl=").concat(this.fixJSON(columns)); url = "".concat(url, "&ft=").concat(this.fixJSON(filterJson)); url = "".concat(url, "&ob=").concat(orderBy); if (this.isSubProfileTable()) { url = "".concat(url, "&type=sub"); } if (this.remoteTableSkipProfileRestriction()) { url = "".concat(url, "&skip=1"); } return url; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return false; } }, { key: "remoteTableSkipProfileRestriction", value: function remoteTableSkipProfileRestriction() { return false; } }, { key: "preProcessTableData", value: function preProcessTableData(row) { return row; } }, { key: "getSuccessCallBack", value: function getSuccessCallBack(callBackData, serverData) { var data = []; var mapping = this.getDataMapping(); for (var i = 0; i < serverData.length; i++) { var row = []; for (var j = 0; j < mapping.length; j++) { row[j] = serverData[i][mapping[j]]; } data.push(this.preProcessTableData(row)); } this.sourceData = serverData; if (callBackData.callBack !== undefined && callBackData.callBack !== null) { if (callBackData.callBackData === undefined || callBackData.callBackData === null) { callBackData.callBackData = []; } callBackData.callBackData.push(serverData); callBackData.callBackData.push(data); this.callFunction(callBackData.callBack, callBackData.callBackData); } this.tableData = data; if (!(callBackData.noRender !== undefined && callBackData.noRender !== null && callBackData.noRender === true)) { this.createTable(this.getTableName()); $("#".concat(this.getTableName(), "Form")).hide(); $("#".concat(this.getTableName())).show(); } } // eslint-disable-next-line no-unused-vars }, { key: "getFailCallBack", value: function getFailCallBack(callBackData, serverData) {} }, { key: "getElement", value: function getElement(id, callBackData, clone) { var that = this; var sourceMappingJson = JSON.stringify(this.getSourceMapping()); sourceMappingJson = this.fixJSON(sourceMappingJson); that.showLoader(); $.post(this.moduleRelativeURL, { t: this.table, a: 'getElement', id: id, sm: sourceMappingJson }, function (data) { if (data.status === 'SUCCESS') { if (clone) { delete data.object.id; } this.currentElement = data.object; that.getElementSuccessCallBack.apply(that, [callBackData, data.object]); } else { that.getElementFailCallBack.apply(that, [callBackData, data.object]); } }, 'json').fail(function (e) { if (e.status === 403) { that.showMessage('Access Forbidden', e.responseJSON.message); } }).always(function () { that.hideLoader(); }); this.trackEvent('getElement', this.tab, this.table); } }, { key: "getElementSuccessCallBack", value: function getElementSuccessCallBack(callBackData, serverData) { if (callBackData.callBack !== undefined && callBackData.callBack !== null) { if (callBackData.callBackData === undefined || callBackData.callBackData === null) { callBackData.callBackData = []; } callBackData.callBackData.push(serverData); this.callFunction(callBackData.callBack, callBackData.callBackData, this); } this.currentElement = serverData; if (!(callBackData.noRender !== undefined && callBackData.noRender !== null && callBackData.noRender === true)) { this.renderForm(serverData); } } // eslint-disable-next-line no-unused-vars }, { key: "getElementFailCallBack", value: function getElementFailCallBack(callBackData, serverData) {} }, { key: "getTableData", value: function getTableData() { return this.tableData; } }, { key: "getTableName", value: function getTableName() { return this.tab; } }, { key: "getFieldValues", value: function getFieldValues(fieldMaster, callBackData) { var that = this; var method = ''; var methodParams = ''; if (fieldMaster[3] !== undefined && fieldMaster[3] !== null) { // eslint-disable-next-line prefer-destructuring method = fieldMaster[3]; } if (fieldMaster[4] !== undefined && fieldMaster[4] !== null) { methodParams = JSON.stringify(fieldMaster[4]); } var key = this.requestCache.getKey(this.moduleRelativeURL, { t: fieldMaster[0], key: fieldMaster[1], value: fieldMaster[2], method: method, methodParams: methodParams, a: 'getFieldValues' }); var cacheData = this.requestCache.getData(key); if (cacheData !== null && cacheData !== undefined) { if (cacheData.status === 'SUCCESS') { callBackData.callBackData.push(cacheData.data); if (callBackData.callBackSuccess !== null && callBackData.callBackSuccess !== undefined) { callBackData.callBackData.push(callBackData.callBackSuccess); } that.callFunction(callBackData.callBack, callBackData.callBackData); } } else { var callbackWraper = function callbackWraper(data) { if (data.status === 'SUCCESS') { that.requestCache.setData(this.success.key, data); var localCallBackData = callBackData; localCallBackData.callBackData = [callBackData.callBackData[0]]; localCallBackData.callBackData.push(data.data); if (localCallBackData.callBackSuccess !== null && localCallBackData.callBackSuccess !== undefined) { localCallBackData.callBackData.push(callBackData.callBackSuccess); } that.callFunction(localCallBackData.callBack, localCallBackData.callBackData); } else if (data.message === 'Access violation') { alert("Error : ".concat(callbackWraper.table, " ").concat(data.message)); } }; callbackWraper.key = key; // eslint-disable-next-line prefer-destructuring callbackWraper.table = fieldMaster[0]; $.post(this.moduleRelativeURL, { t: fieldMaster[0], key: fieldMaster[1], value: fieldMaster[2], method: method, methodParams: methodParams, a: 'getFieldValues' }, callbackWraper, 'json'); } } }, { key: "setAdminProfile", value: function setAdminProfile(empId) { try { localStorage.clear(); } catch (e) {// No need to report } $.post(this.moduleRelativeURL, { a: 'setAdminEmp', empid: empId }, function () { // eslint-disable-next-line no-restricted-globals top.location.href = clientUrl; }, 'json'); } }, { key: "customAction", value: function customAction(subAction, module, request, callBackData, isPost) { var that = this; request = this.fixJSON(request); if (!isPost) { $.getJSON(this.moduleRelativeURL, { t: this.table, a: 'ca', sa: subAction, mod: module, req: request }, function (data) { if (data.status === 'SUCCESS') { callBackData.callBackData.push(data.data); that.callFunction(callBackData.callBackSuccess, callBackData.callBackData); } else { callBackData.callBackData.push(data.data); that.callFunction(callBackData.callBackFail, callBackData.callBackData); } }); } else { $.post(this.moduleRelativeURL, { t: this.table, a: 'ca', sa: subAction, mod: module, req: request }, function (data) { if (data.status === 'SUCCESS') { callBackData.callBackData.push(data.data); that.callFunction(callBackData.callBackSuccess, callBackData.callBackData); } else { callBackData.callBackData.push(data.data); that.callFunction(callBackData.callBackFail, callBackData.callBackData); } }, 'json'); } } }, { key: "sendCustomRequest", value: function sendCustomRequest(action, params, successCallback, failCallback) { params.a = action; $.post(this.moduleRelativeURL, params, function (data) { if (data.status === 'SUCCESS') { successCallback(data.data); } else { failCallback(data.data); } }, 'json'); } }, { key: "getCustomActionUrl", value: function getCustomActionUrl(action, params) { params.a = action; var str = ''; for (var key in params) { if (params.hasOwnProperty(key)) { if (str !== '') { str += '&'; } str += "".concat(key, "=").concat(params[key]); } } return "".concat(this.moduleRelativeURL, "?").concat(str); } }, { key: "getClientDataUrl", value: function getClientDataUrl() { return "".concat(this.moduleRelativeURL.replace('service.php', ''), "data/"); } }, { key: "getCustomUrl", value: function getCustomUrl(str) { return this.moduleRelativeURL.replace('service.php', str); } }]); return AdapterBase; }(_ModuleBase2["default"]); var _default = AdapterBase; exports["default"] = _default; },{"../api-common/RequestCache":51,"./IceApiClient":57,"./MasterDataReader":61,"./ModuleBase":62}],53:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _LogViewAdapter2 = _interopRequireDefault(require("./LogViewAdapter")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var ApproveAdminAdapter = /*#__PURE__*/function (_LogViewAdapter) { _inherits(ApproveAdminAdapter, _LogViewAdapter); var _super = _createSuper(ApproveAdminAdapter); function ApproveAdminAdapter(endPoint, tab, filter, orderBy) { _classCallCheck(this, ApproveAdminAdapter); return _super.call(this, endPoint, tab, filter, orderBy); } _createClass(ApproveAdminAdapter, [{ key: "getStatusFieldPosition", value: function getStatusFieldPosition() { var dm = this.getDataMapping(); return dm.length - 1; } }, { key: "openStatus", value: function openStatus(id, status) { $("#".concat(this.itemNameLower, "StatusModel")).modal('show'); $("#".concat(this.itemNameLower, "_status")).html(this.getStatusOptions(status)); $("#".concat(this.itemNameLower, "_status")).val(status); this.statusChangeId = id; } }, { key: "closeDialog", value: function closeDialog() { $("#".concat(this.itemNameLower, "StatusModel")).modal('hide'); } }, { key: "changeStatus", value: function changeStatus() { var status = $("#".concat(this.itemNameLower, "_status")).val(); var reason = $("#".concat(this.itemNameLower, "_reason")).val(); if (status == undefined || status == null || status == '') { this.showMessage('Error', "Please select ".concat(this.itemNameLower, " status")); return; } var object = { id: this.statusChangeId, status: status, reason: reason }; var reqJson = JSON.stringify(object); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'changeStatusSuccessCallBack'; callBackData.callBackFail = 'changeStatusFailCallBack'; this.customAction('changeStatus', "admin=".concat(this.modulePathName), reqJson, callBackData); this.closeDialog(); this.statusChangeId = null; } }, { key: "changeStatusSuccessCallBack", value: function changeStatusSuccessCallBack(callBackData) { this.showMessage('Successful', "".concat(this.itemName, " Request status changed successfully")); this.get([]); } }, { key: "changeStatusFailCallBack", value: function changeStatusFailCallBack(callBackData) { this.showMessage('Error', "Error occurred while changing ".concat(this.itemName, " request status")); } }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var editButton = ''; var deleteButton = ''; var statusChangeButton = ''; var viewLogsButton = ''; var html = '
_edit__delete__status__logs_
'; var optiondata = this.getStatusOptionsData(data[this.getStatusFieldPosition()]); if (Object.keys(optiondata).length > 0) { html = html.replace('_status_', statusChangeButton); } else { html = html.replace('_status_', ''); } html = html.replace('_logs_', viewLogsButton); if (this.showDelete) { html = html.replace('_delete_', deleteButton); } else { html = html.replace('_delete_', ''); } if (this.showEdit) { html = html.replace('_edit_', editButton); } else { html = html.replace('_edit_', ''); } html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); html = html.replace(/_cstatus_/g, data[this.getStatusFieldPosition()]); return html; } }, { key: "isSubProfileTable", value: function isSubProfileTable() { return this.user.user_level !== 'Admin' && this.user.user_level !== 'Restricted Admin'; } }, { key: "getStatusOptionsData", value: function getStatusOptionsData(currentStatus) { var data = {}; if (currentStatus === 'Approved') {} else if (currentStatus === 'Pending') { data.Approved = 'Approved'; data.Rejected = 'Rejected'; } else if (currentStatus === 'Rejected') {} else if (currentStatus === 'Cancelled') {} else if (currentStatus === 'Processing') {} else { data['Cancellation Requested'] = 'Cancellation Requested'; data.Cancelled = 'Cancelled'; } return data; } }, { key: "getStatusOptions", value: function getStatusOptions(currentStatus) { return this.generateOptions(this.getStatusOptionsData(currentStatus)); } }]); return ApproveAdminAdapter; }(_LogViewAdapter2["default"]); var _default = ApproveAdminAdapter; exports["default"] = _default; },{"./LogViewAdapter":60}],54:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _AdapterBase2 = _interopRequireDefault(require("./AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var BaseGraphAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(BaseGraphAdapter, _AdapterBase); var _super = _createSuper(BaseGraphAdapter); function BaseGraphAdapter() { _classCallCheck(this, BaseGraphAdapter); return _super.apply(this, arguments); } _createClass(BaseGraphAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return []; } }, { key: "getHeaders", value: function getHeaders() { return []; } }, { key: "getFormFields", value: function getFormFields() { return []; } // eslint-disable-next-line no-unused-vars }, { key: "createTable", value: function createTable(elementId) {} }]); return BaseGraphAdapter; }(_AdapterBase2["default"]); var _default = BaseGraphAdapter; exports["default"] = _default; },{"./AdapterBase":52}],55:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _AdapterBase2 = _interopRequireDefault(require("./AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /* * CustomFieldAdapter */ var CustomFieldAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(CustomFieldAdapter, _AdapterBase); var _super = _createSuper(CustomFieldAdapter); function CustomFieldAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, CustomFieldAdapter); _this = _super.call(this, endPoint, tab, filter, orderBy); _this.tableType = ''; return _this; } _createClass(CustomFieldAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'display', 'display_order']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Display Status' }, { sTitle: 'Priority' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }], ['display', { label: 'Display Status', type: 'select', source: [['Form', 'Show'], ['Hidden', 'Hidden']] }], ['field_type', { label: 'Field Type', type: 'select', source: [['text', 'Text Field'], ['textarea', 'Text Area'], ['select', 'Select'], ['select2', 'Select2'], ['select2multi', 'Multi Select'], ['fileupload', 'File Upload'], ['date', 'Date'], ['datetime', 'Date Time'], ['time', 'Time'], ['signature', 'Signature']] }], ['field_label', { label: 'Field Label', type: 'text', validation: '' }], ['field_validation', { label: 'Validation', type: 'select2', validation: 'none', sort: 'none', 'null-label': 'Required', 'allow-null': true, source: [['none', 'None'], ['number', 'Number'], ['numberOrEmpty', 'Number or Empty'], ['float', 'Decimal'], ['email', 'Email'], ['emailOrEmpty', 'Email or Empty']] }], ['field_options', { label: 'Field Options', type: 'datagroup', form: [['label', { label: 'Label', type: 'text', validation: '' }], ['value', { label: 'Value', type: 'text', validation: 'none' }]], html: '
#_delete_##_edit_##_label_#:#_value_#
', validation: 'none' }], ['display_order', { label: 'Priority', type: 'text', validation: 'number' }], ['display_section', { label: 'Display Section', type: 'text', validation: 'none' }]]; } }, { key: "setTableType", value: function setTableType(type) { this.tableType = type; } }, { key: "doCustomValidation", value: function doCustomValidation(params) { var validateName = function validateName(str) { var name = /^[a-z][a-z0-9._]+$/; return str != null && name.test(str); }; if (!validateName(params.name)) { return 'Invalid name for custom field'; } return null; } }, { key: "forceInjectValuesBeforeSave", value: function forceInjectValuesBeforeSave(params) { var data = [params.name]; var options = []; var optionsData; data.push({}); data[1].label = params.field_label; data[1].type = params.field_type; data[1].validation = params.field_validation; if (['select', 'select2', 'select2multi'].indexOf(params.field_type) >= 0) { optionsData = params.field_options === '' || params.field_options === undefined ? [] : JSON.parse(params.field_options); for (var index in optionsData) { options.push([optionsData[index].value, optionsData[index].label]); } data[1].source = options; } if (params.field_validation == null || params.field_validation === undefined) { params.field_validation = ''; } params.data = JSON.stringify(data); params.type = this.tableType; return params; } }]); return CustomFieldAdapter; }(_AdapterBase2["default"]); var _default = CustomFieldAdapter; exports["default"] = _default; },{"./AdapterBase":52}],56:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /* Copyright (c) 2018 [Glacies UG, Berlin, Germany] (http://glacies.de) Developer: Thilina Hasantha (http://lk.linkedin.com/in/thilinah | https://github.com/thilinah) */ /* global tinyMCE */ var ValidationRules = { "float": function float(str) { var floatstr = /^[-+]?[0-9]+(\.[0-9]+)?$/; if (str != null && str.match(floatstr)) { return true; } return false; }, number: function number(str) { var numstr = /^[0-9]+$/; if (str != null && str.match(numstr)) { return true; } return false; }, numberOrEmpty: function numberOrEmpty(str) { if (str === '') { return true; } var numstr = /^[0-9]+$/; if (str != null && str.match(numstr)) { return true; } return false; }, email: function email(str) { var emailPattern = /^\s*[\w\-+_]+(\.[\w\-+_]+)*@[\w\-+_]+\.[\w\-+_]+(\.[\w\-+_]+)*\s*$/; return str != null && emailPattern.test(str); }, emailOrEmpty: function emailOrEmpty(str) { if (str === '') { return true; } var emailPattern = /^\s*[\w\-+_]+(\.[\w\-+_]+)*@[\w\-+_]+\.[\w\-+_]+(\.[\w\-+_]+)*\s*$/; return str != null && emailPattern.test(str); }, username: function username(str) { var username = /^[a-zA-Z0-9.-]+$/; return str != null && username.test(str); }, input: function input(str) { if (str != null && str.length > 0) { return true; } return false; } }; var FormValidation = /*#__PURE__*/function () { function FormValidation(formId, validateAll, options) { _classCallCheck(this, FormValidation); this.tempOptions = {}; this.formId = formId; this.formError = false; this.formObject = null; this.errorMessages = ''; this.popupDialog = null; this.validateAll = validateAll; this.errorMap = []; this.settings = { thirdPartyPopup: null, LabelErrorClass: false, ShowPopup: true }; this.settings = jQuery.extend(this.settings, options); this.inputTypes = ['text', 'radio', 'checkbox', 'file', 'password', 'select-one', 'select-multi', 'textarea', 'fileupload', 'signature']; this.validator = ValidationRules; } // eslint-disable-next-line no-unused-vars _createClass(FormValidation, [{ key: "clearError", value: function clearError(formInput, overrideMessage) { var id = formInput.attr('id'); $("#".concat(this.formId, " #field_").concat(id)).removeClass('error'); $("#".concat(this.formId, " #help_").concat(id)).html(''); } // eslint-disable-next-line no-unused-vars }, { key: "addError", value: function addError(formInput, overrideMessage) { this.formError = true; if (formInput.attr('message') != null) { this.errorMessages += "".concat(formInput.attr('message'), "\n"); this.errorMap[formInput.attr('name')] = formInput.attr('message'); } else { this.errorMap[formInput.attr('name')] = ''; } var id = formInput.attr('id'); var validation = formInput.attr('validation'); var message = formInput.attr('validation'); $("#".concat(this.formId, " #field_").concat(id)).addClass('error'); if (message === undefined || message == null || message === '') { $("#".concat(this.formId, " #help_err_").concat(id)).html(message); } else if (validation === undefined || validation == null || validation === '') { $("#".concat(this.formId, " #help_err_").concat(id)).html('Required'); } else if (validation === 'float' || validation === 'number') { $("#".concat(this.formId, " #help_err_").concat(id)).html('Number required'); } else if (validation === 'email') { $("#".concat(this.formId, " #help_err_").concat(id)).html('Email required'); } else { $("#".concat(this.formId, " #help_err_").concat(id)).html('Required'); } } }, { key: "showErrors", value: function showErrors() { if (this.formError) { if (this.settings.thirdPartyPopup !== undefined && this.settings.thirdPartyPopup != null) { this.settings.thirdPartyPopup.alert(); } else if (this.settings.ShowPopup === true) { if (this.tempOptions.popupTop !== undefined && this.tempOptions.popupTop != null) { this.alert('Errors Found', this.errorMessages, this.tempOptions.popupTop); } else { this.alert('Errors Found', this.errorMessages, -1); } } } } }, { key: "checkValues", value: function checkValues(options) { this.tempOptions = options; var that = this; this.formError = false; this.errorMessages = ''; this.formObject = {}; // eslint-disable-next-line consistent-return var validate = function validate(inputObject) { var inputValue = null; var name = inputObject.attr('name'); if (that.settings.LabelErrorClass !== false) { $("label[for='".concat(name, "']")).removeClass(that.settings.LabelErrorClass); } var id = inputObject.attr('id'); var type = inputObject.attr('type'); if (inputObject.hasClass('select2-focusser') || inputObject.hasClass('select2-input')) { return true; } if (jQuery.inArray(type, that.inputTypes) >= 0) { if (inputObject.hasClass('uploadInput')) { inputValue = inputObject.attr('val'); } else if (type === 'radio' || type === 'checkbox') { inputValue = $("input[name='".concat(name, "']:checked")).val(); } else if (inputObject.hasClass('select2Field')) { if ($("#".concat(that.formId, " #").concat(id)).select2('data') != null && $("#".concat(that.formId, " #").concat(id)).select2('data') !== undefined) { inputValue = $("#".concat(that.formId, " #").concat(id)).select2('data').id; } else { inputValue = ''; } } else if (inputObject.hasClass('select2Multi')) { if ($("#".concat(that.formId, " #").concat(id)).select2('data') != null && $("#".concat(that.formId, " #").concat(id)).select2('data') !== undefined) { var inputValueObjects = $("#".concat(that.formId, " #").concat(id)).select2('data'); inputValue = []; for (var i = 0; i < inputValueObjects.length; i++) { inputValue.push(inputValueObjects[i].id); } inputValue = JSON.stringify(inputValue); } else { inputValue = ''; } } else if (inputObject.hasClass('signatureField')) { if ($("#".concat(that.formId, " #").concat(id)).data('signaturePad').isEmpty()) { inputValue = ''; } else { inputValue = $("#".concat(id)).data('signaturePad').toDataURL(); } } else if (inputObject.hasClass('simplemde')) { inputValue = $("#".concat(that.formId, " #").concat(id)).data('simplemde').value(); } else if (inputObject.hasClass('code')) { inputValue = $("#".concat(that.formId, " #").concat(id)).data('codemirror').getValue(); } else if (inputObject.hasClass('tinymce')) { inputValue = tinyMCE.get(id).getContent({ format: 'raw' }); } else { inputValue = inputObject.val(); } var validation = inputObject.attr('validation'); var valid = false; if (validation !== undefined && validation != null && that.validator[validation] !== undefined && that.validator[validation] != null) { valid = that.validator[validation](inputValue); } else { if (that.validateAll) { if (validation !== undefined && validation != null && validation === 'none') { valid = true; } else { valid = that.validator.input(inputValue); } } else { valid = true; } that.formObject[id] = inputValue; } if (!valid) { that.addError(inputObject, null); } else { that.clearError(inputObject, null); that.formObject[id] = inputValue; } } }; var inputs = $("#".concat(this.formId, " :input")); inputs.each(function () { validate($(this)); }); inputs = $("#".concat(this.formId, " .uploadInput")); inputs.each(function () { validate($(this)); }); this.showErrors(); this.tempOptions = {}; return !this.formError; } }, { key: "getFormParameters", value: function getFormParameters() { return this.formObject; } }, { key: "alert", value: function (_alert) { function alert(_x, _x2) { return _alert.apply(this, arguments); } alert.toString = function () { return _alert.toString(); }; return alert; }(function (title, text) { alert(text); }) }], [{ key: "getValidationRules", value: function getValidationRules() { return ValidationRules; } }]); return FormValidation; }(); var _default = FormValidation; exports["default"] = _default; },{}],57:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var axios = require('axios'); var IceApiClient = /*#__PURE__*/function () { function IceApiClient(baseUrl, token, clientBaseUrl) { var legacyApiWrapper = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; _classCallCheck(this, IceApiClient); this.baseUrl = baseUrl; this.token = token; this.clientBaseUrl = clientBaseUrl; this.legacyApiWrapper = legacyApiWrapper; } _createClass(IceApiClient, [{ key: "get", value: function get(endpoint) { if (this.legacyApiWrapper) { var url = "".concat(this.clientBaseUrl, "api/index.php?token=").concat(this.token, "&method=get&url=/").concat(endpoint); return axios.get(url); } return axios.get(this.baseUrl + endpoint, { headers: { Authorization: "Bearer ".concat(this.token) } }); } }]); return IceApiClient; }(); var _default = IceApiClient; exports["default"] = _default; },{"axios":83}],58:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var axios = require('axios'); var IceDataPipe = /*#__PURE__*/function () { function IceDataPipe(adapter) { var pageSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; _classCallCheck(this, IceDataPipe); this.adapter = adapter; this.pageSize = pageSize; } _createClass(IceDataPipe, [{ key: "readMetaData", value: function readMetaData() { this.adapter.initFieldMasterData(); } }, { key: "get", value: function get(_ref) { var _this = this; var page = _ref.page, search = _ref.search, sortField = _ref.sortField, sortOrder = _ref.sortOrder, filters = _ref.filters, limit = _ref.limit; var pageSize = limit || this.pageSize; var start = (page - 1) * pageSize; var dataUrl = this.getDataUrl(this.adapter.getDataMapping(), search, filters); var url = "".concat(dataUrl, "&iDisplayStart=").concat(start, "&iDisplayLength=").concat(pageSize); url = this.applySortingData(this.adapter.getDataMapping(), url, sortField, sortOrder); // $.post(url, (data) => { // that.getSuccessCallBack(callBackData, data); // }, 'json').always(() => { that.hideLoader(); }); url = "".concat(url, "&version=v2"); return axios.post(url, {}).then(function (data) { var key = _this.getRequestKey(page, search, sortField, sortOrder, filters, limit); var response = { items: data.data.objects, total: data.data.totalRecords }; if (_this.adapter.localStorageEnabled) { window.localStorage.setItem(key, JSON.stringify(response)); } return response; }); } }, { key: "getCachedResponse", value: function getCachedResponse(_ref2) { var page = _ref2.page, search = _ref2.search, sortField = _ref2.sortField, sortOrder = _ref2.sortOrder, filters = _ref2.filters, limit = _ref2.limit; var key = this.getRequestKey(page, search, sortField, sortOrder, filters, limit); var cachedResponse = window.localStorage.getItem(key); if (!cachedResponse) { return null; } return JSON.parse(cachedResponse); } }, { key: "clearCachedResponse", value: function clearCachedResponse(_ref3) { var page = _ref3.page, search = _ref3.search, sortField = _ref3.sortField, sortOrder = _ref3.sortOrder, filters = _ref3.filters, limit = _ref3.limit; var key = this.getRequestKey(page, search, sortField, sortOrder, filters, limit); window.localStorage.setItem(key, null); } }, { key: "getRequestKey", value: function getRequestKey(page, search, sortField, sortOrder, filters, limit) { return "".concat(this.adapter.table, "|").concat(page, "|").concat(search, "|").concat(sortField, "|").concat(sortOrder, "|").concat(filters, "|").concat(limit); } }, { key: "applySortingData", value: function applySortingData(columns, url, sortField, sortOrder) { var orderBy = ''; if (sortField) { url = "".concat(url, "&sorting=1"); url = "".concat(url, "&iSortCol_0=").concat(columns.indexOf(sortField)); url = "".concat(url, "&sSortDir_0=").concat(sortOrder === 'descend' ? 'DESC' : 'ASC'); } else if (this.adapter.getOrderBy() !== null) { // Setting the fix ordering orderBy = this.adapter.getOrderBy(); url = "".concat(url, "&ob=").concat(orderBy); } return url; } }, { key: "getDataUrl", value: function getDataUrl(_columns, searchTerm, filters) { var sourceMappingJson = JSON.stringify(this.adapter.getSourceMapping()); var columns = JSON.stringify(_columns); var filterJson = ''; if (this.adapter.getFilter() !== null) { filterJson = JSON.stringify(this.adapter.getFilter()); } var url = this.adapter.moduleRelativeURL.replace('service.php', 'data.php'); url = "".concat(url, "?t=").concat(this.adapter.table); url = "".concat(url, "&sm=").concat(sourceMappingJson); url = "".concat(url, "&cl=").concat(columns); url = "".concat(url, "&ft=").concat(filterJson); if (searchTerm && searchTerm.trim() !== '') { url += "&sSearch=".concat(searchTerm); } if (this.adapter.isSubProfileTable()) { url = "".concat(url, "&type=sub"); } if (this.adapter.remoteTableSkipProfileRestriction()) { url = "".concat(url, "&skip=1"); } return url; } }]); return IceDataPipe; }(); var _default = IceDataPipe; exports["default"] = _default; },{"axios":83}],59:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _AdapterBase2 = _interopRequireDefault(require("./AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * IdNameAdapter */ var IdNameAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(IdNameAdapter, _AdapterBase); var _super = _createSuper(IdNameAdapter); function IdNameAdapter(endPoint, tab, filter, orderBy) { _classCallCheck(this, IdNameAdapter); return _super.call(this, endPoint, tab, filter, orderBy); } _createClass(IdNameAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['name', { label: 'Name', type: 'text', validation: '' }]]; } }]); return IdNameAdapter; }(_AdapterBase2["default"]); var _default = IdNameAdapter; exports["default"] = _default; },{"./AdapterBase":52}],60:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _AdapterBase2 = _interopRequireDefault(require("./AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var LogViewAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(LogViewAdapter, _AdapterBase); var _super = _createSuper(LogViewAdapter); function LogViewAdapter() { _classCallCheck(this, LogViewAdapter); return _super.apply(this, arguments); } _createClass(LogViewAdapter, [{ key: "getLogs", value: function getLogs(id) { var object = { id: id }; var reqJson = JSON.stringify(object); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'getLogsSuccessCallBack'; callBackData.callBackFail = 'getLogsFailCallBack'; this.customAction('getLogs', "admin=".concat(this.modulePathName), reqJson, callBackData); } }, { key: "getLogsSuccessCallBack", value: function getLogsSuccessCallBack(callBackData) { var tableLog = '_days_
Notes
'; var rowLog = '_date_  _status_
_note_'; var logs = callBackData.data; var html = ''; var rowsLogs = ''; for (var i = 0; i < logs.length; i++) { var trow = rowLog; trow = trow.replace(/_date_/g, logs[i].time); trow = trow.replace(/_status_/g, "".concat(logs[i].status_from, " -> ").concat(logs[i].status_to)); trow = trow.replace(/_note_/g, logs[i].note); rowsLogs += trow; } if (rowsLogs !== '') { tableLog = tableLog.replace('_days_', rowsLogs); html += tableLog; } this.showMessage('Logs', html); timeUtils.convertToRelativeTime($('.logTime')); } // eslint-disable-next-line no-unused-vars }, { key: "getLogsFailCallBack", value: function getLogsFailCallBack(callBackData) { this.showMessage('Error', 'Error occured while getting data'); } }]); return LogViewAdapter; }(_AdapterBase2["default"]); var _default = LogViewAdapter; exports["default"] = _default; },{"./AdapterBase":52}],61:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var axios = require('axios'); var MasterDataReader = /*#__PURE__*/function () { function MasterDataReader(adapter) { _classCallCheck(this, MasterDataReader); this.adapter = adapter; this.requestCache = this.adapter.requestCache; } _createClass(MasterDataReader, [{ key: "fetchMasterData", value: function fetchMasterData(fieldMaster) { var _this = this; var method = ''; var methodParams = ''; if (fieldMaster[3] != null) { method = fieldMaster[3]; } if (fieldMaster[4] != null) { methodParams = JSON.stringify(fieldMaster[4]); } var key = this.requestCache.getKey(this.adapter.moduleRelativeURL, { t: fieldMaster[0], key: fieldMaster[1], value: fieldMaster[2], method: method, methodParams: methodParams, a: 'getFieldValues' }); var cacheData = this.requestCache.getData(key); if (cacheData != null && cacheData.status === 'SUCCESS') { return new Promise(function (resolve, reject) { return resolve(cacheData.data); }); } var urlData = { t: fieldMaster[0], key: fieldMaster[1], value: fieldMaster[2], method: method, methodParams: methodParams, a: 'getFieldValues' }; var url = "".concat(this.adapter.moduleRelativeURL, "?_url=1"); for (var index in urlData) { url = "".concat(url, "&").concat(index, "=").concat(encodeURIComponent(urlData[index])); } // TODO - Should be a get request return axios.post(url, {}).then(function (response) { if (response.data.status !== 'SUCCESS') { throw Error("Response for ".concat(key, " failed")); } _this.requestCache.setData(key, response.data); return response.data.data; }); } }, { key: "updateAllMasterData", value: function updateAllMasterData() { var _this2 = this; var remoteSourceFields = this.adapter.getRemoteSourceFields(); var promiseList = []; for (var i = 0; i < remoteSourceFields.length; i++) { var fieldRemote = remoteSourceFields[i]; if (fieldRemote[1]['remote-source'] !== undefined && fieldRemote[1]['remote-source'] != null) { (function () { var key = "".concat(fieldRemote[1]['remote-source'][0], "_").concat(fieldRemote[1]['remote-source'][1], "_").concat(fieldRemote[1]['remote-source'][2]); if (fieldRemote[1]['remote-source'].length === 4) { key = "".concat(key, "_").concat(fieldRemote[1]['remote-source'][3]); } var masterDataPromise = _this2.fetchMasterData(fieldRemote[1]['remote-source']).then(function (data) { _this2.adapter.fieldMasterData[key] = data; }); promiseList.push(masterDataPromise); })(); } } return Promise.all(promiseList); } }]); return MasterDataReader; }(); var _default = MasterDataReader; exports["default"] = _default; },{"axios":83}],62:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _FormValidation = _interopRequireDefault(require("./FormValidation")); 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 _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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * The base class for providing core functions to all module classes. * @class Base.js */ var ModuleBase = /*#__PURE__*/function () { function ModuleBase() { _classCallCheck(this, ModuleBase); this.deleteParams = {}; this.createRemoteTable = false; this.instanceId = 'None'; this.ga = []; this.showAddNew = true; this.showEdit = true; this.showDelete = true; this.showSave = true; this.showCancel = true; this.showFormOnPopup = false; this.filtersAlreadySet = false; this.currentFilterString = ''; this.sorting = 0; this.settings = {}; this.translations = {}; this.customFields = []; this.csrfRequired = false; this.fieldTemplates = null; this.templates = null; this.customTemplates = null; this.emailTemplates = null; this.fieldMasterData = {}; this.fieldMasterDataKeys = {}; this.fieldMasterDataCallback = null; this.sourceMapping = null; this.currentId = null; this.currentElement = null; this.user = null; this.currentProfile = null; this.permissions = {}; this.baseUrl = null; this.that = this; } // eslint-disable-next-line no-unused-vars _createClass(ModuleBase, [{ key: "init", value: function init(appName, currentView, dataUrl, permissions) {} }, { key: "initForm", value: function initForm() {} }, { key: "setObjectTypeName", value: function setObjectTypeName(objectTypeName) { this.objectTypeName = objectTypeName; } /** * Some browsers do not support sending JSON in get parameters. Set this to true to avoid sending JSON * @method setNoJSONRequests * @param val {Boolean} */ }, { key: "setNoJSONRequests", value: function setNoJSONRequests(val) { this.noJSONRequests = val; } }, { key: "setPermissions", value: function setPermissions(permissions) { this.permissions = permissions; } }, { key: "sortingStarted", value: function sortingStarted(val) { this.sorting = val; } /** * Check if the current user has a permission * @method checkPermission * @param permission {String} * @example * this.checkPermission("Upload/Delete Profile Image") */ }, { key: "checkPermission", value: function checkPermission(permission) { if (this.permissions[permission] === undefined || this.permissions[permission] == null || this.permissions[permission] === 'Yes') { return 'Yes'; } return this.permissions[permission]; } }, { key: "setBaseUrl", value: function setBaseUrl(url) { this.baseUrl = url; } }, { key: "setUser", value: function setUser(user) { this.user = user; } }, { key: "getUser", value: function getUser() { return this.user; } }, { key: "setInstanceId", value: function setInstanceId(id) { this.instanceId = id; } }, { key: "setCSRFRequired", value: function setCSRFRequired(val) { this.csrfRequired = val; } }, { key: "scrollToTop", value: function scrollToTop() { $('html, body').animate({ scrollTop: 0 }, 'fast'); } }, { key: "scrollToBottom", value: function scrollToBottom() { $('html, body').animate({ scrollTop: $(document).height() }, 'slow'); } }, { key: "scrollToElement", value: function scrollToElement(element) { if ($(window).height() <= element.offset().top) { $('html, body').animate({ scrollTop: element.offset().top }, 'slow'); } } }, { key: "scrollToElementBottom", value: function scrollToElementBottom(element) { if ($(window).height() <= element.offset().top + element.height()) { $('html, body').animate({ scrollTop: element.offset().top + element.height() }, 'slow'); } } }, { key: "setTranslations", value: function setTranslations(txt) { this.translations = txt.messages['']; } }, { key: "setTranslationsSubModules", value: function setTranslationsSubModules(translations) { this.translations = translations; } }, { key: "gt", value: function gt(key) { if (this.translations[key] === undefined || this.translations[key] === null) { console.log("Tr:" + key); return key; } return this.translations[key][0]; } }, { key: "addToLangTerms", value: function addToLangTerms(key) { var termsArr; var terms = localStorage.getItem('terms'); if (terms === undefined) { termsArr = {}; } else { try { termsArr = JSON.parse(terms); } catch (e) { termsArr = {}; } } if (this.translations[key] === undefined) { termsArr[key] = key; localStorage.setItem('terms', JSON.stringify(termsArr)); } } /** * If this method returned false the action buttons in data table for modules will not be displayed. * Override this method in module lib.js to hide action buttons * @method showActionButtons * @param permission {String} * @example * EmployeeLeaveEntitlementAdapter.method('showActionButtons() { * return false; * } */ }, { key: "showActionButtons", value: function showActionButtons() { return true; } }, { key: "trackEvent", value: function trackEvent(action, label, value) { try { if (label === undefined || label == null) { this.ga.push(['_trackEvent', this.instanceId, action]); } else if (value === undefined || value == null) { this.ga.push(['_trackEvent', this.instanceId, action, label]); } else { this.ga.push(['_trackEvent', this.instanceId, action, label, value]); } } catch (e) {// Do nothing } } }, { key: "setCurrentProfile", value: function setCurrentProfile(currentProfile) { this.currentProfile = currentProfile; } /** * Get the current profile * @method getCurrentProfile * @returns Profile of the current user if the profile is not switched if not switched profile */ }, { key: "getCurrentProfile", value: function getCurrentProfile() { return this.currentProfile; } /** * Retrive data required to create select boxes for add new /edit forms for a given module. This is called when loading the module * @method initFieldMasterData * @param callback {Function} call this once loading completed * @param callback {Function} call this once all field loading completed. This indicate that the form can be displayed saftly * @example * ReportAdapter.method('renderForm(object) { * var that = this; * this.processFormFieldsWithObject(object); * var cb = function(){ * that.super.renderForm(object); * }; * this.initFieldMasterData(cb); * } */ }, { key: "initFieldMasterData", value: function initFieldMasterData(callback, loadAllCallback, loadAllCallbackData) { this.fieldMasterData = {}; this.fieldMasterDataKeys = {}; this.fieldMasterDataCallback = loadAllCallback; this.fieldMasterDataCallbackData = loadAllCallbackData; var remoteSourceFields = this.getRemoteSourceFields(); for (var i = 0; i < remoteSourceFields.length; i++) { var fieldRemote = remoteSourceFields[i]; if (fieldRemote[1]['remote-source'] !== undefined && fieldRemote[1]['remote-source'] != null) { // let key = `${fieldRemote[1]['remote-source'][0]}_${fieldRemote[1]['remote-source'][1]}_${fieldRemote[1]['remote-source'][2]}`; // if (fieldRemote[1]['remote-source'].length === 4) { // key = `${key}_${fieldRemote[1]['remote-source'][3]}`; // } var key = this.getRemoteSourceKey(fieldRemote); this.fieldMasterDataKeys[key] = false; var callBackData = {}; callBackData.callBack = 'initFieldMasterDataResponse'; callBackData.callBackData = [key]; if (callback !== null && callback !== undefined) { callBackData.callBackSuccess = callback; } this.getFieldValues(fieldRemote[1]['remote-source'], callBackData); } } } }, { key: "initSourceMappings", value: function initSourceMappings() { this.sourceMapping = {}; var remoteSourceFields = this.getRemoteSourceFields(); for (var i = 0; i < remoteSourceFields.length; i++) { var fieldRemote = remoteSourceFields[i]; if (fieldRemote[1]['remote-source'] !== undefined && fieldRemote[1]['remote-source'] != null) { this.sourceMapping[fieldRemote[0]] = fieldRemote[1]['remote-source']; } } } }, { key: "getRemoteSourceKey", value: function getRemoteSourceKey(field) { var key = "".concat(field[1]['remote-source'][0], "_").concat(field[1]['remote-source'][1], "_").concat(field[1]['remote-source'][2]); if (field[1]['remote-source'].length > 3) { key = "".concat(key, "_").concat(field[1]['remote-source'][3]); } return key; } }, { key: "getRemoteSourceFields", value: function getRemoteSourceFields() { var values; var fields = this.getFormFields(); var filterFields = this.getFilters(); if (filterFields != null) { for (var j = 0; j < filterFields.length; j++) { values = this.getMetaFieldValues(filterFields[j][0], fields); if (values == null || values.type !== 'select' && values.type !== 'select2' && values.type !== 'select2multi') { fields.push(filterFields[j]); } } } var remoteSourceFields = []; var remoteSourceFieldKeys = []; var field = null; var fieldSub = null; for (var i = 0; i < fields.length; i++) { field = fields[i]; if (field[1]['remote-source'] !== undefined && field[1]['remote-source'] !== null) { var key = this.getRemoteSourceKey(field); if (remoteSourceFieldKeys.indexOf(key) < 0) { remoteSourceFields.push(field); remoteSourceFieldKeys.push(key); } } else if (field[1].form !== undefined && field[1].form !== null) { for (var _j = 0; _j < field[1].form.length; _j++) { fieldSub = field[1].form[_j]; if (fieldSub[1]['remote-source'] !== undefined && fieldSub[1]['remote-source'] !== null) { var _key = this.getRemoteSourceKey(fieldSub); if (remoteSourceFieldKeys.indexOf(_key) < 0) { remoteSourceFields.push(fieldSub); remoteSourceFieldKeys.push(_key); } } } } } return remoteSourceFields; } /** * Pass true to this method after creating module JS object to open new/edit entry form for the module on a popup. * @method setShowFormOnPopup * @param val {Boolean} * @example * modJs.subModJsList['tabCandidateApplication'] = new CandidateApplicationAdapter('Application','CandidateApplication',{"candidate":data.id} * modJs.subModJsList['tabCandidateApplication'].setShowFormOnPopup(true); */ }, { key: "setShowFormOnPopup", value: function setShowFormOnPopup(val) { this.showFormOnPopup = val; } /** * Set this to true to if you need the datatable to load data page by page instead of loading all data at once. * @method setRemoteTable * @param val {Boolean} * @example * modJs.subModJsList['tabCandidateApplication'] = new CandidateApplicationAdapter('Application','CandidateApplication',{"candidate":data.id} * modJs.subModJsList['tabCandidateApplication'].setRemoteTable(true); */ }, { key: "setRemoteTable", value: function setRemoteTable(val) { this.createRemoteTable = val; } }, { key: "setSettings", value: function setSettings(val) { this.settings = val; } }, { key: "getRemoteTable", value: function getRemoteTable() { return this.createRemoteTable; } }, { key: "isAllLoaded", value: function isAllLoaded(fieldMasterDataKeys) { for (var key in fieldMasterDataKeys) { if (fieldMasterDataKeys[key] === false) { return false; } } return true; } // eslint-disable-next-line no-unused-vars }, { key: "initFieldMasterDataResponse", value: function initFieldMasterDataResponse(key, data, callback, loadAllCallbackData) { this.fieldMasterData[key] = data; this.fieldMasterDataKeys[key] = true; if (callback !== undefined && callback !== null) { callback(); } if (this.fieldMasterDataCallback !== null && this.fieldMasterDataCallback !== undefined && this.isAllLoaded(this.fieldMasterDataKeys) && this.fieldMasterDataCallbackData !== null && this.fieldMasterDataCallbackData !== undefined) { this.fieldMasterDataCallback(this.fieldMasterDataCallbackData); } else if (this.fieldMasterDataCallback !== null && this.fieldMasterDataCallback !== undefined && this.isAllLoaded(this.fieldMasterDataKeys)) { this.fieldMasterDataCallback(); } } }, { key: "getMetaFieldValues", value: function getMetaFieldValues(key, fields) { for (var i = 0; i < fields.length; i++) { if (key === fields[i][0]) { return fields[i][1]; } } return null; } }, { key: "getThemeColors", value: function getThemeColors() { var colors = ['red', 'yellow', 'aqua', 'blue', 'light-blue', 'green', 'navy', 'teal', 'olive', 'orange', 'fuchsia', 'purple']; return colors; } }, { key: "getColorByRandomString", value: function getColorByRandomString(string) { var colors = this.getThemeColors(); var k = string.charCodeAt(0); return colors[k % colors.length]; } }, { key: "getColorByFileType", value: function getColorByFileType(type) { type = type.toLowerCase(); var colorMap = {}; colorMap.pdf = 'red'; colorMap.csv = 'yellow'; colorMap.xls = 'green'; colorMap.xlsx = 'green'; colorMap.doc = 'light-blue'; colorMap.docx = 'light-blue'; colorMap.docx = 'blue'; colorMap.ppt = 'orange'; colorMap.pptx = 'orange'; colorMap.jpg = 'teal'; colorMap.jpeg = 'teal'; colorMap.gif = 'green'; colorMap.png = 'yellow'; colorMap.bmp = 'fuchsia'; if (colorMap[type] !== undefined || colorMap[type] != null) { return colorMap[type]; } return this.getColorByRandomString(type); } }, { key: "getIconByFileType", value: function getIconByFileType(type) { type = type.toLowerCase(); var iconMap = {}; iconMap.pdf = 'fa fa-file-pdf-o'; iconMap.csv = 'fa fa fa-file-code-o'; iconMap.xls = 'fa fa-file-excel-o'; iconMap.xlsx = 'fa fa-file-excel-o'; iconMap.doc = 'fa fa-file-word-o'; iconMap.docx = 'fa fa-file-word-o'; iconMap.ppt = 'fa fa-file-powerpoint-o'; iconMap.pptx = 'fa fa-file-powerpoint-o'; iconMap.jpg = 'fa fa-file-image-o'; iconMap.jpeg = 'fa fa-file-image-o'; iconMap.gif = 'fa fa-file-image-o'; iconMap.png = 'fa fa-file-image-o'; iconMap.bmp = 'fa fa-file-image-o'; iconMap.txt = 'fa fa-file-text-o'; iconMap.rtf = 'fa fa-file-text-o'; if (iconMap[type] !== undefined || iconMap[type] != null) { return iconMap[type]; } return 'fa fa-file-o'; } }, { key: "getSourceMapping", value: function getSourceMapping() { return this.sourceMapping; } }, { key: "setTesting", value: function setTesting(testing) { this.testing = testing; } }, { key: "consoleLog", value: function consoleLog(message) { if (this.testing) { console.log(message); } } }, { key: "setClientMessages", value: function setClientMessages(msgList) { this.msgList = msgList; } }, { key: "setTemplates", value: function setTemplates(templates) { this.templates = templates; } }, { key: "getWSProperty", value: function getWSProperty(array, key) { if (array.hasOwnProperty(key)) { return array[key]; } return null; } }, { key: "getClientMessage", value: function getClientMessage(key) { return this.getWSProperty(this.msgList, key); } }, { key: "getTemplate", value: function getTemplate(key) { return this.getWSProperty(this.templates, key); } }, { key: "setGoogleAnalytics", value: function setGoogleAnalytics(gaq) { this.gaq = gaq; } }, { key: "showView", value: function showView(view) { if (this.currentView != null) { this.previousView = this.currentView; $("#".concat(this.currentView)).hide(); } $("#".concat(view)).show(); this.currentView = view; this.moveToTop(); } }, { key: "showPreviousView", value: function showPreviousView() { this.showView(this.previousView); } }, { key: "moveToTop", value: function moveToTop() {} }, { key: "callFunction", value: function callFunction(callback, cbParams, thisParam) { if ($.isFunction(callback)) { try { if (thisParam === undefined || thisParam === null) { callback.apply(document, cbParams); } else { callback.apply(thisParam, cbParams); } } catch (e) { console.log(e.message); } } else { var f = this[callback]; if ($.isFunction(f)) { try { f.apply(this, cbParams); } catch (e) { console.log(e.message); } } } } }, { key: "getTableTopButtonHtml", value: function getTableTopButtonHtml() { var html = ''; if (this.getShowAddNew()) { html = ""); } if (this.getFilters() != null) { if (html !== '') { html += '  '; } html += ""); html += '  '; if (this.filtersAlreadySet) { html += ''; } else { html += ''; } } html = html.replace(/__id__/g, this.getTableName()); if (this.currentFilterString !== '' && this.currentFilterString != null) { html = html.replace(/__filterString__/g, this.currentFilterString); } else { html = html.replace(/__filterString__/g, 'Reset Filters'); } if (html !== '') { html = "
".concat(html, "
"); } return html; } }, { key: "getActionButtonHeader", value: function getActionButtonHeader() { return { sTitle: '', sClass: 'center' }; } }, { key: "getTableHTMLTemplate", value: function getTableHTMLTemplate() { return '
'; } }, { key: "isSortable", value: function isSortable() { return true; } /** * Create the data table on provided element id * @method createTable * @param val {Boolean} */ }, { key: "createTable", value: function createTable(elementId) { var that = this; if (this.getRemoteTable()) { this.createTableServer(elementId); return; } var headers = this.getHeaders(); // add translations for (var index in headers) { headers[index].sTitle = this.gt(headers[index].sTitle); } var data = this.getTableData(); if (this.showActionButtons()) { headers.push(this.getActionButtonHeader()); } if (this.showActionButtons()) { for (var i = 0; i < data.length; i++) { data[i].push(this.getActionButtonsHtml(data[i][0], data[i])); } } var html = ''; html = this.getTableTopButtonHtml() + this.getTableHTMLTemplate(); /* if(this.getShowAddNew()){ html = this.getTableTopButtonHtml()+'
'; }else{ html = '
'; } */ // Find current page var activePage = $("#".concat(elementId, " .dataTables_paginate .active a")).html(); var start = 0; if (activePage !== undefined && activePage != null) { start = parseInt(activePage, 10) * 15 - 15; } $("#".concat(elementId)).html(html); var dataTableParams = { oLanguage: { sLengthMenu: '_MENU_ records per page' }, aaData: data, aoColumns: headers, bSort: that.isSortable(), iDisplayLength: 15, iDisplayStart: start }; var customTableParams = this.getCustomTableParams(); $.extend(dataTableParams, customTableParams); $("#".concat(elementId, " #grid")).dataTable(dataTableParams); $('.dataTables_paginate ul').addClass('pagination'); $('.dataTables_length').hide(); $('.dataTables_filter input').addClass('form-control'); $('.dataTables_filter input').attr('placeholder', 'Search'); $('.dataTables_filter label').contents().filter(function () { return this.nodeType === 3; }).remove(); $('.tableActionButton').tooltip(); } /** * Create a data table on provided element id which loads data page by page * @method createTableServer * @param val {Boolean} */ }, { key: "createTableServer", value: function createTableServer(elementId) { var that = this; var headers = this.getHeaders(); headers.push({ sTitle: '', sClass: 'center' }); // add translations for (var index in headers) { headers[index].sTitle = this.gt(headers[index].sTitle); } var html = ''; html = this.getTableTopButtonHtml() + this.getTableHTMLTemplate(); // Find current page var activePage = $("#".concat(elementId, " .dataTables_paginate .active a")).html(); var start = 0; if (activePage !== undefined && activePage != null) { start = parseInt(activePage, 10) * 15 - 15; } $("#".concat(elementId)).html(html); var dataTableParams = { oLanguage: { sLengthMenu: '_MENU_ records per page' }, bProcessing: true, bServerSide: true, sAjaxSource: that.getDataUrl(that.getDataMapping()), aoColumns: headers, bSort: that.isSortable(), parent: that, iDisplayLength: 15, iDisplayStart: start }; if (this.showActionButtons()) { dataTableParams.aoColumnDefs = [{ fnRender: that.getActionButtons, aTargets: [that.getDataMapping().length] }]; } var customTableParams = this.getCustomTableParams(); $.extend(dataTableParams, customTableParams); $("#".concat(elementId, " #grid")).dataTable(dataTableParams); $('.dataTables_paginate ul').addClass('pagination'); $('.dataTables_length').hide(); $('.dataTables_filter input').addClass('form-control'); $('.dataTables_filter input').attr('placeholder', 'Search'); $('.dataTables_filter label').contents().filter(function () { return this.nodeType === 3; }).remove(); $('.tableActionButton').tooltip(); } /** * This should be overridden in module lib.js classes to return module headers which are used to create the data table. * @method getHeaders * @example SettingAdapter.method('getHeaders() { return [ { "sTitle": "ID" ,"bVisible":false}, { "sTitle": "Name" }, { "sTitle": "Value"}, { "sTitle": "Details"} ]; } */ }, { key: "getHeaders", value: function getHeaders() {} /** * This should be overridden in module lib.js classes to return module field values which are used to create the data table. * @method getDataMapping * @example SettingAdapter.method('getDataMapping() { return [ "id", "name", "value", "description" ]; } */ }, { key: "getDataMapping", value: function getDataMapping() {} /** * This should be overridden in module lib.js classes to return module from fields which are used to create the add/edit form and also used for initializing select box values in form. * @method getFormFields * @example SettingAdapter.method('getFormFields() { return [ [ "id", {"label":"ID","type":"hidden"}], [ "value", {"label":"Value","type":"text","validation":"none"}] ]; } */ }, { key: "getFormFields", value: function getFormFields() {} }, { key: "getTableColumns", value: function getTableColumns() { return []; } }, { key: "getTableData", value: function getTableData() {} /** * This can be overridden in module lib.js classes inorder to show a filter form * @method getFilters * @example EmployeeAdapter.method('getFilters() { return [ [ "job_title", {"label":"Job Title","type":"select2","allow-null":true,"null-label":"All Job Titles","remote-source":["JobTitle","id","name"]}], [ "department", {"label":"Department","type":"select2","allow-null":true,"null-label":"All Departments","remote-source":["CompanyStructure","id","title"]}], [ "supervisor", {"label":"Supervisor","type":"select2","allow-null":true,"null-label":"Anyone","remote-source":["Employee","id","first_name+last_name"]}] ]; } */ }, { key: "getFilters", value: function getFilters() { return null; } /** * Show the edit form for an item * @method edit * @param id {int} id of the item to edit */ }, { key: "edit", value: function edit(id) { this.currentId = id; this.getElement(id, []); } }, { key: "copyRow", value: function copyRow(id) { this.getElement(id, [], true); } }, { key: "renderModel", value: function renderModel(id, header, body) { $("#".concat(id, "ModelBody")).html(''); if (body === undefined || body == null) { body = ''; } $("#".concat(id, "ModelLabel")).html(header); $("#".concat(id, "ModelBody")).html(body); } }, { key: "renderYesNoModel", value: function renderYesNoModel(header, body, yesBtnName, noBtnName, callback, callbackParams) { var that = this; var modelId = '#yesnoModel'; if (body === undefined || body == null) { body = ''; } $("".concat(modelId, "Label")).html(header); $("".concat(modelId, "Body")).html(body); if (yesBtnName != null) { $("".concat(modelId, "YesBtn")).html(yesBtnName); } if (noBtnName != null) { $("".concat(modelId, "NoBtn")).html(noBtnName); } $("".concat(modelId, "YesBtn")).off().on('click', function () { if (callback !== undefined && callback != null) { callback.apply(that, callbackParams); that.cancelYesno(); } }); $(modelId).modal({ backdrop: 'static' }); } }, { key: "renderModelFromDom", value: function renderModelFromDom(id, header, element) { $("#".concat(id, "ModelBody")).html(''); if (element === undefined || element == null) { element = $('
'); } $("#".concat(id, "ModelLabel")).html(header); $("#".concat(id, "ModelBody")).html(''); $("#".concat(id, "ModelBody")).append(element); } /** * Delete an item * @method deleteRow * @param id {int} id of the item to edit */ }, { key: "deleteRow", value: function deleteRow(id) { this.deleteParams.id = id; this.renderModel('delete', 'Confirm Deletion', 'Are you sure you want to delete this item ?'); $('#deleteModel').modal('show'); } /** * Show a popup with message * @method showMessage * @param title {String} title of the message box * @param message {String} message * @param closeCallback {Function} this will be called once the dialog is closed (optional) * @param closeCallback {Function} data to pass to close callback (optional) * @param closeCallbackData * @param isPlain {Boolean} if true buttons are not shown (optional / default = true) * @example * this.showMessage("Error Occured while Applying Leave", callBackData); */ }, { key: "showMessage", value: function showMessage(title, message) { var closeCallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var closeCallbackData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var isPlain = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var that = this; var modelId = ''; if (isPlain) { modelId = '#plainMessageModel'; } else { modelId = '#messageModel'; } $(modelId).off(); if (isPlain) { this.renderModel('plainMessage', title, message); } else { this.renderModel('message', title, message); } if (closeCallback !== null && closeCallback !== undefined) { $(modelId).modal({ show: true }); $(modelId).on('hidden.bs.modal', function () { closeCallback.apply(that, closeCallbackData); $('.modal-backdrop').remove(); }); } else { $(modelId).modal({ backdrop: 'static' }); } } }, { key: "showDomElement", value: function showDomElement(title, element, closeCallback, closeCallbackData, isPlain) { var that = this; var modelId = ''; if (isPlain) { modelId = '#dataMessageModel'; } else { modelId = '#messageModel'; } $(modelId).unbind('hide'); if (isPlain) { this.renderModelFromDom('dataMessage', title, element); } else { this.renderModelFromDom('message', title, element); } if (closeCallback !== null && closeCallback !== undefined) { $(modelId).modal({ show: true }); $(modelId).on('hidden.bs.modal', function () { closeCallback.apply(that, closeCallbackData); $('.modal-backdrop').remove(); }); } else { $(modelId).modal({ backdrop: 'static' }); } } }, { key: "confirmDelete", value: function confirmDelete() { if (this.deleteParams.id !== undefined || this.deleteParams.id != null) { this.deleteObj(this.deleteParams.id, []); } $('#deleteModel').modal('hide'); } }, { key: "cancelDelete", value: function cancelDelete() { $('#deleteModel').modal('hide'); this.deleteParams.id = null; } }, { key: "closeMessage", value: function closeMessage() { $('#messageModel').modal('hide'); } }, { key: "cancelYesno", value: function cancelYesno() { $('#yesnoModel').modal('hide'); } }, { key: "closePlainMessage", value: function closePlainMessage() { $('#plainMessageModel').modal('hide'); $('#dataMessageModel').modal('hide'); } }, { key: "closeDataMessage", value: function closeDataMessage() { $('#dataMessageModel').modal('hide'); } /** * Create or edit an element * @method save * @param getFunctionCallBackData {Array} once a success is returned call get() function for this module with these parameters * @param successCallback {Function} this will get called after success response */ }, { key: "save", value: function save(callGetFunction, successCallback) { var validator = new _FormValidation["default"]("".concat(this.getTableName(), "_submit"), true, { ShowPopup: false, LabelErrorClass: 'error' }); if (validator.checkValues()) { var params = validator.getFormParameters(); params = this.forceInjectValuesBeforeSave(params); var msg = this.doCustomValidation(params); if (msg == null) { if (this.csrfRequired) { params.csrf = $("#".concat(this.getTableName(), "Form")).data('csrf'); } var id = $("#".concat(this.getTableName(), "_submit #id")).val(); if (id != null && id !== undefined && id !== '') { params.id = id; } params = this.makeEmptyDateFieldsNull(params); this.add(params, [], callGetFunction, successCallback); } else { $("#".concat(this.getTableName(), "Form .label")).html(msg); $("#".concat(this.getTableName(), "Form .label")).show(); this.scrollToTop(); } } } }, { key: "makeEmptyDateFieldsNull", value: function makeEmptyDateFieldsNull(params) { var fields = this.getFormFields(); fields.forEach(function (field) { if ((field[1].type === 'date' || field[1].type === 'datetime') && (params[field[0]] === '' || params[field[0]] === '0000-00-00' || params[field[0]] === '0000-00-00 00:00:00')) { if (field[1].validation === 'none') { params[field[0]] = 'NULL'; } else { delete params[field[0]]; } } }); return params; } }, { key: "validatePassword", value: function validatePassword(password) { if (password.length < 8) { return this.gt('Password too short'); } if (password.length > 30) { return this.gt('Password too long'); } var numberTester = /.*[0-9]+.*$/; if (!password.match(numberTester)) { return this.gt('Password must include at least one number'); } var lowerTester = /.*[a-z]+.*$/; if (!password.match(lowerTester)) { return this.gt('Password must include at least one lowercase letter'); } var upperTester = /.*[A-Z]+.*$/; if (!password.match(upperTester)) { return this.gt('Password must include at least one uppercase letter'); } var symbolTester = /.*[\W]+.*$/; if (!password.match(symbolTester)) { return this.gt('Password must include at least one symbol'); } return null; } /** * Override this method to inject attitional parameters or modify existing parameters retrived from * add/edit form before sending to the server * @method forceInjectValuesBeforeSave * @param params {Array} keys and values in form * @returns {Array} modified parameters */ }, { key: "forceInjectValuesBeforeSave", value: function forceInjectValuesBeforeSave(params) { return params; } /** * Override this method to do custom validations at client side * @method doCustomValidation * @param params {Array} keys and values in form * @returns {Null or String} return null if validation success, returns error message if unsuccessful * @example EmployeeLeaveAdapter.method('doCustomValidation(params) { try{ if(params['date_start'] != params['date_end']){ var ds = new Date(params['date_start']); var de = new Date(params['date_end']); if(de < ds){ return "Start date should be earlier than end date of the leave period"; } } }catch(e){ } return null; } */ // eslint-disable-next-line no-unused-vars }, { key: "doCustomValidation", value: function doCustomValidation(params) { return null; } }, { key: "filterQuery", value: function filterQuery() { var validator = new _FormValidation["default"]("".concat(this.getTableName(), "_filter"), true, { ShowPopup: false, LabelErrorClass: 'error' }); if (validator.checkValues()) { var params = validator.getFormParameters(); if (this.doCustomFilterValidation(params)) { // remove null params for (var prop in params) { if (params.hasOwnProperty(prop)) { if (params[prop] === 'NULL') { delete params[prop]; } } } this.setFilter(params); this.filtersAlreadySet = true; $("#".concat(this.getTableName(), "_resetFilters")).show(); this.currentFilterString = this.getFilterString(params); this.get([]); this.closePlainMessage(); } } } }, { key: "getFilterString", value: function getFilterString(filters) { var str = ''; var rmf; var source; var values; var select2MVal; var value; var valueOrig; var filterFields = this.getFilters(); if (values == null) { values = []; } for (var prop in filters) { if (filters.hasOwnProperty(prop)) { values = this.getMetaFieldValues(prop, filterFields); if (!values) { continue; } value = ''; valueOrig = null; if (values.type === 'select' || values.type === 'select2') { if (values['remote-source'] !== undefined && values['remote-source'] != null) { rmf = values['remote-source']; if (filters[prop] === 'NULL') { if (values['null-label'] !== undefined && values['null-label'] != null) { value = values['null-label']; } else { value = 'Not Selected'; } } else { var key = "".concat(rmf[0], "_").concat(rmf[1], "_").concat(rmf[2]); if (rmf.length > 3) { key = "".concat(key, "_").concat(rmf[3]); } //value = this.fieldMasterData[`${rmf[0]}_${rmf[1]}_${rmf[2]}`][filters[prop]]; value = this.fieldMasterData[key][filters[prop]]; valueOrig = value; } } else { source = values.source[0]; if (filters[prop] === 'NULL') { if (values['null-label'] !== undefined && values['null-label'] != null) { value = values['null-label']; } else { value = 'Not Selected'; } } else { for (var i = 0; i < source.length; i++) { if (filters[prop] === values.source[i][0]) { value = values.source[i][1]; valueOrig = value; break; } } } } } else if (values.type === 'select2multi') { select2MVal = []; try { select2MVal = JSON.parse(filters[prop]); } catch (e) {// Do nothing } value = select2MVal.join(','); if (value !== '') { valueOrig = value; } } else { value = filters[prop]; if (value !== '') { valueOrig = value; } } if (valueOrig != null) { if (str !== '') { str += ' | '; } str += "".concat(values.label, " = ").concat(value); } } } return str; } /** * Override this method to do custom validations at client side for values selected in filters * @method doCustomFilterValidation * @param params {Array} keys and values in form * @returns {Null or String} return null if validation success, returns error message if unsuccessful */ }, { key: "doCustomFilterValidation", value: function doCustomFilterValidation(params) { return true; } /** * Reset selected filters * @method resetFilters */ }, { key: "resetFilters", value: function resetFilters() { this.filter = this.origFilter; this.filtersAlreadySet = false; $("#".concat(this.getTableName(), "_resetFilters")).hide(); this.currentFilterString = ''; this.get([]); } }, { key: "showFilters", value: function showFilters(object) { var formHtml = this.templates.filterTemplate; var html = ''; var fields = this.getFilters(); for (var i = 0; i < fields.length; i++) { var metaField = this.getMetaFieldForRendering(fields[i][0]); if (metaField === '' || metaField === undefined) { html += this.renderFormField(fields[i]); } else { var metaVal = object[metaField]; if (metaVal !== '' && metaVal != null && metaVal !== undefined && metaVal.trim() !== '') { html += this.renderFormField(JSON.parse(metaVal)); } else { html += this.renderFormField(fields[i]); } } } formHtml = formHtml.replace(/_id_/g, "".concat(this.getTableName(), "_filter")); formHtml = formHtml.replace(/_fields_/g, html); var randomFormId = this.generateRandom(14); var $tempDomObj = $('
'); $tempDomObj.attr('id', randomFormId); $tempDomObj.html(formHtml); $tempDomObj.find('.datefield').datepicker({ viewMode: 2 }); $tempDomObj.find('.timefield').datetimepicker({ language: 'en', pickDate: false }); $tempDomObj.find('.datetimefield').datetimepicker({ language: 'en' }); $tempDomObj.find('.colorpick').colorpicker(); tinymce.init({ selector: "#".concat($tempDomObj.attr('id'), " .tinymce"), height: '400' }); $tempDomObj.find('.simplemde').each(function () { var simplemde = new SimpleMDE({ element: $(this)[0] }); $(this).data('simplemde', simplemde); // simplemde.value($(this).val()); }); // $tempDomObj.find('.select2Field').select2(); $tempDomObj.find('.select2Field').each(function () { $(this).select2().select2('val', $(this).find('option:eq(0)').val()); }); $tempDomObj.find('.select2Multi').each(function () { $(this).select2().on('change', function (e) { var parentRow = $(this).parents('.row'); var height = parentRow.find('.select2-choices').height(); parentRow.height(parseInt(height, 10)); }); }); /* $tempDomObj.find('.signatureField').each(function() { $(this).data('signaturePad',new SignaturePad($(this))); }); */ // var tHtml = $tempDomObj.wrap('
').parent().html(); this.showDomElement('Edit', $tempDomObj, null, null, true); $('.filterBtn').off(); $('.filterBtn').on('click', function (e) { e.preventDefault(); e.stopPropagation(); try { modJs.filterQuery(); } catch (err) { console.log(err); console.log(err.message); } return false; }); if (this.filter !== undefined && this.filter != null && this.filter !== '') { this.fillForm(this.filter, "#".concat(this.getTableName(), "_filter"), this.getFilters()); } } /** * Override this method in your module class to make changes to data fo the form before showing the form * @method preRenderForm * @param object {Array} keys value list for populating form */ }, { key: "preRenderForm", value: function preRenderForm(object) {} /** * Create the form * @method renderForm * @param object {Array} keys value list for populating form */ }, { key: "renderForm", value: function renderForm(object) { var signatureIds = []; if (object == null || object === undefined) { this.currentId = null; } this.preRenderForm(object); var formHtml = this.templates.formTemplate; var html = ''; var fields = this.getFormFields(); for (var i = 0; i < fields.length; i++) { var metaField = this.getMetaFieldForRendering(fields[i][0]); if (metaField === '' || metaField === undefined) { html += this.renderFormField(fields[i]); } else { var metaVal = object[metaField]; if (metaVal !== '' && metaVal != null && metaVal !== undefined && metaVal.trim() !== '') { html += this.renderFormField(JSON.parse(metaVal)); } else { html += this.renderFormField(fields[i]); } } } formHtml = formHtml.replace(/_id_/g, "".concat(this.getTableName(), "_submit")); formHtml = formHtml.replace(/_fields_/g, html); var $tempDomObj; var randomFormId = this.generateRandom(14); if (!this.showFormOnPopup) { $tempDomObj = $("#".concat(this.getTableName(), "Form")); } else { $tempDomObj = $('
'); $tempDomObj.attr('id', randomFormId); } $tempDomObj.html(formHtml); $tempDomObj.find('.datefield').datepicker({ viewMode: 2 }); $tempDomObj.find('.timefield').datetimepicker({ language: 'en', pickDate: false }); $tempDomObj.find('.datetimefield').datetimepicker({ language: 'en' }); $tempDomObj.find('.colorpick').colorpicker(); tinymce.init({ selector: "#".concat($tempDomObj.attr('id'), " .tinymce"), height: '400' }); $tempDomObj.find('.simplemde').each(function () { var simplemde = new SimpleMDE({ element: $(this)[0] }); $(this).data('simplemde', simplemde); // simplemde.value($(this).val()); }); var codeMirror = this.codeMirror; if (codeMirror) { $tempDomObj.find('.code').each(function () { var editor = codeMirror.fromTextArea($(this)[0], { lineNumbers: false, matchBrackets: true, continueComments: 'Enter', extraKeys: { 'Ctrl-Q': 'toggleComment' } }); $(this).data('codemirror', editor); }); } // $tempDomObj.find('.select2Field').select2(); $tempDomObj.find('.select2Field').each(function () { $(this).select2().select2('val', $(this).find('option:eq(0)').val()); }); $tempDomObj.find('.select2Multi').each(function () { $(this).select2().on('change', function (e) { var parentRow = $(this).parents('.row'); var height = parentRow.find('.select2-choices').height(); parentRow.height(parseInt(height, 10)); }); }); $tempDomObj.find('.signatureField').each(function () { // $(this).data('signaturePad',new SignaturePad($(this))); signatureIds.push($(this).attr('id')); }); for (var _i = 0; _i < fields.length; _i++) { if (fields[_i][1].type === 'datagroup') { $tempDomObj.find("#".concat(fields[_i][0])).data('field', fields[_i]); } } if (this.showSave === false) { $tempDomObj.find('.saveBtn').remove(); } else { $tempDomObj.find('.saveBtn').off(); $tempDomObj.find('.saveBtn').data('modJs', this); $tempDomObj.find('.saveBtn').on('click', function () { if ($(this).data('modJs').saveSuccessItemCallback != null && $(this).data('modJs').saveSuccessItemCallback !== undefined) { $(this).data('modJs').save($(this).data('modJs').retriveItemsAfterSave(), $(this).data('modJs').saveSuccessItemCallback); } else { $(this).data('modJs').save(); } return false; }); } if (this.showCancel === false) { $tempDomObj.find('.cancelBtn').remove(); } else { $tempDomObj.find('.cancelBtn').off(); $tempDomObj.find('.cancelBtn').data('modJs', this); $tempDomObj.find('.cancelBtn').on('click', function () { $(this).data('modJs').cancel(); return false; }); } // Input mask $tempDomObj.find('[mask]').each(function () { $(this).inputmask($(this).attr('mask')); }); $tempDomObj.find('[datemask]').each(function () { $(this).inputmask({ mask: 'y-1-2', placeholder: 'YYYY-MM-DD', leapday: '-02-29', separator: '-', alias: 'yyyy/mm/dd' }); }); $tempDomObj.find('[datetimemask]').each(function () { $(this).inputmask('datetime', { mask: 'y-2-1 h:s:00', placeholder: 'YYYY-MM-DD hh:mm:ss', leapday: '-02-29', separator: '-', alias: 'yyyy/mm/dd' }); }); if (!this.showFormOnPopup) { $("#".concat(this.getTableName(), "Form")).show(); $("#".concat(this.getTableName())).hide(); for (var _i2 = 0; _i2 < signatureIds.length; _i2++) { $("#".concat(signatureIds[_i2])).data('signaturePad', new SignaturePad(document.getElementById(signatureIds[_i2]))); } if (object !== undefined && object != null) { this.fillForm(object); } else { this.setDefaultValues(); } this.scrollToTop(); } else { // var tHtml = $tempDomObj.wrap('
').parent().html(); // this.showMessage("Edit",tHtml,null,null,true); this.showMessage('Edit', '', null, null, true); $('#plainMessageModel .modal-body').html(''); $('#plainMessageModel .modal-body').append($tempDomObj); for (var _i3 = 0; _i3 < signatureIds.length; _i3++) { $("#".concat(signatureIds[_i3])).data('signaturePad', new SignaturePad(document.getElementById(signatureIds[_i3]))); } if (object !== undefined && object != null) { this.fillForm(object, "#".concat(randomFormId)); } else { this.setDefaultValues("#".concat(randomFormId)); } } this.postRenderForm(object, $tempDomObj); } }, { key: "setDefaultValues", value: function setDefaultValues(formId, fields) { if (fields == null || fields === undefined) { fields = this.getFormFields(); } if (formId == null || formId === undefined || formId === '') { formId = "#".concat(this.getTableName(), "Form"); } for (var i = 0; i < fields.length; i++) { if (fields[i][1].type !== 'text' && fields[i][1].type !== 'textarea') { continue; } if (fields[i][1]["default"] !== undefined && fields[i][1]["default"] !== null) { $("".concat(formId, " #").concat(fields[i][0])).val(fields[i][1]["default"]); } } } }, { key: "retriveItemsAfterSave", value: function retriveItemsAfterSave() { return true; } /** * Override this method in your module class to make changes to data fo the form after showing it * @method postRenderForm * @param object {Array} keys value list for populating form * @param $tempDomObj {DOM} a DOM element for the form * @example * UserAdapter.method('postRenderForm(object, $tempDomObj) { if(object == null || object == undefined){ $tempDomObj.find("#changePasswordBtn").remove(); } } */ }, { key: "postRenderForm", value: function postRenderForm(object, $tempDomObj) {} /** * Convert data group field to HTML * @method dataGroupToHtml * @param val {String} value in the field * @param field {Array} field meta data */ }, { key: "dataGroupToHtml", value: function dataGroupToHtml(val, field) { var data = JSON.parse(val); var t; var sortFunction; var item; var itemHtml; var itemVal; var deleteButton = '
  • '; var editButton = '
  • '; var template = field[1].html; if (data != null && data !== undefined && field[1]['sort-function'] !== undefined && field[1]['sort-function'] != null) { data.sort(field[1]['sort-function']); } var html = $("
    ")); for (var i = 0; i < data.length; i++) { item = data[i]; if (field[1]['pre-format-function'] !== undefined && field[1]['pre-format-function'] != null) { item = field[1]['pre-format-function'].apply(this, [item]); } t = template; t = t.replace('#_delete_#', deleteButton); t = t.replace('#_edit_#', editButton); t = t.replace(/#_id_#/g, item.id); for (var key in item) { itemVal = item[key]; if (itemVal !== undefined && itemVal != null && typeof itemVal === 'string') { itemVal = itemVal.replace(/(?:\r\n|\r|\n)/g, '
    '); } t = t.replace("#_".concat(key, "_#"), itemVal); } if (field[1].render !== undefined && field[1].render != null) { t = t.replace('#_renderFunction_#', field[1].render(item)); } itemHtml = $(t); itemHtml.attr('fieldId', "".concat(field[0], "_div")); html.append(itemHtml); } return html; } /** * Reset the DataGroup for a given field * @method resetDataGroup * @param field {Array} field meta data */ }, { key: "resetDataGroup", value: function resetDataGroup(field) { $("#".concat(field[0])).val(''); $("#".concat(field[0], "_div")).html(''); } }, { key: "showDataGroup", value: function showDataGroup(field, object, callback) { var formHtml = this.templates.datagroupTemplate; var html = ''; var fields = field[1].form; if (object !== undefined && object != null && object.id !== undefined) { this.currentDataGroupItemId = object.id; } else { this.currentDataGroupItemId = null; } for (var i = 0; i < fields.length; i++) { html += this.renderFormField(fields[i]); } formHtml = formHtml.replace(/_id_/g, "".concat(this.getTableName(), "_field_").concat(field[0])); formHtml = formHtml.replace(/_fields_/g, html); var randomFormId = this.generateRandom(14); var $tempDomObj = $('
    '); $tempDomObj.attr('id', randomFormId); $tempDomObj.html(formHtml); $tempDomObj.find('.datefield').datepicker({ viewMode: 2 }); $tempDomObj.find('.timefield').datetimepicker({ language: 'en', pickDate: false }); $tempDomObj.find('.datetimefield').datetimepicker({ language: 'en' }); $tempDomObj.find('.colorpick').colorpicker(); tinymce.init({ selector: "#".concat($tempDomObj.attr('id'), " .tinymce"), height: '400' }); $tempDomObj.find('.simplemde').each(function () { var simplemde = new SimpleMDE({ element: $(this)[0] }); $(this).data('simplemde', simplemde); // simplemde.value($(this).val()); }); $tempDomObj.find('.select2Field').each(function () { $(this).select2().select2('val', $(this).find('option:eq(0)').val()); }); $tempDomObj.find('.select2Multi').each(function () { $(this).select2().on('change', function (e) { var parentRow = $(this).parents('.row'); var height = parentRow.find('.select2-choices').height(); parentRow.height(parseInt(height, 10)); }); }); this.currentDataGroupField = field; this.showDomElement("Add ".concat(field[1].label), $tempDomObj, null, null, true); if (object !== undefined && object != null) { this.fillForm(object, "#".concat(this.getTableName(), "_field_").concat(field[0]), field[1].form); } else { this.setDefaultValues("#".concat(this.getTableName(), "_field_").concat(field[0]), field[1].form); } $('.groupAddBtn').off(); if (object !== undefined && object != null && object.id !== undefined) { $('.groupAddBtn').on('click', function (e) { e.preventDefault(); e.stopPropagation(); try { modJs.editDataGroup(callback); } catch (err) { console.log("Error editing data group: ".concat(err.message)); } return false; }); } else { $('.groupAddBtn').on('click', function (e) { e.preventDefault(); e.stopPropagation(); try { modJs.addDataGroup(callback); } catch (err) { console.log("Error adding data group: ".concat(err.message)); } return false; }); } } }, { key: "addDataGroup", value: function addDataGroup(callback, existingData) { var field = this.currentDataGroupField; var tempParams; $("#".concat(this.getTableName(), "_field_").concat(field[0], "_error")).html(''); $("#".concat(this.getTableName(), "_field_").concat(field[0], "_error")).hide(); var validator = new _FormValidation["default"]("".concat(this.getTableName(), "_field_").concat(field[0]), true, { ShowPopup: false, LabelErrorClass: 'error' }); if (validator.checkValues()) { var params = validator.getFormParameters(); if (field[1]['custom-validate-function'] !== undefined && field[1]['custom-validate-function'] != null) { tempParams = field[1]['custom-validate-function'].apply(this, [params]); if (tempParams.valid) { params = tempParams.params; } else { $("#".concat(this.getTableName(), "_field_").concat(field[0], "_error")).html(tempParams.message); $("#".concat(this.getTableName(), "_field_").concat(field[0], "_error")).show(); return false; } } var val = '[]'; if (existingData) { val = existingData; } else { val = $("#".concat(field[0])).val(); if (val === '' || val == null) { val = '[]'; } } var data = JSON.parse(val); params.id = "".concat(field[0], "_").concat(this.dataGroupGetNextAutoIncrementId(data)); data.push(params); if (field[1]['sort-function'] !== undefined && field[1]['sort-function'] != null) { data.sort(field[1]['sort-function']); } val = JSON.stringify(data); var html = this.dataGroupToHtml(val, field); if (callback) { callback(val); } $("#".concat(field[0], "_div")).html(''); $("#".concat(field[0], "_div")).append(html); this.makeDataGroupSortable(field, $("#".concat(field[0], "_div_inner"))); $("#".concat(field[0])).val(val); this.orderDataGroup(field); this.closeDataMessage(); this.showMessage('Item Added', 'This change will be effective only when you save the form'); } return true; } }, { key: "nl2br", value: function nl2br(str, len) { var t = ''; try { var arr = str.split(' '); var count = 0; for (var i = 0; i < arr.length; i++) { count += arr[i].length + 1; if (count > len) { t += "".concat(arr[i], "
    "); count = 0; } else { t += "".concat(arr[i], " "); } } } catch (e) {// Do nothing } return t; } }, { key: "makeDataGroupSortable", value: function makeDataGroupSortable(field, obj) { obj.data('field', field); obj.data('firstSort', true); obj.sortable({ create: function create() { $(this).height($(this).height()); }, 'ui-floating': false, start: function start(e, uiStart) { $('#sortable-ul-selector-id').sortable({ sort: function sort(event, ui) { var $target = $(event.target); if (!/html|body/i.test($target.offsetParent()[0].tagName)) { var top = event.pageY - $target.offsetParent().offset().top - ui.helper.outerHeight(true) / 2; ui.helper.css({ top: "".concat(top, "px") }); } } }); }, revert: true, stop: function stop() { modJs.orderDataGroup($(this).data('field')); }, axis: 'y', scroll: false, placeholder: 'sortable-placeholder', cursor: 'move' }); } }, { key: "orderDataGroup", value: function orderDataGroup(field, callback) { var newArr = []; var id; var list = $("#".concat(field[0], "_div_inner [fieldid='").concat(field[0], "_div']")); var val = $("#".concat(field[0])).val(); if (val === '' || val == null) { val = '[]'; } var data = JSON.parse(val); list.each(function () { id = $(this).attr('id'); for (var index in data) { if (data[index].id === id) { newArr.push(data[index]); break; } } }); $("#".concat(field[0])).val(JSON.stringify(newArr)); if (callback != null) { callback(newArr); } } }, { key: "editDataGroup", value: function editDataGroup(callback, existingData) { var field = this.currentDataGroupField; var id = this.currentDataGroupItemId; var validator = new _FormValidation["default"]("".concat(this.getTableName(), "_field_").concat(field[0]), true, { ShowPopup: false, LabelErrorClass: 'error' }); if (validator.checkValues()) { var params = validator.getFormParameters(); if (field[1]['custom-validate-function'] !== undefined && field[1]['custom-validate-function'] != null) { var tempParams = field[1]['custom-validate-function'].apply(this, [params]); if (tempParams.valid) { params = tempParams.params; } else { $("#".concat(this.getTableName(), "_field_").concat(field[0], "_error")).html(tempParams.message); $("#".concat(this.getTableName(), "_field_").concat(field[0], "_error")).show(); return false; } } if (this.doCustomFilterValidation(params)) { var val = '[]'; if (existingData) { val = existingData; } else { val = $("#".concat(field[0])).val(); if (val === '' || val == null) { val = '[]'; } } var data = JSON.parse(val); var editVal = {}; var editValIndex = -1; var newVals = []; for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.id === id) { editVal = item; editValIndex = i; } newVals.push(item); } params.id = editVal.id; newVals[editValIndex] = params; if (field[1]['sort-function'] !== undefined && field[1]['sort-function'] != null) { newVals.sort(field[1]['sort-function']); } val = JSON.stringify(newVals); $("#".concat(field[0])).val(val); var html = this.dataGroupToHtml(val, field); if (callback) { callback(newVals); } this.orderDataGroup(field); $("#".concat(field[0], "_div")).html(''); $("#".concat(field[0], "_div")).append(html); this.makeDataGroupSortable(field, $("#".concat(field[0], "_div_inner"))); this.closeDataMessage(); this.showMessage('Item Edited', 'This change will be effective only when you save the form'); } } return true; } }, { key: "editDataGroupItem", value: function editDataGroupItem(id, existingData, field) { var fieldId = id.substring(0, id.lastIndexOf('_')); var val; if (existingData) { val = decodeURI(existingData); } else { val = $("#".concat(fieldId)).val(); } var data = JSON.parse(val); var editVal = {}; for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.id === id) { editVal = item; } } if (field) { field = JSON.parse(decodeURI(field)); } else { field = $("#".concat(fieldId)).data('field'); } this.showDataGroup(field, editVal); } }, { key: "dataGroupGetNextAutoIncrementId", value: function dataGroupGetNextAutoIncrementId(data) { var autoId = 1; var id; for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.id === undefined || item.id == null) { item.id = 1; } id = item.id.substring(item.id.lastIndexOf('_') + 1, item.id.length); if (id >= autoId) { autoId = parseInt(id, 10) + 1; } } return autoId; } }, { key: "deleteDataGroupItem", value: function deleteDataGroupItem(id, existingData) { var fieldId = id.substring(0, id.lastIndexOf('_')); var val; if (existingData) { val = decodeURI(existingData); } else { val = $("#".concat(fieldId)).val(); } var data = JSON.parse(val); var newVal = []; for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.id !== id) { newVal.push(item); } } $("#".concat(fieldId)).val(JSON.stringify(newVal)); $("#".concat(id)).remove(); this.showMessage('Item Removed', 'Item removed. This change will be effective only when you save the form'); } /** * Fill a form with required values after showing it * @method fillForm * @param object {Array} form data * @param formId {String} id of the form * @param formId {Array} field meta data */ }, { key: "fillForm", value: function fillForm(object, formId, fields) { var placeHolderVal; if (fields == null || fields === undefined) { fields = this.getFormFields(); } if (formId == null || formId === undefined || formId === '') { formId = "#".concat(this.getTableName(), "Form"); } for (var i = 0; i < fields.length; i++) { if (fields[i][1].type === 'date') { if (object[fields[i][0]] !== '0000-00-00' && object[fields[i][0]] !== '' && object[fields[i][0]] != null && object[fields[i][0]] !== undefined) { $("".concat(formId, " #").concat(fields[i][0], "_date")).datepicker('setValue', object[fields[i][0]]); } } else if (fields[i][1].type === 'colorpick') { if (object[fields[i][0]] != null && object[fields[i][0]] !== undefined) { $("".concat(formId, " #").concat(fields[i][0], "_colorpick")).colorpicker('setValue', object[fields[i][0]]); $("".concat(formId, " #").concat(fields[i][0])).val(object[fields[i][0]]); } } else if (fields[i][1].type === 'datetime' || fields[i][1].type === 'time') { if (object[fields[i][0]] !== '0000-00-00 00:00:00' && object[fields[i][0]] !== '' && object[fields[i][0]] != null && object[fields[i][0]] !== undefined) { var tempDate = object[fields[i][0]]; var arr = tempDate.split(' '); var dateArr = arr[0].split('-'); var timeArr = arr[1].split(':'); $("".concat(formId, " #").concat(fields[i][0], "_datetime")).data('datetimepicker').setLocalDate(new Date(dateArr[0], parseInt(dateArr[1], 10) - 1, dateArr[2], timeArr[0], timeArr[1], timeArr[2])); } } else if (fields[i][1].type === 'label') { $("".concat(formId, " #").concat(fields[i][0])).html(object[fields[i][0]]); } else if (fields[i][1].type === 'placeholder') { if (fields[i][1]['remote-source'] !== undefined && fields[i][1]['remote-source'] != null) { //const key = `${fields[i][1]['remote-source'][0]}_${fields[i][1]['remote-source'][1]}_${fields[i][1]['remote-source'][2]}`; var key = this.getRemoteSourceKey(fields[i]); placeHolderVal = this.fieldMasterData[key][object[fields[i][0]]]; } else { placeHolderVal = object[fields[i][0]]; } if (placeHolderVal === undefined || placeHolderVal == null) { placeHolderVal = ''; } else { try { placeHolderVal = placeHolderVal.replace(/(?:\r\n|\r|\n)/g, '
    '); } catch (e) {// Do nothing } } if (fields[i][1].formatter !== undefined && fields[i][1].formatter && $.isFunction(fields[i][1].formatter)) { try { placeHolderVal = fields[i][1].formatter(placeHolderVal); } catch (e) {// Do nothing } } $("".concat(formId, " #").concat(fields[i][0])).html(placeHolderVal); } else if (fields[i][1].type === 'fileupload') { if (object[fields[i][0]] != null && object[fields[i][0]] !== undefined && object[fields[i][0]] !== '') { $("".concat(formId, " #").concat(fields[i][0])).html(object[fields[i][0]]); $("".concat(formId, " #").concat(fields[i][0])).attr('val', object[fields[i][0]]); $("".concat(formId, " #").concat(fields[i][0])).show(); $("".concat(formId, " #").concat(fields[i][0], "_download")).show(); $("".concat(formId, " #").concat(fields[i][0], "_remove")).show(); } if (fields[i][1].readonly === true) { $("".concat(formId, " #").concat(fields[i][0], "_upload")).remove(); } } else if (fields[i][1].type === 'select') { if (object[fields[i][0]] === undefined || object[fields[i][0]] == null || object[fields[i][0]] === '') { object[fields[i][0]] = 'NULL'; } $("".concat(formId, " #").concat(fields[i][0])).val(object[fields[i][0]]); } else if (fields[i][1].type === 'select2') { if (object[fields[i][0]] === undefined || object[fields[i][0]] == null || object[fields[i][0]] === '') { object[fields[i][0]] = 'NULL'; } $("".concat(formId, " #").concat(fields[i][0])).select2('val', object[fields[i][0]]); } else if (fields[i][1].type === 'select2multi') { // TODO - SM if (object[fields[i][0]] === undefined || object[fields[i][0]] == null || object[fields[i][0]] === '') { object[fields[i][0]] = 'NULL'; } var msVal = []; if (object[fields[i][0]] !== undefined && object[fields[i][0]] != null && object[fields[i][0]] !== '') { try { msVal = JSON.parse(object[fields[i][0]]); } catch (e) {// Do nothing } } $("".concat(formId, " #").concat(fields[i][0])).select2('val', msVal); var select2Height = $("".concat(formId, " #").concat(fields[i][0])).find('.select2-choices').height(); $("".concat(formId, " #").concat(fields[i][0])).find('.controls').css('min-height', "".concat(select2Height, "px")); $("".concat(formId, " #").concat(fields[i][0])).css('min-height', "".concat(select2Height, "px")); } else if (fields[i][1].type === 'datagroup') { try { var html = this.dataGroupToHtml(object[fields[i][0]], fields[i]); $("".concat(formId, " #").concat(fields[i][0])).val(object[fields[i][0]]); $("".concat(formId, " #").concat(fields[i][0], "_div")).html(''); $("".concat(formId, " #").concat(fields[i][0], "_div")).append(html); this.makeDataGroupSortable(fields[i], $("".concat(formId, " #").concat(fields[i][0], "_div_inner"))); } catch (e) {// Do nothing } } else if (fields[i][1].type === 'signature') { if (object[fields[i][0]] !== '' || object[fields[i][0]] !== undefined || object[fields[i][0]] != null) { $("".concat(formId, " #").concat(fields[i][0])).data('signaturePad').fromDataURL(object[fields[i][0]]); } } else if (fields[i][1].type === 'simplemde') { $("".concat(formId, " #").concat(fields[i][0])).data('simplemde').value(object[fields[i][0]]); } else if (fields[i][1].type === 'code') { var cm = $("".concat(formId, " #").concat(fields[i][0])).data('codemirror'); if (cm) { cm.getDoc().setValue(object[fields[i][0]]); } } else { $("".concat(formId, " #").concat(fields[i][0])).val(object[fields[i][0]]); } } } /** * Cancel edit or add new on modules * @method cancel */ }, { key: "cancel", value: function cancel() { $("#".concat(this.getTableName(), "Form")).hide(); $("#".concat(this.getTableName())).show(); } }, { key: "renderFormField", value: function renderFormField(field) { var userId = 0; if (this.fieldTemplates[field[1].type] === undefined || this.fieldTemplates[field[1].type] == null) { return ''; } var t = this.fieldTemplates[field[1].type]; field[1].label = this.gt(field[1].label); if (field[1].validation !== 'none' && field[1].validation !== 'emailOrEmpty' && field[1].validation !== 'numberOrEmpty' && field[1].type !== 'placeholder' && field[1].label.indexOf('*') < 0) { var tempSelectBoxes = ['select', 'select2']; if (!(tempSelectBoxes.indexOf(field[1].type) >= 0 && field[1]['allow-null'] === true)) { field[1].label = "".concat(field[1].label, "*"); } } if (field[1].type === 'select' || field[1].type === 'select2' || field[1].type === 'select2multi') { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); if (field[1].source !== undefined && field[1].source != null) { t = t.replace('_options_', this.renderFormSelectOptions(field[1].source, field)); } else if (field[1]['remote-source'] !== undefined && field[1]['remote-source'] != null) { // let key = `${field[1]['remote-source'][0]}_${field[1]['remote-source'][1]}_${field[1]['remote-source'][2]}`; // if (field[1]['remote-source'].length === 4) { // key = `${key}_${field[1]['remote-source'][3]}`; // } var key = this.getRemoteSourceKey(field); t = t.replace('_options_', this.renderFormSelectOptionsRemote(this.fieldMasterData[key], field)); } } else if (field[1].type === 'colorpick') { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); } else if (field[1].type === 'date') { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); } else if (field[1].type === 'datetime') { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); } else if (field[1].type === 'time') { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); } else if (field[1].type === 'fileupload') { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); var ce = this.getCurrentProfile(); if (ce != null && ce !== undefined) { userId = ce.id; } else { userId = this.getUser().id * -1; } t = t.replace(/_userId_/g, userId); t = t.replace(/_group_/g, this.tab); if (field[1].filetypes !== undefined && field[1].filetypes != null) { t = t.replace(/_filetypes_/g, field[1].filetypes); } else { t = t.replace(/_filetypes_/g, 'all'); } t = t.replace(/_rand_/g, this.generateRandom(14)); } else if (field[1].type === 'datagroup') { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); } else if (field[1].type === 'signature') { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); } else if (field[1].type === 'tinymce' || field[1].type === 'simplemde') { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); } else { t = t.replace(/_id_/g, field[0]); t = t.replace(/_label_/g, field[1].label); } if (field[1].validation !== undefined && field[1].validation != null && field[1].validation !== '') { t = t.replace(/_validation_/g, "validation=\"".concat(field[1].validation, "\"")); } else { t = t.replace(/_validation_/g, ''); } if (field[1].help !== undefined && field[1].help !== null) { t = t.replace(/_helpline_/g, field[1].help); t = t.replace(/_hidden_class_help_/g, ''); } else { t = t.replace(/_helpline_/g, ''); t = t.replace(/_hidden_class_help_/g, 'hide'); } if (field[1].placeholder !== undefined && field[1].placeholder !== null) { t = t.replace(/_placeholder_/g, "placeholder=\"".concat(field[1].placeholder, "\"")); } else { t = t.replace(/_placeholder_/g, ''); } if (field[1].mask !== undefined && field[1].mask !== null) { t = t.replace(/_mask_/g, "mask=\"".concat(field[1].mask, "\"")); } else { t = t.replace(/_mask_/g, ''); } return t; } }, { key: "renderFormSelectOptions", value: function renderFormSelectOptions(options, field) { var html = ''; if (field != null && field !== undefined) { if (field[1]['allow-null'] === true) { if (field[1]['null-label'] !== undefined && field[1]['null-label'] != null) { html += ""); } else { html += ''; } } } // Sort options var tuples = []; for (var key in options) { tuples.push(options[key]); } if (field[1].sort === true) { tuples.sort(function (a, b) { a = a[1]; b = b[1]; // eslint-disable-next-line no-nested-ternary return a < b ? -1 : a > b ? 1 : 0; }); } for (var i = 0; i < tuples.length; i++) { var prop = tuples[i][0]; var value = tuples[i][1]; var t = ''; t = t.replace('_id_', prop); t = t.replace('_val_', this.gt(value)); html += t; } return html; } }, { key: "renderFormSelectOptionsRemote", value: function renderFormSelectOptionsRemote(options, field) { var html = ''; if (field[1]['allow-null'] === true) { if (field[1]['null-label'] !== undefined && field[1]['null-label'] != null) { html += ""); } else { html += ''; } } // Sort options var tuples = []; for (var key in options) { tuples.push([key, options[key]]); } if (field[1].sort === 'true') { tuples.sort(function (a, b) { a = a[1]; b = b[1]; // eslint-disable-next-line no-nested-ternary return a < b ? -1 : a > b ? 1 : 0; }); } for (var i = 0; i < tuples.length; i++) { var prop = tuples[i][0]; var value = tuples[i][1]; var t = ''; t = t.replace('_id_', prop); t = t.replace('_val_', this.gt(value)); html += t; } return html; } }, { key: "setCustomTemplates", value: function setCustomTemplates(templates) { this.customTemplates = templates; } }, { key: "setEmailTemplates", value: function setEmailTemplates(templates) { this.emailTemplates = templates; } }, { key: "getCustomTemplate", value: function getCustomTemplate(file) { return this.customTemplates[file]; } }, { key: "setFieldTemplates", value: function setFieldTemplates(templates) { this.fieldTemplates = templates; } }, { key: "getMetaFieldForRendering", value: function getMetaFieldForRendering(fieldName) { return ''; } }, { key: "clearDeleteParams", value: function clearDeleteParams() { this.deleteParams = {}; } }, { key: "getShowAddNew", value: function getShowAddNew() { return this.showAddNew; } /** * Override this method to change add new button label * @method getAddNewLabel */ }, { key: "getAddNewLabel", value: function getAddNewLabel() { return 'Add New'; } /** * Used to set whether to show the add new button for a module * @method setShowAddNew * @param showAddNew {Boolean} value */ }, { key: "setShowAddNew", value: function setShowAddNew(showAddNew) { this.showAddNew = showAddNew; } /** * Used to set whether to show delete button for each entry in module * @method setShowDelete * @param val {Boolean} value */ }, { key: "setShowDelete", value: function setShowDelete(val) { this.showDelete = val; } /** * Used to set whether to show edit button for each entry in module * @method setShowEdit * @param val {Boolean} value */ }, { key: "setShowEdit", value: function setShowEdit(val) { this.showEdit = val; } /** * Used to set whether to show save button in form * @method setShowSave * @param val {Boolean} value */ }, { key: "setShowSave", value: function setShowSave(val) { this.showSave = val; } /** * Used to set whether to show cancel button in form * @method setShowCancel * @param val {Boolean} value */ }, { key: "setShowCancel", value: function setShowCancel(val) { this.showCancel = val; } /** * Datatable option array will be extended with associative array provided here * @method getCustomTableParams * @param val {Boolean} value */ }, { key: "getCustomTableParams", value: function getCustomTableParams() { return {}; } }, { key: "getActionButtons", value: function getActionButtons(obj) { return modJs.getActionButtonsHtml(obj.aData[0], obj.aData); } /** * This return html for action buttons in each row. Override this method if you need to make changes to action buttons. * @method getActionButtonsHtml * @param id {int} id of the row * @param data {Array} data for the row * @returns {String} html for action buttons */ }, { key: "getActionButtonsHtml", value: function getActionButtonsHtml(id, data) { var editButton = ''; var deleteButton = ''; var cloneButton = ''; var html = '
    _edit__delete__clone_
    '; if (this.showAddNew) { html = html.replace('_clone_', cloneButton); } else { html = html.replace('_clone_', ''); } if (this.showDelete) { html = html.replace('_delete_', deleteButton); } else { html = html.replace('_delete_', ''); } if (this.showEdit) { html = html.replace('_edit_', editButton); } else { html = html.replace('_edit_', ''); } html = html.replace(/_id_/g, id); html = html.replace(/_BASE_/g, this.baseUrl); return html; } /** * Generates a random string * @method generateRandom * @param length {int} required length of the string * @returns {String} random string */ }, { key: "generateRandom", value: function generateRandom(length) { var d = new Date(); var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var result = ''; for (var i = length; i > 0; --i) { result += chars[Math.round(Math.random() * (chars.length - 1))]; } return result + d.getTime(); } }, { key: "checkFileType", value: function checkFileType(elementName, fileTypes) { var fileElement = document.getElementById(elementName); var fileExtension = ''; if (fileElement.value.lastIndexOf('.') > 0) { fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf('.') + 1, fileElement.value.length); } fileExtension = fileExtension.toLowerCase(); var allowed = fileTypes.split(','); if (allowed.indexOf(fileExtension) < 0) { fileElement.value = ''; this.showMessage('File Type Error', 'Selected file type is not supported'); this.clearFileElement(elementName); return false; } return true; } }, { key: "clearFileElement", value: function clearFileElement(elementName) { var control = $("#".concat(elementName)); control.replaceWith(control = control.val('').clone(true)); } }, { key: "fixJSON", value: function fixJSON(json) { if (this.noJSONRequests === '1') { json = window.btoa(json); } return json; } }, { key: "getClientDate", value: function getClientDate(date) { var offset = this.getClientGMTOffset(); var tzDate = date.addMinutes(offset * 60); return tzDate; } }, { key: "getClientGMTOffset", value: function getClientGMTOffset() { var rightNow = new Date(); var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0); var temp = jan1.toGMTString(); var jan2 = new Date(temp.substring(0, temp.lastIndexOf(' ') - 1)); return (jan1 - jan2) / (1000 * 60 * 60); } /** * Override this method in a module to provide the help link for the module. Help link of the module on frontend will get updated with this. * @method getHelpLink * @returns {String} help link */ }, { key: "getHelpLink", value: function getHelpLink() { return null; } }, { key: "showLoader", value: function showLoader() { $('#iceloader').show(); } }, { key: "hideLoader", value: function hideLoader() { $('#iceloader').hide(); } }, { key: "generateOptions", value: function generateOptions(data) { var template = ''; var options = ''; for (var index in data) { options += template.replace('__val__', index).replace('__text__', data[index]); } return options; } }, { key: "isModuleInstalled", value: function isModuleInstalled(type, name) { if (modulesInstalled === undefined || modulesInstalled === null) { return false; } return modulesInstalled["".concat(type, "_").concat(name)] === 1; } }, { key: "setCustomFields", value: function setCustomFields(fields) { var field; var parsed; for (var i = 0; i < fields.length; i++) { field = fields[i]; if (field.display !== 'Hidden' && field.data !== '' && field.data !== undefined) { try { parsed = JSON.parse(field.data); if (parsed === undefined || parsed == null) { continue; } else if (parsed.length !== 2) { continue; } else if (parsed[1].type === undefined || parsed[1].type == null) { continue; } this.customFields.push(parsed); } catch (e) {// Do nothing } } } } }, { key: "addCustomFields", value: function addCustomFields(fields) { for (var i = 0; i < this.customFields.length; i++) { fields.push(this.customFields[i]); } return fields; } }, { key: "getImageUrlFromName", value: function getImageUrlFromName(firstName, lastName) { var seed = firstName.substring(0, 1); if (!lastName && lastName.length > 0) { seed += firstName.substring(firstName.length - 1, 1); } else { seed += lastName.substring(0, 1); } var arr = "".concat(firstName).concat(lastName).split(''); seed += arr.reduce(function (acc, item) { return parseInt(item.charCodeAt(0), 10) + acc; }, 0); return "https://avatars.dicebear.com/api/initials/:".concat(seed, ".svg"); } }]); return ModuleBase; }(); var _default = ModuleBase; exports["default"] = _default; },{"./FormValidation":56}],63:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _ReactModalAdapterBase = _interopRequireDefault(require("./ReactModalAdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /* * CustomFieldAdapter */ var ReactCustomFieldAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(ReactCustomFieldAdapter, _AdapterBase); var _super = _createSuper(ReactCustomFieldAdapter); function ReactCustomFieldAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, ReactCustomFieldAdapter); _this = _super.call(this, endPoint, tab, filter, orderBy); _this.tableType = ''; return _this; } _createClass(ReactCustomFieldAdapter, [{ key: "getDataMapping", value: function getDataMapping() { return ['id', 'name', 'field_type', 'field_label', 'display', 'display_order']; } }, { key: "getHeaders", value: function getHeaders() { return [{ sTitle: 'ID', bVisible: false }, { sTitle: 'Name' }, { sTitle: 'Field Type' }, { sTitle: 'Field Label' }, { sTitle: 'Display Status' }, { sTitle: 'Priority' }]; } }, { key: "getTableColumns", value: function getTableColumns() { return [{ title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Field Label', dataIndex: 'field_label' }, { title: 'Field Type', dataIndex: 'field_type' }, { title: 'Display Status', dataIndex: 'display', sorter: true }, { title: 'Priority', dataIndex: 'display_order', sorter: true }]; } }, { key: "getFormFields", value: function getFormFields() { return [['id', { label: 'ID', type: 'hidden' }], ['field_label', { label: 'Field Label', type: 'text', validation: '' }], ['field_type', { label: 'Field Type', type: 'select', source: [['text', 'Text Field'], ['textarea', 'Text Area'], ['select', 'Select'], ['select2', 'Select2'], ['select2multi', 'Multi Select'], ['fileupload', 'File Upload'], ['date', 'Date'], ['datetime', 'Date Time'], ['time', 'Time'], ['signature', 'Signature']] }], ['field_validation', { label: 'Validation', type: 'select2', validation: 'none', sort: 'none', 'null-label': 'Required', 'allow-null': true, source: [['none', 'None'], ['number', 'Number'], ['numberOrEmpty', 'Number or Empty'], ['float', 'Decimal'], ['email', 'Email'], ['emailOrEmpty', 'Email or Empty']] }], ['field_options', { label: 'Field Options', type: 'datagroup', form: [['label', { label: 'Label', type: 'text', validation: '' }], ['value', { label: 'Value', type: 'text', validation: 'none' }]], html: '
    #_delete_##_edit_##_label_#:#_value_#
    ', columns: [{ title: 'Label', dataIndex: 'label', key: 'label' }, { title: 'Option Value', dataIndex: 'value', key: 'value' }], validation: 'none' }], ['display_order', { label: 'Priority', type: 'text', validation: 'none' }]]; } }, { key: "getNameFromFieldName", value: function getNameFromFieldName(fieldName) { return fieldName.replace(/[^a-z0-9+]+/gi, '').toLowerCase(); } }, { key: "setTableType", value: function setTableType(type) { this.tableType = type; } }, { key: "doCustomValidation", value: function doCustomValidation(params) { var validateName = function validateName(str) { var name = /^[a-z][a-z0-9._]+$/; return str != null && name.test(str); }; if (this.currentElement == null || this.currentElement.name == null || this.currentElement.name === '') { params.name = this.getNameFromFieldName(params.field_label); if (!validateName(params.name)) { return 'Invalid field label for custom field'; } } else { params.name = this.currentElement.name; } if (!validateName(params.name)) { return 'Invalid name for custom field'; } return null; } }, { key: "forceInjectValuesBeforeSave", value: function forceInjectValuesBeforeSave(params) { var data = ['', {}]; var options = []; var optionsData; data[1].label = params.field_label; data[1].type = params.field_type; data[1].validation = params.field_validation; if (['select', 'select2', 'select2multi'].indexOf(params.field_type) >= 0) { optionsData = params.field_options === '' || params.field_options === undefined ? [] : JSON.parse(params.field_options); for (var index in optionsData) { options.push([optionsData[index].value, optionsData[index].label]); } data[1].source = options; } if (params.field_validation == null || params.field_validation === undefined) { params.field_validation = ''; } params.type = this.tableType; if (this.currentElement == null || this.currentElement.name == null || this.currentElement.name === '') { params.name = this.getNameFromFieldName(params.field_label); } else { params.name = this.currentElement.name; } data[0] = params.name; params.data = JSON.stringify(data); params.display = 'Form'; params.display_order = parseInt(params.display_order); if (!Number.isInteger(params.display_order)) { params.display_order = 1; } return params; } }]); return ReactCustomFieldAdapter; }(_ReactModalAdapterBase["default"]); var _default = ReactCustomFieldAdapter; exports["default"] = _default; },{"./ReactModalAdapterBase":65,"antd":"antd","react":"react"}],64:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _ReactModalAdapterBase = _interopRequireDefault(require("./ReactModalAdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var ReactLegacyModalAdapterBase = /*#__PURE__*/function (_ReactModalAdapterBas) { _inherits(ReactLegacyModalAdapterBase, _ReactModalAdapterBas); var _super = _createSuper(ReactLegacyModalAdapterBase); function ReactLegacyModalAdapterBase() { _classCallCheck(this, ReactLegacyModalAdapterBase); return _super.apply(this, arguments); } _createClass(ReactLegacyModalAdapterBase, [{ key: "get", // Due to having same method in ReactModalAdapterBase value: function get(callBackData) { var that = this; if (this.getRemoteTable()) { this.createTableServer(this.getTableName()); $("#".concat(this.getTableName(), "Form")).hide(); $("#".concat(this.getTableName())).show(); return; } var sourceMappingJson = JSON.stringify(this.getSourceMapping()); var filterJson = ''; if (this.getFilter() !== null) { filterJson = JSON.stringify(this.getFilter()); } var orderBy = ''; if (this.getOrderBy() !== null) { orderBy = this.getOrderBy(); } sourceMappingJson = this.fixJSON(sourceMappingJson); filterJson = this.fixJSON(filterJson); that.showLoader(); $.post(this.moduleRelativeURL, { t: this.table, a: 'get', sm: sourceMappingJson, ft: filterJson, ob: orderBy }, function (data) { if (data.status === 'SUCCESS') { that.getSuccessCallBack(callBackData, data.object); } else { that.getFailCallBack(callBackData, data.object); } }, 'json').fail(function (e) { if (e.status === 403) { that.showMessage('Access Forbidden', e.responseJSON.message); } }).always(function () { that.hideLoader(); }); that.initFieldMasterData(); this.trackEvent('get', this.tab, this.table); // var url = this.getDataUrl(); // console.log(url); } }, { key: "showFilters", value: function showFilters(object) { var formHtml = this.templates.filterTemplate; var html = ''; var fields = this.getFilters(); for (var i = 0; i < fields.length; i++) { var metaField = this.getMetaFieldForRendering(fields[i][0]); if (metaField === '' || metaField === undefined) { html += this.renderFormField(fields[i]); } else { var metaVal = object[metaField]; if (metaVal !== '' && metaVal != null && metaVal !== undefined && metaVal.trim() !== '') { html += this.renderFormField(JSON.parse(metaVal)); } else { html += this.renderFormField(fields[i]); } } } formHtml = formHtml.replace(/_id_/g, "".concat(this.getTableName(), "_filter")); formHtml = formHtml.replace(/_fields_/g, html); var randomFormId = this.generateRandom(14); var $tempDomObj = $('
    '); $tempDomObj.attr('id', randomFormId); $tempDomObj.html(formHtml); $tempDomObj.find('.datefield').datepicker({ viewMode: 2 }); $tempDomObj.find('.timefield').datetimepicker({ language: 'en', pickDate: false }); $tempDomObj.find('.datetimefield').datetimepicker({ language: 'en' }); $tempDomObj.find('.colorpick').colorpicker(); tinymce.init({ selector: "#".concat($tempDomObj.attr('id'), " .tinymce"), height: '400' }); $tempDomObj.find('.simplemde').each(function () { var simplemde = new SimpleMDE({ element: $(this)[0] }); $(this).data('simplemde', simplemde); // simplemde.value($(this).val()); }); // $tempDomObj.find('.select2Field').select2(); $tempDomObj.find('.select2Field').each(function () { $(this).select2().select2('val', $(this).find('option:eq(0)').val()); }); $tempDomObj.find('.select2Multi').each(function () { $(this).select2().on('change', function (e) { var parentRow = $(this).parents('.row'); var height = parentRow.find('.select2-choices').height(); parentRow.height(parseInt(height, 10)); }); }); /* $tempDomObj.find('.signatureField').each(function() { $(this).data('signaturePad',new SignaturePad($(this))); }); */ // var tHtml = $tempDomObj.wrap('
    ').parent().html(); this.showDomElement('Edit', $tempDomObj, null, null, true); $('.filterBtn').off(); $('.filterBtn').on('click', function (e) { e.preventDefault(); e.stopPropagation(); try { modJs.filterQuery(); } catch (err) {// Do Nothing } return false; }); if (this.filter !== undefined && this.filter != null && this.filter !== '') { this.fillForm(this.filter, "#".concat(this.getTableName(), "_filter"), this.getFilters()); } } }, { key: "resetFilters", value: function resetFilters() { this.filter = this.origFilter; this.filtersAlreadySet = false; $("#".concat(this.getTableName(), "_resetFilters")).hide(); this.currentFilterString = ''; this.get([]); } }]); return ReactLegacyModalAdapterBase; }(_ReactModalAdapterBase["default"]); var _default = ReactLegacyModalAdapterBase; exports["default"] = _default; },{"./ReactModalAdapterBase":65}],65:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _reactDom = _interopRequireDefault(require("react-dom")); var _antd = require("antd"); var _icons = require("@ant-design/icons"); var _AdapterBase2 = _interopRequireDefault(require("./AdapterBase")); var _IceFormModal = _interopRequireDefault(require("../components/IceFormModal")); var _IceStepFromModal = _interopRequireDefault(require("../components/IceStepFromModal")); var _IceTable = _interopRequireDefault(require("../components/IceTable")); var _MasterDataReader = _interopRequireDefault(require("./MasterDataReader")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var ReactModalAdapterBase = /*#__PURE__*/function (_AdapterBase) { _inherits(ReactModalAdapterBase, _AdapterBase); var _super = _createSuper(ReactModalAdapterBase); _createClass(ReactModalAdapterBase, null, [{ key: "MODAL_TYPE_NORMAL", get: function get() { return 'Normal'; } }, { key: "MODAL_TYPE_STEPS", get: function get() { return 'Steps'; } }]); function ReactModalAdapterBase(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, ReactModalAdapterBase); _this = _super.call(this, endPoint, tab, filter, orderBy); _this.modalType = _this.MODAL_TYPE_NORMAL; _this.dataPipe = null; _this.formInitialized = false; _this.tableInitialized = false; _this.access = []; _this.localStorageEnabled = false; _this.isV2 = true; _this.masterDataReader = new _MasterDataReader["default"](_assertThisInitialized(_this)); return _this; } _createClass(ReactModalAdapterBase, [{ key: "enableLocalStorage", value: function enableLocalStorage() { this.localStorageEnabled = true; } }, { key: "setModalType", value: function setModalType(type) { this.modalType = type; } }, { key: "setDataPipe", value: function setDataPipe(dataPipe) { this.dataPipe = dataPipe; } }, { key: "setAccess", value: function setAccess(access) { this.access = access; } }, { key: "hasAccess", value: function hasAccess(type) { return this.access.indexOf(type) > 0; } }, { key: "hasCustomButtons", value: function hasCustomButtons() { return false; } }, { key: "initTable", value: function initTable() { var _this2 = this; if (this.tableInitialized) { return false; } var tableDom = document.getElementById("".concat(this.tab, "Table")); if (tableDom) { this.tableContainer = _react["default"].createRef(); var columns = this.getTableColumns(); if (this.hasAccess('save') || this.hasAccess('delete') || this.hasAccess('element') || this.hasCustomButtons()) { columns.push({ title: 'Actions', key: 'actions', render: this.getTableActionButtonJsx(this) }); } columns = columns.map(function (item) { item.title = _this2.gt(item.title); return item; }); _reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(_IceTable["default"], { ref: this.tableContainer, reader: this.dataPipe, columns: columns, adapter: this }, this.getTableChildComponents()), tableDom); } this.tableInitialized = true; return true; } }, { key: "initForm", value: function initForm() { var _this3 = this; if (this.formInitialized) { return false; } this.formContainer = _react["default"].createRef(); if (this.modalType === this.MODAL_TYPE_NORMAL) { _reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(_IceFormModal["default"], { ref: this.formContainer, fields: this.getFormFields(), adapter: this, formReference: this.formReference }), document.getElementById("".concat(this.tab, "Form"))); } else { _reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(_IceStepFromModal["default"], { ref: this.formContainer, fields: this.getMappedFields(), adapter: this, formReference: this.formReference }), document.getElementById("".concat(this.tab, "Form"))); } var filterDom = document.getElementById("".concat(this.tab, "FilterForm")); if (filterDom && this.getFilters()) { this.filtersContainer = _react["default"].createRef(); _reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(_IceFormModal["default"], { ref: this.filtersContainer, fields: this.getFilters(), adapter: this, saveCallback: function saveCallback(values, showError, closeModal) { _this3.setFilter(values); _this3.filtersAlreadySet = true; _this3.get([]); _this3.tableContainer.current.setFilterData(values); closeModal(); } }), filterDom); } this.formInitialized = true; return true; } }, { key: "getTableChildComponents", value: function getTableChildComponents() { return false; } }, { key: "reloadCurrentElement", value: function reloadCurrentElement() { this.viewElement(this.currentId); } }, { key: "getTableActionButtonJsx", value: function getTableActionButtonJsx(adapter) { return function (text, record) { return /*#__PURE__*/_react["default"].createElement(_antd.Space, { size: "middle" }, adapter.hasAccess('save') && adapter.showEdit && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "green", onClick: function onClick() { return modJs.edit(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.EditOutlined, null), " ".concat(adapter.gt('Edit'))), adapter.hasAccess('element') && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "blue", onClick: function onClick() { return modJs.viewElement(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.MonitorOutlined, null), " ".concat(adapter.gt('View'))), adapter.hasAccess('delete') && adapter.showDelete && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "volcano", onClick: function onClick() { return modJs.deleteRow(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.DeleteOutlined, null), " ".concat(adapter.gt('Delete'))), adapter.hasAccess('save') && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "cyan", onClick: function onClick() { return modJs.copyRow(record.id); }, style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.CopyOutlined, null), " ".concat(adapter.gt('Copy')))); }; } }, { key: "setTableLoading", value: function setTableLoading(value) { this.tableContainer.current.setLoading(value); } /** * Show the view form for an item * @method viewElement * @param id {int} id of the item to view */ }, { key: "viewElement", value: function viewElement(id) { var _this4 = this; this.setTableLoading(true); this.currentId = id; this.getElement(id, { noRender: true, callBack: function callBack(element) { _this4.showElement(element); _this4.setTableLoading(false); } }); } }, { key: "showElement", value: function showElement(element) { this.renderForm(element, true); } /** * Show the edit form for an item * @method edit * @param id {int} id of the item to edit */ }, { key: "edit", value: function edit(id) { this.setTableLoading(true); this.currentId = id; this.getElement(id, []); } }, { key: "renderForm", value: function renderForm() { var object = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var viewOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (object == null) { this.currentId = null; this.currentElement = null; } this.setTableLoading(false); this.initForm(); this.formContainer.current.setViewOnly(viewOnly); this.formContainer.current.show(object); } }, { key: "showFilters", value: function showFilters() { this.initForm(); this.filtersContainer.current.show(this.filter); } }, { key: "resetFilters", value: function resetFilters() { this.filter = this.origFilter; this.filtersAlreadySet = false; this.currentFilterString = ''; this.get([]); this.tableContainer.current.setFilterData(this.filter); } }, { key: "get", value: function get() { var _this5 = this; if (this.tableContainer && this.tableContainer.current) { this.tableContainer.current.setCurrentElement(null); } this.initTable(); this.masterDataReader.updateAllMasterData().then(function () { _this5.tableContainer.current.reload(); }); this.trackEvent('get', this.tab, this.table); } }, { key: "showLoader", value: function showLoader() {// $('#iceloader').show(); } }, { key: "addActualFieldsForStepModal", value: function addActualFieldsForStepModal(steps, fields) { return steps.map(function (item) { item.fields = item.fields.reduce(function (acc, fieldName) { var field = fields.find(function (_ref) { var _ref2 = _slicedToArray(_ref, 1), name = _ref2[0]; return name === fieldName; }); if (field) { acc.push(field); } return acc; }, []); return item; }); } }, { key: "getFormOptions", value: function getFormOptions() { return { width: 1024, twoColumnLayout: false }; } }]); return ReactModalAdapterBase; }(_AdapterBase2["default"]); var _default = ReactModalAdapterBase; exports["default"] = _default; },{"../components/IceFormModal":71,"../components/IceStepFromModal":76,"../components/IceTable":77,"./AdapterBase":52,"./MasterDataReader":61,"@ant-design/icons":"@ant-design/icons","antd":"antd","react":"react","react-dom":"react-dom"}],66:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _AdapterBase2 = _interopRequireDefault(require("./AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @class SubAdapterBase * @param endPoint * @param tab * @param filter * @param orderBy * @returns */ var SubAdapterBase = /*#__PURE__*/function (_AdapterBase) { _inherits(SubAdapterBase, _AdapterBase); var _super = _createSuper(SubAdapterBase); function SubAdapterBase() { _classCallCheck(this, SubAdapterBase); return _super.apply(this, arguments); } _createClass(SubAdapterBase, [{ key: "deleteRow", value: function deleteRow(id) { this.deleteParams.id = id; this.confirmDelete(); } }, { key: "createTable", value: function createTable(elementId) { var item; var itemHtml; var itemDelete; var itemEdit; var data = this.getTableData(); var deleteButton = ""); var editButton = ""); var table = $('
    '); // add Header var header = this.getSubHeader(); table.append(header); if (data.length === 0) { table.append("".concat(this.getNoDataMessage(), "")); } else { for (var i = 0; i < data.length; i++) { item = data[i]; itemDelete = deleteButton.replace(/_id_/g, item[0]); itemEdit = editButton.replace(/_id_/g, item[0]); itemHtml = this.getSubItemHtml(item, itemDelete, itemEdit); table.append(itemHtml); } } $("#".concat(elementId)).html(''); $("#".concat(elementId)).append(table); $('#plainMessageModel').modal('hide'); } }, { key: "getNoDataMessage", value: function getNoDataMessage() { return 'No data found'; } }, { key: "getSubHeader", value: function getSubHeader() { var header = $("

    ".concat(this.getSubHeaderTitle(), "

    ")); return header; } }]); return SubAdapterBase; }(_AdapterBase2["default"]); var _default = SubAdapterBase; exports["default"] = _default; },{"./AdapterBase":52}],67:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _AdapterBase2 = _interopRequireDefault(require("./AdapterBase")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * TableEditAdapter */ var TableEditAdapter = /*#__PURE__*/function (_AdapterBase) { _inherits(TableEditAdapter, _AdapterBase); var _super = _createSuper(TableEditAdapter); function TableEditAdapter(endPoint, tab, filter, orderBy) { var _this; _classCallCheck(this, TableEditAdapter); _this = _super.call(this, endPoint, tab, filter, orderBy); _this.cellDataUpdates = {}; _this.modulePath = ''; _this.rowFieldName = ''; _this.columnFieldName = ''; _this.rowTable = ''; _this.columnTable = ''; _this.valueTable = ''; _this.csvData = []; _this.columnIDMap = {}; return _this; } _createClass(TableEditAdapter, [{ key: "setModulePath", value: function setModulePath(path) { this.modulePath = path; } }, { key: "setRowFieldName", value: function setRowFieldName(name) { this.rowFieldName = name; } }, { key: "setTables", value: function setTables(rowTable, columnTable, valueTable) { this.rowTable = rowTable; this.columnTable = columnTable; this.valueTable = valueTable; } }, { key: "setColumnFieldName", value: function setColumnFieldName(name) { this.columnFieldName = name; } }, { key: "getDataMapping", value: function getDataMapping() { return []; } }, { key: "getFormFields", value: function getFormFields() { return []; } }, { key: "get", value: function get() { this.getAllData(); } }, { key: "getAllData", value: function getAllData(save) { var req = {}; req.rowTable = this.rowTable; req.columnTable = this.columnTable; req.valueTable = this.valueTable; req = this.addAdditionalRequestData('getAllData', req); req.save = save === undefined || save == null || save === false ? 0 : 1; var reqJson = JSON.stringify(req); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'getAllDataSuccessCallBack'; callBackData.callBackFail = 'getAllDataFailCallBack'; this.customAction('getAllData', this.modulePath, reqJson, callBackData); } }, { key: "getDataItem", value: function getDataItem(row, column, allData) { var columnData = allData[1]; var rowData = allData[0]; var serverData = allData[2]; if (column === -1) { return rowData[row].name; } return this.getDataItemByKeyValues(this.rowFieldName, rowData[row].id, this.columnFieldName, columnData[column].id, serverData); } }, { key: "getDataItemByKeyValues", value: function getDataItemByKeyValues(rowKeyName, rowKeyVal, colKeyName, colKeyVal, data) { for (var i = 0; i < data.length; i++) { if (data[i][rowKeyName] === rowKeyVal && data[i][colKeyName] === colKeyVal) { return data[i].amount !== undefined && data[i].amount != null ? data[i].amount : ''; } } return ''; } }, { key: "getAllDataSuccessCallBack", value: function getAllDataSuccessCallBack(allData) { var serverData = allData[2]; var columnData = allData[1]; var rowData = allData[0]; var data = []; for (var i = 0; i < rowData.length; i++) { var row = []; for (var j = -1; j < columnData.length; j++) { row[j + 1] = this.getDataItem(i, j, allData); } data.push(this.preProcessTableData(row)); } this.sourceData = serverData; this.tableData = data; this.setHeaders(columnData, rowData); this.createTable(this.getTableName()); $("#".concat(this.getTableName(), "Form")).hide(); $("#".concat(this.getTableName())).show(); this.csvData = []; var tmpRow = []; for (var _i = 0; _i < columnData.length; _i++) { tmpRow.push(columnData[_i].name); } tmpRow = this.modifyCSVHeader(tmpRow); this.csvData.push(tmpRow); for (var _i2 = 0; _i2 < data.length; _i2++) { this.csvData.push(data[_i2]); } } }, { key: "modifyCSVHeader", value: function modifyCSVHeader(header) { return header; } }, { key: "getAllDataFailCallBack", value: function getAllDataFailCallBack(callBackData, serverData) {} }, { key: "setHeaders", value: function setHeaders(columns, rows) { var headers = []; headers.push({ sTitle: '', sWidth: '180px;' }); var sclass = ''; this.columnIDMap = {}; for (var i = 0; i < columns.length; i++) { this.columnIDMap[columns[i].id] = i; if (columns[i].editable === undefined || columns[i].editable == null || columns[i].editable === 'Yes') { sclass = 'editcell'; } else { sclass = ''; } headers.push({ sTitle: columns[i].name, sClass: sclass, fnCreatedCell: function fnCreatedCell(nTd, sData, oData, iRow, iCol) { $(nTd).data('colId', columns[iCol - 1].id); $(nTd).data('rowId', rows[iRow].id); } }); } this.headers = headers; } }, { key: "getHeaders", value: function getHeaders() { return this.headers; } }, { key: "createTable", value: function createTable(elementId) { var data = this.getTableData(); var headers = this.getHeaders(); if (this.showActionButtons()) { headers.push({ sTitle: '', sClass: 'center' }); } if (this.showActionButtons()) { for (var i = 0; i < data.length; i++) { data[i].push(this.getActionButtonsHtml(data[i][0], data[i])); } } var html = ''; html = "".concat(this.getTableTopButtonHtml(), "
    "); // Find current page var activePage = $("#".concat(elementId, " .dataTables_paginate .active a")).html(); var start = 0; if (activePage !== undefined && activePage != null) { start = parseInt(activePage, 10) * 15 - 15; } $("#".concat(elementId)).html(html); var dataTableParams = { oLanguage: { sLengthMenu: '_MENU_ records per page' }, aaData: data, aoColumns: headers, bSort: false, iDisplayLength: 15, iDisplayStart: start }; var customTableParams = this.getCustomTableParams(); $.extend(dataTableParams, customTableParams); $("#".concat(elementId, " #grid")).dataTable(dataTableParams); $('.dataTables_paginate ul').addClass('pagination'); $('.dataTables_length').hide(); $('.dataTables_filter input').addClass('form-control'); $('.dataTables_filter input').attr('placeholder', 'Search'); $('.dataTables_filter label').contents().filter(function () { return this.nodeType === 3; }).remove(); // $('.tableActionButton').tooltip(); $("#".concat(elementId, " #grid")).editableTableWidget(); $("#".concat(elementId, " #grid .editcell")).on('validate', function (evt, newValue) { return modJs.validateCellValue($(this), evt, newValue); }); this.afterCreateTable(elementId); } }, { key: "afterCreateTable", value: function afterCreateTable(elementId) {} }, { key: "addCellDataUpdate", value: function addCellDataUpdate(colId, rowId, data) { this.cellDataUpdates["".concat(colId, "=").concat(rowId)] = [colId, rowId, data]; } }, { key: "addAdditionalRequestData", value: function addAdditionalRequestData(type, req) { return req; } }, { key: "sendCellDataUpdates", value: function sendCellDataUpdates() { var req = this.cellDataUpdates; req.rowTable = this.rowTable; req.columnTable = this.columnTable; req.valueTable = this.valueTable; req = this.addAdditionalRequestData('updateData', req); var reqJson = JSON.stringify(req); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'updateDataSuccessCallBack'; callBackData.callBackFail = 'updateDataFailCallBack'; this.showLoader(); this.customAction('updateData', this.modulePath, reqJson, callBackData); } }, { key: "updateDataSuccessCallBack", value: function updateDataSuccessCallBack(callBackData, serverData) { this.hideLoader(); modJs.cellDataUpdates = {}; modJs.get(); } }, { key: "updateDataFailCallBack", value: function updateDataFailCallBack(callBackData, serverData) { this.hideLoader(); } }, { key: "sendAllCellDataUpdates", value: function sendAllCellDataUpdates() { var req = this.cellDataUpdates; req.rowTable = this.rowTable; req.columnTable = this.columnTable; req.valueTable = this.valueTable; req = this.addAdditionalRequestData('updateAllData', req); var reqJson = JSON.stringify(req); var callBackData = []; callBackData.callBackData = []; callBackData.callBackSuccess = 'updateDataAllSuccessCallBack'; callBackData.callBackFail = 'updateDataAllFailCallBack'; this.showLoader(); this.customAction('updateAllData', this.modulePath, reqJson, callBackData); } }, { key: "updateDataAllSuccessCallBack", value: function updateDataAllSuccessCallBack(callBackData, serverData) { this.hideLoader(); modJs.cellDataUpdates = {}; modJs.getAllData(true); } }, { key: "updateDataAllFailCallBack", value: function updateDataAllFailCallBack(callBackData, serverData) { this.hideLoader(); } }, { key: "showActionButtons", value: function showActionButtons() { return false; } }]); return TableEditAdapter; }(_AdapterBase2["default"]); var _default = TableEditAdapter; exports["default"] = _default; },{"./AdapterBase":52}],68:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireWildcard(require("react")); var _reactColor = require("react-color"); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function useComponentVisible(initialIsVisible) { var _useState = (0, _react.useState)(initialIsVisible), _useState2 = _slicedToArray(_useState, 2), isComponentVisible = _useState2[0], setIsComponentVisible = _useState2[1]; var ref = (0, _react.useRef)(null); var handleClickOutside = function handleClickOutside(event) { if (ref.current && !ref.current.contains(event.target)) { setIsComponentVisible(false); } }; (0, _react.useEffect)(function () { document.addEventListener('click', handleClickOutside, true); return function () { document.removeEventListener('click', handleClickOutside, true); }; }); return { ref: ref, isComponentVisible: isComponentVisible, setIsComponentVisible: setIsComponentVisible }; } function IceColorPick(props) { var value = props.value, onChange = props.onChange, readOnly = props.readOnly; var _useComponentVisible = useComponentVisible(true), ref = _useComponentVisible.ref, isComponentVisible = _useComponentVisible.isComponentVisible, setIsComponentVisible = _useComponentVisible.setIsComponentVisible; var _useState3 = (0, _react.useState)(value || '#FFF'), _useState4 = _slicedToArray(_useState3, 2), color = _useState4[0], setColor = _useState4[1]; var _useState5 = (0, _react.useState)(false), _useState6 = _slicedToArray(_useState5, 2), showPicker = _useState6[0], setShowPicker = _useState6[1]; (0, _react.useEffect)(function () { if (!isComponentVisible) { setShowPicker(false); } }, [isComponentVisible]); (0, _react.useEffect)(function () { if (value) { setColor(value); } }, [value]); return /*#__PURE__*/_react["default"].createElement("div", { className: "colorpicker-container" }, /*#__PURE__*/_react["default"].createElement("div", { className: "colorpicker-preview", onClick: function onClick() { if (!showPicker) { setIsComponentVisible(true); } setShowPicker(!showPicker); }, style: { backgroundColor: color } }), /*#__PURE__*/_react["default"].createElement("div", { ref: ref, className: "colorpicker-component ".concat(readOnly || !showPicker ? 'hidden' : '') }, /*#__PURE__*/_react["default"].createElement(_reactColor.SketchPicker, { color: color, disableAlpha: true, presetColors: [], onChangeComplete: function onChangeComplete(_ref) { var hex = _ref.hex; onChange(hex); setColor(hex); } }))); } var _default = IceColorPick; exports["default"] = _default; },{"react":"react","react-color":354}],69:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _IceFormModal = _interopRequireDefault(require("./IceFormModal")); var _reactDom = _interopRequireDefault(require("react-dom")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Option = _antd.Select.Option; var IceDataGroup = /*#__PURE__*/function (_React$Component) { _inherits(IceDataGroup, _React$Component); var _super = _createSuper(IceDataGroup); function IceDataGroup(props) { var _this; _classCallCheck(this, IceDataGroup); _this = _super.call(this, props); _this.state = {}; _this.onChange = props.onChange; _this.formReference = _react["default"].createRef(); return _this; } _createClass(IceDataGroup, [{ key: "render", value: function render() { var _this2 = this; var _this$props = this.props, field = _this$props.field, adapter = _this$props.adapter; var value = this.props.value; value = this.parseValue(value); value = value.map(function (item) { return _objectSpread({}, item, { key: item.id }); }); var columns = JSON.parse(JSON.stringify(field[1].columns)); if (!this.props.readOnly) { columns.push({ title: 'Action', key: 'action', render: function render(text, record) { return _this2.getDefaultButtons(record.id); } }); } return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, !this.props.readOnly && /*#__PURE__*/_react["default"].createElement(_antd.Space, { direction: "horizontal" }, /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "link", htmlType: "button", onClick: function onClick() { _this2.createForm(field, adapter, {}); } }, "Add"), /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "link", htmlType: "button", danger: true, onClick: function onClick() { _this2.resetDataGroup(); } }, "Reset")), /*#__PURE__*/_react["default"].createElement(_antd.Table, { columns: columns, dataSource: value })); } }, { key: "createForm", value: function createForm(field, adapter, object) { this.formContainer = _react["default"].createRef(); var formFields = field[1].form; formFields.unshift(['id', { label: 'ID', type: 'hidden' }]); _reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(_IceFormModal["default"], { ref: this.formContainer, fields: formFields, title: this.props.title, adapter: adapter, formReference: this.formReference, saveCallback: this.save.bind(this), cancelCallback: this.unmountForm.bind(this) }), document.getElementById('dataGroup')); this.formContainer.current.show(object); } }, { key: "unmountForm", value: function unmountForm() { _reactDom["default"].unmountComponentAtNode(document.getElementById('dataGroup')); } }, { key: "show", value: function show(data) { var _this3 = this; if (!data) { this.setState({ visible: true }); this.updateFields(data); } else { this.setState({ visible: true }); if (this.formReference.current) { this.updateFields(data); } else { this.waitForIt(function () { return _this3.formReference.current != null; }, function () { _this3.updateFields(data); }, 100); } } } }, { key: "parseValue", value: function parseValue(value) { try { value = JSON.parse(value); } catch (e) { value = []; } if (value == null) { value = []; } return value; } }, { key: "save", value: function save(params, errorCallback, closeCallback) { var _this$props2 = this.props, field = _this$props2.field, value = _this$props2.value; if (field[1]['custom-validate-function'] != null) { var tempParams = field[1]['custom-validate-function'].apply(this, [params]); if (tempParams.valid) { params = tempParams.params; } else { errorCallback(tempParams.message); return false; } } var data = this.parseValue(value); var newData = []; if (!params.id) { params.id = "".concat(field[0], "_").concat(this.dataGroupGetNextAutoIncrementId(data)); data.push(params); newData = data; } else { for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.id !== params.id) { newData.push(item); } else { newData.push(params); } } } if (field[1]['sort-function'] != null) { newData.sort(field[1]['sort-function']); } var val = JSON.stringify(newData); this.onChange(val); this.unmountForm(); } }, { key: "createCard", value: function createCard(item) { var field = this.props.field; if (field[1]['pre-format-function'] != null) { item = field[1]['pre-format-function'].apply(this, [item]); } var template = field[1].html; var t = template.replace('#_delete_#', ''); t = t.replace('#_edit_#', ''); t = t.replace(/#_id_#/g, item.id); for (var key in item) { var itemVal = item[key]; if (itemVal !== undefined && itemVal != null && typeof itemVal === 'string') { itemVal = itemVal.replace(/(?:\r\n|\r|\n)/g, '
    '); } t = t.replace("#_".concat(key, "_#"), itemVal); } if (field[1].render !== undefined && field[1].render != null) { t = t.replace('#_renderFunction_#', field[1].render(item)); } return /*#__PURE__*/_react["default"].createElement(_antd.Card, { key: item.id, title: "", extra: this.getDefaultButtons(item.id) }, /*#__PURE__*/_react["default"].createElement("div", { dangerouslySetInnerHTML: { __html: t } })); } }, { key: "getDefaultButtons", value: function getDefaultButtons(id) { var _this4 = this; return /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement("a", { href: "#", onClick: function onClick() { _this4.editDataGroupItem(id); } }, /*#__PURE__*/_react["default"].createElement("li", { className: "fa fa-edit" })), /*#__PURE__*/_react["default"].createElement("a", { href: "#", onClick: function onClick() { _this4.deleteDataGroupItem(id); } }, /*#__PURE__*/_react["default"].createElement("li", { className: "fa fa-times" }))); } }, { key: "deleteDataGroupItem", value: function deleteDataGroupItem(id) { var value = this.props.value; var data = this.parseValue(value); var newVal = []; for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.id !== id) { newVal.push(item); } } var val = JSON.stringify(newVal); this.onChange(val); } }, { key: "editDataGroupItem", value: function editDataGroupItem(id) { var _this$props3 = this.props, field = _this$props3.field, adapter = _this$props3.adapter, value = _this$props3.value; var data = this.parseValue(value); var editVal = {}; for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.id === id) { editVal = item; } } this.createForm(field, adapter, editVal); } }, { key: "resetDataGroup", value: function resetDataGroup() { this.onChange('[]'); } }, { key: "dataGroupGetNextAutoIncrementId", value: function dataGroupGetNextAutoIncrementId(data) { var autoId = 1; var id; for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.id === undefined || item.id == null) { item.id = 1; } id = item.id.substring(item.id.lastIndexOf('_') + 1, item.id.length); if (id >= autoId) { autoId = parseInt(id, 10) + 1; } } return autoId; } }]); return IceDataGroup; }(_react["default"].Component); var _default = IceDataGroup; exports["default"] = _default; },{"./IceFormModal":71,"antd":"antd","react":"react","react-dom":"react-dom"}],70:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _moment = _interopRequireDefault(require("moment")); var _IceUpload = _interopRequireDefault(require("./IceUpload")); var _IceDataGroup = _interopRequireDefault(require("./IceDataGroup")); var _IceSelect = _interopRequireDefault(require("./IceSelect")); var _IceLabel = _interopRequireDefault(require("./IceLabel")); var _IceColorPick = _interopRequireDefault(require("./IceColorPick")); var _IceSignature = _interopRequireDefault(require("./IceSignature")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var ValidationRules = { "float": function float(str) { var floatstr = /^[-+]?[0-9]+(\.[0-9]+)?$/; if (str != null && str.match(floatstr)) { return true; } return false; }, number: function number(str) { var numstr = /^[0-9]+$/; if (str != null && str.match(numstr)) { return true; } return false; }, numberOrEmpty: function numberOrEmpty(str) { if (str === '') { return true; } var numstr = /^[0-9]+$/; if (str != null && str.match(numstr)) { return true; } return false; }, email: function email(str) { var emailPattern = /^\s*[\w\-+_]+(\.[\w\-+_]+)*@[\w\-+_]+\.[\w\-+_]+(\.[\w\-+_]+)*\s*$/; return str != null && emailPattern.test(str); }, emailOrEmpty: function emailOrEmpty(str) { if (str === '') { return true; } var emailPattern = /^\s*[\w\-+_]+(\.[\w\-+_]+)*@[\w\-+_]+\.[\w\-+_]+(\.[\w\-+_]+)*\s*$/; return str != null && emailPattern.test(str); }, username: function username(str) { var username = /^[a-zA-Z0-9.-]+$/; return str != null && username.test(str); } }; var IceForm = /*#__PURE__*/function (_React$Component) { _inherits(IceForm, _React$Component); var _super = _createSuper(IceForm); function IceForm(props) { var _this; _classCallCheck(this, IceForm); _this = _super.call(this, props); _this.validationRules = {}; _this.state = { validations: {}, errorMsg: false }; _this.formReference = _react["default"].createRef(); return _this; } _createClass(IceForm, [{ key: "showError", value: function showError(errorMsg) { this.setState({ errorMsg: errorMsg }); } }, { key: "hideError", value: function hideError() { this.setState({ errorMsg: false }); } }, { key: "isReady", value: function isReady() { return this.formReference.current != null; } }, { key: "validateFields", value: function validateFields() { return this.formReference.current.validateFields(); } }, { key: "render", value: function render() { var _this$props = this.props, fields = _this$props.fields, twoColumnLayout = _this$props.twoColumnLayout, adapter = _this$props.adapter; var formInputs = []; var formInputs1 = []; var formInputs2 = []; var columns = !twoColumnLayout ? 1 : 2; for (var i = 0; i < fields.length; i++) { formInputs.push(adapter.beforeRenderFieldHook(fields[i][0], this.createFromField(fields[i], this.props.viewOnly), fields[i][1])); } formInputs = formInputs.filter(function (input) { return !!input; }); for (var _i = 0; _i < formInputs.length; _i++) { if (formInputs[_i] != null) { if (columns === 1) { formInputs1.push(formInputs[_i]); } else if (_i % 2 === 0) { formInputs1.push(formInputs[_i]); } else { formInputs2.push(formInputs[_i]); } } } var onFormLayoutChange = function onFormLayoutChange() {}; return /*#__PURE__*/_react["default"].createElement(_antd.Form, { ref: this.formReference, labelCol: { span: 6 }, wrapperCol: { span: 16 }, layout: this.props.layout || 'horizontal', initialValues: { size: 'middle' }, onValuesChange: onFormLayoutChange, size: "middle" }, this.state.errorMsg && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_antd.Alert, { message: this.state.errorMsg, type: "error", showIcon: true }), /*#__PURE__*/_react["default"].createElement("br", null)), columns === 1 && formInputs1, columns === 2 && /*#__PURE__*/_react["default"].createElement(_antd.Row, { gutter: 16 }, /*#__PURE__*/_react["default"].createElement(_antd.Col, { className: "gutter-row", span: 12 }, formInputs1), /*#__PURE__*/_react["default"].createElement(_antd.Col, { className: "gutter-row", span: 12 }, formInputs2))); } }, { key: "isValid", value: function isValid() { var _this2 = this; return Object.keys(this.validationRules).reduce(function (acc, fieldName) { return acc && (_this2.state[fieldName] === 'success' || _this2.state[fieldName] == null); }, true); } }, { key: "validateOnChange", value: function validateOnChange(event) { var validationRule = this.validationRules[event.target.id]; var validations = this.state.validations; if (validationRule) { if (validationRule.rule(event.target.value)) { this.state[event.target.id] = 'success'; this.state["".concat(event.target.id, "_message")] = null; } else { this.state[event.target.id] = 'error'; this.state["".concat(event.target.id, "_message")] = validationRule.message; } } this.setState({ validations: validations }); } }, { key: "createFromField", value: function createFromField(field) { var viewOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var userId = 0; var rules = []; var requiredRule = { required: true }; var _field = _slicedToArray(field, 2), name = _field[0], data = _field[1]; var _this$props2 = this.props, adapter = _this$props2.adapter, layout = _this$props2.layout; var validationRule = null; data.label = adapter.gt(data.label); var labelSpan = layout === 'vertical' ? { span: 24 } : { span: 6 }; var tempSelectBoxes = ['select', 'select2', 'select2multi']; if (tempSelectBoxes.indexOf(data.type) >= 0 && data['allow-null'] === true) { requiredRule.required = false; } else if (data.validation === 'none' || data.validation === 'emailOrEmpty' || data.validation === 'numberOrEmpty') { requiredRule.required = false; } else { requiredRule.required = true; requiredRule.message = this.generateFieldMessage(data.label); } rules.push(requiredRule); if (data.type === 'hidden') { requiredRule.required = false; return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, style: { display: 'none' }, label: data.label, key: name, name: name, rules: rules }, /*#__PURE__*/_react["default"].createElement(_antd.Input, null)); } if (data.type === 'text') { if (data.validation) { data.validation = data.validation.replace('OrEmpty', ''); validationRule = this.getValidationRule(data); if (validationRule) { this.validationRules[name] = { rule: validationRule, message: "Invalid value for ".concat(data.label) }; } } if (validationRule != null) { return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, label: data.label, key: name, name: name, rules: rules, validateStatus: this.state[name], help: this.state["".concat(name, "_message")] }, viewOnly ? /*#__PURE__*/_react["default"].createElement(_IceLabel["default"], null) : /*#__PURE__*/_react["default"].createElement(_antd.Input, { onChange: this.validateOnChange.bind(this) })); } return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, label: data.label, key: name, name: name, rules: rules }, viewOnly ? /*#__PURE__*/_react["default"].createElement(_IceLabel["default"], null) : /*#__PURE__*/_react["default"].createElement(_antd.Input, null)); } if (data.type === 'textarea') { if (!data.rows) { data.rows = 4; } return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, label: data.label, key: name, name: name, rules: rules }, viewOnly ? /*#__PURE__*/_react["default"].createElement(_IceLabel["default"], null) : /*#__PURE__*/_react["default"].createElement(_antd.Input.TextArea, { rows: data.rows })); } if (data.type === 'date') { return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, label: data.label, key: name, name: name, rules: rules }, /*#__PURE__*/_react["default"].createElement(_antd.DatePicker, { disabled: viewOnly })); } if (data.type === 'datetime') { return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, label: data.label, key: name, name: name, rules: rules }, /*#__PURE__*/_react["default"].createElement(_antd.DatePicker, { format: "YYYY-MM-DD HH:mm:ss", disabled: viewOnly })); } if (data.type === 'time') { return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, label: data.label, key: name, name: name, rules: rules }, /*#__PURE__*/_react["default"].createElement(_antd.TimePicker, { format: "HH:mm", disabled: viewOnly })); } if (data.type === 'fileupload') { var currentEmployee = adapter.getCurrentProfile(); if (currentEmployee != null) { userId = currentEmployee.id; } else { userId = adapter.getUser().id * -1; } if (data.filetypes == null) { data.filetypes = '.doc,.docx,.xml,' + 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,' + 'image/*,' + '.pdf'; } return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, name: name, key: name, label: data.label }, /*#__PURE__*/_react["default"].createElement(_IceUpload["default"], { user: userId, fileGroup: adapter.tab, fileName: name, adapter: adapter, accept: data.filetypes, readOnly: viewOnly })); } if (data.type === 'datagroup') { return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, name: name, key: name, label: data.label }, /*#__PURE__*/_react["default"].createElement(_IceDataGroup["default"], { adapter: adapter, field: field, title: data.label, readOnly: viewOnly })); } if (data.type === 'select2' || data.type === 'select' || data.type === 'select2multi') { return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, label: data.label, key: name, name: name, rules: rules }, /*#__PURE__*/_react["default"].createElement(_IceSelect["default"], { adapter: adapter, field: field, readOnly: viewOnly })); } if (data.type === 'colorpick') { return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, name: name, key: name, label: data.label }, /*#__PURE__*/_react["default"].createElement(_IceColorPick["default"], { adapter: adapter, field: field, title: data.label, readOnly: viewOnly })); } if (data.type === 'signature') { return /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { labelCol: labelSpan, label: data.label, key: name, name: name, rules: rules }, /*#__PURE__*/_react["default"].createElement(_IceSignature["default"], { readOnly: viewOnly })); } return null; } }, { key: "generateFieldMessage", value: function generateFieldMessage(label) { return "".concat(label, ": ").concat(this.props.adapter.gt('is required')); } }, { key: "getValidationRule", value: function getValidationRule(data) { if (ValidationRules[data.validation] == null) { return null; } return ValidationRules[data.validation]; } }, { key: "dataToFormFields", value: function dataToFormFields(data, fields) { for (var i = 0; i < fields.length; i++) { var _fields$i = _slicedToArray(fields[i], 2), key = _fields$i[0], formInputData = _fields$i[1]; if (formInputData.type === 'date') { data[key] = data[key] ? (0, _moment["default"])(data[key], 'YYYY-MM-DD') : null; } else if (formInputData.type === 'datetime') { data[key] = data[key] ? (0, _moment["default"])(data[key], 'YYYY-MM-DD HH:mm:ss') : null; } else if (formInputData.type === 'time') { data[key] = data[key] ? (0, _moment["default"])(data[key], 'HH:mm') : null; } } return data; } }, { key: "formFieldsToData", value: function formFieldsToData(params, fields) { for (var i = 0; i < fields.length; i++) { var _fields$i2 = _slicedToArray(fields[i], 2), key = _fields$i2[0], formInputData = _fields$i2[1]; if (formInputData.type === 'date') { params[key] = params[key] ? params[key].format('YYYY-MM-DD') : 'NULL'; } else if (formInputData.type === 'datetime') { params[key] = params[key] ? params[key].format('YYYY-MM-DD HH:mm:ss') : 'NULL'; } else if (formInputData.type === 'time') { params[key] = params[key] ? params[key].format('HH:mm') : 'NULL'; } else if ((formInputData.type === 'select' || formInputData.type === 'select2') && params[key] == null) { params[key] = 'NULL'; } } return params; } }, { key: "updateFields", value: function updateFields(data) { var fields = this.props.fields; data = this.dataToFormFields(data, fields); this.formReference.current.resetFields(); if (data == null) { return; } try { this.formReference.current.setFieldsValue(data); } catch (e) { console.log(e); } } }, { key: "resetFields", value: function resetFields() { this.formReference.current.resetFields(); } }, { key: "setFieldsValue", value: function setFieldsValue(data) { this.formReference.current.setFieldsValue(data); } }, { key: "save", value: function save(params, success) { var _this3 = this; var _this$props3 = this.props, adapter = _this$props3.adapter, fields = _this$props3.fields; var values = params; values = adapter.forceInjectValuesBeforeSave(values); var msg = adapter.doCustomValidation(values); if (msg !== null) { this.showError(msg); return; } if (adapter.csrfRequired) { values.csrf = $("#".concat(adapter.getTableName(), "Form")).data('csrf'); } var id = adapter.currentElement != null ? adapter.currentElement.id : null; if (id != null && id !== '') { values.id = id; } values = this.formFieldsToData(values, fields); adapter.add(values, [], function () { return adapter.get([]); }, function () { _this3.formReference.current.resetFields(); _this3.showError(false); success(); }); } }]); return IceForm; }(_react["default"].Component); var _default = IceForm; exports["default"] = _default; },{"./IceColorPick":68,"./IceDataGroup":69,"./IceLabel":72,"./IceSelect":73,"./IceSignature":74,"./IceUpload":78,"antd":"antd","moment":"moment","react":"react"}],71:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _IceForm = _interopRequireDefault(require("./IceForm")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var IceFormModal = /*#__PURE__*/function (_React$Component) { _inherits(IceFormModal, _React$Component); var _super = _createSuper(IceFormModal); function IceFormModal(props) { var _this; _classCallCheck(this, IceFormModal); _this = _super.call(this, props); _this.state = { visible: false, viewOnly: false, loading: false }; _this.iceFormReference = _react["default"].createRef(); _this.width = 800; return _this; } _createClass(IceFormModal, [{ key: "setViewOnly", value: function setViewOnly(value) { this.setState({ viewOnly: value }); } }, { key: "show", value: function show(data) { var _this2 = this; this.props.adapter.beforeRenderFieldHook = this.props.adapter.beforeRenderField ? this.props.adapter.beforeRenderField(data) : function (fieldName, field) { return field; }; if (!data) { this.setState({ visible: true }); if (this.iceFormReference.current) { this.iceFormReference.current.resetFields(); } } else { this.setState({ visible: true }); if (this.iceFormReference.current && this.iceFormReference.current.isReady()) { this.iceFormReference.current.updateFields(data); } else { this.waitForIt(function () { return _this2.iceFormReference.current && _this2.iceFormReference.current.isReady(); }, function () { _this2.iceFormReference.current.updateFields(data); }, 1000); } } } }, { key: "waitForIt", value: function waitForIt(condition, callback, time) { var _this3 = this; setTimeout(function () { if (condition()) { callback(); } else { _this3.waitForIt(condition, callback, time); } }, time); } }, { key: "hide", value: function hide() { this.setState({ visible: false }); } }, { key: "save", value: function save(params) { var _this4 = this; this.iceFormReference.current.save(params, function () { _this4.closeModal(); }); } }, { key: "closeModal", value: function closeModal() { this.hide(); this.iceFormReference.current.showError(false); } }, { key: "render", value: function render() { var _this5 = this; var _this$props = this.props, fields = _this$props.fields, adapter = _this$props.adapter, saveCallback = _this$props.saveCallback, cancelCallback = _this$props.cancelCallback; var additionalProps = {}; additionalProps.footer = /*#__PURE__*/_react["default"].createElement(_antd.Row, { gutter: 16 }, /*#__PURE__*/_react["default"].createElement(_antd.Col, { className: "gutter-row", span: 12, style: {} }), /*#__PURE__*/_react["default"].createElement(_antd.Col, { className: "gutter-row", span: 12, style: { textAlign: 'right' } }, /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement(_antd.Button, { onClick: function onClick() { if (cancelCallback) { cancelCallback(); } else { _this5.closeModal(); } } }, this.props.adapter.gt('Cancel')), /*#__PURE__*/_react["default"].createElement(_antd.Button, { loading: this.state.loading, type: "primary", onClick: function onClick() { _this5.setState({ loading: true }); var iceFrom = _this5.iceFormReference.current; iceFrom.validateFields().then(function (values) { if (!iceFrom.isValid()) { _this5.setState({ loading: false }); return; } if (saveCallback) { saveCallback(values, iceFrom.showError.bind(_this5), _this5.closeModal.bind(_this5)); } else { _this5.save(values); } _this5.setState({ loading: false }); })["catch"](function (info) { _this5.setState({ loading: false }); }); } }, this.state.viewOnly ? this.props.adapter.gt('Done') : this.props.adapter.gt('Save'))))); if (this.state.viewOnly) { additionalProps.footer = null; } return /*#__PURE__*/_react["default"].createElement(_antd.Modal, _extends({ visible: this.state.visible, title: this.props.adapter.gt(this.props.title || adapter.objectTypeName), maskClosable: false, width: this.width, onCancel: function onCancel() { if (cancelCallback) { cancelCallback(); } else { _this5.closeModal(); } } }, additionalProps), /*#__PURE__*/_react["default"].createElement(_IceForm["default"], { ref: this.iceFormReference, adapter: adapter, fields: fields, viewOnly: this.state.viewOnly })); } }]); return IceFormModal; }(_react["default"].Component); var _default = IceFormModal; exports["default"] = _default; },{"./IceForm":70,"antd":"antd","react":"react"}],72:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var IceLabel = /*#__PURE__*/function (_React$Component) { _inherits(IceLabel, _React$Component); var _super = _createSuper(IceLabel); function IceLabel(props) { _classCallCheck(this, IceLabel); return _super.call(this, props); } _createClass(IceLabel, [{ key: "render", value: function render() { var value = this.props.value; return /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement("div", { contentEditable: "true", dangerouslySetInnerHTML: { __html: this.nl2br(value || '') } })); } }, { key: "nl2br", value: function nl2br(str) { return "".concat(str).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '
    '); } }]); return IceLabel; }(_react["default"].Component); var _default = IceLabel; exports["default"] = _default; },{"antd":"antd","react":"react"}],73:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Option = _antd.Select.Option; var IceSelect = /*#__PURE__*/function (_React$Component) { _inherits(IceSelect, _React$Component); var _super = _createSuper(IceSelect); function IceSelect(props) { var _this; _classCallCheck(this, IceSelect); _this = _super.call(this, props); _this.onChange = props.onChange; return _this; } _createClass(IceSelect, [{ key: "render", value: function render() { var options; var _this$props = this.props, field = _this$props.field, adapter = _this$props.adapter; var value = this.props.value; var data = field[1]; if (data['remote-source'] != null) { var key = "".concat(data['remote-source'][0], "_").concat(data['remote-source'][1], "_").concat(data['remote-source'][2]); if (data['remote-source'].length === 4) { key = "".concat(key, "_").concat(data['remote-source'][3]); } options = adapter.fieldMasterData[key]; } else { options = data.source; } var optionData = this.getFormSelectOptionsRemote(options, field, adapter); // value should be an array if multi-select if (data.type === 'select2multi') { try { value = JSON.parse(value); if (value == null) { value = []; } value = value.map(function (item) { return "".concat(item); }); } catch (e) { value = []; } } return /*#__PURE__*/_react["default"].createElement(_antd.Select, { mode: data.type === 'select2multi' ? 'multiple' : undefined, showSearch: true, placeholder: "Select ".concat(data.label), optionFilterProp: "children", filterOption: function filterOption(input, option) { return input != null && option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0; }, value: value, options: optionData, allowClear: true, onChange: this.handleChange.bind(this), disabled: this.props.readOnly }); } }, { key: "handleChange", value: function handleChange(value) { var field = this.props.field; var data = field[1]; if (data.type === 'select2multi') { this.onChange(JSON.stringify(value)); } else { this.onChange(value); } } }, { key: "makeOption", value: function makeOption(option) { return /*#__PURE__*/_react["default"].createElement(Option, { key: "".concat(option[0]), value: "".concat(option[0]) }, option[1]); } }, { key: "getFormSelectOptionsRemote", value: function getFormSelectOptionsRemote(options, field, adapter) { var optionData = []; if (Array.isArray(options)) { for (var i = 0; i < options.length; i++) { optionData.push({ label: options[i][1], value: options[i][0] }); } } else { for (var key in options) { optionData.push({ label: options[key], value: key }); } } // if (field[1].sort === 'true') { // tuples.sort((a, b) => { // a = a[1]; // b = b[1]; // // // eslint-disable-next-line no-nested-ternary // return a < b ? -1 : (a > b ? 1 : 0); // }); // } // for (let i = 0; i < tuples.length; i++) { // const prop = tuples[i][0]; // const value = tuples[i][1]; // optionData.push([prop, adapter.gt(value)]); // } return optionData; } }]); return IceSelect; }(_react["default"].Component); var _default = IceSelect; exports["default"] = _default; },{"antd":"antd","react":"react"}],74:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _reactSignatureCanvas = _interopRequireDefault(require("react-signature-canvas")); var _antd = require("antd"); var _icons = require("@ant-design/icons"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var IceSignature = /*#__PURE__*/function (_React$Component) { _inherits(IceSignature, _React$Component); var _super = _createSuper(IceSignature); function IceSignature(props) { var _this; _classCallCheck(this, IceSignature); _this = _super.call(this, props); _this.onChange = props.onChange; _this.state = { visible: false }; _this.signature = _react["default"].createRef(); return _this; } _createClass(IceSignature, [{ key: "componentDidMount", value: function componentDidMount() {} }, { key: "show", value: function show() { this.setState({ visible: true }); } }, { key: "setSignature", value: function setSignature(ref) { if (ref == null) { return; } var value = this.props.value; if (value != null && value.length > 10) { ref.fromDataURL(value); } } }, { key: "hide", value: function hide() { this.setState({ visible: false }); } }, { key: "clear", value: function clear() { this.signature.clear(); } }, { key: "save", value: function save() { var data = this.signature.toDataURL('image/png'); this.onChange(data); this.setState({ visible: false }); } }, { key: "render", value: function render() { var _this2 = this; var readOnly = this.props.readOnly; return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_antd.Modal, { visible: this.state.visible, title: "Signature", maskClosable: false, centered: true, width: 300, onCancel: function onCancel() { _this2.hide(); }, footer: [/*#__PURE__*/_react["default"].createElement(_antd.Button, { key: "cancel", onClick: function onClick() { _this2.hide(); } }, "Cancel"), /*#__PURE__*/_react["default"].createElement(_antd.Button, { key: "clear", disabled: readOnly, type: "dashed", onClick: function onClick() { if (!readOnly) { _this2.clear(); } } }, "Clear"), /*#__PURE__*/_react["default"].createElement(_antd.Button, { key: "ok", disabled: readOnly, type: "primary", onClick: function onClick() { if (!readOnly) { _this2.save(); } } }, "Submit")] }, /*#__PURE__*/_react["default"].createElement(_reactSignatureCanvas["default"], { ref: function ref(_ref) { _this2.signature = _ref; _this2.setSignature(_ref); }, canvasProps: _objectSpread({ width: 250, height: 200, className: 'sigCanvas' }, readOnly ? { readOnly: readOnly } : {}) })), /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "blue", style: { cursor: 'pointer' }, onClick: function onClick() { _this2.show(); } }, /*#__PURE__*/_react["default"].createElement(_icons.VerifiedOutlined, null), ' ', "Sign")); } }]); return IceSignature; }(_react["default"].Component); var _default = IceSignature; exports["default"] = _default; },{"@ant-design/icons":"@ant-design/icons","antd":"antd","react":"react","react-signature-canvas":358}],75:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _IceForm2 = _interopRequireDefault(require("./IceForm")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Step = _antd.Steps.Step; var IceStepForm = /*#__PURE__*/function (_IceForm) { _inherits(IceStepForm, _IceForm); var _super = _createSuper(IceStepForm); function IceStepForm(props) { var _this; _classCallCheck(this, IceStepForm); _this = _super.call(this, props); _this.onChange = props.onChange; var steps = _this.props.fields.map(function (item) { return _objectSpread({}, item, { ref: _react["default"].createRef() }); }); steps = steps.map(function (item) { var ref = item.ref, fields = item.fields; item.content = /*#__PURE__*/_react["default"].createElement(_IceForm2["default"], { ref: ref, adapter: props.adapter, fields: fields, twoColumnLayout: props.twoColumnLayout, width: props.width, layout: props.layout || 'horizontal' }); return item; }); _this.state = { current: 0, steps: steps, loading: false }; return _this; } _createClass(IceStepForm, [{ key: "moveToStep", value: function moveToStep(current) { this.setState({ current: current }); } }, { key: "next", value: function next() { if (this.validateFields(false) === false) { return; } this.showError(false); var current = this.state.current + 1; this.setState({ current: current }); } }, { key: "prev", value: function prev() { var current = this.state.current - 1; if (current < 0) { return; } this.setState({ current: current }); } }, { key: "render", value: function render() { var _this2 = this; var adapter = this.props.adapter; var _this$state = this.state, current = _this$state.current, steps = _this$state.steps; return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_antd.Steps, { current: current }, steps.map(function (item, index) { return /*#__PURE__*/_react["default"].createElement(Step, { key: item.title, title: item.title, onClick: function onClick() { return _this2.moveToStep(index); } }); })), /*#__PURE__*/_react["default"].createElement(_antd.Divider, null), /*#__PURE__*/_react["default"].createElement("div", { className: "steps-content" }, steps.map(function (item, index) { return /*#__PURE__*/_react["default"].createElement("div", { style: { display: index === current ? 'block' : 'none' } }, item.content); })), /*#__PURE__*/_react["default"].createElement(_antd.Divider, null), /*#__PURE__*/_react["default"].createElement("div", { className: "steps-action" }, /*#__PURE__*/_react["default"].createElement(_antd.Row, { gutter: 16 }, /*#__PURE__*/_react["default"].createElement(_antd.Col, { className: "gutter-row", span: 12, style: {} }, /*#__PURE__*/_react["default"].createElement(_antd.Space, null, current < steps.length - 1 && /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "primary", onClick: function onClick() { return _this2.next(); } }, adapter.gt('Next')), current > 0 && /*#__PURE__*/_react["default"].createElement(_antd.Button, { onClick: function onClick() { return _this2.prev(); } }, adapter.gt('Previous')))), /*#__PURE__*/_react["default"].createElement(_antd.Col, { className: "gutter-row", span: 12, style: { textAlign: 'right' } }, /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement(_antd.Button, { onClick: function onClick() { return _this2.props.closeModal(); } }, adapter.gt('Cancel')), /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "primary", loading: this.state.loading, onClick: function onClick() { return _this2.saveData(); } }, adapter.gt('Save'))))))); } }, { key: "saveData", value: function () { var _saveData = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { var _this3 = this; var data; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: this.setState({ loading: true }); _context.next = 3; return this.validateFields(true); case 3: data = _context.sent; if (data) { this.save(data, function () { return _this3.props.closeModal(); }); } this.setState({ loading: false }); case 6: case "end": return _context.stop(); } } }, _callee, this); })); function saveData() { return _saveData.apply(this, arguments); } return saveData; }() }, { key: "save", value: function save(params, success) { var _this4 = this; var adapter = this.props.adapter; adapter.add(params, [], function () { return adapter.get([]); }, function () { _this4.resetFields(); _this4.showError(false); success(); }); } }, { key: "updateFields", value: function updateFields(data) { var _this5 = this; this.state.steps.forEach(function (item) { var subData = {}; item.fields.forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 1), key = _ref2[0]; subData[key] = data[key]; }); _this5.updateFieldsSubForm(item.ref, item.fields, subData); }); } }, { key: "updateFieldsSubForm", value: function updateFieldsSubForm(ref, fields, data) { data = this.dataToFormFields(data, fields); ref.current.resetFields(); if (data == null) { return; } try { ref.current.setFieldsValue(data); } catch (e) { console.log(e); } } }, { key: "validateFields", value: function () { var _validateFields = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(all) { var adapter, steps, promiseList, allData, failedIndex, values, msg, id, fields; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: adapter = this.props.adapter; steps = all ? this.state.steps : this.state.steps.slice(0, this.state.current + 1); promiseList = steps.map(function (item) { return item.ref.current.validateFields().then(function (values) { if (!item.ref.current.isValid()) { return false; } return values; })["catch"](function () { return false; }); }); _context2.next = 5; return Promise.all(promiseList); case 5: allData = _context2.sent; failedIndex = allData.findIndex(function (item) { return item === false; }); if (!(failedIndex >= 0)) { _context2.next = 10; break; } this.setState({ current: failedIndex }); return _context2.abrupt("return", false); case 10: values = Object.assign.apply(Object, [{}].concat(_toConsumableArray(allData))); values = adapter.forceInjectValuesBeforeSave(values); msg = adapter.doCustomValidation(values); if (!(msg !== null)) { _context2.next = 16; break; } this.showError(msg); return _context2.abrupt("return", false); case 16: if (adapter.csrfRequired) { values.csrf = $("#".concat(adapter.getTableName(), "Form")).data('csrf'); } id = adapter.currentElement != null ? adapter.currentElement.id : null; if (id != null && id !== '') { values.id = id; } fields = [].concat.apply([], this.state.steps.map(function (item) { return item.fields; })); return _context2.abrupt("return", this.formFieldsToData(values, fields)); case 21: case "end": return _context2.stop(); } } }, _callee2, this); })); function validateFields(_x) { return _validateFields.apply(this, arguments); } return validateFields; }() }, { key: "getSubFormData", value: function getSubFormData(ref, fields, params) { var adapter = this.props.adapter; var values = params; values = adapter.forceInjectValuesBeforeSave(values); var msg = adapter.doCustomValidation(values); if (msg !== null) { ref.current.showError(msg); return; } if (adapter.csrfRequired) { values.csrf = $("#".concat(adapter.getTableName(), "Form")).data('csrf'); } var id = adapter.currentElement != null ? adapter.currentElement.id : null; if (id != null && id !== '') { values.id = id; } return this.formFieldsToData(values, fields); } }, { key: "showError", value: function showError(errorMsg) { this.state.steps.forEach(function (item) { return item.ref.current.showError(errorMsg); }); } }, { key: "resetFields", value: function resetFields() { this.state.steps.forEach(function (item) { return item.ref.current.resetFields(); }); } }, { key: "hideError", value: function hideError() { this.state.steps.forEach(function (item) { return item.ref.current.hideError(); }); } }, { key: "isReady", value: function isReady() { return this.state.steps.reduce(function (acc, item) { return acc && item.ref.current != null; }, true); } }]); return IceStepForm; }(_IceForm2["default"]); var _default = IceStepForm; exports["default"] = _default; },{"./IceForm":70,"antd":"antd","react":"react"}],76:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _IceFormModal2 = _interopRequireDefault(require("./IceFormModal")); var _IceStepForm = _interopRequireDefault(require("./IceStepForm")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var IceStepFormModal = /*#__PURE__*/function (_IceFormModal) { _inherits(IceStepFormModal, _IceFormModal); var _super = _createSuper(IceStepFormModal); function IceStepFormModal(props) { var _this; _classCallCheck(this, IceStepFormModal); _this = _super.call(this, props); _this.width = 850; return _this; } _createClass(IceStepFormModal, [{ key: "show", value: function show(data) { var _this2 = this; this.props.adapter.beforeRenderFieldHook = this.props.adapter.beforeRenderField ? this.props.adapter.beforeRenderField(data) : function (fieldName, field) { return field; }; if (!data) { this.setState({ visible: true }); if (this.iceFormReference.current) { this.iceFormReference.current.resetFields(); } } else { this.setState({ visible: true }); if (this.iceFormReference.current && this.iceFormReference.current.isReady()) { this.iceFormReference.current.moveToStep(0); this.iceFormReference.current.updateFields(data); } else { this.waitForIt(function () { return _this2.iceFormReference.current && _this2.iceFormReference.current.isReady(); }, function () { _this2.iceFormReference.current.updateFields(data); _this2.iceFormReference.current.moveToStep(0); }, 1000); } } } }, { key: "hide", value: function hide() { this.iceFormReference.current.moveToStep(0); this.setState({ visible: false }); } }, { key: "render", value: function render() { var _this3 = this; var _this$props = this.props, fields = _this$props.fields, adapter = _this$props.adapter; var _this$props$adapter$g = this.props.adapter.getFormOptions(), width = _this$props$adapter$g.width, twoColumnLayout = _this$props$adapter$g.twoColumnLayout, layout = _this$props$adapter$g.layout; return /*#__PURE__*/_react["default"].createElement(_antd.Modal, { visible: this.state.visible, title: this.props.adapter.gt(this.props.title || adapter.objectTypeName), maskClosable: false, width: width || this.width, footer: [], onCancel: function onCancel() { _this3.closeModal(); } }, /*#__PURE__*/_react["default"].createElement(_IceStepForm["default"], { ref: this.iceFormReference, adapter: adapter, fields: fields, closeModal: function closeModal() { _this3.closeModal(); }, twoColumnLayout: twoColumnLayout || false, layout: layout })); } }]); return IceStepFormModal; }(_IceFormModal2["default"]); var _default = IceStepFormModal; exports["default"] = _default; },{"./IceFormModal":71,"./IceStepForm":75,"antd":"antd","react":"react"}],77:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireWildcard(require("react")); var _antd = require("antd"); var _icons = require("@ant-design/icons"); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Search = _antd.Input.Search; var IceTable = /*#__PURE__*/function (_React$Component) { _inherits(IceTable, _React$Component); var _super = _createSuper(IceTable); function IceTable(props) { var _this; _classCallCheck(this, IceTable); _this = _super.call(this, props); _this.state = { data: [], pagination: {}, loading: true, fetchConfig: false, //filter: null, showLoading: true, currentElement: null, fetchCompleted: false }; _this.handleTableChange = function (pagination, filters, sorter) { var pager = _objectSpread({}, _this.state.pagination); var search = _this.state.search; pager.current = pagination.current; _this.setState({ pagination: pager }); var fetchConfig = { limit: pagination.pageSize, page: pagination.current, sortField: sorter.field, sortOrder: sorter.order, filters: JSON.stringify(filters), search: search }; _this.setState({ fetchConfig: fetchConfig }); _this.fetch(fetchConfig); }; _this.reload = function () { var fetchConfig = _this.state.fetchConfig; if (fetchConfig) { _this.fetch(fetchConfig); } }; _this.search = function (value) { _this.setState({ search: value }); var fetchConfig = _this.state.fetchConfig; console.log(fetchConfig); if (fetchConfig) { fetchConfig.search = value; _this.setState({ fetchConfig: fetchConfig }); _this.fetch(fetchConfig); } }; _this.addNew = function () { _this.props.adapter.renderForm(); }; _this.showFilters = function () { _this.props.adapter.showFilters(); }; _this.setFilterData = function (filter) { _this.setState({ filter: filter }); }; _this.setCurrentElement = function (currentElement) { _this.setState({ currentElement: currentElement }); }; _this.fetch = function () { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; //this.setState({ loading: this.state.showLoading }); _this.setState({ loading: true }); //const hideMessage = message.loading({ content: 'Loading Latest Data ...', key: 'loadingTable', duration: 1}); var pagination = _objectSpread({}, _this.state.pagination); if (_this.props.adapter.localStorageEnabled) { try { var cachedResponse = _this.props.reader.getCachedResponse(params); if (cachedResponse.items) { _this.setState({ loading: false, data: cachedResponse.items, pagination: pagination, showLoading: false }); } else { _this.props.reader.clearCachedResponse(params); } } catch (e) { _this.props.reader.clearCachedResponse(params); } } _this.props.reader.get(params).then(function (data) { // Read total count from server // pagination.total = data.totalCount; pagination.total = data.total; //hideMessage(); // setTimeout( // () => message.success({ content: 'Loading Completed!', key: 'loadingSuccess', duration: 1 }), // 600 // ); _this.setState({ loading: false, data: data.items, pagination: pagination, showLoading: false, fetchCompleted: true }); }); }; return _this; } _createClass(IceTable, [{ key: "componentDidMount", value: function componentDidMount() { var fetchConfig = { page: 1 }; _antd.message.config({ top: 40 }); this.setState({ fetchConfig: fetchConfig, //filter: this.props.adapter.filter, pagination: { 'pageSize': this.props.reader.pageSize } }); //this.fetch(fetchConfig); } }, { key: "setLoading", value: function setLoading(value) { this.setState({ loading: value }); } }, { key: "getChildrenWithProps", value: function getChildrenWithProps(element) { var _this2 = this; var childrenWithProps = _react["default"].Children.map(this.props.children, function (child) { // checking isValidElement is the safe way and avoids a typescript error too var props = { element: element, adapter: _this2.props.adapter, loading: _this2.state.loading }; if (_react["default"].isValidElement(child)) { return _react["default"].cloneElement(child, props); } return child; }); return childrenWithProps; } }, { key: "render", value: function render() { var _this3 = this; return /*#__PURE__*/_react["default"].createElement(_antd.Row, { direction: "vertical", style: { width: '100%' } }, !this.state.currentElement && /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Row, { gutter: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 18 }, /*#__PURE__*/_react["default"].createElement(_antd.Space, null, this.props.adapter.hasAccess('save') && this.props.adapter.getShowAddNew() && /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "primary", onClick: this.addNew }, /*#__PURE__*/_react["default"].createElement(_icons.PlusCircleOutlined, null), " Add New"), this.props.adapter.getFilters() && /*#__PURE__*/_react["default"].createElement(_antd.Button, { onClick: this.showFilters }, /*#__PURE__*/_react["default"].createElement(_icons.FilterOutlined, null), " Filters"), this.state.fetchCompleted && this.props.adapter.getFilters() && this.props.adapter.filter != null && this.props.adapter.filter !== [] && this.props.adapter.filter !== '' && this.props.adapter.getFilterString(this.props.adapter.filter) !== '' && /*#__PURE__*/_react["default"].createElement(_antd.Tag, { closable: true, style: { 'lineHeight': '30px' }, color: "blue", onClose: function onClose() { return _this3.props.adapter.resetFilters(); }, visible: this.props.adapter.filter != null && this.props.adapter.filter !== [] && this.props.adapter.filter !== '' }, this.props.adapter.getFilterString(this.props.adapter.filter)))), /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 6 }, /*#__PURE__*/_react["default"].createElement(_antd.Form, { ref: function ref(formRef) { return _this3.form = formRef; }, name: "advanced_search", className: "ant-advanced-search-form" }, /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, { name: "searchTerm", label: "", rules: [{ required: false }] }, /*#__PURE__*/_react["default"].createElement(Search, { placeholder: "input search text", enterButton: "Search", onSearch: function onSearch(value) { return _this3.search(value); } }))))), /*#__PURE__*/_react["default"].createElement(_antd.Row, { gutter: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Col, { span: 24 }, /*#__PURE__*/_react["default"].createElement(_antd.Table // bordered , { rowClassName: function rowClassName(record, index) { return index % 2 === 0 ? 'table-row-light' : 'table-row-dark'; }, columns: this.props.columns, rowKey: function rowKey(record) { return record.id; }, dataSource: this.state.data, pagination: this.state.pagination, loading: this.state.loading, onChange: this.handleTableChange, reader: this.props.dataPipe })))), this.state.currentElement && this.getChildrenWithProps(this.state.currentElement)); } }]); return IceTable; }(_react["default"].Component); var _default = IceTable; exports["default"] = _default; },{"@ant-design/icons":"@ant-design/icons","antd":"antd","react":"react"}],78:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _icons = require("@ant-design/icons"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var IceUpload = /*#__PURE__*/function (_React$Component) { _inherits(IceUpload, _React$Component); var _super = _createSuper(IceUpload); function IceUpload(props) { var _this; _classCallCheck(this, IceUpload); _this = _super.call(this, props); _this.state = { fileList: [], uploaded: false }; _this._isMounted = false; _this.handleDelete = function () { _this.setState({ fileList: [], value: null, uploaded: false }); _this.onChange(null); }; _this.handleView = function () { var currentValue = _this.props.value; if (_this.state.value != null && _this.state.value !== '') { currentValue = _this.state.value; } if (currentValue == null || currentValue === '') { _antd.message.error('File not found'); return; } var adapter = _this.props.adapter; adapter.getFile(currentValue).then(function (data) { var file = { key: data.uid, uid: data.uid, name: data.name, status: data.status, url: data.filename }; window.open(file.url); })["catch"](function (e) {}); }; _this.handleChange = function (info) { var fileList = _toConsumableArray(info.fileList); if (fileList.length === 0) { _this.setState({ value: null }); _this.onChange(null); _this.setState({ fileList: [] }); _this.setState({ uploaded: false }); return; } fileList = fileList.slice(-1); if (fileList[0].response && fileList[0].response.status === 'error') { _this.setState({ value: null }); _this.onChange(null); _this.setState({ fileList: [] }); _this.setState({ uploaded: false }); _antd.message.error("Error: ".concat(fileList[0].response.message)); return; } fileList = fileList.map(function (file) { if (file.response) { // Component will show file.url as link file.name = file.response.name; file.url = file.response.url; } return file; }); _this.setState({ fileList: fileList }); _this.setState({ value: _this.getFileName(fileList), uploaded: true }); _this.onChange(_this.getFileName(fileList)); }; _this.onChange = props.onChange; return _this; } _createClass(IceUpload, [{ key: "componentDidMount", value: function componentDidMount() { this._isMounted = true; _antd.message.config({ top: 55, duration: 2 }); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this._isMounted = false; } }, { key: "getFileName", value: function getFileName(fileList) { var file = null; if (fileList) { file = fileList[0]; } return file ? file.name : ''; } }, { key: "generateRandom", value: function generateRandom(length) { var d = new Date(); var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var result = ''; for (var i = length; i > 0; --i) { result += chars[Math.round(Math.random() * (chars.length - 1))]; } return result + d.getTime(); } }, { key: "render", value: function render() { var fileName = this.generateRandom(14); var props = { action: "".concat(window.CLIENT_BASE_URL, "fileupload-new.php?user=").concat(this.props.user, "&file_group=").concat(this.props.fileGroup, "&file_name=").concat(fileName), onChange: this.handleChange, onRemove: this.handleDelete, multiple: false, listType: 'picture' }; return /*#__PURE__*/_react["default"].createElement(_antd.Space, { direction: 'vertical' }, !this.props.readOnly && /*#__PURE__*/_react["default"].createElement(_antd.Space, null, /*#__PURE__*/_react["default"].createElement(_antd.Upload, _extends({}, props, { fileList: this.state.fileList }), /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: "blue", style: { cursor: 'pointer' } }, /*#__PURE__*/_react["default"].createElement(_icons.UploadOutlined, null), ' ', "Upload"))), /*#__PURE__*/_react["default"].createElement(_antd.Space, null, (this.props.value != null && this.props.value !== '' || this.state.value != null && this.state.value !== '') && !this.state.uploaded && /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "link", htmlType: "button", onClick: this.handleView }, /*#__PURE__*/_react["default"].createElement(_icons.DownloadOutlined, null), " View File"), (this.props.value != null && this.props.value !== '' || this.state.value != null && this.state.value !== '') && !this.state.uploaded && !this.props.readOnly && /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "link", htmlType: "button", danger: true, onClick: this.handleDelete }, /*#__PURE__*/_react["default"].createElement(_icons.DeleteOutlined, null), " Delete"))); } }]); return IceUpload; }(_react["default"].Component); var _default = IceUpload; exports["default"] = _default; },{"@ant-design/icons":"@ant-design/icons","antd":"antd","react":"react"}],79:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var TagList = /*#__PURE__*/function (_React$Component) { _inherits(TagList, _React$Component); var _super = _createSuper(TagList); function TagList(props) { var _this; _classCallCheck(this, TagList); _this = _super.call(this, props); _this.state = { tags: [], loading: true }; return _this; } _createClass(TagList, [{ key: "componentDidMount", value: function componentDidMount() { this.fetch(); } }, { key: "fetch", value: function fetch() { var _this2 = this; this.setState({ loading: true }); this.props.apiClient.get(this.props.url).then(function (response) { var tags = response.data.data.map(_this2.props.extractTag); _this2.setState({ tags: tags, loading: false }); }); } }, { key: "render", value: function render() { var _this3 = this; return /*#__PURE__*/_react["default"].createElement("div", { style: { display: 'inline-block', textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden', width: '100%' } }, this.state.loading && /*#__PURE__*/_react["default"].createElement(_antd.Skeleton, { active: true }), !this.state.loading && this.state.tags.map(function (tag, index) { return _this3.props.render ? _this3.props.render(tag) : /*#__PURE__*/_react["default"].createElement("div", { key: "p".concat(index) }, /*#__PURE__*/_react["default"].createElement(_antd.Tag, { color: _this3.props.color, key: index, style: { margin: '10px' } }, tag), /*#__PURE__*/_react["default"].createElement("br", null)); })); } }]); return TagList; }(_react["default"].Component); var _default = TagList; exports["default"] = _default; },{"antd":"antd","react":"react"}],80:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _antd = require("antd"); var _icons = require("@ant-design/icons"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Paragraph = _antd.Typography.Paragraph; var TaskList = /*#__PURE__*/function (_React$Component) { _inherits(TaskList, _React$Component); var _super = _createSuper(TaskList); function TaskList(props) { var _this; _classCallCheck(this, TaskList); _this = _super.call(this, props); _this.state = { tasks: [], showAll: false }; _this.state.tasks = _this.props.tasks.map(function (item) { return false; }); return _this; } _createClass(TaskList, [{ key: "render", value: function render() { return this.createTaskList(4); } }, { key: "createTaskList", value: function createTaskList(maxNumberOfTasks) { var _this2 = this; var tasks = this.props.tasks.slice(0, maxNumberOfTasks); return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_antd.Space, { direction: "vertical", size: "large", style: { width: '100%' } }, this.props.tasks && this.props.tasks.length > 0 && /*#__PURE__*/_react["default"].createElement(_antd.Space, { direction: "vertical", style: { width: '100%' } }, /*#__PURE__*/_react["default"].createElement(_antd.Timeline, { style: { width: '100%' } }, tasks.map(function (task, index) { return _this2.createTask(task, index); })), this.props.tasks.length > maxNumberOfTasks && /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "primary", onClick: function onClick() { return _this2.showAllTasks(); } }, "View All", ' ', this.props.tasks.length, ' ', "Tasks")), this.props.tasks && this.props.tasks.length === 0 && /*#__PURE__*/_react["default"].createElement(_antd.Empty, { description: "You're all caught up!" })), /*#__PURE__*/_react["default"].createElement(_antd.Drawer, { title: "Task List", width: 470, onClose: function onClose() { return _this2.hideAllTasks(); }, visible: this.state.showAll, bodyStyle: { paddingBottom: 80 }, zIndex: 1200, maskClosable: false }, /*#__PURE__*/_react["default"].createElement(_antd.Timeline, { style: { width: '100%' } }, this.props.tasks.map(function (task, index) { return _this2.createTask(task, index); })))); } }, { key: "visitLink", value: function visitLink(link) { setTimeout(function () { window.open(link); }, 100); } }, { key: "handleTaskHover", value: function handleTaskHover(index) { this.setState({ tasks: this.props.tasks.map(function (item, i) { return index === i; }) }); } }, { key: "createTask", value: function createTask(task, index) { var _this3 = this; if (task.priority === 100) { return /*#__PURE__*/_react["default"].createElement(_antd.Timeline.Item, { onMouseEnter: function onMouseEnter() { return _this3.handleTaskHover(index); }, dot: /*#__PURE__*/_react["default"].createElement(_icons.ClockCircleOutlined, { style: { fontSize: '16px' } }), color: "red" }, this.getText(task), task.link && this.state.tasks[index] && /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "link", onClick: function onClick() { return _this3.visitLink(task.link); } }, /*#__PURE__*/_react["default"].createElement(_icons.MedicineBoxOutlined, { style: { fontSize: '16px' } }), ' ', task.action)); } if (task.priority === 50) { return /*#__PURE__*/_react["default"].createElement(_antd.Timeline.Item, { onMouseEnter: function onMouseEnter() { return _this3.handleTaskHover(index); }, dot: /*#__PURE__*/_react["default"].createElement(_icons.InfoCircleOutlined, { style: { fontSize: '16px' } }), color: "blue" }, this.getText(task), task.link && this.state.tasks[index] && /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "link", onClick: function onClick() { return _this3.visitLink(task.link); } }, /*#__PURE__*/_react["default"].createElement(_icons.MedicineBoxOutlined, { style: { fontSize: '16px' } }), ' ', task.action)); } if (task.priority === 20) { return /*#__PURE__*/_react["default"].createElement(_antd.Timeline.Item, { onMouseEnter: function onMouseEnter() { return _this3.handleTaskHover(index); }, dot: /*#__PURE__*/_react["default"].createElement(_icons.PlusCircleOutlined, { style: { fontSize: '16px' } }), color: "blue" }, this.getText(task), task.link && this.state.tasks[index] && /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "link", onClick: function onClick() { return _this3.visitLink(task.link); } }, /*#__PURE__*/_react["default"].createElement(_icons.MedicineBoxOutlined, { style: { fontSize: '16px' } }), ' ', task.action)); } if (task.priority === 10) { return /*#__PURE__*/_react["default"].createElement(_antd.Timeline.Item, { onMouseEnter: function onMouseEnter() { return _this3.handleTaskHover(index); }, dot: /*#__PURE__*/_react["default"].createElement(_icons.PauseCircleOutlined, { style: { fontSize: '16px' } }), color: "green" }, this.getText(task), task.link && this.state.tasks[index] && /*#__PURE__*/_react["default"].createElement(_antd.Button, { type: "link", onClick: function onClick() { return _this3.visitLink(task.link); } }, /*#__PURE__*/_react["default"].createElement(_icons.MedicineBoxOutlined, { style: { fontSize: '16px' } }), ' ', task.action)); } } }, { key: "getText", value: function getText(task) { if (!task.details) { return /*#__PURE__*/_react["default"].createElement(Paragraph, { ellipsis: { rows: 1, expandable: true } }, task.text); } return /*#__PURE__*/_react["default"].createElement(_antd.Popover, { content: task.details }, /*#__PURE__*/_react["default"].createElement(Paragraph, { ellipsis: { rows: 1, expandable: true } }, task.text)); } }, { key: "showAllTasks", value: function showAllTasks() { this.setState({ showAll: true }); } }, { key: "hideAllTasks", value: function hideAllTasks() { this.setState({ showAll: false }); } }]); return TaskList; }(_react["default"].Component); var _default = TaskList; exports["default"] = _default; },{"@ant-design/icons":"@ant-design/icons","antd":"antd","react":"react"}],81:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var DEFAULT_SIZE = 24; exports.default = function (_ref) { var _ref$fill = _ref.fill, fill = _ref$fill === undefined ? 'currentColor' : _ref$fill, _ref$width = _ref.width, width = _ref$width === undefined ? DEFAULT_SIZE : _ref$width, _ref$height = _ref.height, height = _ref$height === undefined ? DEFAULT_SIZE : _ref$height, _ref$style = _ref.style, style = _ref$style === undefined ? {} : _ref$style, props = _objectWithoutProperties(_ref, ['fill', 'width', 'height', 'style']); return _react2.default.createElement( 'svg', _extends({ viewBox: '0 0 ' + DEFAULT_SIZE + ' ' + DEFAULT_SIZE, style: _extends({ fill: fill, width: width, height: height }, style) }, props), _react2.default.createElement('path', { d: 'M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z' }) ); }; },{"react":"react"}],82:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var DEFAULT_SIZE = 24; exports.default = function (_ref) { var _ref$fill = _ref.fill, fill = _ref$fill === undefined ? 'currentColor' : _ref$fill, _ref$width = _ref.width, width = _ref$width === undefined ? DEFAULT_SIZE : _ref$width, _ref$height = _ref.height, height = _ref$height === undefined ? DEFAULT_SIZE : _ref$height, _ref$style = _ref.style, style = _ref$style === undefined ? {} : _ref$style, props = _objectWithoutProperties(_ref, ['fill', 'width', 'height', 'style']); return _react2.default.createElement( 'svg', _extends({ viewBox: '0 0 ' + DEFAULT_SIZE + ' ' + DEFAULT_SIZE, style: _extends({ fill: fill, width: width, height: height }, style) }, props), _react2.default.createElement('path', { d: 'M12,18.17L8.83,15L7.42,16.41L12,21L16.59,16.41L15.17,15M12,5.83L15.17,9L16.58,7.59L12,3L7.41,7.59L8.83,9L12,5.83Z' }) ); }; },{"react":"react"}],83:[function(require,module,exports){ module.exports = require('./lib/axios'); },{"./lib/axios":85}],84:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); var settle = require('./../core/settle'); var cookies = require('./../helpers/cookies'); var buildURL = require('./../helpers/buildURL'); var buildFullPath = require('../core/buildFullPath'); var parseHeaders = require('./../helpers/parseHeaders'); var isURLSameOrigin = require('./../helpers/isURLSameOrigin'); var createError = require('../core/createError'); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } if ( (utils.isBlob(requestData) || utils.isFile(requestData)) && requestData.type ) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = unescape(encodeURIComponent(config.auth.password)) || ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } var fullPath = buildFullPath(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // Clean up request request = null; }; // Handle browser request cancellation (as opposed to a manual cancellation) request.onabort = function handleAbort() { if (!request) { return; } reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(createError('Network Error', config, null, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (!utils.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. if (config.responseType !== 'json') { throw e; } } } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (!request) { return; } request.abort(); reject(cancel); // Clean up request request = null; }); } if (!requestData) { requestData = null; } // Send the request request.send(requestData); }); }; },{"../core/buildFullPath":91,"../core/createError":92,"./../core/settle":96,"./../helpers/buildURL":100,"./../helpers/cookies":102,"./../helpers/isURLSameOrigin":104,"./../helpers/parseHeaders":106,"./../utils":108}],85:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var bind = require('./helpers/bind'); var Axios = require('./core/Axios'); var mergeConfig = require('./core/mergeConfig'); var defaults = require('./defaults'); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); return instance; } // Create the default instance to be exported var axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios; // Factory for creating new instances axios.create = function create(instanceConfig) { return createInstance(mergeConfig(axios.defaults, instanceConfig)); }; // Expose Cancel & CancelToken axios.Cancel = require('./cancel/Cancel'); axios.CancelToken = require('./cancel/CancelToken'); axios.isCancel = require('./cancel/isCancel'); // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = require('./helpers/spread'); module.exports = axios; // Allow use of default import syntax in TypeScript module.exports.default = axios; },{"./cancel/Cancel":86,"./cancel/CancelToken":87,"./cancel/isCancel":88,"./core/Axios":89,"./core/mergeConfig":95,"./defaults":98,"./helpers/bind":99,"./helpers/spread":107,"./utils":108}],86:[function(require,module,exports){ 'use strict'; /** * A `Cancel` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function Cancel(message) { this.message = message; } Cancel.prototype.toString = function toString() { return 'Cancel' + (this.message ? ': ' + this.message : ''); }; Cancel.prototype.__CANCEL__ = true; module.exports = Cancel; },{}],87:[function(require,module,exports){ 'use strict'; var Cancel = require('./Cancel'); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new Cancel(message); resolvePromise(token.reason); }); } /** * Throws a `Cancel` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; module.exports = CancelToken; },{"./Cancel":86}],88:[function(require,module,exports){ 'use strict'; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; },{}],89:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); var buildURL = require('../helpers/buildURL'); var InterceptorManager = require('./InterceptorManager'); var dispatchRequest = require('./dispatchRequest'); var mergeConfig = require('./mergeConfig'); /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = arguments[1] || {}; config.url = arguments[0]; } else { config = config || {}; } config = mergeConfig(this.defaults, config); // Set config.method if (config.method) { config.method = config.method.toLowerCase(); } else if (this.defaults.method) { config.method = this.defaults.method.toLowerCase(); } else { config.method = 'get'; } // Hook up interceptors middleware var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; }; Axios.prototype.getUri = function getUri(config) { config = mergeConfig(this.defaults, config); return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { method: method, url: url })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: data })); }; }); module.exports = Axios; },{"../helpers/buildURL":100,"./../utils":108,"./InterceptorManager":90,"./dispatchRequest":93,"./mergeConfig":95}],90:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function use(fulfilled, rejected) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function forEach(fn) { utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; },{"./../utils":108}],91:[function(require,module,exports){ 'use strict'; var isAbsoluteURL = require('../helpers/isAbsoluteURL'); var combineURLs = require('../helpers/combineURLs'); /** * Creates a new URL by combining the baseURL with the requestedURL, * only when the requestedURL is not already an absolute URL. * If the requestURL is absolute, this function returns the requestedURL untouched. * * @param {string} baseURL The base URL * @param {string} requestedURL Absolute or relative URL to combine * @returns {string} The combined full path */ module.exports = function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; }; },{"../helpers/combineURLs":101,"../helpers/isAbsoluteURL":103}],92:[function(require,module,exports){ 'use strict'; var enhanceError = require('./enhanceError'); /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ module.exports = function createError(message, config, code, request, response) { var error = new Error(message); return enhanceError(error, config, code, request, response); }; },{"./enhanceError":94}],93:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); var transformData = require('./transformData'); var isCancel = require('../cancel/isCancel'); var defaults = require('../defaults'); /** * Throws a `Cancel` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData( config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers ); utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData( response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData( reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; },{"../cancel/isCancel":88,"../defaults":98,"./../utils":108,"./transformData":97}],94:[function(require,module,exports){ 'use strict'; /** * Update an Error with the specified config, error code, and response. * * @param {Error} error The error to update. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The error. */ module.exports = function enhanceError(error, config, code, request, response) { error.config = config; if (code) { error.code = code; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function toJSON() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code }; }; return error; }; },{}],95:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. * * @param {Object} config1 * @param {Object} config2 * @returns {Object} New object resulting from merging config2 to config1 */ module.exports = function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; var config = {}; var valueFromConfig2Keys = ['url', 'method', 'data']; var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; var defaultToConfig2Keys = [ 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' ]; var directMergeKeys = ['validateStatus']; function getMergedValue(target, source) { if (utils.isPlainObject(target) && utils.isPlainObject(source)) { return utils.merge(target, source); } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } else if (utils.isArray(source)) { return source.slice(); } return source; } function mergeDeepProperties(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } } utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } }); utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } }); utils.forEach(directMergeKeys, function merge(prop) { if (prop in config2) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (prop in config1) { config[prop] = getMergedValue(undefined, config1[prop]); } }); var axiosKeys = valueFromConfig2Keys .concat(mergeDeepPropertiesKeys) .concat(defaultToConfig2Keys) .concat(directMergeKeys); var otherKeys = Object .keys(config1) .concat(Object.keys(config2)) .filter(function filterAxiosKeys(key) { return axiosKeys.indexOf(key) === -1; }); utils.forEach(otherKeys, mergeDeepProperties); return config; }; },{"../utils":108}],96:[function(require,module,exports){ 'use strict'; var createError = require('./createError'); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(createError( 'Request failed with status code ' + response.status, response.config, null, response.request, response )); } }; },{"./createError":92}],97:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { data = fn(data, headers); }); return data; }; },{"./../utils":108}],98:[function(require,module,exports){ (function (process){ 'use strict'; var utils = require('./utils'); var normalizeHeaderName = require('./helpers/normalizeHeaderName'); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = require('./adapters/xhr'); } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = require('./adapters/http'); } return adapter; } var defaults = { adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data)) { setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { /*eslint no-param-reassign:0*/ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } }; defaults.headers = { common: { 'Accept': 'application/json, text/plain, */*' } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; }).call(this,require('_process')) },{"./adapters/http":84,"./adapters/xhr":84,"./helpers/normalizeHeaderName":105,"./utils":108,"_process":1}],99:[function(require,module,exports){ 'use strict'; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; },{}],100:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); function encode(val) { return encodeURIComponent(val). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { var hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; },{"./../utils":108}],101:[function(require,module,exports){ 'use strict'; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; },{}],102:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); },{"./../utils":108}],103:[function(require,module,exports){ 'use strict'; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; },{}],104:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); },{"./../utils":108}],105:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); module.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; },{"../utils":108}],106:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; },{"./../utils":108}],107:[function(require,module,exports){ 'use strict'; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; },{}],108:[function(require,module,exports){ 'use strict'; var bind = require('./helpers/bind'); /*global toString:true*/ // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is a Buffer * * @param {Object} val The value to test * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return (typeof FormData !== 'undefined') && (val instanceof FormData); } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a plain Object * * @param {Object} val The value to test * @return {boolean} True if value is a plain Object, otherwise false */ function isPlainObject(val) { if (toString.call(val) !== '[object Object]') { return false; } var prototype = Object.getPrototypeOf(val); return prototype === null || prototype === Object.prototype; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject(val) && isFunction(val.pipe); } /** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ function isURLSearchParams(val) { return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (isPlainObject(result[key]) && isPlainObject(val)) { result[key] = merge(result[key], val); } else if (isPlainObject(val)) { result[key] = merge({}, val); } else if (isArray(val)) { result[key] = val.slice(); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind(val, thisArg); } else { a[key] = val; } }); return a; } /** * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * * @param {string} content with BOM * @return {string} content value without BOM */ function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isPlainObject: isPlainObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, extend: extend, trim: trim, stripBOM: stripBOM }; },{"./helpers/bind":99}],109:[function(require,module,exports){ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")) else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod) else // Plain browser env mod(CodeMirror) })(function(CodeMirror) { "use strict" CodeMirror.defineOption("autoRefresh", false, function(cm, val) { if (cm.state.autoRefresh) { stopListening(cm, cm.state.autoRefresh) cm.state.autoRefresh = null } if (val && cm.display.wrapper.offsetHeight == 0) startListening(cm, cm.state.autoRefresh = {delay: val.delay || 250}) }) function startListening(cm, state) { function check() { if (cm.display.wrapper.offsetHeight) { stopListening(cm, state) if (cm.display.lastWrapHeight != cm.display.wrapper.clientHeight) cm.refresh() } else { state.timeout = setTimeout(check, state.delay) } } state.timeout = setTimeout(check, state.delay) state.hurry = function() { clearTimeout(state.timeout) state.timeout = setTimeout(check, 50) } CodeMirror.on(window, "mouseup", state.hurry) CodeMirror.on(window, "keyup", state.hurry) } function stopListening(_cm, state) { clearTimeout(state.timeout) CodeMirror.off(window, "mouseup", state.hurry) CodeMirror.off(window, "keyup", state.hurry) } }); },{"../../lib/codemirror":111}],110:[function(require,module,exports){ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { var defaults = { pairs: "()[]{}''\"\"", closeBefore: ")]}'\":;>", triples: "", explode: "[]{}" }; var Pos = CodeMirror.Pos; CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { cm.removeKeyMap(keyMap); cm.state.closeBrackets = null; } if (val) { ensureBound(getOption(val, "pairs")) cm.state.closeBrackets = val; cm.addKeyMap(keyMap); } }); function getOption(conf, name) { if (name == "pairs" && typeof conf == "string") return conf; if (typeof conf == "object" && conf[name] != null) return conf[name]; return defaults[name]; } var keyMap = {Backspace: handleBackspace, Enter: handleEnter}; function ensureBound(chars) { for (var i = 0; i < chars.length; i++) { var ch = chars.charAt(i), key = "'" + ch + "'" if (!keyMap[key]) keyMap[key] = handler(ch) } } ensureBound(defaults.pairs + "`") function handler(ch) { return function(cm) { return handleChar(cm, ch); }; } function getConfig(cm) { var deflt = cm.state.closeBrackets; if (!deflt || deflt.override) return deflt; var mode = cm.getModeAt(cm.getCursor()); return mode.closeBrackets || deflt; } function handleBackspace(cm) { var conf = getConfig(cm); if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; var pairs = getOption(conf, "pairs"); var ranges = cm.listSelections(); for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var around = charsAround(cm, ranges[i].head); if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; } for (var i = ranges.length - 1; i >= 0; i--) { var cur = ranges[i].head; cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); } } function handleEnter(cm) { var conf = getConfig(cm); var explode = conf && getOption(conf, "explode"); if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; var ranges = cm.listSelections(); for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var around = charsAround(cm, ranges[i].head); if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; } cm.operation(function() { var linesep = cm.lineSeparator() || "\n"; cm.replaceSelection(linesep + linesep, null); cm.execCommand("goCharLeft"); ranges = cm.listSelections(); for (var i = 0; i < ranges.length; i++) { var line = ranges[i].head.line; cm.indentLine(line, null, true); cm.indentLine(line + 1, null, true); } }); } function contractSelection(sel) { var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))}; } function handleChar(cm, ch) { var conf = getConfig(cm); if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; var pairs = getOption(conf, "pairs"); var pos = pairs.indexOf(ch); if (pos == -1) return CodeMirror.Pass; var closeBefore = getOption(conf,"closeBefore"); var triples = getOption(conf, "triples"); var identical = pairs.charAt(pos + 1) == ch; var ranges = cm.listSelections(); var opening = pos % 2 == 0; var type; for (var i = 0; i < ranges.length; i++) { var range = ranges[i], cur = range.head, curType; var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); if (opening && !range.empty()) { curType = "surround"; } else if ((identical || !opening) && next == ch) { if (identical && stringStartsAfter(cm, cur)) curType = "both"; else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) curType = "skipThree"; else curType = "skip"; } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) { if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass; curType = "addFour"; } else if (identical) { var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur) if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both"; else return CodeMirror.Pass; } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) { curType = "both"; } else { return CodeMirror.Pass; } if (!type) type = curType; else if (type != curType) return CodeMirror.Pass; } var left = pos % 2 ? pairs.charAt(pos - 1) : ch; var right = pos % 2 ? ch : pairs.charAt(pos + 1); cm.operation(function() { if (type == "skip") { cm.execCommand("goCharRight"); } else if (type == "skipThree") { for (var i = 0; i < 3; i++) cm.execCommand("goCharRight"); } else if (type == "surround") { var sels = cm.getSelections(); for (var i = 0; i < sels.length; i++) sels[i] = left + sels[i] + right; cm.replaceSelections(sels, "around"); sels = cm.listSelections().slice(); for (var i = 0; i < sels.length; i++) sels[i] = contractSelection(sels[i]); cm.setSelections(sels); } else if (type == "both") { cm.replaceSelection(left + right, null); cm.triggerElectric(left + right); cm.execCommand("goCharLeft"); } else if (type == "addFour") { cm.replaceSelection(left + left + left + left, "before"); cm.execCommand("goCharRight"); } }); } function charsAround(cm, pos) { var str = cm.getRange(Pos(pos.line, pos.ch - 1), Pos(pos.line, pos.ch + 1)); return str.length == 2 ? str : null; } function stringStartsAfter(cm, pos) { var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)) return /\bstring/.test(token.type) && token.start == pos.ch && (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))) } }); },{"../../lib/codemirror":111}],111:[function(require,module,exports){ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // This is CodeMirror (https://codemirror.net), a code editor // implemented in JavaScript on top of the browser's DOM. // // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.CodeMirror = factory()); }(this, (function () { 'use strict'; // Kludges for bugs and behavior differences that can't be feature // detected are enabled based on userAgent etc sniffing. var userAgent = navigator.userAgent; var platform = navigator.platform; var gecko = /gecko\/\d/i.test(userAgent); var ie_upto10 = /MSIE \d/.test(userAgent); var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); var edge = /Edge\/(\d+)/.exec(userAgent); var ie = ie_upto10 || ie_11up || edge; var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); var webkit = !edge && /WebKit\//.test(userAgent); var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); var chrome = !edge && /Chrome\//.test(userAgent); var presto = /Opera\//.test(userAgent); var safari = /Apple Computer/.test(navigator.vendor); var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); var phantom = /PhantomJS/.test(userAgent); var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); var android = /Android/.test(userAgent); // This is woefully incomplete. Suggestions for alternative methods welcome. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); var mac = ios || /Mac/.test(platform); var chromeOS = /\bCrOS\b/.test(userAgent); var windows = /win/i.test(platform); var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); if (presto_version) { presto_version = Number(presto_version[1]); } if (presto_version && presto_version >= 15) { presto = false; webkit = true; } // Some browsers use the wrong event properties to signal cmd/ctrl on OS X var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); var captureRightClick = gecko || (ie && ie_version >= 9); function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } var rmClass = function(node, cls) { var current = node.className; var match = classTest(cls).exec(current); if (match) { var after = current.slice(match.index + match[0].length); node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); } }; function removeChildren(e) { for (var count = e.childNodes.length; count > 0; --count) { e.removeChild(e.firstChild); } return e } function removeChildrenAndAdd(parent, e) { return removeChildren(parent).appendChild(e) } function elt(tag, content, className, style) { var e = document.createElement(tag); if (className) { e.className = className; } if (style) { e.style.cssText = style; } if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } return e } // wrapper for elt, which removes the elt from the accessibility tree function eltP(tag, content, className, style) { var e = elt(tag, content, className, style); e.setAttribute("role", "presentation"); return e } var range; if (document.createRange) { range = function(node, start, end, endNode) { var r = document.createRange(); r.setEnd(endNode || node, end); r.setStart(node, start); return r }; } else { range = function(node, start, end) { var r = document.body.createTextRange(); try { r.moveToElementText(node.parentNode); } catch(e) { return r } r.collapse(true); r.moveEnd("character", end); r.moveStart("character", start); return r }; } function contains(parent, child) { if (child.nodeType == 3) // Android browser always returns false when child is a textnode { child = child.parentNode; } if (parent.contains) { return parent.contains(child) } do { if (child.nodeType == 11) { child = child.host; } if (child == parent) { return true } } while (child = child.parentNode) } function activeElt() { // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. // IE < 10 will throw when accessed while the page is loading or in an iframe. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. var activeElement; try { activeElement = document.activeElement; } catch(e) { activeElement = document.body || null; } while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { activeElement = activeElement.shadowRoot.activeElement; } return activeElement } function addClass(node, cls) { var current = node.className; if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } } function joinClasses(a, b) { var as = a.split(" "); for (var i = 0; i < as.length; i++) { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } return b } var selectInput = function(node) { node.select(); }; if (ios) // Mobile Safari apparently has a bug where select() is broken. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } else if (ie) // Suppress mysterious IE10 errors { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } function bind(f) { var args = Array.prototype.slice.call(arguments, 1); return function(){return f.apply(null, args)} } function copyObj(obj, target, overwrite) { if (!target) { target = {}; } for (var prop in obj) { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) { target[prop] = obj[prop]; } } return target } // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. function countColumn(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) { end = string.length; } } for (var i = startIndex || 0, n = startValue || 0;;) { var nextTab = string.indexOf("\t", i); if (nextTab < 0 || nextTab >= end) { return n + (end - i) } n += nextTab - i; n += tabSize - (n % tabSize); i = nextTab + 1; } } var Delayed = function() { this.id = null; this.f = null; this.time = 0; this.handler = bind(this.onTimeout, this); }; Delayed.prototype.onTimeout = function (self) { self.id = 0; if (self.time <= +new Date) { self.f(); } else { setTimeout(self.handler, self.time - +new Date); } }; Delayed.prototype.set = function (ms, f) { this.f = f; var time = +new Date + ms; if (!this.id || time < this.time) { clearTimeout(this.id); this.id = setTimeout(this.handler, ms); this.time = time; } }; function indexOf(array, elt) { for (var i = 0; i < array.length; ++i) { if (array[i] == elt) { return i } } return -1 } // Number of pixels added to scroller and sizer to hide scrollbar var scrollerGap = 50; // Returned or thrown by various protocols to signal 'I'm not // handling this'. var Pass = {toString: function(){return "CodeMirror.Pass"}}; // Reused option objects for setSelection & friends var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; // The inverse of countColumn -- find the offset that corresponds to // a particular column. function findColumn(string, goal, tabSize) { for (var pos = 0, col = 0;;) { var nextTab = string.indexOf("\t", pos); if (nextTab == -1) { nextTab = string.length; } var skipped = nextTab - pos; if (nextTab == string.length || col + skipped >= goal) { return pos + Math.min(skipped, goal - col) } col += nextTab - pos; col += tabSize - (col % tabSize); pos = nextTab + 1; if (col >= goal) { return pos } } } var spaceStrs = [""]; function spaceStr(n) { while (spaceStrs.length <= n) { spaceStrs.push(lst(spaceStrs) + " "); } return spaceStrs[n] } function lst(arr) { return arr[arr.length-1] } function map(array, f) { var out = []; for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } return out } function insertSorted(array, value, score) { var pos = 0, priority = score(value); while (pos < array.length && score(array[pos]) <= priority) { pos++; } array.splice(pos, 0, value); } function nothing() {} function createObj(base, props) { var inst; if (Object.create) { inst = Object.create(base); } else { nothing.prototype = base; inst = new nothing(); } if (props) { copyObj(props, inst); } return inst } var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; function isWordCharBasic(ch) { return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) } function isWordChar(ch, helper) { if (!helper) { return isWordCharBasic(ch) } if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } return helper.test(ch) } function isEmpty(obj) { for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } return true } // Extending unicode characters. A series of a non-extending char + // any number of extending chars is treated as a single unit as far // as editing and measuring is concerned. This is not fully correct, // since some scripts/fonts/browsers also treat other configurations // of code points as a group. var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. function skipExtendingChars(str, pos, dir) { while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } return pos } // Returns the value from the range [`from`; `to`] that satisfies // `pred` and is closest to `from`. Assumes that at least `to` // satisfies `pred`. Supports `from` being greater than `to`. function findFirst(pred, from, to) { // At any point we are certain `to` satisfies `pred`, don't know // whether `from` does. var dir = from > to ? -1 : 1; for (;;) { if (from == to) { return from } var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); if (mid == from) { return pred(mid) ? from : to } if (pred(mid)) { to = mid; } else { from = mid + dir; } } } // BIDI HELPERS function iterateBidiSections(order, from, to, f) { if (!order) { return f(from, to, "ltr", 0) } var found = false; for (var i = 0; i < order.length; ++i) { var part = order[i]; if (part.from < to && part.to > from || from == to && part.to == from) { f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); found = true; } } if (!found) { f(from, to, "ltr"); } } var bidiOther = null; function getBidiPartAt(order, ch, sticky) { var found; bidiOther = null; for (var i = 0; i < order.length; ++i) { var cur = order[i]; if (cur.from < ch && cur.to > ch) { return i } if (cur.to == ch) { if (cur.from != cur.to && sticky == "before") { found = i; } else { bidiOther = i; } } if (cur.from == ch) { if (cur.from != cur.to && sticky != "before") { found = i; } else { bidiOther = i; } } } return found != null ? found : bidiOther } // Bidirectional ordering algorithm // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm // that this (partially) implements. // One-char codes used for character types: // L (L): Left-to-Right // R (R): Right-to-Left // r (AL): Right-to-Left Arabic // 1 (EN): European Number // + (ES): European Number Separator // % (ET): European Number Terminator // n (AN): Arabic Number // , (CS): Common Number Separator // m (NSM): Non-Spacing Mark // b (BN): Boundary Neutral // s (B): Paragraph Separator // t (S): Segment Separator // w (WS): Whitespace // N (ON): Other Neutrals // Returns null if characters are ordered as they appear // (left-to-right), or an array of sections ({from, to, level} // objects) in the order in which they occur visually. var bidiOrdering = (function() { // Character types for codepoints 0 to 0xff var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; // Character types for codepoints 0x600 to 0x6f9 var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; function charType(code) { if (code <= 0xf7) { return lowTypes.charAt(code) } else if (0x590 <= code && code <= 0x5f4) { return "R" } else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } else if (0x6ee <= code && code <= 0x8ac) { return "r" } else if (0x2000 <= code && code <= 0x200b) { return "w" } else if (code == 0x200c) { return "b" } else { return "L" } } var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; function BidiSpan(level, from, to) { this.level = level; this.from = from; this.to = to; } return function(str, direction) { var outerType = direction == "ltr" ? "L" : "R"; if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } var len = str.length, types = []; for (var i = 0; i < len; ++i) { types.push(charType(str.charCodeAt(i))); } // W1. Examine each non-spacing mark (NSM) in the level run, and // change the type of the NSM to the type of the previous // character. If the NSM is at the start of the level run, it will // get the type of sor. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { var type = types[i$1]; if (type == "m") { types[i$1] = prev; } else { prev = type; } } // W2. Search backwards from each instance of a European number // until the first strong type (R, L, AL, or sor) is found. If an // AL is found, change the type of the European number to Arabic // number. // W3. Change all ALs to R. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { var type$1 = types[i$2]; if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } } // W4. A single European separator between two European numbers // changes to a European number. A single common separator between // two numbers of the same type changes to that type. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { var type$2 = types[i$3]; if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } else if (type$2 == "," && prev$1 == types[i$3+1] && (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } prev$1 = type$2; } // W5. A sequence of European terminators adjacent to European // numbers changes to all European numbers. // W6. Otherwise, separators and terminators change to Other // Neutral. for (var i$4 = 0; i$4 < len; ++i$4) { var type$3 = types[i$4]; if (type$3 == ",") { types[i$4] = "N"; } else if (type$3 == "%") { var end = (void 0); for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; for (var j = i$4; j < end; ++j) { types[j] = replace; } i$4 = end - 1; } } // W7. Search backwards from each instance of a European number // until the first strong type (R, L, or sor) is found. If an L is // found, then change the type of the European number to L. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { var type$4 = types[i$5]; if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } else if (isStrong.test(type$4)) { cur$1 = type$4; } } // N1. A sequence of neutrals takes the direction of the // surrounding strong text if the text on both sides has the same // direction. European and Arabic numbers act as if they were R in // terms of their influence on neutrals. Start-of-level-run (sor) // and end-of-level-run (eor) are used at level run boundaries. // N2. Any remaining neutrals take the embedding direction. for (var i$6 = 0; i$6 < len; ++i$6) { if (isNeutral.test(types[i$6])) { var end$1 = (void 0); for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} var before = (i$6 ? types[i$6-1] : outerType) == "L"; var after = (end$1 < len ? types[end$1] : outerType) == "L"; var replace$1 = before == after ? (before ? "L" : "R") : outerType; for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } i$6 = end$1 - 1; } } // Here we depart from the documented algorithm, in order to avoid // building up an actual levels array. Since there are only three // levels (0, 1, 2) in an implementation that doesn't take // explicit embedding into account, we can build up the order on // the fly, without following the level-based algorithm. var order = [], m; for (var i$7 = 0; i$7 < len;) { if (countsAsLeft.test(types[i$7])) { var start = i$7; for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} order.push(new BidiSpan(0, start, i$7)); } else { var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0; for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} for (var j$2 = pos; j$2 < i$7;) { if (countsAsNum.test(types[j$2])) { if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; } var nstart = j$2; for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} order.splice(at, 0, new BidiSpan(2, nstart, j$2)); at += isRTL; pos = j$2; } else { ++j$2; } } if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } } } if (direction == "ltr") { if (order[0].level == 1 && (m = str.match(/^\s+/))) { order[0].from = m[0].length; order.unshift(new BidiSpan(0, 0, m[0].length)); } if (lst(order).level == 1 && (m = str.match(/\s+$/))) { lst(order).to -= m[0].length; order.push(new BidiSpan(0, len - m[0].length, len)); } } return direction == "rtl" ? order.reverse() : order } })(); // Get the bidi ordering for the given line (and cache it). Returns // false for lines that are fully left-to-right, and an array of // BidiSpan objects otherwise. function getOrder(line, direction) { var order = line.order; if (order == null) { order = line.order = bidiOrdering(line.text, direction); } return order } // EVENT HANDLING // Lightweight event framework. on/off also work on DOM nodes, // registering native DOM handlers. var noHandlers = []; var on = function(emitter, type, f) { if (emitter.addEventListener) { emitter.addEventListener(type, f, false); } else if (emitter.attachEvent) { emitter.attachEvent("on" + type, f); } else { var map = emitter._handlers || (emitter._handlers = {}); map[type] = (map[type] || noHandlers).concat(f); } }; function getHandlers(emitter, type) { return emitter._handlers && emitter._handlers[type] || noHandlers } function off(emitter, type, f) { if (emitter.removeEventListener) { emitter.removeEventListener(type, f, false); } else if (emitter.detachEvent) { emitter.detachEvent("on" + type, f); } else { var map = emitter._handlers, arr = map && map[type]; if (arr) { var index = indexOf(arr, f); if (index > -1) { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } } } } function signal(emitter, type /*, values...*/) { var handlers = getHandlers(emitter, type); if (!handlers.length) { return } var args = Array.prototype.slice.call(arguments, 2); for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } } // The DOM events that CodeMirror handles can be overridden by // registering a (non-DOM) handler on the editor for the event name, // and preventDefault-ing the event in that handler. function signalDOMEvent(cm, e, override) { if (typeof e == "string") { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } signal(cm, override || e.type, cm, e); return e_defaultPrevented(e) || e.codemirrorIgnore } function signalCursorActivity(cm) { var arr = cm._handlers && cm._handlers.cursorActivity; if (!arr) { return } var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) { set.push(arr[i]); } } } function hasHandler(emitter, type) { return getHandlers(emitter, type).length > 0 } // Add on and off methods to a constructor's prototype, to make // registering events on such objects more convenient. function eventMixin(ctor) { ctor.prototype.on = function(type, f) {on(this, type, f);}; ctor.prototype.off = function(type, f) {off(this, type, f);}; } // Due to the fact that we still support jurassic IE versions, some // compatibility wrappers are needed. function e_preventDefault(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } function e_stopPropagation(e) { if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; } } function e_defaultPrevented(e) { return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false } function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} function e_target(e) {return e.target || e.srcElement} function e_button(e) { var b = e.which; if (b == null) { if (e.button & 1) { b = 1; } else if (e.button & 2) { b = 3; } else if (e.button & 4) { b = 2; } } if (mac && e.ctrlKey && b == 1) { b = 3; } return b } // Detect drag-and-drop var dragAndDrop = function() { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. if (ie && ie_version < 9) { return false } var div = elt('div'); return "draggable" in div || "dragDrop" in div }(); var zwspSupported; function zeroWidthElement(measure) { if (zwspSupported == null) { var test = elt("span", "\u200b"); removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); if (measure.firstChild.offsetHeight != 0) { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } } var node = zwspSupported ? elt("span", "\u200b") : elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); node.setAttribute("cm-text", ""); return node } // Feature-detect IE's crummy client rect reporting for bidi text var badBidiRects; function hasBadBidiRects(measure) { if (badBidiRects != null) { return badBidiRects } var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); var r0 = range(txt, 0, 1).getBoundingClientRect(); var r1 = range(txt, 1, 2).getBoundingClientRect(); removeChildren(measure); if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) return badBidiRects = (r1.right - r0.right < 3) } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { var pos = 0, result = [], l = string.length; while (pos <= l) { var nl = string.indexOf("\n", pos); if (nl == -1) { nl = string.length; } var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); var rt = line.indexOf("\r"); if (rt != -1) { result.push(line.slice(0, rt)); pos += rt + 1; } else { result.push(line); pos = nl + 1; } } return result } : function (string) { return string.split(/\r\n?|\n/); }; var hasSelection = window.getSelection ? function (te) { try { return te.selectionStart != te.selectionEnd } catch(e) { return false } } : function (te) { var range; try {range = te.ownerDocument.selection.createRange();} catch(e) {} if (!range || range.parentElement() != te) { return false } return range.compareEndPoints("StartToEnd", range) != 0 }; var hasCopyEvent = (function () { var e = elt("div"); if ("oncopy" in e) { return true } e.setAttribute("oncopy", "return;"); return typeof e.oncopy == "function" })(); var badZoomedRects = null; function hasBadZoomedRects(measure) { if (badZoomedRects != null) { return badZoomedRects } var node = removeChildrenAndAdd(measure, elt("span", "x")); var normal = node.getBoundingClientRect(); var fromRange = range(node, 0, 1).getBoundingClientRect(); return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 } // Known modes, by name and by MIME var modes = {}, mimeModes = {}; // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) function defineMode(name, mode) { if (arguments.length > 2) { mode.dependencies = Array.prototype.slice.call(arguments, 2); } modes[name] = mode; } function defineMIME(mime, spec) { mimeModes[mime] = spec; } // Given a MIME type, a {name, ...options} config object, or a name // string, return a mode config object. function resolveMode(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { spec = mimeModes[spec]; } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { var found = mimeModes[spec.name]; if (typeof found == "string") { found = {name: found}; } spec = createObj(found, spec); spec.name = found.name; } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { return resolveMode("application/xml") } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { return resolveMode("application/json") } if (typeof spec == "string") { return {name: spec} } else { return spec || {name: "null"} } } // Given a mode spec (anything that resolveMode accepts), find and // initialize an actual mode object. function getMode(options, spec) { spec = resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) { return getMode(options, "text/plain") } var modeObj = mfactory(options, spec); if (modeExtensions.hasOwnProperty(spec.name)) { var exts = modeExtensions[spec.name]; for (var prop in exts) { if (!exts.hasOwnProperty(prop)) { continue } if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } modeObj[prop] = exts[prop]; } } modeObj.name = spec.name; if (spec.helperType) { modeObj.helperType = spec.helperType; } if (spec.modeProps) { for (var prop$1 in spec.modeProps) { modeObj[prop$1] = spec.modeProps[prop$1]; } } return modeObj } // This can be used to attach properties to mode objects from // outside the actual mode definition. var modeExtensions = {}; function extendMode(mode, properties) { var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); copyObj(properties, exts); } function copyState(mode, state) { if (state === true) { return state } if (mode.copyState) { return mode.copyState(state) } var nstate = {}; for (var n in state) { var val = state[n]; if (val instanceof Array) { val = val.concat([]); } nstate[n] = val; } return nstate } // Given a mode and a state (for that mode), find the inner mode and // state at the position that the state refers to. function innerMode(mode, state) { var info; while (mode.innerMode) { info = mode.innerMode(state); if (!info || info.mode == mode) { break } state = info.state; mode = info.mode; } return info || {mode: mode, state: state} } function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true } // STRING STREAM // Fed to the mode parsers, provides helper functions to make // parsers more succinct. var StringStream = function(string, tabSize, lineOracle) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; this.lineStart = 0; this.lineOracle = lineOracle; }; StringStream.prototype.eol = function () {return this.pos >= this.string.length}; StringStream.prototype.sol = function () {return this.pos == this.lineStart}; StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; StringStream.prototype.next = function () { if (this.pos < this.string.length) { return this.string.charAt(this.pos++) } }; StringStream.prototype.eat = function (match) { var ch = this.string.charAt(this.pos); var ok; if (typeof match == "string") { ok = ch == match; } else { ok = ch && (match.test ? match.test(ch) : match(ch)); } if (ok) {++this.pos; return ch} }; StringStream.prototype.eatWhile = function (match) { var start = this.pos; while (this.eat(match)){} return this.pos > start }; StringStream.prototype.eatSpace = function () { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; } return this.pos > start }; StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; StringStream.prototype.skipTo = function (ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true} }; StringStream.prototype.backUp = function (n) {this.pos -= n;}; StringStream.prototype.column = function () { if (this.lastColumnPos < this.start) { this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); this.lastColumnPos = this.start; } return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) }; StringStream.prototype.indentation = function () { return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) }; StringStream.prototype.match = function (pattern, consume, caseInsensitive) { if (typeof pattern == "string") { var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; var substr = this.string.substr(this.pos, pattern.length); if (cased(substr) == cased(pattern)) { if (consume !== false) { this.pos += pattern.length; } return true } } else { var match = this.string.slice(this.pos).match(pattern); if (match && match.index > 0) { return null } if (match && consume !== false) { this.pos += match[0].length; } return match } }; StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; StringStream.prototype.hideFirstChars = function (n, inner) { this.lineStart += n; try { return inner() } finally { this.lineStart -= n; } }; StringStream.prototype.lookAhead = function (n) { var oracle = this.lineOracle; return oracle && oracle.lookAhead(n) }; StringStream.prototype.baseToken = function () { var oracle = this.lineOracle; return oracle && oracle.baseToken(this.pos) }; // Find the line object corresponding to the given line number. function getLine(doc, n) { n -= doc.first; if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } var chunk = doc; while (!chunk.lines) { for (var i = 0;; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; break } n -= sz; } } return chunk.lines[n] } // Get the part of a document between two positions, as an array of // strings. function getBetween(doc, start, end) { var out = [], n = start.line; doc.iter(start.line, end.line + 1, function (line) { var text = line.text; if (n == end.line) { text = text.slice(0, end.ch); } if (n == start.line) { text = text.slice(start.ch); } out.push(text); ++n; }); return out } // Get the lines between from and to, as array of strings. function getLines(doc, from, to) { var out = []; doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value return out } // Update the height of a line, propagating the height change // upwards to parent nodes. function updateLineHeight(line, height) { var diff = height - line.height; if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } } // Given a line object, find its line number by walking up through // its parent links. function lineNo(line) { if (line.parent == null) { return null } var cur = line.parent, no = indexOf(cur.lines, line); for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (var i = 0;; ++i) { if (chunk.children[i] == cur) { break } no += chunk.children[i].chunkSize(); } } return no + cur.first } // Find the line at the given vertical position, using the height // information in the document tree. function lineAtHeight(chunk, h) { var n = chunk.first; outer: do { for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { var child = chunk.children[i$1], ch = child.height; if (h < ch) { chunk = child; continue outer } h -= ch; n += child.chunkSize(); } return n } while (!chunk.lines) var i = 0; for (; i < chunk.lines.length; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) { break } h -= lh; } return n + i } function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} function lineNumberFor(options, i) { return String(options.lineNumberFormatter(i + options.firstLineNumber)) } // A Pos instance represents a position within the text. function Pos(line, ch, sticky) { if ( sticky === void 0 ) sticky = null; if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } this.line = line; this.ch = ch; this.sticky = sticky; } // Compare two positions, return 0 if they are the same, a negative // number when a is less, and a positive number otherwise. function cmp(a, b) { return a.line - b.line || a.ch - b.ch } function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } function copyPos(x) {return Pos(x.line, x.ch)} function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } function minPos(a, b) { return cmp(a, b) < 0 ? a : b } // Most of the external API clips given positions to make sure they // actually exist within the document. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} function clipPos(doc, pos) { if (pos.line < doc.first) { return Pos(doc.first, 0) } var last = doc.first + doc.size - 1; if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } return clipToLen(pos, getLine(doc, pos.line).text.length) } function clipToLen(pos, linelen) { var ch = pos.ch; if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } else if (ch < 0) { return Pos(pos.line, 0) } else { return pos } } function clipPosArray(doc, array) { var out = []; for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } return out } var SavedContext = function(state, lookAhead) { this.state = state; this.lookAhead = lookAhead; }; var Context = function(doc, state, line, lookAhead) { this.state = state; this.doc = doc; this.line = line; this.maxLookAhead = lookAhead || 0; this.baseTokens = null; this.baseTokenPos = 1; }; Context.prototype.lookAhead = function (n) { var line = this.doc.getLine(this.line + n); if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } return line }; Context.prototype.baseToken = function (n) { if (!this.baseTokens) { return null } while (this.baseTokens[this.baseTokenPos] <= n) { this.baseTokenPos += 2; } var type = this.baseTokens[this.baseTokenPos + 1]; return {type: type && type.replace(/( |^)overlay .*/, ""), size: this.baseTokens[this.baseTokenPos] - n} }; Context.prototype.nextLine = function () { this.line++; if (this.maxLookAhead > 0) { this.maxLookAhead--; } }; Context.fromSaved = function (doc, saved, line) { if (saved instanceof SavedContext) { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } else { return new Context(doc, copyState(doc.mode, saved), line) } }; Context.prototype.save = function (copy) { var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state }; // Compute a style array (an array starting with a mode generation // -- for invalidation -- followed by pairs of end positions and // style strings), which is used to highlight the tokens on the // line. function highlightLine(cm, line, context, forceToEnd) { // A styles array always starts with a number identifying the // mode/overlays that it is based on (for easy invalidation). var st = [cm.state.modeGen], lineClasses = {}; // Compute the base array of styles runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, lineClasses, forceToEnd); var state = context.state; // Run overlays, adjust style array. var loop = function ( o ) { context.baseTokens = st; var overlay = cm.state.overlays[o], i = 1, at = 0; context.state = true; runMode(cm, line.text, overlay.mode, context, function (end, style) { var start = i; // Ensure there's a token end at the current position, and that i points at it while (at < end) { var i_end = st[i]; if (i_end > end) { st.splice(i, 1, end, st[i+1], i_end); } i += 2; at = Math.min(end, i_end); } if (!style) { return } if (overlay.opaque) { st.splice(start, i - start, end, "overlay " + style); i = start + 2; } else { for (; start < i; start += 2) { var cur = st[start+1]; st[start+1] = (cur ? cur + " " : "") + "overlay " + style; } } }, lineClasses); context.state = state; context.baseTokens = null; context.baseTokenPos = 1; }; for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} } function getLineStyles(cm, line, updateFrontier) { if (!line.styles || line.styles[0] != cm.state.modeGen) { var context = getContextBefore(cm, lineNo(line)); var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); var result = highlightLine(cm, line, context); if (resetState) { context.state = resetState; } line.stateAfter = context.save(!resetState); line.styles = result.styles; if (result.classes) { line.styleClasses = result.classes; } else if (line.styleClasses) { line.styleClasses = null; } if (updateFrontier === cm.doc.highlightFrontier) { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } } return line.styles } function getContextBefore(cm, n, precise) { var doc = cm.doc, display = cm.display; if (!doc.mode.startState) { return new Context(doc, true, n) } var start = findStartLine(cm, n, precise); var saved = start > doc.first && getLine(doc, start - 1).stateAfter; var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); doc.iter(start, n, function (line) { processLine(cm, line.text, context); var pos = context.line; line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; context.nextLine(); }); if (precise) { doc.modeFrontier = context.line; } return context } // Lightweight form of highlight -- proceed over this line and // update state, but don't save a style array. Used for lines that // aren't currently visible. function processLine(cm, text, context, startAt) { var mode = cm.doc.mode; var stream = new StringStream(text, cm.options.tabSize, context); stream.start = stream.pos = startAt || 0; if (text == "") { callBlankLine(mode, context.state); } while (!stream.eol()) { readToken(mode, stream, context.state); stream.start = stream.pos; } } function callBlankLine(mode, state) { if (mode.blankLine) { return mode.blankLine(state) } if (!mode.innerMode) { return } var inner = innerMode(mode, state); if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } } function readToken(mode, stream, state, inner) { for (var i = 0; i < 10; i++) { if (inner) { inner[0] = innerMode(mode, state).mode; } var style = mode.token(stream, state); if (stream.pos > stream.start) { return style } } throw new Error("Mode " + mode.name + " failed to advance stream.") } var Token = function(stream, type, state) { this.start = stream.start; this.end = stream.pos; this.string = stream.current(); this.type = type || null; this.state = state; }; // Utility for getTokenAt and getLineTokens function takeToken(cm, pos, precise, asArray) { var doc = cm.doc, mode = doc.mode, style; pos = clipPos(doc, pos); var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; if (asArray) { tokens = []; } while ((asArray || stream.pos < pos.ch) && !stream.eol()) { stream.start = stream.pos; style = readToken(mode, stream, context.state); if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } } return asArray ? tokens : new Token(stream, style, context.state) } function extractLineClasses(type, output) { if (type) { for (;;) { var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); if (!lineClass) { break } type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); var prop = lineClass[1] ? "bgClass" : "textClass"; if (output[prop] == null) { output[prop] = lineClass[2]; } else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop])) { output[prop] += " " + lineClass[2]; } } } return type } // Run the given mode's parser over a line, calling f for each token. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { var flattenSpans = mode.flattenSpans; if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } var curStart = 0, curStyle = null; var stream = new StringStream(text, cm.options.tabSize, context), style; var inner = cm.options.addModeClass && [null]; if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } while (!stream.eol()) { if (stream.pos > cm.options.maxHighlightLength) { flattenSpans = false; if (forceToEnd) { processLine(cm, text, context, stream.pos); } stream.pos = text.length; style = null; } else { style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); } if (inner) { var mName = inner[0].name; if (mName) { style = "m-" + (style ? mName + " " + style : mName); } } if (!flattenSpans || curStyle != style) { while (curStart < stream.start) { curStart = Math.min(stream.start, curStart + 5000); f(curStart, curStyle); } curStyle = style; } stream.start = stream.pos; } while (curStart < stream.pos) { // Webkit seems to refuse to render text nodes longer than 57444 // characters, and returns inaccurate measurements in nodes // starting around 5000 chars. var pos = Math.min(stream.pos, curStart + 5000); f(pos, curStyle); curStart = pos; } } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(cm, n, precise) { var minindent, minline, doc = cm.doc; var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); for (var search = n; search > lim; --search) { if (search <= doc.first) { return doc.first } var line = getLine(doc, search - 1), after = line.stateAfter; if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) { return search } var indented = countColumn(line.text, null, cm.options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline } function retreatFrontier(doc, n) { doc.modeFrontier = Math.min(doc.modeFrontier, n); if (doc.highlightFrontier < n - 10) { return } var start = doc.first; for (var line = n - 1; line > start; line--) { var saved = getLine(doc, line).stateAfter; // change is on 3 // state on line 1 looked ahead 2 -- so saw 3 // test 1 + 2 < 3 should cover this if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { start = line + 1; break } } doc.highlightFrontier = Math.min(doc.highlightFrontier, start); } // Optimize some code when these features are not used. var sawReadOnlySpans = false, sawCollapsedSpans = false; function seeReadOnlySpans() { sawReadOnlySpans = true; } function seeCollapsedSpans() { sawCollapsedSpans = true; } // TEXTMARKER SPANS function MarkedSpan(marker, from, to) { this.marker = marker; this.from = from; this.to = to; } // Search an array of spans for a span matching the given marker. function getMarkedSpanFor(spans, marker) { if (spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.marker == marker) { return span } } } } // Remove a span from an array, returning undefined if no spans are // left (we don't store arrays for lines without spans). function removeMarkedSpan(spans, span) { var r; for (var i = 0; i < spans.length; ++i) { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } return r } // Add a span to a line. function addMarkedSpan(line, span) { line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; span.marker.attachLine(line); } // Used for the algorithm that adjusts markers for a change in the // document. These functions cut an array of spans at a given // character position, returning an array of remaining chunks (or // undefined if nothing remains). function markedSpansBefore(old, startCh, isInsert) { var nw; if (old) { for (var i = 0; i < old.length; ++i) { var span = old[i], marker = span.marker; var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); } } } return nw } function markedSpansAfter(old, endCh, isInsert) { var nw; if (old) { for (var i = 0; i < old.length; ++i) { var span = old[i], marker = span.marker; var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); } } } return nw } // Given a change object, compute the new set of marker spans that // cover the line in which the change took place. Removes spans // entirely within the change, reconnects spans belonging to the // same marker that appear on both sides of the change, and cuts off // spans partially within the change. Returns an array of span // arrays with one element for each line in (after) the change. function stretchSpansOverChange(doc, change) { if (change.full) { return null } var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; if (!oldFirst && !oldLast) { return null } var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; // Get the spans that 'stick out' on both sides var first = markedSpansBefore(oldFirst, startCh, isInsert); var last = markedSpansAfter(oldLast, endCh, isInsert); // Next, merge those two ends var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); if (first) { // Fix up .to properties of first for (var i = 0; i < first.length; ++i) { var span = first[i]; if (span.to == null) { var found = getMarkedSpanFor(last, span.marker); if (!found) { span.to = startCh; } else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } } } } if (last) { // Fix up .from in last (or move them into first in case of sameLine) for (var i$1 = 0; i$1 < last.length; ++i$1) { var span$1 = last[i$1]; if (span$1.to != null) { span$1.to += offset; } if (span$1.from == null) { var found$1 = getMarkedSpanFor(first, span$1.marker); if (!found$1) { span$1.from = offset; if (sameLine) { (first || (first = [])).push(span$1); } } } else { span$1.from += offset; if (sameLine) { (first || (first = [])).push(span$1); } } } } // Make sure we didn't create any zero-length spans if (first) { first = clearEmptySpans(first); } if (last && last != first) { last = clearEmptySpans(last); } var newMarkers = [first]; if (!sameLine) { // Fill gap with whole-line-spans var gap = change.text.length - 2, gapMarkers; if (gap > 0 && first) { for (var i$2 = 0; i$2 < first.length; ++i$2) { if (first[i$2].to == null) { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } for (var i$3 = 0; i$3 < gap; ++i$3) { newMarkers.push(gapMarkers); } newMarkers.push(last); } return newMarkers } // Remove spans that are empty and don't have a clearWhenEmpty // option of false. function clearEmptySpans(spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { spans.splice(i--, 1); } } if (!spans.length) { return null } return spans } // Used to 'clip' out readOnly ranges when making a change. function removeReadOnlyRanges(doc, from, to) { var markers = null; doc.iter(from.line, to.line + 1, function (line) { if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var mark = line.markedSpans[i].marker; if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { (markers || (markers = [])).push(mark); } } } }); if (!markers) { return null } var parts = [{from: from, to: to}]; for (var i = 0; i < markers.length; ++i) { var mk = markers[i], m = mk.find(0); for (var j = 0; j < parts.length; ++j) { var p = parts[j]; if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { newParts.push({from: p.from, to: m.from}); } if (dto > 0 || !mk.inclusiveRight && !dto) { newParts.push({from: m.to, to: p.to}); } parts.splice.apply(parts, newParts); j += newParts.length - 3; } } return parts } // Connect or disconnect spans from a line. function detachMarkedSpans(line) { var spans = line.markedSpans; if (!spans) { return } for (var i = 0; i < spans.length; ++i) { spans[i].marker.detachLine(line); } line.markedSpans = null; } function attachMarkedSpans(line, spans) { if (!spans) { return } for (var i = 0; i < spans.length; ++i) { spans[i].marker.attachLine(line); } line.markedSpans = spans; } // Helpers used when computing which overlapping collapsed span // counts as the larger one. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } // Returns a number indicating which of two overlapping collapsed // spans is larger (and thus includes the other). Falls back to // comparing ids when the spans cover exactly the same range. function compareCollapsedMarkers(a, b) { var lenDiff = a.lines.length - b.lines.length; if (lenDiff != 0) { return lenDiff } var aPos = a.find(), bPos = b.find(); var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); if (fromCmp) { return -fromCmp } var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); if (toCmp) { return toCmp } return b.id - a.id } // Find out whether a line ends or starts in a collapsed span. If // so, return the marker for that span. function collapsedSpanAtSide(line, start) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { sp = sps[i]; if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } } } return found } function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } function collapsedSpanAround(line, ch) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) { for (var i = 0; i < sps.length; ++i) { var sp = sps[i]; if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } } } return found } // Test whether there exists a collapsed span that partially // overlaps (covers the start or end, but not both) of a new span. // Such overlap is not allowed. function conflictingCollapsedRange(doc, lineNo, from, to, marker) { var line = getLine(doc, lineNo); var sps = sawCollapsedSpans && line.markedSpans; if (sps) { for (var i = 0; i < sps.length; ++i) { var sp = sps[i]; if (!sp.marker.collapsed) { continue } var found = sp.marker.find(0); var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { return true } } } } // A visual line is a line as drawn on the screen. Folding, for // example, can cause multiple logical lines to appear on the same // visual line. This finds the start of the visual line that the // given line is part of (usually that is the line itself). function visualLine(line) { var merged; while (merged = collapsedSpanAtStart(line)) { line = merged.find(-1, true).line; } return line } function visualLineEnd(line) { var merged; while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; } return line } // Returns an array of logical lines that continue the visual line // started by the argument, or undefined if there are no such lines. function visualLineContinued(line) { var merged, lines; while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line ;(lines || (lines = [])).push(line); } return lines } // Get the line number of the start of the visual line that the // given line number is part of. function visualLineNo(doc, lineN) { var line = getLine(doc, lineN), vis = visualLine(line); if (line == vis) { return lineN } return lineNo(vis) } // Get the line number of the start of the next visual line after // the given line. function visualLineEndNo(doc, lineN) { if (lineN > doc.lastLine()) { return lineN } var line = getLine(doc, lineN), merged; if (!lineIsHidden(doc, line)) { return lineN } while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; } return lineNo(line) + 1 } // Compute whether a line is hidden. Lines count as hidden when they // are part of a visual line that starts with another line, or when // they are entirely covered by collapsed, non-widget span. function lineIsHidden(doc, line) { var sps = sawCollapsedSpans && line.markedSpans; if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) { continue } if (sp.from == null) { return true } if (sp.marker.widgetNode) { continue } if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) { return true } } } } function lineIsHiddenInner(doc, line, span) { if (span.to == null) { var end = span.marker.find(1, true); return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) } if (span.marker.inclusiveRight && span.to == line.text.length) { return true } for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { sp = line.markedSpans[i]; if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) { return true } } } // Find the height above the given line. function heightAtLine(lineObj) { lineObj = visualLine(lineObj); var h = 0, chunk = lineObj.parent; for (var i = 0; i < chunk.lines.length; ++i) { var line = chunk.lines[i]; if (line == lineObj) { break } else { h += line.height; } } for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { for (var i$1 = 0; i$1 < p.children.length; ++i$1) { var cur = p.children[i$1]; if (cur == chunk) { break } else { h += cur.height; } } } return h } // Compute the character length of a line, taking into account // collapsed ranges (see markText) that might hide parts, and join // other lines onto it. function lineLength(line) { if (line.height == 0) { return 0 } var len = line.text.length, merged, cur = line; while (merged = collapsedSpanAtStart(cur)) { var found = merged.find(0, true); cur = found.from.line; len += found.from.ch - found.to.ch; } cur = line; while (merged = collapsedSpanAtEnd(cur)) { var found$1 = merged.find(0, true); len -= cur.text.length - found$1.from.ch; cur = found$1.to.line; len += cur.text.length - found$1.to.ch; } return len } // Find the longest line in the document. function findMaxLine(cm) { var d = cm.display, doc = cm.doc; d.maxLine = getLine(doc, doc.first); d.maxLineLength = lineLength(d.maxLine); d.maxLineChanged = true; doc.iter(function (line) { var len = lineLength(line); if (len > d.maxLineLength) { d.maxLineLength = len; d.maxLine = line; } }); } // LINE DATA STRUCTURE // Line objects. These hold state related to a line, including // highlighting info (the styles array). var Line = function(text, markedSpans, estimateHeight) { this.text = text; attachMarkedSpans(this, markedSpans); this.height = estimateHeight ? estimateHeight(this) : 1; }; Line.prototype.lineNo = function () { return lineNo(this) }; eventMixin(Line); // Change the content (text, markers) of a line. Automatically // invalidates cached information and tries to re-estimate the // line's height. function updateLine(line, text, markedSpans, estimateHeight) { line.text = text; if (line.stateAfter) { line.stateAfter = null; } if (line.styles) { line.styles = null; } if (line.order != null) { line.order = null; } detachMarkedSpans(line); attachMarkedSpans(line, markedSpans); var estHeight = estimateHeight ? estimateHeight(line) : 1; if (estHeight != line.height) { updateLineHeight(line, estHeight); } } // Detach a line from the document tree and its markers. function cleanUpLine(line) { line.parent = null; detachMarkedSpans(line); } // Convert a style as returned by a mode (either null, or a string // containing one or more styles) to a CSS style. This is cached, // and also looks for line-wide styles. var styleToClassCache = {}, styleToClassCacheWithMode = {}; function interpretTokenStyle(style, options) { if (!style || /^\s*$/.test(style)) { return null } var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")) } // Render the DOM representation of the text of a line. Also builds // up a 'line map', which points at the DOM nodes that represent // specific stretches of text, and is used by the measuring code. // The returned object contains the DOM node, this map, and // information about line-wide styles that were set by the mode. function buildLineContent(cm, lineView) { // The padding-right forces the element to have a 'border', which // is needed on Webkit to be able to get line-level bounding // rectangles for it (in measureChar). var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, col: 0, pos: 0, cm: cm, trailingSpace: false, splitSpaces: cm.getOption("lineWrapping")}; lineView.measure = {}; // Iterate over the logical lines that make up this visual line. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); builder.pos = 0; builder.addToken = buildToken; // Optionally wire in some hacks into the token-rendering // algorithm, to deal with browser quirks. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { builder.addToken = buildTokenBadBidi(builder.addToken, order); } builder.map = []; var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); if (line.styleClasses) { if (line.styleClasses.bgClass) { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } if (line.styleClasses.textClass) { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } } // Ensure at least a single node is present, for measuring. if (builder.map.length == 0) { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } // Store the map and a cache object for the current logical line if (i == 0) { lineView.measure.map = builder.map; lineView.measure.cache = {}; } else { (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); } } // See issue #2901 if (webkit) { var last = builder.content.lastChild; if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) { builder.content.className = "cm-tab-wrap-hack"; } } signal(cm, "renderLine", cm, lineView.line, builder.pre); if (builder.pre.className) { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } return builder } function defaultSpecialCharPlaceholder(ch) { var token = elt("span", "\u2022", "cm-invalidchar"); token.title = "\\u" + ch.charCodeAt(0).toString(16); token.setAttribute("aria-label", token.title); return token } // Build up the DOM representation for a single token, and add it to // the line map. Takes care to render special characters separately. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { if (!text) { return } var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; var special = builder.cm.state.specialChars, mustWrap = false; var content; if (!special.test(text)) { builder.col += text.length; content = document.createTextNode(displayText); builder.map.push(builder.pos, builder.pos + text.length, content); if (ie && ie_version < 9) { mustWrap = true; } builder.pos += text.length; } else { content = document.createDocumentFragment(); var pos = 0; while (true) { special.lastIndex = pos; var m = special.exec(text); var skipped = m ? m.index - pos : text.length - pos; if (skipped) { var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } else { content.appendChild(txt); } builder.map.push(builder.pos, builder.pos + skipped, txt); builder.col += skipped; builder.pos += skipped; } if (!m) { break } pos += skipped + 1; var txt$1 = (void 0); if (m[0] == "\t") { var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); txt$1.setAttribute("role", "presentation"); txt$1.setAttribute("cm-text", "\t"); builder.col += tabWidth; } else if (m[0] == "\r" || m[0] == "\n") { txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); txt$1.setAttribute("cm-text", m[0]); builder.col += 1; } else { txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); txt$1.setAttribute("cm-text", m[0]); if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } else { content.appendChild(txt$1); } builder.col += 1; } builder.map.push(builder.pos, builder.pos + 1, txt$1); builder.pos++; } } builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; if (style || startStyle || endStyle || mustWrap || css || attributes) { var fullStyle = style || ""; if (startStyle) { fullStyle += startStyle; } if (endStyle) { fullStyle += endStyle; } var token = elt("span", [content], fullStyle, css); if (attributes) { for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { token.setAttribute(attr, attributes[attr]); } } } return builder.content.appendChild(token) } builder.content.appendChild(content); } // Change some spaces to NBSP to prevent the browser from collapsing // trailing spaces at the end of a line when rendering text (issue #1362). function splitSpaces(text, trailingBefore) { if (text.length > 1 && !/ /.test(text)) { return text } var spaceBefore = trailingBefore, result = ""; for (var i = 0; i < text.length; i++) { var ch = text.charAt(i); if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) { ch = "\u00a0"; } result += ch; spaceBefore = ch == " "; } return result } // Work around nonsense dimensions being reported for stretches of // right-to-left text. function buildTokenBadBidi(inner, order) { return function (builder, text, style, startStyle, endStyle, css, attributes) { style = style ? style + " cm-force-border" : "cm-force-border"; var start = builder.pos, end = start + text.length; for (;;) { // Find the part that overlaps with the start of this text var part = (void 0); for (var i = 0; i < order.length; i++) { part = order[i]; if (part.to > start && part.from <= start) { break } } if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) } inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); startStyle = null; text = text.slice(part.to - start); start = part.to; } } } function buildCollapsedSpan(builder, size, marker, ignoreWidget) { var widget = !ignoreWidget && marker.widgetNode; if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { if (!widget) { widget = builder.content.appendChild(document.createElement("span")); } widget.setAttribute("cm-marker", marker.id); } if (widget) { builder.cm.display.input.setUneditable(widget); builder.content.appendChild(widget); } builder.pos += size; builder.trailingSpace = false; } // Outputs a number of spans to make up a line, taking highlighting // and marked text into account. function insertLineContent(line, builder, styles) { var spans = line.markedSpans, allText = line.text, at = 0; if (!spans) { for (var i$1 = 1; i$1 < styles.length; i$1+=2) { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } return } var len = allText.length, pos = 0, i = 1, text = "", style, css; var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes; for (;;) { if (nextChange == pos) { // Update current marker set spanStyle = spanEndStyle = spanStartStyle = css = ""; attributes = null; collapsed = null; nextChange = Infinity; var foundBookmarks = [], endStyles = (void 0); for (var j = 0; j < spans.length; ++j) { var sp = spans[j], m = sp.marker; if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { foundBookmarks.push(m); } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { if (sp.to != null && sp.to != pos && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } if (m.className) { spanStyle += " " + m.className; } if (m.css) { css = (css ? css + ";" : "") + m.css; } if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } // support for the old title property // https://github.com/codemirror/CodeMirror/pull/5673 if (m.title) { (attributes || (attributes = {})).title = m.title; } if (m.attributes) { for (var attr in m.attributes) { (attributes || (attributes = {}))[attr] = m.attributes[attr]; } } if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { collapsed = sp; } } else if (sp.from > pos && nextChange > sp.from) { nextChange = sp.from; } } if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } if (collapsed && (collapsed.from || 0) == pos) { buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); if (collapsed.to == null) { return } if (collapsed.to == pos) { collapsed = false; } } } if (pos >= len) { break } var upto = Math.min(len, nextChange); while (true) { if (text) { var end = pos + text.length; if (!collapsed) { var tokenText = end > upto ? text.slice(0, upto - pos) : text; builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); } if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} pos = end; spanStartStyle = ""; } text = allText.slice(at, at = styles[i++]); style = interpretTokenStyle(styles[i++], builder.cm.options); } } } // These objects are used to represent the visible (currently drawn) // part of the document. A LineView may correspond to multiple // logical lines, if those are connected by collapsed ranges. function LineView(doc, line, lineN) { // The starting line this.line = line; // Continuing lines, if any this.rest = visualLineContinued(line); // Number of logical lines in this visual line this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; this.node = this.text = null; this.hidden = lineIsHidden(doc, line); } // Create a range of LineView objects for the given lines. function buildViewArray(cm, from, to) { var array = [], nextPos; for (var pos = from; pos < to; pos = nextPos) { var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); nextPos = pos + view.size; array.push(view); } return array } var operationGroup = null; function pushOperation(op) { if (operationGroup) { operationGroup.ops.push(op); } else { op.ownsGroup = operationGroup = { ops: [op], delayedCallbacks: [] }; } } function fireCallbacksForOps(group) { // Calls delayed callbacks and cursorActivity handlers until no // new ones appear var callbacks = group.delayedCallbacks, i = 0; do { for (; i < callbacks.length; i++) { callbacks[i].call(null); } for (var j = 0; j < group.ops.length; j++) { var op = group.ops[j]; if (op.cursorActivityHandlers) { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } } } while (i < callbacks.length) } function finishOperation(op, endCb) { var group = op.ownsGroup; if (!group) { return } try { fireCallbacksForOps(group); } finally { operationGroup = null; endCb(group); } } var orphanDelayedCallbacks = null; // Often, we want to signal events at a point where we are in the // middle of some work, but don't want the handler to start calling // other methods on the editor, which might be in an inconsistent // state or simply not expect any other events to happen. // signalLater looks whether there are any handlers, and schedules // them to be executed when the last operation ends, or, if no // operation is active, when a timeout fires. function signalLater(emitter, type /*, values...*/) { var arr = getHandlers(emitter, type); if (!arr.length) { return } var args = Array.prototype.slice.call(arguments, 2), list; if (operationGroup) { list = operationGroup.delayedCallbacks; } else if (orphanDelayedCallbacks) { list = orphanDelayedCallbacks; } else { list = orphanDelayedCallbacks = []; setTimeout(fireOrphanDelayed, 0); } var loop = function ( i ) { list.push(function () { return arr[i].apply(null, args); }); }; for (var i = 0; i < arr.length; ++i) loop( i ); } function fireOrphanDelayed() { var delayed = orphanDelayedCallbacks; orphanDelayedCallbacks = null; for (var i = 0; i < delayed.length; ++i) { delayed[i](); } } // When an aspect of a line changes, a string is added to // lineView.changes. This updates the relevant part of the line's // DOM structure. function updateLineForChanges(cm, lineView, lineN, dims) { for (var j = 0; j < lineView.changes.length; j++) { var type = lineView.changes[j]; if (type == "text") { updateLineText(cm, lineView); } else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } else if (type == "class") { updateLineClasses(cm, lineView); } else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } } lineView.changes = null; } // Lines with gutter elements, widgets or a background class need to // be wrapped, and have the extra elements added to the wrapper div function ensureLineWrapped(lineView) { if (lineView.node == lineView.text) { lineView.node = elt("div", null, null, "position: relative"); if (lineView.text.parentNode) { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } lineView.node.appendChild(lineView.text); if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } } return lineView.node } function updateLineBackground(cm, lineView) { var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; if (cls) { cls += " CodeMirror-linebackground"; } if (lineView.background) { if (cls) { lineView.background.className = cls; } else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } } else if (cls) { var wrap = ensureLineWrapped(lineView); lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); cm.display.input.setUneditable(lineView.background); } } // Wrapper around buildLineContent which will reuse the structure // in display.externalMeasured when possible. function getLineContent(cm, lineView) { var ext = cm.display.externalMeasured; if (ext && ext.line == lineView.line) { cm.display.externalMeasured = null; lineView.measure = ext.measure; return ext.built } return buildLineContent(cm, lineView) } // Redraw the line's text. Interacts with the background and text // classes because the mode may output tokens that influence these // classes. function updateLineText(cm, lineView) { var cls = lineView.text.className; var built = getLineContent(cm, lineView); if (lineView.text == lineView.node) { lineView.node = built.pre; } lineView.text.parentNode.replaceChild(built.pre, lineView.text); lineView.text = built.pre; if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { lineView.bgClass = built.bgClass; lineView.textClass = built.textClass; updateLineClasses(cm, lineView); } else if (cls) { lineView.text.className = cls; } } function updateLineClasses(cm, lineView) { updateLineBackground(cm, lineView); if (lineView.line.wrapClass) { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } else if (lineView.node != lineView.text) { lineView.node.className = ""; } var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; lineView.text.className = textClass || ""; } function updateLineGutter(cm, lineView, lineN, dims) { if (lineView.gutter) { lineView.node.removeChild(lineView.gutter); lineView.gutter = null; } if (lineView.gutterBackground) { lineView.node.removeChild(lineView.gutterBackground); lineView.gutterBackground = null; } if (lineView.line.gutterClass) { var wrap = ensureLineWrapped(lineView); lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); cm.display.input.setUneditable(lineView.gutterBackground); wrap.insertBefore(lineView.gutterBackground, lineView.text); } var markers = lineView.line.gutterMarkers; if (cm.options.lineNumbers || markers) { var wrap$1 = ensureLineWrapped(lineView); var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); cm.display.input.setUneditable(gutterWrap); wrap$1.insertBefore(gutterWrap, lineView.text); if (lineView.line.gutterClass) { gutterWrap.className += " " + lineView.line.gutterClass; } if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { lineView.lineNumber = gutterWrap.appendChild( elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id]; if (found) { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } } } } } function updateLineWidgets(cm, lineView, dims) { if (lineView.alignable) { lineView.alignable = null; } var isWidget = classTest("CodeMirror-linewidget"); for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { next = node.nextSibling; if (isWidget.test(node.className)) { lineView.node.removeChild(node); } } insertLineWidgets(cm, lineView, dims); } // Build a line's DOM representation from scratch function buildLineElement(cm, lineView, lineN, dims) { var built = getLineContent(cm, lineView); lineView.text = lineView.node = built.pre; if (built.bgClass) { lineView.bgClass = built.bgClass; } if (built.textClass) { lineView.textClass = built.textClass; } updateLineClasses(cm, lineView); updateLineGutter(cm, lineView, lineN, dims); insertLineWidgets(cm, lineView, dims); return lineView.node } // A lineView may contain multiple logical lines (when merged by // collapsed spans). The widgets for all of them need to be drawn. function insertLineWidgets(cm, lineView, dims) { insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } } function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { if (!line.widgets) { return } var wrap = ensureLineWrapped(lineView); for (var i = 0, ws = line.widgets; i < ws.length; ++i) { var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } positionLineWidget(widget, node, lineView, dims); cm.display.input.setUneditable(node); if (allowAbove && widget.above) { wrap.insertBefore(node, lineView.gutter || lineView.text); } else { wrap.appendChild(node); } signalLater(widget, "redraw"); } } function positionLineWidget(widget, node, lineView, dims) { if (widget.noHScroll) { (lineView.alignable || (lineView.alignable = [])).push(node); var width = dims.wrapperWidth; node.style.left = dims.fixedPos + "px"; if (!widget.coverGutter) { width -= dims.gutterTotalWidth; node.style.paddingLeft = dims.gutterTotalWidth + "px"; } node.style.width = width + "px"; } if (widget.coverGutter) { node.style.zIndex = 5; node.style.position = "relative"; if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } } } function widgetHeight(widget) { if (widget.height != null) { return widget.height } var cm = widget.doc.cm; if (!cm) { return 0 } if (!contains(document.body, widget.node)) { var parentStyle = "position: relative;"; if (widget.coverGutter) { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } if (widget.noHScroll) { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); } return widget.height = widget.node.parentNode.offsetHeight } // Return true when the given mouse event happened in a widget function eventInWidget(display, e) { for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || (n.parentNode == display.sizer && n != display.mover)) { return true } } } // POSITION MEASUREMENT function paddingTop(display) {return display.lineSpace.offsetTop} function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} function paddingH(display) { if (display.cachedPaddingH) { return display.cachedPaddingH } var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } return data } function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } function displayWidth(cm) { return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth } function displayHeight(cm) { return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight } // Ensure the lineView.wrapping.heights array is populated. This is // an array of bottom offsets for the lines that make up a drawn // line. When lineWrapping is on, there might be more than one // height. function ensureLineHeights(cm, lineView, rect) { var wrapping = cm.options.lineWrapping; var curWidth = wrapping && displayWidth(cm); if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { var heights = lineView.measure.heights = []; if (wrapping) { lineView.measure.width = curWidth; var rects = lineView.text.firstChild.getClientRects(); for (var i = 0; i < rects.length - 1; i++) { var cur = rects[i], next = rects[i + 1]; if (Math.abs(cur.bottom - next.bottom) > 2) { heights.push((cur.bottom + next.top) / 2 - rect.top); } } } heights.push(rect.bottom - rect.top); } } // Find a line map (mapping character offsets to text nodes) and a // measurement cache for the given line number. (A line view might // contain multiple lines when collapsed ranges are present.) function mapFromLineView(lineView, line, lineN) { if (lineView.line == line) { return {map: lineView.measure.map, cache: lineView.measure.cache} } for (var i = 0; i < lineView.rest.length; i++) { if (lineView.rest[i] == line) { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) { if (lineNo(lineView.rest[i$1]) > lineN) { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } } // Render a line into the hidden node display.externalMeasured. Used // when measurement is needed for a line that's not in the viewport. function updateExternalMeasurement(cm, line) { line = visualLine(line); var lineN = lineNo(line); var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); view.lineN = lineN; var built = view.built = buildLineContent(cm, view); view.text = built.pre; removeChildrenAndAdd(cm.display.lineMeasure, built.pre); return view } // Get a {top, bottom, left, right} box (in line-local coordinates) // for a given character. function measureChar(cm, line, ch, bias) { return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) } // Find a line view that corresponds to the given line number. function findViewForLine(cm, lineN) { if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { return cm.display.view[findViewIndex(cm, lineN)] } var ext = cm.display.externalMeasured; if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { return ext } } // Measurement can be split in two steps, the set-up work that // applies to the whole line, and the measurement of the actual // character. Functions like coordsChar, that need to do a lot of // measurements in a row, can thus ensure that the set-up work is // only done once. function prepareMeasureForLine(cm, line) { var lineN = lineNo(line); var view = findViewForLine(cm, lineN); if (view && !view.text) { view = null; } else if (view && view.changes) { updateLineForChanges(cm, view, lineN, getDimensions(cm)); cm.curOp.forceUpdate = true; } if (!view) { view = updateExternalMeasurement(cm, line); } var info = mapFromLineView(view, line, lineN); return { line: line, view: view, rect: null, map: info.map, cache: info.cache, before: info.before, hasHeights: false } } // Given a prepared measurement object, measures the position of an // actual character (or fetches it from the cache). function measureCharPrepared(cm, prepared, ch, bias, varHeight) { if (prepared.before) { ch = -1; } var key = ch + (bias || ""), found; if (prepared.cache.hasOwnProperty(key)) { found = prepared.cache[key]; } else { if (!prepared.rect) { prepared.rect = prepared.view.text.getBoundingClientRect(); } if (!prepared.hasHeights) { ensureLineHeights(cm, prepared.view, prepared.rect); prepared.hasHeights = true; } found = measureCharInner(cm, prepared, ch, bias); if (!found.bogus) { prepared.cache[key] = found; } } return {left: found.left, right: found.right, top: varHeight ? found.rtop : found.top, bottom: varHeight ? found.rbottom : found.bottom} } var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; function nodeAndOffsetInLineMap(map, ch, bias) { var node, start, end, collapse, mStart, mEnd; // First, search the line map for the text node corresponding to, // or closest to, the target character. for (var i = 0; i < map.length; i += 3) { mStart = map[i]; mEnd = map[i + 1]; if (ch < mStart) { start = 0; end = 1; collapse = "left"; } else if (ch < mEnd) { start = ch - mStart; end = start + 1; } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { end = mEnd - mStart; start = end - 1; if (ch >= mEnd) { collapse = "right"; } } if (start != null) { node = map[i + 2]; if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { collapse = bias; } if (bias == "left" && start == 0) { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { node = map[(i -= 3) + 2]; collapse = "left"; } } if (bias == "right" && start == mEnd - mStart) { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { node = map[(i += 3) + 2]; collapse = "right"; } } break } } return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} } function getUsefulRect(rects, bias) { var rect = nullRect; if (bias == "left") { for (var i = 0; i < rects.length; i++) { if ((rect = rects[i]).left != rect.right) { break } } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { if ((rect = rects[i$1]).left != rect.right) { break } } } return rect } function measureCharInner(cm, prepared, ch, bias) { var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); var node = place.node, start = place.start, end = place.end, collapse = place.collapse; var rect; if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { rect = node.parentNode.getBoundingClientRect(); } else { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } if (rect.left || rect.right || start == 0) { break } end = start; start = start - 1; collapse = "right"; } if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } } else { // If it is a widget, simply get the box for the whole widget. if (start > 0) { collapse = bias = "right"; } var rects; if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { rect = rects[bias == "right" ? rects.length - 1 : 0]; } else { rect = node.getBoundingClientRect(); } } if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { var rSpan = node.parentNode.getClientRects()[0]; if (rSpan) { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } else { rect = nullRect; } } var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; var mid = (rtop + rbot) / 2; var heights = prepared.view.measure.heights; var i = 0; for (; i < heights.length - 1; i++) { if (mid < heights[i]) { break } } var top = i ? heights[i - 1] : 0, bot = heights[i]; var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, top: top, bottom: bot}; if (!rect.left && !rect.right) { result.bogus = true; } if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } return result } // Work around problem with bounding client rects on ranges being // returned incorrectly when zoomed on IE10 and below. function maybeUpdateRectForZooming(measure, rect) { if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { return rect } var scaleX = screen.logicalXDPI / screen.deviceXDPI; var scaleY = screen.logicalYDPI / screen.deviceYDPI; return {left: rect.left * scaleX, right: rect.right * scaleX, top: rect.top * scaleY, bottom: rect.bottom * scaleY} } function clearLineMeasurementCacheFor(lineView) { if (lineView.measure) { lineView.measure.cache = {}; lineView.measure.heights = null; if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) { lineView.measure.caches[i] = {}; } } } } function clearLineMeasurementCache(cm) { cm.display.externalMeasure = null; removeChildren(cm.display.lineMeasure); for (var i = 0; i < cm.display.view.length; i++) { clearLineMeasurementCacheFor(cm.display.view[i]); } } function clearCaches(cm) { clearLineMeasurementCache(cm); cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } cm.display.lineNumChars = null; } function pageScrollX() { // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 // which causes page_Offset and bounding client rects to use // different reference viewports and invalidate our calculations. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } return window.pageXOffset || (document.documentElement || document.body).scrollLeft } function pageScrollY() { if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } return window.pageYOffset || (document.documentElement || document.body).scrollTop } function widgetTopHeight(lineObj) { var height = 0; if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) { height += widgetHeight(lineObj.widgets[i]); } } } return height } // Converts a {top, bottom, left, right} box from line-local // coordinates into another coordinate system. Context may be one of // "line", "div" (display.lineDiv), "local"./null (editor), "window", // or "page". function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { if (!includeWidgets) { var height = widgetTopHeight(lineObj); rect.top += height; rect.bottom += height; } if (context == "line") { return rect } if (!context) { context = "local"; } var yOff = heightAtLine(lineObj); if (context == "local") { yOff += paddingTop(cm.display); } else { yOff -= cm.display.viewOffset; } if (context == "page" || context == "window") { var lOff = cm.display.lineSpace.getBoundingClientRect(); yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); rect.left += xOff; rect.right += xOff; } rect.top += yOff; rect.bottom += yOff; return rect } // Coverts a box from "div" coords to another coordinate system. // Context may be "window", "page", "div", or "local"./null. function fromCoordSystem(cm, coords, context) { if (context == "div") { return coords } var left = coords.left, top = coords.top; // First move into "page" coordinate system if (context == "page") { left -= pageScrollX(); top -= pageScrollY(); } else if (context == "local" || !context) { var localBox = cm.display.sizer.getBoundingClientRect(); left += localBox.left; top += localBox.top; } var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} } function charCoords(cm, pos, context, lineObj, bias) { if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) } // Returns a box for a given cursor position, which may have an // 'other' property containing the position of the secondary cursor // on a bidi boundary. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` // and after `char - 1` in writing order of `char - 1` // A cursor Pos(line, char, "after") is on the same visual line as `char` // and before `char` in writing order of `char` // Examples (upper-case letters are RTL, lower-case are LTR): // Pos(0, 1, ...) // before after // ab a|b a|b // aB a|B aB| // Ab |Ab A|b // AB B|A B|A // Every position after the last character on a line is considered to stick // to the last character on the line. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { lineObj = lineObj || getLine(cm.doc, pos.line); if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } function get(ch, right) { var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); if (right) { m.left = m.right; } else { m.right = m.left; } return intoCoordSystem(cm, lineObj, m, context) } var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; if (ch >= lineObj.text.length) { ch = lineObj.text.length; sticky = "before"; } else if (ch <= 0) { ch = 0; sticky = "after"; } if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } function getBidi(ch, partPos, invert) { var part = order[partPos], right = part.level == 1; return get(invert ? ch - 1 : ch, right != invert) } var partPos = getBidiPartAt(order, ch, sticky); var other = bidiOther; var val = getBidi(ch, partPos, sticky == "before"); if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } return val } // Used to cheaply estimate the coordinates for a position. Used for // intermediate scroll updates. function estimateCoords(cm, pos) { var left = 0; pos = clipPos(cm.doc, pos); if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } var lineObj = getLine(cm.doc, pos.line); var top = heightAtLine(lineObj) + paddingTop(cm.display); return {left: left, right: left, top: top, bottom: top + lineObj.height} } // Positions returned by coordsChar contain some extra information. // xRel is the relative x position of the input coordinates compared // to the found position (so xRel > 0 means the coordinates are to // the right of the character position, for example). When outside // is true, that means the coordinates lie outside the line's // vertical range. function PosWithInfo(line, ch, sticky, outside, xRel) { var pos = Pos(line, ch, sticky); pos.xRel = xRel; if (outside) { pos.outside = outside; } return pos } // Compute the character position closest to the given coordinates. // Input must be lineSpace-local ("div" coordinate system). function coordsChar(cm, x, y) { var doc = cm.doc; y += cm.display.viewOffset; if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) } var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; if (lineN > last) { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) } if (x < 0) { x = 0; } var lineObj = getLine(doc, lineN); for (;;) { var found = coordsCharInner(cm, lineObj, lineN, x, y); var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); if (!collapsed) { return found } var rangeEnd = collapsed.find(1); if (rangeEnd.line == lineN) { return rangeEnd } lineObj = getLine(doc, lineN = rangeEnd.line); } } function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { y -= widgetTopHeight(lineObj); var end = lineObj.text.length; var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0); end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end); return {begin: begin, end: end} } function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) } // Returns true if the given side of a box is after the given // coordinates, in top-to-bottom, left-to-right order. function boxIsAfter(box, x, y, left) { return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x } function coordsCharInner(cm, lineObj, lineNo, x, y) { // Move y into line-local coordinate space y -= heightAtLine(lineObj); var preparedMeasure = prepareMeasureForLine(cm, lineObj); // When directly calling `measureCharPrepared`, we have to adjust // for the widgets at this line. var widgetHeight = widgetTopHeight(lineObj); var begin = 0, end = lineObj.text.length, ltr = true; var order = getOrder(lineObj, cm.doc.direction); // If the line isn't plain left-to-right text, first figure out // which bidi section the coordinates fall into. if (order) { var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) (cm, lineObj, lineNo, preparedMeasure, order, x, y); ltr = part.level != 1; // The awkward -1 offsets are needed because findFirst (called // on these below) will treat its first bound as inclusive, // second as exclusive, but we want to actually address the // characters in the part's range begin = ltr ? part.from : part.to - 1; end = ltr ? part.to : part.from - 1; } // A binary search to find the first character whose bounding box // starts after the coordinates. If we run across any whose box wrap // the coordinates, store that. var chAround = null, boxAround = null; var ch = findFirst(function (ch) { var box = measureCharPrepared(cm, preparedMeasure, ch); box.top += widgetHeight; box.bottom += widgetHeight; if (!boxIsAfter(box, x, y, false)) { return false } if (box.top <= y && box.left <= x) { chAround = ch; boxAround = box; } return true }, begin, end); var baseX, sticky, outside = false; // If a box around the coordinates was found, use that if (boxAround) { // Distinguish coordinates nearer to the left or right side of the box var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; ch = chAround + (atStart ? 0 : 1); sticky = atStart ? "after" : "before"; baseX = atLeft ? boxAround.left : boxAround.right; } else { // (Adjust for extended bound, if necessary.) if (!ltr && (ch == end || ch == begin)) { ch++; } // To determine which side to associate with, get the box to the // left of the character and compare it's vertical position to the // coordinates sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ? "after" : "before"; // Now get accurate coordinates for this place, in order to get a // base X position var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure); baseX = coords.left; outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; } ch = skipExtendingChars(lineObj.text, ch, 1); return PosWithInfo(lineNo, ch, sticky, outside, x - baseX) } function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) { // Bidi parts are sorted left-to-right, and in a non-line-wrapping // situation, we can take this ordering to correspond to the visual // ordering. This finds the first part whose end is after the given // coordinates. var index = findFirst(function (i) { var part = order[i], ltr = part.level != 1; return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true) }, 0, order.length - 1); var part = order[index]; // If this isn't the first part, the part's start is also after // the coordinates, and the coordinates aren't on the same line as // that start, move one part back. if (index > 0) { var ltr = part.level != 1; var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure); if (boxIsAfter(start, x, y, true) && start.top > y) { part = order[index - 1]; } } return part } function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { // In a wrapped line, rtl text on wrapping boundaries can do things // that don't correspond to the ordering in our `order` array at // all, so a binary search doesn't work, and we want to return a // part that only spans one line so that the binary search in // coordsCharInner is safe. As such, we first find the extent of the // wrapped line, and then do a flat search in which we discard any // spans that aren't on the line. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); var begin = ref.begin; var end = ref.end; if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; } var part = null, closestDist = null; for (var i = 0; i < order.length; i++) { var p = order[i]; if (p.from >= end || p.to <= begin) { continue } var ltr = p.level != 1; var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; // Weigh against spans ending before this, so that they are only // picked if nothing ends after var dist = endX < x ? x - endX + 1e9 : endX - x; if (!part || closestDist > dist) { part = p; closestDist = dist; } } if (!part) { part = order[order.length - 1]; } // Clip the part to the wrapped line. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; } if (part.to > end) { part = {from: part.from, to: end, level: part.level}; } return part } var measureText; // Compute the default text height. function textHeight(display) { if (display.cachedTextHeight != null) { return display.cachedTextHeight } if (measureText == null) { measureText = elt("pre", null, "CodeMirror-line-like"); // Measure a bunch of lines, for browsers that compute // fractional heights. for (var i = 0; i < 49; ++i) { measureText.appendChild(document.createTextNode("x")); measureText.appendChild(elt("br")); } measureText.appendChild(document.createTextNode("x")); } removeChildrenAndAdd(display.measure, measureText); var height = measureText.offsetHeight / 50; if (height > 3) { display.cachedTextHeight = height; } removeChildren(display.measure); return height || 1 } // Compute the default character width. function charWidth(display) { if (display.cachedCharWidth != null) { return display.cachedCharWidth } var anchor = elt("span", "xxxxxxxxxx"); var pre = elt("pre", [anchor], "CodeMirror-line-like"); removeChildrenAndAdd(display.measure, pre); var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; if (width > 2) { display.cachedCharWidth = width; } return width || 10 } // Do a bulk-read of the DOM positions and sizes needed to draw the // view, so that we don't interleave reading and writing to the DOM. function getDimensions(cm) { var d = cm.display, left = {}, width = {}; var gutterLeft = d.gutters.clientLeft; for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { var id = cm.display.gutterSpecs[i].className; left[id] = n.offsetLeft + n.clientLeft + gutterLeft; width[id] = n.clientWidth; } return {fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth} } // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, // but using getBoundingClientRect to get a sub-pixel-accurate // result. function compensateForHScroll(display) { return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left } // Returns a function that estimates the height of a line, to use as // first approximation until the line becomes visible (and is thus // properly measurable). function estimateHeight(cm) { var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); return function (line) { if (lineIsHidden(cm.doc, line)) { return 0 } var widgetsHeight = 0; if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } } } if (wrapping) { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } else { return widgetsHeight + th } } } function estimateLineHeights(cm) { var doc = cm.doc, est = estimateHeight(cm); doc.iter(function (line) { var estHeight = est(line); if (estHeight != line.height) { updateLineHeight(line, estHeight); } }); } // Given a mouse event, find the corresponding position. If liberal // is false, it checks whether a gutter or scrollbar was clicked, // and returns null if it was. forRect is used by rectangular // selections, and tries to estimate a character position even for // coordinates beyond the right of the text. function posFromMouse(cm, e, liberal, forRect) { var display = cm.display; if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } var x, y, space = display.lineSpace.getBoundingClientRect(); // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX - space.left; y = e.clientY - space.top; } catch (e$1) { return null } var coords = coordsChar(cm, x, y), line; if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); } return coords } // Find the view element corresponding to a given line. Return null // when the line isn't visible. function findViewIndex(cm, n) { if (n >= cm.display.viewTo) { return null } n -= cm.display.viewFrom; if (n < 0) { return null } var view = cm.display.view; for (var i = 0; i < view.length; i++) { n -= view[i].size; if (n < 0) { return i } } } // Updates the display.view data structure for a given change to the // document. From and to are in pre-change coordinates. Lendiff is // the amount of lines added or subtracted by the change. This is // used for changes that span multiple lines, or change the way // lines are divided into visual lines. regLineChange (below) // registers single-line changes. function regChange(cm, from, to, lendiff) { if (from == null) { from = cm.doc.first; } if (to == null) { to = cm.doc.first + cm.doc.size; } if (!lendiff) { lendiff = 0; } var display = cm.display; if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { display.updateLineNumbers = from; } cm.curOp.viewChanged = true; if (from >= display.viewTo) { // Change after if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { resetView(cm); } } else if (to <= display.viewFrom) { // Change before if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { resetView(cm); } else { display.viewFrom += lendiff; display.viewTo += lendiff; } } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap resetView(cm); } else if (from <= display.viewFrom) { // Top overlap var cut = viewCuttingPoint(cm, to, to + lendiff, 1); if (cut) { display.view = display.view.slice(cut.index); display.viewFrom = cut.lineN; display.viewTo += lendiff; } else { resetView(cm); } } else if (to >= display.viewTo) { // Bottom overlap var cut$1 = viewCuttingPoint(cm, from, from, -1); if (cut$1) { display.view = display.view.slice(0, cut$1.index); display.viewTo = cut$1.lineN; } else { resetView(cm); } } else { // Gap in the middle var cutTop = viewCuttingPoint(cm, from, from, -1); var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); if (cutTop && cutBot) { display.view = display.view.slice(0, cutTop.index) .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) .concat(display.view.slice(cutBot.index)); display.viewTo += lendiff; } else { resetView(cm); } } var ext = display.externalMeasured; if (ext) { if (to < ext.lineN) { ext.lineN += lendiff; } else if (from < ext.lineN + ext.size) { display.externalMeasured = null; } } } // Register a change to a single line. Type must be one of "text", // "gutter", "class", "widget" function regLineChange(cm, line, type) { cm.curOp.viewChanged = true; var display = cm.display, ext = cm.display.externalMeasured; if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { display.externalMeasured = null; } if (line < display.viewFrom || line >= display.viewTo) { return } var lineView = display.view[findViewIndex(cm, line)]; if (lineView.node == null) { return } var arr = lineView.changes || (lineView.changes = []); if (indexOf(arr, type) == -1) { arr.push(type); } } // Clear the view. function resetView(cm) { cm.display.viewFrom = cm.display.viewTo = cm.doc.first; cm.display.view = []; cm.display.viewOffset = 0; } function viewCuttingPoint(cm, oldN, newN, dir) { var index = findViewIndex(cm, oldN), diff, view = cm.display.view; if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { return {index: index, lineN: newN} } var n = cm.display.viewFrom; for (var i = 0; i < index; i++) { n += view[i].size; } if (n != oldN) { if (dir > 0) { if (index == view.length - 1) { return null } diff = (n + view[index].size) - oldN; index++; } else { diff = n - oldN; } oldN += diff; newN += diff; } while (visualLineNo(cm.doc, newN) != newN) { if (index == (dir < 0 ? 0 : view.length - 1)) { return null } newN += dir * view[index - (dir < 0 ? 1 : 0)].size; index += dir; } return {index: index, lineN: newN} } // Force the view to cover a given range, adding empty view element // or clipping off existing ones as needed. function adjustView(cm, from, to) { var display = cm.display, view = display.view; if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { display.view = buildViewArray(cm, from, to); display.viewFrom = from; } else { if (display.viewFrom > from) { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } else if (display.viewFrom < from) { display.view = display.view.slice(findViewIndex(cm, from)); } display.viewFrom = from; if (display.viewTo < to) { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } else if (display.viewTo > to) { display.view = display.view.slice(0, findViewIndex(cm, to)); } } display.viewTo = to; } // Count the number of lines in the view whose DOM representation is // out of date (or nonexistent). function countDirtyView(cm) { var view = cm.display.view, dirty = 0; for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } } return dirty } function updateSelection(cm) { cm.display.input.showSelection(cm.display.input.prepareSelection()); } function prepareSelection(cm, primary) { if ( primary === void 0 ) primary = true; var doc = cm.doc, result = {}; var curFragment = result.cursors = document.createDocumentFragment(); var selFragment = result.selection = document.createDocumentFragment(); for (var i = 0; i < doc.sel.ranges.length; i++) { if (!primary && i == doc.sel.primIndex) { continue } var range = doc.sel.ranges[i]; if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue } var collapsed = range.empty(); if (collapsed || cm.options.showCursorWhenSelecting) { drawSelectionCursor(cm, range.head, curFragment); } if (!collapsed) { drawSelectionRange(cm, range, selFragment); } } return result } // Draws a cursor for the given range function drawSelectionCursor(cm, head, output) { var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); cursor.style.left = pos.left + "px"; cursor.style.top = pos.top + "px"; cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; if (pos.other) { // Secondary cursor, shown when on a 'jump' in bi-directional text var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); otherCursor.style.display = ""; otherCursor.style.left = pos.other.left + "px"; otherCursor.style.top = pos.other.top + "px"; otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } } function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } // Draws the given range as a highlighted selection function drawSelectionRange(cm, range, output) { var display = cm.display, doc = cm.doc; var fragment = document.createDocumentFragment(); var padding = paddingH(cm.display), leftSide = padding.left; var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; var docLTR = doc.direction == "ltr"; function add(left, top, width, bottom) { if (top < 0) { top = 0; } top = Math.round(top); bottom = Math.round(bottom); fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))); } function drawForLine(line, fromArg, toArg) { var lineObj = getLine(doc, line); var lineLen = lineObj.text.length; var start, end; function coords(ch, bias) { return charCoords(cm, Pos(line, ch), "div", lineObj, bias) } function wrapX(pos, dir, side) { var extent = wrappedLineExtentChar(cm, lineObj, null, pos); var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); return coords(ch, prop)[prop] } var order = getOrder(lineObj, doc.direction); iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { var ltr = dir == "ltr"; var fromPos = coords(from, ltr ? "left" : "right"); var toPos = coords(to - 1, ltr ? "right" : "left"); var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; var first = i == 0, last = !order || i == order.length - 1; if (toPos.top - fromPos.top <= 3) { // Single line var openLeft = (docLTR ? openStart : openEnd) && first; var openRight = (docLTR ? openEnd : openStart) && last; var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; add(left, fromPos.top, right - left, fromPos.bottom); } else { // Multiple lines var topLeft, topRight, botLeft, botRight; if (ltr) { topLeft = docLTR && openStart && first ? leftSide : fromPos.left; topRight = docLTR ? rightSide : wrapX(from, dir, "before"); botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); botRight = docLTR && openEnd && last ? rightSide : toPos.right; } else { topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); topRight = !docLTR && openStart && first ? rightSide : fromPos.right; botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); } add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); } if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; } if (cmpCoords(toPos, start) < 0) { start = toPos; } if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; } if (cmpCoords(toPos, end) < 0) { end = toPos; } }); return {start: start, end: end} } var sFrom = range.from(), sTo = range.to(); if (sFrom.line == sTo.line) { drawForLine(sFrom.line, sFrom.ch, sTo.ch); } else { var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); var singleVLine = visualLine(fromLine) == visualLine(toLine); var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; if (singleVLine) { if (leftEnd.top < rightStart.top - 2) { add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); } else { add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); } } if (leftEnd.bottom < rightStart.top) { add(leftSide, leftEnd.bottom, null, rightStart.top); } } output.appendChild(fragment); } // Cursor-blinking function restartBlink(cm) { if (!cm.state.focused) { return } var display = cm.display; clearInterval(display.blinker); var on = true; display.cursorDiv.style.visibility = ""; if (cm.options.cursorBlinkRate > 0) { display.blinker = setInterval(function () { if (!cm.hasFocus()) { onBlur(cm); } display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, cm.options.cursorBlinkRate); } else if (cm.options.cursorBlinkRate < 0) { display.cursorDiv.style.visibility = "hidden"; } } function ensureFocus(cm) { if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } } function delayBlurEvent(cm) { cm.state.delayingBlurEvent = true; setTimeout(function () { if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; onBlur(cm); } }, 100); } function onFocus(cm, e) { if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } if (cm.options.readOnly == "nocursor") { return } if (!cm.state.focused) { signal(cm, "focus", cm, e); cm.state.focused = true; addClass(cm.display.wrapper, "CodeMirror-focused"); // This test prevents this from firing when a context // menu is closed (since the input reset would kill the // select-all detection hack) if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { cm.display.input.reset(); if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 } cm.display.input.receivedFocus(); } restartBlink(cm); } function onBlur(cm, e) { if (cm.state.delayingBlurEvent) { return } if (cm.state.focused) { signal(cm, "blur", cm, e); cm.state.focused = false; rmClass(cm.display.wrapper, "CodeMirror-focused"); } clearInterval(cm.display.blinker); setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); } // Read the actual heights of the rendered lines, and update their // stored heights to match. function updateHeightsInViewport(cm) { var display = cm.display; var prevBottom = display.lineDiv.offsetTop; for (var i = 0; i < display.view.length; i++) { var cur = display.view[i], wrapping = cm.options.lineWrapping; var height = (void 0), width = 0; if (cur.hidden) { continue } if (ie && ie_version < 8) { var bot = cur.node.offsetTop + cur.node.offsetHeight; height = bot - prevBottom; prevBottom = bot; } else { var box = cur.node.getBoundingClientRect(); height = box.bottom - box.top; // Check that lines don't extend past the right of the current // editor width if (!wrapping && cur.text.firstChild) { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; } } var diff = cur.line.height - height; if (diff > .005 || diff < -.005) { updateLineHeight(cur.line, height); updateWidgetHeight(cur.line); if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) { updateWidgetHeight(cur.rest[j]); } } } if (width > cm.display.sizerWidth) { var chWidth = Math.ceil(width / charWidth(cm.display)); if (chWidth > cm.display.maxLineLength) { cm.display.maxLineLength = chWidth; cm.display.maxLine = cur.line; cm.display.maxLineChanged = true; } } } } // Read and store the height of line widgets associated with the // given line. function updateWidgetHeight(line) { if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) { var w = line.widgets[i], parent = w.node.parentNode; if (parent) { w.height = parent.offsetHeight; } } } } // Compute the lines that are visible in a given viewport (defaults // the the current scroll position). viewport may contain top, // height, and ensure (see op.scrollToPos) properties. function visibleLines(display, doc, viewport) { var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; top = Math.floor(top - paddingTop(display)); var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); // Ensure is a {from: {line, ch}, to: {line, ch}} object, and // forces those lines into the viewport (if possible). if (viewport && viewport.ensure) { var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; if (ensureFrom < from) { from = ensureFrom; to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); } else if (Math.min(ensureTo, doc.lastLine()) >= to) { from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); to = ensureTo; } } return {from: from, to: Math.max(to, from + 1)} } // SCROLLING THINGS INTO VIEW // If an editor sits on the top or bottom of the window, partially // scrolled out of view, this ensures that the cursor is visible. function maybeScrollWindow(cm, rect) { if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; if (rect.top + box.top < 0) { doScroll = true; } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } if (doScroll != null && !phantom) { var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")); cm.display.lineSpace.appendChild(scrollNode); scrollNode.scrollIntoView(doScroll); cm.display.lineSpace.removeChild(scrollNode); } } // Scroll a given position into view (immediately), verifying that // it actually became visible (as line heights are accurately // measured, the position of something may 'drift' during drawing). function scrollPosIntoView(cm, pos, end, margin) { if (margin == null) { margin = 0; } var rect; if (!cm.options.lineWrapping && pos == end) { // Set pos and end to the cursor positions around the character pos sticks to // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch // If pos == Pos(_, 0, "before"), pos and end are unchanged pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; } for (var limit = 0; limit < 5; limit++) { var changed = false; var coords = cursorCoords(cm, pos); var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); rect = {left: Math.min(coords.left, endCoords.left), top: Math.min(coords.top, endCoords.top) - margin, right: Math.max(coords.left, endCoords.left), bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; var scrollPos = calculateScrollPos(cm, rect); var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } } if (!changed) { break } } return rect } // Scroll a given set of coordinates into view (immediately). function scrollIntoView(cm, rect) { var scrollPos = calculateScrollPos(cm, rect); if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } } // Calculate a new scroll position needed to scroll the given // rectangle into view. Returns an object with scrollTop and // scrollLeft properties. When these are undefined, the // vertical/horizontal position does not need to be adjusted. function calculateScrollPos(cm, rect) { var display = cm.display, snapMargin = textHeight(cm.display); if (rect.top < 0) { rect.top = 0; } var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; var screen = displayHeight(cm), result = {}; if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } var docBottom = cm.doc.height + paddingVert(display); var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; if (rect.top < screentop) { result.scrollTop = atTop ? 0 : rect.top; } else if (rect.bottom > screentop + screen) { var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); if (newTop != screentop) { result.scrollTop = newTop; } } var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); var tooWide = rect.right - rect.left > screenw; if (tooWide) { rect.right = rect.left + screenw; } if (rect.left < 10) { result.scrollLeft = 0; } else if (rect.left < screenleft) { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); } else if (rect.right > screenw + screenleft - 3) { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } return result } // Store a relative adjustment to the scroll position in the current // operation (to be applied when the operation finishes). function addToScrollTop(cm, top) { if (top == null) { return } resolveScrollToPos(cm); cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; } // Make sure that at the end of the operation the current cursor is // shown. function ensureCursorVisible(cm) { resolveScrollToPos(cm); var cur = cm.getCursor(); cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; } function scrollToCoords(cm, x, y) { if (x != null || y != null) { resolveScrollToPos(cm); } if (x != null) { cm.curOp.scrollLeft = x; } if (y != null) { cm.curOp.scrollTop = y; } } function scrollToRange(cm, range) { resolveScrollToPos(cm); cm.curOp.scrollToPos = range; } // When an operation has its scrollToPos property set, and another // scroll action is applied before the end of the operation, this // 'simulates' scrolling that position into view in a cheap way, so // that the effect of intermediate scroll commands is not ignored. function resolveScrollToPos(cm) { var range = cm.curOp.scrollToPos; if (range) { cm.curOp.scrollToPos = null; var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); scrollToCoordsRange(cm, from, to, range.margin); } } function scrollToCoordsRange(cm, from, to, margin) { var sPos = calculateScrollPos(cm, { left: Math.min(from.left, to.left), top: Math.min(from.top, to.top) - margin, right: Math.max(from.right, to.right), bottom: Math.max(from.bottom, to.bottom) + margin }); scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); } // Sync the scrollable area and scrollbars, ensure the viewport // covers the visible area. function updateScrollTop(cm, val) { if (Math.abs(cm.doc.scrollTop - val) < 2) { return } if (!gecko) { updateDisplaySimple(cm, {top: val}); } setScrollTop(cm, val, true); if (gecko) { updateDisplaySimple(cm); } startWorker(cm, 100); } function setScrollTop(cm, val, forceScroll) { val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); if (cm.display.scroller.scrollTop == val && !forceScroll) { return } cm.doc.scrollTop = val; cm.display.scrollbars.setScrollTop(val); if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } } // Sync scroller and scrollbar, ensure the gutter elements are // aligned. function setScrollLeft(cm, val, isScroller, forceScroll) { val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } cm.doc.scrollLeft = val; alignHorizontally(cm); if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } cm.display.scrollbars.setScrollLeft(val); } // SCROLLBARS // Prepare DOM reads needed to update the scrollbars. Done in one // shot to minimize update/measure roundtrips. function measureForScrollbars(cm) { var d = cm.display, gutterW = d.gutters.offsetWidth; var docH = Math.round(cm.doc.height + paddingVert(cm.display)); return { clientHeight: d.scroller.clientHeight, viewHeight: d.wrapper.clientHeight, scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, viewWidth: d.wrapper.clientWidth, barLeft: cm.options.fixedGutter ? gutterW : 0, docHeight: docH, scrollHeight: docH + scrollGap(cm) + d.barHeight, nativeBarWidth: d.nativeBarWidth, gutterWidth: gutterW } } var NativeScrollbars = function(place, scroll, cm) { this.cm = cm; var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); vert.tabIndex = horiz.tabIndex = -1; place(vert); place(horiz); on(vert, "scroll", function () { if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } }); on(horiz, "scroll", function () { if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } }); this.checkedZeroWidth = false; // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } }; NativeScrollbars.prototype.update = function (measure) { var needsH = measure.scrollWidth > measure.clientWidth + 1; var needsV = measure.scrollHeight > measure.clientHeight + 1; var sWidth = measure.nativeBarWidth; if (needsV) { this.vert.style.display = "block"; this.vert.style.bottom = needsH ? sWidth + "px" : "0"; var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); // A bug in IE8 can cause this value to be negative, so guard it. this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; } else { this.vert.style.display = ""; this.vert.firstChild.style.height = "0"; } if (needsH) { this.horiz.style.display = "block"; this.horiz.style.right = needsV ? sWidth + "px" : "0"; this.horiz.style.left = measure.barLeft + "px"; var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; } else { this.horiz.style.display = ""; this.horiz.firstChild.style.width = "0"; } if (!this.checkedZeroWidth && measure.clientHeight > 0) { if (sWidth == 0) { this.zeroWidthHack(); } this.checkedZeroWidth = true; } return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} }; NativeScrollbars.prototype.setScrollLeft = function (pos) { if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } }; NativeScrollbars.prototype.setScrollTop = function (pos) { if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } }; NativeScrollbars.prototype.zeroWidthHack = function () { var w = mac && !mac_geMountainLion ? "12px" : "18px"; this.horiz.style.height = this.vert.style.width = w; this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; this.disableHoriz = new Delayed; this.disableVert = new Delayed; }; NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { bar.style.pointerEvents = "auto"; function maybeDisable() { // To find out whether the scrollbar is still visible, we // check whether the element under the pixel in the bottom // right corner of the scrollbar box is the scrollbar box // itself (when the bar is still visible) or its filler child // (when the bar is hidden). If it is still visible, we keep // it enabled, if it's hidden, we disable pointer events. var box = bar.getBoundingClientRect(); var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); if (elt != bar) { bar.style.pointerEvents = "none"; } else { delay.set(1000, maybeDisable); } } delay.set(1000, maybeDisable); }; NativeScrollbars.prototype.clear = function () { var parent = this.horiz.parentNode; parent.removeChild(this.horiz); parent.removeChild(this.vert); }; var NullScrollbars = function () {}; NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; NullScrollbars.prototype.setScrollLeft = function () {}; NullScrollbars.prototype.setScrollTop = function () {}; NullScrollbars.prototype.clear = function () {}; function updateScrollbars(cm, measure) { if (!measure) { measure = measureForScrollbars(cm); } var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; updateScrollbarsInner(cm, measure); for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { updateHeightsInViewport(cm); } updateScrollbarsInner(cm, measureForScrollbars(cm)); startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; } } // Re-synchronize the fake scrollbars with the actual size of the // content. function updateScrollbarsInner(cm, measure) { var d = cm.display; var sizes = d.scrollbars.update(measure); d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; if (sizes.right && sizes.bottom) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = sizes.bottom + "px"; d.scrollbarFiller.style.width = sizes.right + "px"; } else { d.scrollbarFiller.style.display = ""; } if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = sizes.bottom + "px"; d.gutterFiller.style.width = measure.gutterWidth + "px"; } else { d.gutterFiller.style.display = ""; } } var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; function initScrollbars(cm) { if (cm.display.scrollbars) { cm.display.scrollbars.clear(); if (cm.display.scrollbars.addClass) { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } } cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); // Prevent clicks in the scrollbars from killing focus on(node, "mousedown", function () { if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } }); node.setAttribute("cm-not-content", "true"); }, function (pos, axis) { if (axis == "horizontal") { setScrollLeft(cm, pos); } else { updateScrollTop(cm, pos); } }, cm); if (cm.display.scrollbars.addClass) { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } } // Operations are used to wrap a series of changes to the editor // state in such a way that each change won't have to update the // cursor and display (which would be awkward, slow, and // error-prone). Instead, display updates are batched and then all // combined and executed at once. var nextOpId = 0; // Start a new operation. function startOperation(cm) { cm.curOp = { cm: cm, viewChanged: false, // Flag that indicates that lines might need to be redrawn startHeight: cm.doc.height, // Used to detect need to update scrollbar forceUpdate: false, // Used to force a redraw updateInput: 0, // Whether to reset the input textarea typing: false, // Whether this reset should be careful to leave existing text (for compositing) changeObjs: null, // Accumulated changes, for firing change events cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already selectionChanged: false, // Whether the selection needs to be redrawn updateMaxLine: false, // Set when the widest line needs to be determined anew scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet scrollToPos: null, // Used to scroll to a specific position focus: false, id: ++nextOpId // Unique ID }; pushOperation(cm.curOp); } // Finish an operation, updating the display and signalling delayed events function endOperation(cm) { var op = cm.curOp; if (op) { finishOperation(op, function (group) { for (var i = 0; i < group.ops.length; i++) { group.ops[i].cm.curOp = null; } endOperations(group); }); } } // The DOM updates done when an operation finishes are batched so // that the minimum number of relayouts are required. function endOperations(group) { var ops = group.ops; for (var i = 0; i < ops.length; i++) // Read DOM { endOperation_R1(ops[i]); } for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) { endOperation_W1(ops[i$1]); } for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM { endOperation_R2(ops[i$2]); } for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) { endOperation_W2(ops[i$3]); } for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM { endOperation_finish(ops[i$4]); } } function endOperation_R1(op) { var cm = op.cm, display = cm.display; maybeClipScrollbars(cm); if (op.updateMaxLine) { findMaxLine(cm); } op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); } function endOperation_W1(op) { op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); } function endOperation_R2(op) { var cm = op.cm, display = cm.display; if (op.updatedDisplay) { updateHeightsInViewport(cm); } op.barMeasure = measureForScrollbars(cm); // If the max line changed since it was last measured, measure it, // and ensure the document's width matches it. // updateDisplay_W2 will use these properties to do the actual resizing if (display.maxLineChanged && !cm.options.lineWrapping) { op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; cm.display.sizerWidth = op.adjustWidthTo; op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); } if (op.updatedDisplay || op.selectionChanged) { op.preparedSelection = display.input.prepareSelection(); } } function endOperation_W2(op) { var cm = op.cm; if (op.adjustWidthTo != null) { cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; if (op.maxScrollLeft < cm.doc.scrollLeft) { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } cm.display.maxLineChanged = false; } var takeFocus = op.focus && op.focus == activeElt(); if (op.preparedSelection) { cm.display.input.showSelection(op.preparedSelection, takeFocus); } if (op.updatedDisplay || op.startHeight != cm.doc.height) { updateScrollbars(cm, op.barMeasure); } if (op.updatedDisplay) { setDocumentHeight(cm, op.barMeasure); } if (op.selectionChanged) { restartBlink(cm); } if (cm.state.focused && op.updateInput) { cm.display.input.reset(op.typing); } if (takeFocus) { ensureFocus(op.cm); } } function endOperation_finish(op) { var cm = op.cm, display = cm.display, doc = cm.doc; if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } // Abort mouse wheel delta measurement, when scrolling explicitly if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { display.wheelStartX = display.wheelStartY = null; } // Propagate the scroll position to the actual DOM scroller if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } // If we need to scroll a specific position into view, do so. if (op.scrollToPos) { var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); maybeScrollWindow(cm, rect); } // Fire events for markers that are hidden/unidden by editing or // undoing var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; if (hidden) { for (var i = 0; i < hidden.length; ++i) { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } if (display.wrapper.offsetHeight) { doc.scrollTop = cm.display.scroller.scrollTop; } // Fire change events, and delayed event handlers if (op.changeObjs) { signal(cm, "changes", cm, op.changeObjs); } if (op.update) { op.update.finish(); } } // Run the given function in an operation function runInOp(cm, f) { if (cm.curOp) { return f() } startOperation(cm); try { return f() } finally { endOperation(cm); } } // Wraps a function in an operation. Returns the wrapped function. function operation(cm, f) { return function() { if (cm.curOp) { return f.apply(cm, arguments) } startOperation(cm); try { return f.apply(cm, arguments) } finally { endOperation(cm); } } } // Used to add methods to editor and doc instances, wrapping them in // operations. function methodOp(f) { return function() { if (this.curOp) { return f.apply(this, arguments) } startOperation(this); try { return f.apply(this, arguments) } finally { endOperation(this); } } } function docMethodOp(f) { return function() { var cm = this.cm; if (!cm || cm.curOp) { return f.apply(this, arguments) } startOperation(cm); try { return f.apply(this, arguments) } finally { endOperation(cm); } } } // HIGHLIGHT WORKER function startWorker(cm, time) { if (cm.doc.highlightFrontier < cm.display.viewTo) { cm.state.highlight.set(time, bind(highlightWorker, cm)); } } function highlightWorker(cm) { var doc = cm.doc; if (doc.highlightFrontier >= cm.display.viewTo) { return } var end = +new Date + cm.options.workTime; var context = getContextBefore(cm, doc.highlightFrontier); var changedLines = []; doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { if (context.line >= cm.display.viewFrom) { // Visible var oldStyles = line.styles; var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; var highlighted = highlightLine(cm, line, context, true); if (resetState) { context.state = resetState; } line.styles = highlighted.styles; var oldCls = line.styleClasses, newCls = highlighted.classes; if (newCls) { line.styleClasses = newCls; } else if (oldCls) { line.styleClasses = null; } var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } if (ischange) { changedLines.push(context.line); } line.stateAfter = context.save(); context.nextLine(); } else { if (line.text.length <= cm.options.maxHighlightLength) { processLine(cm, line.text, context); } line.stateAfter = context.line % 5 == 0 ? context.save() : null; context.nextLine(); } if (+new Date > end) { startWorker(cm, cm.options.workDelay); return true } }); doc.highlightFrontier = context.line; doc.modeFrontier = Math.max(doc.modeFrontier, context.line); if (changedLines.length) { runInOp(cm, function () { for (var i = 0; i < changedLines.length; i++) { regLineChange(cm, changedLines[i], "text"); } }); } } // DISPLAY DRAWING var DisplayUpdate = function(cm, viewport, force) { var display = cm.display; this.viewport = viewport; // Store some values that we'll need later (but don't want to force a relayout for) this.visible = visibleLines(display, cm.doc, viewport); this.editorIsHidden = !display.wrapper.offsetWidth; this.wrapperHeight = display.wrapper.clientHeight; this.wrapperWidth = display.wrapper.clientWidth; this.oldDisplayWidth = displayWidth(cm); this.force = force; this.dims = getDimensions(cm); this.events = []; }; DisplayUpdate.prototype.signal = function (emitter, type) { if (hasHandler(emitter, type)) { this.events.push(arguments); } }; DisplayUpdate.prototype.finish = function () { for (var i = 0; i < this.events.length; i++) { signal.apply(null, this.events[i]); } }; function maybeClipScrollbars(cm) { var display = cm.display; if (!display.scrollbarsClipped && display.scroller.offsetWidth) { display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; display.heightForcer.style.height = scrollGap(cm) + "px"; display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; display.scrollbarsClipped = true; } } function selectionSnapshot(cm) { if (cm.hasFocus()) { return null } var active = activeElt(); if (!active || !contains(cm.display.lineDiv, active)) { return null } var result = {activeElt: active}; if (window.getSelection) { var sel = window.getSelection(); if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { result.anchorNode = sel.anchorNode; result.anchorOffset = sel.anchorOffset; result.focusNode = sel.focusNode; result.focusOffset = sel.focusOffset; } } return result } function restoreSelection(snapshot) { if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } snapshot.activeElt.focus(); if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { var sel = window.getSelection(), range = document.createRange(); range.setEnd(snapshot.anchorNode, snapshot.anchorOffset); range.collapse(false); sel.removeAllRanges(); sel.addRange(range); sel.extend(snapshot.focusNode, snapshot.focusOffset); } } // Does the actual updating of the line display. Bails out // (returning false) when there is nothing to be done and forced is // false. function updateDisplayIfNeeded(cm, update) { var display = cm.display, doc = cm.doc; if (update.editorIsHidden) { resetView(cm); return false } // Bail out if the visible area is already rendered and nothing changed. if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { return false } if (maybeUpdateLineNumberWidth(cm)) { resetView(cm); update.dims = getDimensions(cm); } // Compute a suitable new viewport (from & to) var end = doc.first + doc.size; var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); var to = Math.min(end, update.visible.to + cm.options.viewportMargin); if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } if (sawCollapsedSpans) { from = visualLineNo(cm.doc, from); to = visualLineEndNo(cm.doc, to); } var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; adjustView(cm, from, to); display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); // Position the mover div to align with the current scroll position cm.display.mover.style.top = display.viewOffset + "px"; var toUpdate = countDirtyView(cm); if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { return false } // For big changes, we hide the enclosing element during the // update, since that speeds up the operations on most browsers. var selSnapshot = selectionSnapshot(cm); if (toUpdate > 4) { display.lineDiv.style.display = "none"; } patchDisplay(cm, display.updateLineNumbers, update.dims); if (toUpdate > 4) { display.lineDiv.style.display = ""; } display.renderedView = display.view; // There might have been a widget with a focused element that got // hidden or updated, if so re-focus it. restoreSelection(selSnapshot); // Prevent selection and cursors from interfering with the scroll // width and height. removeChildren(display.cursorDiv); removeChildren(display.selectionDiv); display.gutters.style.height = display.sizer.style.minHeight = 0; if (different) { display.lastWrapHeight = update.wrapperHeight; display.lastWrapWidth = update.wrapperWidth; startWorker(cm, 400); } display.updateLineNumbers = null; return true } function postUpdateDisplay(cm, update) { var viewport = update.viewport; for (var first = true;; first = false) { if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { // Clip forced viewport to actual scrollable area. if (viewport && viewport.top != null) { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } // Updated line heights might result in the drawn area not // actually covering the viewport. Keep looping until it does. update.visible = visibleLines(cm.display, cm.doc, viewport); if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { break } } else if (first) { update.visible = visibleLines(cm.display, cm.doc, viewport); } if (!updateDisplayIfNeeded(cm, update)) { break } updateHeightsInViewport(cm); var barMeasure = measureForScrollbars(cm); updateSelection(cm); updateScrollbars(cm, barMeasure); setDocumentHeight(cm, barMeasure); update.force = false; } update.signal(cm, "update", cm); if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; } } function updateDisplaySimple(cm, viewport) { var update = new DisplayUpdate(cm, viewport); if (updateDisplayIfNeeded(cm, update)) { updateHeightsInViewport(cm); postUpdateDisplay(cm, update); var barMeasure = measureForScrollbars(cm); updateSelection(cm); updateScrollbars(cm, barMeasure); setDocumentHeight(cm, barMeasure); update.finish(); } } // Sync the actual display DOM structure with display.view, removing // nodes for lines that are no longer in view, and creating the ones // that are not there yet, and updating the ones that are out of // date. function patchDisplay(cm, updateNumbersFrom, dims) { var display = cm.display, lineNumbers = cm.options.lineNumbers; var container = display.lineDiv, cur = container.firstChild; function rm(node) { var next = node.nextSibling; // Works around a throw-scroll bug in OS X Webkit if (webkit && mac && cm.display.currentWheelTarget == node) { node.style.display = "none"; } else { node.parentNode.removeChild(node); } return next } var view = display.view, lineN = display.viewFrom; // Loop over the elements in the view, syncing cur (the DOM nodes // in display.lineDiv) with the view as we go. for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet var node = buildLineElement(cm, lineView, lineN, dims); container.insertBefore(node, cur); } else { // Already drawn while (cur != lineView.node) { cur = rm(cur); } var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; if (lineView.changes) { if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } updateLineForChanges(cm, lineView, lineN, dims); } if (updateNumber) { removeChildren(lineView.lineNumber); lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); } cur = lineView.node.nextSibling; } lineN += lineView.size; } while (cur) { cur = rm(cur); } } function updateGutterSpace(display) { var width = display.gutters.offsetWidth; display.sizer.style.marginLeft = width + "px"; } function setDocumentHeight(cm, measure) { cm.display.sizer.style.minHeight = measure.docHeight + "px"; cm.display.heightForcer.style.top = measure.docHeight + "px"; cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; } // Re-align line numbers and gutter marks to compensate for // horizontal scrolling. function alignHorizontally(cm) { var display = cm.display, view = display.view; if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; var gutterW = display.gutters.offsetWidth, left = comp + "px"; for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { if (cm.options.fixedGutter) { if (view[i].gutter) { view[i].gutter.style.left = left; } if (view[i].gutterBackground) { view[i].gutterBackground.style.left = left; } } var align = view[i].alignable; if (align) { for (var j = 0; j < align.length; j++) { align[j].style.left = left; } } } } if (cm.options.fixedGutter) { display.gutters.style.left = (comp + gutterW) + "px"; } } // Used to ensure that the line number gutter is still the right // size for the current document size. Returns true when an update // is needed. function maybeUpdateLineNumberWidth(cm) { if (!cm.options.lineNumbers) { return false } var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; if (last.length != display.lineNumChars) { var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; display.lineGutter.style.width = ""; display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; display.lineNumWidth = display.lineNumInnerWidth + padding; display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; display.lineGutter.style.width = display.lineNumWidth + "px"; updateGutterSpace(cm.display); return true } return false } function getGutters(gutters, lineNumbers) { var result = [], sawLineNumbers = false; for (var i = 0; i < gutters.length; i++) { var name = gutters[i], style = null; if (typeof name != "string") { style = name.style; name = name.className; } if (name == "CodeMirror-linenumbers") { if (!lineNumbers) { continue } else { sawLineNumbers = true; } } result.push({className: name, style: style}); } if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); } return result } // Rebuild the gutter elements, ensure the margin to the left of the // code matches their width. function renderGutters(display) { var gutters = display.gutters, specs = display.gutterSpecs; removeChildren(gutters); display.lineGutter = null; for (var i = 0; i < specs.length; ++i) { var ref = specs[i]; var className = ref.className; var style = ref.style; var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); if (style) { gElt.style.cssText = style; } if (className == "CodeMirror-linenumbers") { display.lineGutter = gElt; gElt.style.width = (display.lineNumWidth || 1) + "px"; } } gutters.style.display = specs.length ? "" : "none"; updateGutterSpace(display); } function updateGutters(cm) { renderGutters(cm.display); regChange(cm); alignHorizontally(cm); } // The display handles the DOM integration, both for input reading // and content drawing. It holds references to DOM nodes and // display-related state. function Display(place, doc, input, options) { var d = this; this.input = input; // Covers bottom-right square when both scrollbars are present. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); d.scrollbarFiller.setAttribute("cm-not-content", "true"); // Covers bottom of gutter when coverGutterNextToScrollbar is on // and h scrollbar is present. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); d.gutterFiller.setAttribute("cm-not-content", "true"); // Will contain the actual code, positioned to cover the viewport. d.lineDiv = eltP("div", null, "CodeMirror-code"); // Elements are added to these to represent selection and cursors. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); d.cursorDiv = elt("div", null, "CodeMirror-cursors"); // A visibility: hidden element used to find the size of things. d.measure = elt("div", null, "CodeMirror-measure"); // When lines outside of the viewport are measured, they are drawn in this. d.lineMeasure = elt("div", null, "CodeMirror-measure"); // Wraps everything that needs to exist inside the vertically-padded coordinate system d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); // Moved around its parent to cover visible view. d.mover = elt("div", [lines], null, "position: relative"); // Set to the height of the document, allowing scrolling. d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); d.sizerWidth = null; // Behavior of elts with overflow: auto and padding is // inconsistent across browsers. This is used to ensure the // scrollable area is big enough. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); // Will contain the gutters, if any. d.gutters = elt("div", null, "CodeMirror-gutters"); d.lineGutter = null; // Actual scrollable element. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); d.scroller.setAttribute("tabIndex", "-1"); // The element in which the editor lives. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } if (place) { if (place.appendChild) { place.appendChild(d.wrapper); } else { place(d.wrapper); } } // Current rendered range (may be bigger than the view window). d.viewFrom = d.viewTo = doc.first; d.reportedViewFrom = d.reportedViewTo = doc.first; // Information about the rendered lines. d.view = []; d.renderedView = null; // Holds info about a single rendered line when it was rendered // for measurement, while not in view. d.externalMeasured = null; // Empty space (in pixels) above the view d.viewOffset = 0; d.lastWrapHeight = d.lastWrapWidth = 0; d.updateLineNumbers = null; d.nativeBarWidth = d.barHeight = d.barWidth = 0; d.scrollbarsClipped = false; // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; // Set to true when a non-horizontal-scrolling line widget is // added. As an optimization, line widget aligning is skipped when // this is false. d.alignWidgets = false; d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; // Tracks the maximum line length so that the horizontal scrollbar // can be kept static when scrolling. d.maxLine = null; d.maxLineLength = 0; d.maxLineChanged = false; // Used for measuring wheel scrolling granularity d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; // True when shift is held down. d.shift = false; // Used to track whether anything happened since the context menu // was opened. d.selForContextMenu = null; d.activeTouch = null; d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); renderGutters(d); input.init(d); } // Since the delta values reported on mouse wheel events are // unstandardized between browsers and even browser versions, and // generally horribly unpredictable, this code starts by measuring // the scroll effect that the first few mouse wheel events have, // and, from that, detects the way it can convert deltas to pixel // offsets afterwards. // // The reason we want to know the amount a wheel event will scroll // is that it gives us a chance to update the display before the // actual scrolling happens, reducing flickering. var wheelSamples = 0, wheelPixelsPerUnit = null; // Fill in a browser-detected starting value on browsers where we // know one. These don't have to be accurate -- the result of them // being wrong would just be a slight flicker on the first wheel // scroll (if it is large enough). if (ie) { wheelPixelsPerUnit = -.53; } else if (gecko) { wheelPixelsPerUnit = 15; } else if (chrome) { wheelPixelsPerUnit = -.7; } else if (safari) { wheelPixelsPerUnit = -1/3; } function wheelEventDelta(e) { var dx = e.wheelDeltaX, dy = e.wheelDeltaY; if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } else if (dy == null) { dy = e.wheelDelta; } return {x: dx, y: dy} } function wheelEventPixels(e) { var delta = wheelEventDelta(e); delta.x *= wheelPixelsPerUnit; delta.y *= wheelPixelsPerUnit; return delta } function onScrollWheel(cm, e) { var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; var display = cm.display, scroll = display.scroller; // Quit if there's nothing to scroll here var canScrollX = scroll.scrollWidth > scroll.clientWidth; var canScrollY = scroll.scrollHeight > scroll.clientHeight; if (!(dx && canScrollX || dy && canScrollY)) { return } // Webkit browsers on OS X abort momentum scrolls when the target // of the scroll event is removed from the scrollable element. // This hack (see related code in patchDisplay) makes sure the // element is kept around. if (dy && mac && webkit) { outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { for (var i = 0; i < view.length; i++) { if (view[i].node == cur) { cm.display.currentWheelTarget = cur; break outer } } } } // On some browsers, horizontal scrolling will cause redraws to // happen before the gutter has been realigned, causing it to // wriggle around in a most unseemly way. When we have an // estimated pixels/delta value, we just handle horizontal // scrolling entirely here. It'll be slightly off from native, but // better than glitching out. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { if (dy && canScrollY) { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); } setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)); // Only prevent default scrolling if vertical scrolling is // actually possible. Otherwise, it causes vertical scroll // jitter on OSX trackpads when deltaX is small and deltaY // is large (issue #3579) if (!dy || (dy && canScrollY)) { e_preventDefault(e); } display.wheelStartX = null; // Abort measurement, if in progress return } // 'Project' the visible viewport to cover the area that is being // scrolled into view (if we know enough to estimate it). if (dy && wheelPixelsPerUnit != null) { var pixels = dy * wheelPixelsPerUnit; var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; if (pixels < 0) { top = Math.max(0, top + pixels - 50); } else { bot = Math.min(cm.doc.height, bot + pixels + 50); } updateDisplaySimple(cm, {top: top, bottom: bot}); } if (wheelSamples < 20) { if (display.wheelStartX == null) { display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; display.wheelDX = dx; display.wheelDY = dy; setTimeout(function () { if (display.wheelStartX == null) { return } var movedX = scroll.scrollLeft - display.wheelStartX; var movedY = scroll.scrollTop - display.wheelStartY; var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || (movedX && display.wheelDX && movedX / display.wheelDX); display.wheelStartX = display.wheelStartY = null; if (!sample) { return } wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); ++wheelSamples; }, 200); } else { display.wheelDX += dx; display.wheelDY += dy; } } } // Selection objects are immutable. A new one is created every time // the selection changes. A selection is one or more non-overlapping // (and non-touching) ranges, sorted, and an integer that indicates // which one is the primary selection (the one that's scrolled into // view, that getCursor returns, etc). var Selection = function(ranges, primIndex) { this.ranges = ranges; this.primIndex = primIndex; }; Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; Selection.prototype.equals = function (other) { if (other == this) { return true } if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } for (var i = 0; i < this.ranges.length; i++) { var here = this.ranges[i], there = other.ranges[i]; if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } } return true }; Selection.prototype.deepCopy = function () { var out = []; for (var i = 0; i < this.ranges.length; i++) { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); } return new Selection(out, this.primIndex) }; Selection.prototype.somethingSelected = function () { for (var i = 0; i < this.ranges.length; i++) { if (!this.ranges[i].empty()) { return true } } return false }; Selection.prototype.contains = function (pos, end) { if (!end) { end = pos; } for (var i = 0; i < this.ranges.length; i++) { var range = this.ranges[i]; if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) { return i } } return -1 }; var Range = function(anchor, head) { this.anchor = anchor; this.head = head; }; Range.prototype.from = function () { return minPos(this.anchor, this.head) }; Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; // Take an unsorted, potentially overlapping set of ranges, and // build a selection out of it. 'Consumes' ranges array (modifying // it). function normalizeSelection(cm, ranges, primIndex) { var mayTouch = cm && cm.options.selectionsMayTouch; var prim = ranges[primIndex]; ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); primIndex = indexOf(ranges, prim); for (var i = 1; i < ranges.length; i++) { var cur = ranges[i], prev = ranges[i - 1]; var diff = cmp(prev.to(), cur.from()); if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; if (i <= primIndex) { --primIndex; } ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); } } return new Selection(ranges, primIndex) } function simpleSelection(anchor, head) { return new Selection([new Range(anchor, head || anchor)], 0) } // Compute the position of the end of a change (its 'to' property // refers to the pre-change end). function changeEnd(change) { if (!change.text) { return change.to } return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) } // Adjust a position to refer to the post-change position of the // same text, or the end of the change if the change covers it. function adjustForChange(pos, change) { if (cmp(pos, change.from) < 0) { return pos } if (cmp(pos, change.to) <= 0) { return changeEnd(change) } var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } return Pos(line, ch) } function computeSelAfterChange(doc, change) { var out = []; for (var i = 0; i < doc.sel.ranges.length; i++) { var range = doc.sel.ranges[i]; out.push(new Range(adjustForChange(range.anchor, change), adjustForChange(range.head, change))); } return normalizeSelection(doc.cm, out, doc.sel.primIndex) } function offsetPos(pos, old, nw) { if (pos.line == old.line) { return Pos(nw.line, pos.ch - old.ch + nw.ch) } else { return Pos(nw.line + (pos.line - old.line), pos.ch) } } // Used by replaceSelections to allow moving the selection to the // start or around the replaced test. Hint may be "start" or "around". function computeReplacedSel(doc, changes, hint) { var out = []; var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; for (var i = 0; i < changes.length; i++) { var change = changes[i]; var from = offsetPos(change.from, oldPrev, newPrev); var to = offsetPos(changeEnd(change), oldPrev, newPrev); oldPrev = change.to; newPrev = to; if (hint == "around") { var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; out[i] = new Range(inv ? to : from, inv ? from : to); } else { out[i] = new Range(from, from); } } return new Selection(out, doc.sel.primIndex) } // Used to get the editor into a consistent state again when options change. function loadMode(cm) { cm.doc.mode = getMode(cm.options, cm.doc.modeOption); resetModeState(cm); } function resetModeState(cm) { cm.doc.iter(function (line) { if (line.stateAfter) { line.stateAfter = null; } if (line.styles) { line.styles = null; } }); cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) { regChange(cm); } } // DOCUMENT DATA STRUCTURE // By default, updates that start and end at the beginning of a line // are treated specially, in order to make the association of line // widgets and marker elements with the text behave more intuitive. function isWholeLineUpdate(doc, change) { return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore) } // Perform a change on the document data structure. function updateDoc(doc, change, markedSpans, estimateHeight) { function spansFor(n) {return markedSpans ? markedSpans[n] : null} function update(line, text, spans) { updateLine(line, text, spans, estimateHeight); signalLater(line, "change", line, change); } function linesFor(start, end) { var result = []; for (var i = start; i < end; ++i) { result.push(new Line(text[i], spansFor(i), estimateHeight)); } return result } var from = change.from, to = change.to, text = change.text; var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; // Adjust the line structure if (change.full) { doc.insert(0, linesFor(0, text.length)); doc.remove(text.length, doc.size - text.length); } else if (isWholeLineUpdate(doc, change)) { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. var added = linesFor(0, text.length - 1); update(lastLine, lastLine.text, lastSpans); if (nlines) { doc.remove(from.line, nlines); } if (added.length) { doc.insert(from.line, added); } } else if (firstLine == lastLine) { if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); } else { var added$1 = linesFor(1, text.length - 1); added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); doc.insert(from.line + 1, added$1); } } else if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); doc.remove(from.line + 1, nlines); } else { update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); var added$2 = linesFor(1, text.length - 1); if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } doc.insert(from.line + 1, added$2); } signalLater(doc, "change", doc, change); } // Call f for all linked documents. function linkedDocs(doc, f, sharedHistOnly) { function propagate(doc, skip, sharedHist) { if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { var rel = doc.linked[i]; if (rel.doc == skip) { continue } var shared = sharedHist && rel.sharedHist; if (sharedHistOnly && !shared) { continue } f(rel.doc, shared); propagate(rel.doc, doc, shared); } } } propagate(doc, null, true); } // Attach a document to an editor. function attachDoc(cm, doc) { if (doc.cm) { throw new Error("This document is already in use.") } cm.doc = doc; doc.cm = cm; estimateLineHeights(cm); loadMode(cm); setDirectionClass(cm); if (!cm.options.lineWrapping) { findMaxLine(cm); } cm.options.mode = doc.modeOption; regChange(cm); } function setDirectionClass(cm) { (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); } function directionChanged(cm) { runInOp(cm, function () { setDirectionClass(cm); regChange(cm); }); } function History(startGen) { // Arrays of change events and selections. Doing something adds an // event to done and clears undo. Undoing moves events from done // to undone, redoing moves them in the other direction. this.done = []; this.undone = []; this.undoDepth = Infinity; // Used to track when changes can be merged into a single undo // event this.lastModTime = this.lastSelTime = 0; this.lastOp = this.lastSelOp = null; this.lastOrigin = this.lastSelOrigin = null; // Used by the isClean() method this.generation = this.maxGeneration = startGen || 1; } // Create a history change event from an updateDoc-style change // object. function historyChangeFromChange(doc, change) { var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); return histChange } // Pop all selection events off the end of a history array. Stop at // a change event. function clearSelectionEvents(array) { while (array.length) { var last = lst(array); if (last.ranges) { array.pop(); } else { break } } } // Find the top change event in the history. Pop off selection // events that are in the way. function lastChangeEvent(hist, force) { if (force) { clearSelectionEvents(hist.done); return lst(hist.done) } else if (hist.done.length && !lst(hist.done).ranges) { return lst(hist.done) } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { hist.done.pop(); return lst(hist.done) } } // Register a change in the history. Merges changes that are within // a single operation, or are close together with an origin that // allows merging (starting with "+") into a single event. function addChangeToHistory(doc, change, selAfter, opId) { var hist = doc.history; hist.undone.length = 0; var time = +new Date, cur; var last; if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { // Merge this change into the last event last = lst(cur.changes); if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { // Optimized case for simple insertion -- don't want to add // new changesets for every character typed last.to = changeEnd(change); } else { // Add new sub-event cur.changes.push(historyChangeFromChange(doc, change)); } } else { // Can not be merged, start a new event. var before = lst(hist.done); if (!before || !before.ranges) { pushSelectionToHistory(doc.sel, hist.done); } cur = {changes: [historyChangeFromChange(doc, change)], generation: hist.generation}; hist.done.push(cur); while (hist.done.length > hist.undoDepth) { hist.done.shift(); if (!hist.done[0].ranges) { hist.done.shift(); } } } hist.done.push(selAfter); hist.generation = ++hist.maxGeneration; hist.lastModTime = hist.lastSelTime = time; hist.lastOp = hist.lastSelOp = opId; hist.lastOrigin = hist.lastSelOrigin = change.origin; if (!last) { signal(doc, "historyAdded"); } } function selectionEventCanBeMerged(doc, origin, prev, sel) { var ch = origin.charAt(0); return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) } // Called whenever the selection changes, sets the new selection as // the pending selection in the history, and pushes the old pending // selection into the 'done' array when it was significantly // different (in number of selected ranges, emptiness, or time). function addSelectionToHistory(doc, sel, opId, options) { var hist = doc.history, origin = options && options.origin; // A new event is started when the previous origin does not match // the current, or the origins don't allow matching. Origins // starting with * are always merged, those starting with + are // merged when similar and close together in time. if (opId == hist.lastSelOp || (origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) { hist.done[hist.done.length - 1] = sel; } else { pushSelectionToHistory(sel, hist.done); } hist.lastSelTime = +new Date; hist.lastSelOrigin = origin; hist.lastSelOp = opId; if (options && options.clearRedo !== false) { clearSelectionEvents(hist.undone); } } function pushSelectionToHistory(sel, dest) { var top = lst(dest); if (!(top && top.ranges && top.equals(sel))) { dest.push(sel); } } // Used to store marked span information in the history. function attachLocalSpans(doc, change, from, to) { var existing = change["spans_" + doc.id], n = 0; doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { if (line.markedSpans) { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } ++n; }); } // When un/re-doing restores text containing marked spans, those // that have been explicitly cleared should not be restored. function removeClearedSpans(spans) { if (!spans) { return null } var out; for (var i = 0; i < spans.length; ++i) { if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } else if (out) { out.push(spans[i]); } } return !out ? spans : out.length ? out : null } // Retrieve and filter the old marked spans stored in a change event. function getOldSpans(doc, change) { var found = change["spans_" + doc.id]; if (!found) { return null } var nw = []; for (var i = 0; i < change.text.length; ++i) { nw.push(removeClearedSpans(found[i])); } return nw } // Used for un/re-doing changes from the history. Combines the // result of computing the existing spans with the set of spans that // existed in the history (so that deleting around a span and then // undoing brings back the span). function mergeOldSpans(doc, change) { var old = getOldSpans(doc, change); var stretched = stretchSpansOverChange(doc, change); if (!old) { return stretched } if (!stretched) { return old } for (var i = 0; i < old.length; ++i) { var oldCur = old[i], stretchCur = stretched[i]; if (oldCur && stretchCur) { spans: for (var j = 0; j < stretchCur.length; ++j) { var span = stretchCur[j]; for (var k = 0; k < oldCur.length; ++k) { if (oldCur[k].marker == span.marker) { continue spans } } oldCur.push(span); } } else if (stretchCur) { old[i] = stretchCur; } } return old } // Used both to provide a JSON-safe object in .getHistory, and, when // detaching a document, to split the history in two function copyHistoryArray(events, newGroup, instantiateSel) { var copy = []; for (var i = 0; i < events.length; ++i) { var event = events[i]; if (event.ranges) { copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); continue } var changes = event.changes, newChanges = []; copy.push({changes: newChanges}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m = (void 0); newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } } } return copy } // The 'scroll' parameter given to many of these indicated whether // the new cursor position should be scrolled into view after // modifying the selection. // If shift is held or the extend flag is set, extends a range to // include a given position (and optionally a second position). // Otherwise, simply returns the range between the given positions. // Used for cursor motion and such. function extendRange(range, head, other, extend) { if (extend) { var anchor = range.anchor; if (other) { var posBefore = cmp(head, anchor) < 0; if (posBefore != (cmp(other, anchor) < 0)) { anchor = head; head = other; } else if (posBefore != (cmp(head, other) < 0)) { head = other; } } return new Range(anchor, head) } else { return new Range(other || head, head) } } // Extend the primary selection range, discard the rest. function extendSelection(doc, head, other, options, extend) { if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); } // Extend all selections (pos is an array of selections with length // equal the number of selections) function extendSelections(doc, heads, options) { var out = []; var extend = doc.cm && (doc.cm.display.shift || doc.extend); for (var i = 0; i < doc.sel.ranges.length; i++) { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); setSelection(doc, newSel, options); } // Updates a single range in the selection. function replaceOneSelection(doc, i, range, options) { var ranges = doc.sel.ranges.slice(0); ranges[i] = range; setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); } // Reset the selection to a single range. function setSimpleSelection(doc, anchor, head, options) { setSelection(doc, simpleSelection(anchor, head), options); } // Give beforeSelectionChange handlers a change to influence a // selection update. function filterSelectionChange(doc, sel, options) { var obj = { ranges: sel.ranges, update: function(ranges) { this.ranges = []; for (var i = 0; i < ranges.length; i++) { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), clipPos(doc, ranges[i].head)); } }, origin: options && options.origin }; signal(doc, "beforeSelectionChange", doc, obj); if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) } else { return sel } } function setSelectionReplaceHistory(doc, sel, options) { var done = doc.history.done, last = lst(done); if (last && last.ranges) { done[done.length - 1] = sel; setSelectionNoUndo(doc, sel, options); } else { setSelection(doc, sel, options); } } // Set a new selection. function setSelection(doc, sel, options) { setSelectionNoUndo(doc, sel, options); addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); } function setSelectionNoUndo(doc, sel, options) { if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { sel = filterSelectionChange(doc, sel, options); } var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); if (!(options && options.scroll === false) && doc.cm) { ensureCursorVisible(doc.cm); } } function setSelectionInner(doc, sel) { if (sel.equals(doc.sel)) { return } doc.sel = sel; if (doc.cm) { doc.cm.curOp.updateInput = 1; doc.cm.curOp.selectionChanged = true; signalCursorActivity(doc.cm); } signalLater(doc, "cursorActivity", doc); } // Verify that the selection does not partially select any atomic // marked ranges. function reCheckSelection(doc) { setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); } // Return a selection that does not partially select any atomic // ranges. function skipAtomicInSelection(doc, sel, bias, mayClear) { var out; for (var i = 0; i < sel.ranges.length; i++) { var range = sel.ranges[i]; var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); if (out || newAnchor != range.anchor || newHead != range.head) { if (!out) { out = sel.ranges.slice(0, i); } out[i] = new Range(newAnchor, newHead); } } return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel } function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { var line = getLine(doc, pos.line); if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var sp = line.markedSpans[i], m = sp.marker; // Determine if we should prevent the cursor being placed to the left/right of an atomic marker // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it // is with selectLeft/Right var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft; var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight; if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { if (mayClear) { signal(m, "beforeCursorEnter"); if (m.explicitlyCleared) { if (!line.markedSpans) { break } else {--i; continue} } } if (!m.atomic) { continue } if (oldPos) { var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); if (dir < 0 ? preventCursorRight : preventCursorLeft) { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { return skipAtomicInner(doc, near, pos, dir, mayClear) } } var far = m.find(dir < 0 ? -1 : 1); if (dir < 0 ? preventCursorLeft : preventCursorRight) { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null } } } return pos } // Ensure a given position is not inside an atomic range. function skipAtomic(doc, pos, oldPos, bias, mayClear) { var dir = bias || 1; var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); if (!found) { doc.cantEdit = true; return Pos(doc.first, 0) } return found } function movePos(doc, pos, dir, line) { if (dir < 0 && pos.ch == 0) { if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } else { return null } } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } else { return null } } else { return new Pos(pos.line, pos.ch + dir) } } function selectAll(cm) { cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); } // UPDATING // Allow "beforeChange" event handlers to influence a change function filterChange(doc, change, update) { var obj = { canceled: false, from: change.from, to: change.to, text: change.text, origin: change.origin, cancel: function () { return obj.canceled = true; } }; if (update) { obj.update = function (from, to, text, origin) { if (from) { obj.from = clipPos(doc, from); } if (to) { obj.to = clipPos(doc, to); } if (text) { obj.text = text; } if (origin !== undefined) { obj.origin = origin; } }; } signal(doc, "beforeChange", doc, obj); if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } if (obj.canceled) { if (doc.cm) { doc.cm.curOp.updateInput = 2; } return null } return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} } // Apply a change to a document, and add it to the document's // history, and propagating it to all linked documents. function makeChange(doc, change, ignoreReadOnly) { if (doc.cm) { if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } if (doc.cm.state.suppressEdits) { return } } if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { change = filterChange(doc, change, true); if (!change) { return } } // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); if (split) { for (var i = split.length - 1; i >= 0; --i) { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); } } else { makeChangeInner(doc, change); } } function makeChangeInner(doc, change) { if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } var selAfter = computeSelAfterChange(doc, change); addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); var rebased = []; linkedDocs(doc, function (doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); }); } // Revert a change stored in a document's history. function makeChangeFromHistory(doc, type, allowSelectionOnly) { var suppress = doc.cm && doc.cm.state.suppressEdits; if (suppress && !allowSelectionOnly) { return } var hist = doc.history, event, selAfter = doc.sel; var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; // Verify that there is a useable event (so that ctrl-z won't // needlessly clear selection events) var i = 0; for (; i < source.length; i++) { event = source[i]; if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) { break } } if (i == source.length) { return } hist.lastOrigin = hist.lastSelOrigin = null; for (;;) { event = source.pop(); if (event.ranges) { pushSelectionToHistory(event, dest); if (allowSelectionOnly && !event.equals(doc.sel)) { setSelection(doc, event, {clearRedo: false}); return } selAfter = event; } else if (suppress) { source.push(event); return } else { break } } // Build up a reverse change object to add to the opposite history // stack (redo when undoing, and vice versa). var antiChanges = []; pushSelectionToHistory(selAfter, dest); dest.push({changes: antiChanges, generation: hist.generation}); hist.generation = event.generation || ++hist.maxGeneration; var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); var loop = function ( i ) { var change = event.changes[i]; change.origin = type; if (filter && !filterChange(doc, change, false)) { source.length = 0; return {} } antiChanges.push(historyChangeFromChange(doc, change)); var after = i ? computeSelAfterChange(doc, change) : lst(source); makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } var rebased = []; // Propagate to the linked documents linkedDocs(doc, function (doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); }); }; for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { var returned = loop( i$1 ); if ( returned ) return returned.v; } } // Sub-views need their line numbers shifted when text is added // above or below them in the parent document. function shiftDoc(doc, distance) { if (distance == 0) { return } doc.first += distance; doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( Pos(range.anchor.line + distance, range.anchor.ch), Pos(range.head.line + distance, range.head.ch) ); }), doc.sel.primIndex); if (doc.cm) { regChange(doc.cm, doc.first, doc.first - distance, distance); for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) { regLineChange(doc.cm, l, "gutter"); } } } // More lower-level change function, handling only a single document // (not linked ones). function makeChangeSingleDoc(doc, change, selAfter, spans) { if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } if (change.to.line < doc.first) { shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); return } if (change.from.line > doc.lastLine()) { return } // Clip the change to the size of this doc if (change.from.line < doc.first) { var shift = change.text.length - 1 - (doc.first - change.from.line); shiftDoc(doc, shift); change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), text: [lst(change.text)], origin: change.origin}; } var last = doc.lastLine(); if (change.to.line > last) { change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), text: [change.text[0]], origin: change.origin}; } change.removed = getBetween(doc, change.from, change.to); if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } else { updateDoc(doc, change, spans); } setSelectionNoUndo(doc, selAfter, sel_dontScroll); if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) { doc.cantEdit = false; } } // Handle the interaction of a change to a document with the editor // that this document is part of. function makeChangeSingleDocInEditor(cm, change, spans) { var doc = cm.doc, display = cm.display, from = change.from, to = change.to; var recomputeMaxLength = false, checkWidthStart = from.line; if (!cm.options.lineWrapping) { checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); doc.iter(checkWidthStart, to.line + 1, function (line) { if (line == display.maxLine) { recomputeMaxLength = true; return true } }); } if (doc.sel.contains(change.from, change.to) > -1) { signalCursorActivity(cm); } updateDoc(doc, change, spans, estimateHeight(cm)); if (!cm.options.lineWrapping) { doc.iter(checkWidthStart, from.line + change.text.length, function (line) { var len = lineLength(line); if (len > display.maxLineLength) { display.maxLine = line; display.maxLineLength = len; display.maxLineChanged = true; recomputeMaxLength = false; } }); if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } } retreatFrontier(doc, from.line); startWorker(cm, 400); var lendiff = change.text.length - (to.line - from.line) - 1; // Remember that these lines changed, for updating the display if (change.full) { regChange(cm); } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { regLineChange(cm, from.line, "text"); } else { regChange(cm, from.line, to.line + 1, lendiff); } var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); if (changeHandler || changesHandler) { var obj = { from: from, to: to, text: change.text, removed: change.removed, origin: change.origin }; if (changeHandler) { signalLater(cm, "change", cm, obj); } if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } } cm.display.selForContextMenu = null; } function replaceRange(doc, code, from, to, origin) { var assign; if (!to) { to = from; } if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); } if (typeof code == "string") { code = doc.splitLines(code); } makeChange(doc, {from: from, to: to, text: code, origin: origin}); } // Rebasing/resetting history to deal with externally-sourced changes function rebaseHistSelSingle(pos, from, to, diff) { if (to < pos.line) { pos.line += diff; } else if (from < pos.line) { pos.line = from; pos.ch = 0; } } // Tries to rebase an array of history events given a change in the // document. If the change touches the same lines as the event, the // event, and everything 'behind' it, is discarded. If the change is // before the event, the event's positions are updated. Uses a // copy-on-write scheme for the positions, to avoid having to // reallocate them all on every rebase, but also avoid problems with // shared position objects being unsafely updated. function rebaseHistArray(array, from, to, diff) { for (var i = 0; i < array.length; ++i) { var sub = array[i], ok = true; if (sub.ranges) { if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } for (var j = 0; j < sub.ranges.length; j++) { rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); } continue } for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { var cur = sub.changes[j$1]; if (to < cur.from.line) { cur.from = Pos(cur.from.line + diff, cur.from.ch); cur.to = Pos(cur.to.line + diff, cur.to.ch); } else if (from <= cur.to.line) { ok = false; break } } if (!ok) { array.splice(0, i + 1); i = 0; } } } function rebaseHist(hist, change) { var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; rebaseHistArray(hist.done, from, to, diff); rebaseHistArray(hist.undone, from, to, diff); } // Utility for applying a change to a line by handle or number, // returning the number and optionally registering the line as // changed. function changeLine(doc, handle, changeType, op) { var no = handle, line = handle; if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } else { no = lineNo(handle); } if (no == null) { return null } if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } return line } // The document is represented as a BTree consisting of leaves, with // chunk of lines in them, and branches, with up to ten leaves or // other branch nodes below them. The top node is always a branch // node, and is the document object itself (meaning it has // additional methods and properties). // // All nodes have parent links. The tree is used both to go from // line numbers to line objects, and to go from objects to numbers. // It also indexes by height, and is used to convert between height // and line object, and to find the total height of the document. // // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html function LeafChunk(lines) { this.lines = lines; this.parent = null; var height = 0; for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length }, // Remove the n lines at offset 'at'. removeInner: function(at, n) { for (var i = at, e = at + n; i < e; ++i) { var line = this.lines[i]; this.height -= line.height; cleanUpLine(line); signalLater(line, "delete"); } this.lines.splice(at, n); }, // Helper used to collapse a small branch into a single leaf. collapse: function(lines) { lines.push.apply(lines, this.lines); }, // Insert the given array of lines at offset 'at', count them as // having the given height. insertInner: function(at, lines, height) { this.height += height; this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; } }, // Used to iterate over a part of the tree. iterN: function(at, n, op) { for (var e = at + n; at < e; ++at) { if (op(this.lines[at])) { return true } } } }; function BranchChunk(children) { this.children = children; var size = 0, height = 0; for (var i = 0; i < children.length; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size }, removeInner: function(at, n) { this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.removeInner(at, rm); this.height -= oldHeight - child.height; if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) { break } at = 0; } else { at -= sz; } } // If the result is smaller than 25 lines, ensure that it is a // single leaf node. if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; this.children[0].parent = this; } }, collapse: function(lines) { for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); } }, insertInner: function(at, lines, height) { this.size += lines.length; this.height += height; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertInner(at, lines, height); if (child.lines && child.lines.length > 50) { // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. var remaining = child.lines.length % 25 + 25; for (var pos = remaining; pos < child.lines.length;) { var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); child.height -= leaf.height; this.children.splice(++i, 0, leaf); leaf.parent = this; } child.lines = child.lines.slice(0, remaining); this.maybeSpill(); } break } at -= sz; } }, // When a node has grown, check whether it should be split. maybeSpill: function() { if (this.children.length <= 10) { return } var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10) me.parent.maybeSpill(); }, iterN: function(at, n, op) { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var used = Math.min(n, sz - at); if (child.iterN(at, used, op)) { return true } if ((n -= used) == 0) { break } at = 0; } else { at -= sz; } } } }; // Line widgets are block elements displayed above or below a line. var LineWidget = function(doc, node, options) { if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) { this[opt] = options[opt]; } } } this.doc = doc; this.node = node; }; LineWidget.prototype.clear = function () { var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); if (no == null || !ws) { return } for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } } if (!ws.length) { line.widgets = null; } var height = widgetHeight(this); updateLineHeight(line, Math.max(0, line.height - height)); if (cm) { runInOp(cm, function () { adjustScrollWhenAboveVisible(cm, line, -height); regLineChange(cm, no, "widget"); }); signalLater(cm, "lineWidgetCleared", cm, this, no); } }; LineWidget.prototype.changed = function () { var this$1 = this; var oldH = this.height, cm = this.doc.cm, line = this.line; this.height = null; var diff = widgetHeight(this) - oldH; if (!diff) { return } if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); } if (cm) { runInOp(cm, function () { cm.curOp.forceUpdate = true; adjustScrollWhenAboveVisible(cm, line, diff); signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); }); } }; eventMixin(LineWidget); function adjustScrollWhenAboveVisible(cm, line, diff) { if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) { addToScrollTop(cm, diff); } } function addLineWidget(doc, handle, node, options) { var widget = new LineWidget(doc, node, options); var cm = doc.cm; if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } changeLine(doc, handle, "widget", function (line) { var widgets = line.widgets || (line.widgets = []); if (widget.insertAt == null) { widgets.push(widget); } else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); } widget.line = line; if (cm && !lineIsHidden(doc, line)) { var aboveVisible = heightAtLine(line) < doc.scrollTop; updateLineHeight(line, line.height + widgetHeight(widget)); if (aboveVisible) { addToScrollTop(cm, widget.height); } cm.curOp.forceUpdate = true; } return true }); if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); } return widget } // TEXTMARKERS // Created with markText and setBookmark methods. A TextMarker is a // handle that can be used to clear or find a marked position in the // document. Line objects hold arrays (markedSpans) containing // {from, to, marker} object pointing to such marker objects, and // indicating that such a marker is present on that line. Multiple // lines may point to the same marker when it spans across lines. // The spans will have null for their from/to properties when the // marker continues beyond the start/end of the line. Markers have // links back to the lines they currently touch. // Collapsed markers have unique ids, in order to be able to order // them, which is needed for uniquely determining an outer marker // when they overlap (they may nest, but not partially overlap). var nextMarkerId = 0; var TextMarker = function(doc, type) { this.lines = []; this.type = type; this.doc = doc; this.id = ++nextMarkerId; }; // Clear the marker. TextMarker.prototype.clear = function () { if (this.explicitlyCleared) { return } var cm = this.doc.cm, withOp = cm && !cm.curOp; if (withOp) { startOperation(cm); } if (hasHandler(this, "clear")) { var found = this.find(); if (found) { signalLater(this, "clear", found.from, found.to); } } var min = null, max = null; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); } else if (cm) { if (span.to != null) { max = lineNo(line); } if (span.from != null) { min = lineNo(line); } } line.markedSpans = removeMarkedSpan(line.markedSpans, span); if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) { updateLineHeight(line, textHeight(cm.display)); } } if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { var visual = visualLine(this.lines[i$1]), len = lineLength(visual); if (len > cm.display.maxLineLength) { cm.display.maxLine = visual; cm.display.maxLineLength = len; cm.display.maxLineChanged = true; } } } if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } this.lines.length = 0; this.explicitlyCleared = true; if (this.atomic && this.doc.cantEdit) { this.doc.cantEdit = false; if (cm) { reCheckSelection(cm.doc); } } if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } if (withOp) { endOperation(cm); } if (this.parent) { this.parent.clear(); } }; // Find the position of the marker in the document. Returns a {from, // to} object by default. Side can be passed to get a specific side // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the // Pos objects returned contain a line object, rather than a line // number (used to prevent looking up the same line twice). TextMarker.prototype.find = function (side, lineObj) { if (side == null && this.type == "bookmark") { side = 1; } var from, to; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (span.from != null) { from = Pos(lineObj ? line : lineNo(line), span.from); if (side == -1) { return from } } if (span.to != null) { to = Pos(lineObj ? line : lineNo(line), span.to); if (side == 1) { return to } } } return from && {from: from, to: to} }; // Signals that the marker's widget changed, and surrounding layout // should be recomputed. TextMarker.prototype.changed = function () { var this$1 = this; var pos = this.find(-1, true), widget = this, cm = this.doc.cm; if (!pos || !cm) { return } runInOp(cm, function () { var line = pos.line, lineN = lineNo(pos.line); var view = findViewForLine(cm, lineN); if (view) { clearLineMeasurementCacheFor(view); cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; } cm.curOp.updateMaxLine = true; if (!lineIsHidden(widget.doc, line) && widget.height != null) { var oldHeight = widget.height; widget.height = null; var dHeight = widgetHeight(widget) - oldHeight; if (dHeight) { updateLineHeight(line, line.height + dHeight); } } signalLater(cm, "markerChanged", cm, this$1); }); }; TextMarker.prototype.attachLine = function (line) { if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp; if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } } this.lines.push(line); }; TextMarker.prototype.detachLine = function (line) { this.lines.splice(indexOf(this.lines, line), 1); if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); } }; eventMixin(TextMarker); // Create a marker, wire it up to the right lines, and function markText(doc, from, to, options, type) { // Shared markers (across linked documents) are handled separately // (markTextShared will call out to this again, once per // document). if (options && options.shared) { return markTextShared(doc, from, to, options, type) } // Ensure we are in an operation. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } var marker = new TextMarker(doc, type), diff = cmp(from, to); if (options) { copyObj(options, marker, false); } // Don't connect empty markers unless clearWhenEmpty is false if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { return marker } if (marker.replacedWith) { // Showing up as a widget implies collapsed (widget replaces text) marker.collapsed = true; marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } if (options.insertLeft) { marker.widgetNode.insertLeft = true; } } if (marker.collapsed) { if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) { throw new Error("Inserting collapsed marker partially overlapping an existing one") } seeCollapsedSpans(); } if (marker.addToHistory) { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } var curLine = from.line, cm = doc.cm, updateMaxLine; doc.iter(curLine, to.line + 1, function (line) { if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { updateMaxLine = true; } if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null)); ++curLine; }); // lineIsHidden depends on the presence of the spans, so needs a second pass if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } }); } if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } if (marker.readOnly) { seeReadOnlySpans(); if (doc.history.done.length || doc.history.undone.length) { doc.clearHistory(); } } if (marker.collapsed) { marker.id = ++nextMarkerId; marker.atomic = true; } if (cm) { // Sync editor state if (updateMaxLine) { cm.curOp.updateMaxLine = true; } if (marker.collapsed) { regChange(cm, from.line, to.line + 1); } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } if (marker.atomic) { reCheckSelection(cm.doc); } signalLater(cm, "markerAdded", cm, marker); } return marker } // SHARED TEXTMARKERS // A shared marker spans multiple linked documents. It is // implemented as a meta-marker-object controlling multiple normal // markers. var SharedTextMarker = function(markers, primary) { this.markers = markers; this.primary = primary; for (var i = 0; i < markers.length; ++i) { markers[i].parent = this; } }; SharedTextMarker.prototype.clear = function () { if (this.explicitlyCleared) { return } this.explicitlyCleared = true; for (var i = 0; i < this.markers.length; ++i) { this.markers[i].clear(); } signalLater(this, "clear"); }; SharedTextMarker.prototype.find = function (side, lineObj) { return this.primary.find(side, lineObj) }; eventMixin(SharedTextMarker); function markTextShared(doc, from, to, options, type) { options = copyObj(options); options.shared = false; var markers = [markText(doc, from, to, options, type)], primary = markers[0]; var widget = options.widgetNode; linkedDocs(doc, function (doc) { if (widget) { options.widgetNode = widget.cloneNode(true); } markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); for (var i = 0; i < doc.linked.length; ++i) { if (doc.linked[i].isParent) { return } } primary = lst(markers); }); return new SharedTextMarker(markers, primary) } function findSharedMarkers(doc) { return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) } function copySharedMarkers(doc, markers) { for (var i = 0; i < markers.length; i++) { var marker = markers[i], pos = marker.find(); var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); if (cmp(mFrom, mTo)) { var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); marker.markers.push(subMark); subMark.parent = marker; } } } function detachSharedMarkers(markers) { var loop = function ( i ) { var marker = markers[i], linked = [marker.primary.doc]; linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); for (var j = 0; j < marker.markers.length; j++) { var subMarker = marker.markers[j]; if (indexOf(linked, subMarker.doc) == -1) { subMarker.parent = null; marker.markers.splice(j--, 1); } } }; for (var i = 0; i < markers.length; i++) loop( i ); } var nextDocId = 0; var Doc = function(text, mode, firstLine, lineSep, direction) { if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } if (firstLine == null) { firstLine = 0; } BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); this.first = firstLine; this.scrollTop = this.scrollLeft = 0; this.cantEdit = false; this.cleanGeneration = 1; this.modeFrontier = this.highlightFrontier = firstLine; var start = Pos(firstLine, 0); this.sel = simpleSelection(start); this.history = new History(null); this.id = ++nextDocId; this.modeOption = mode; this.lineSep = lineSep; this.direction = (direction == "rtl") ? "rtl" : "ltr"; this.extend = false; if (typeof text == "string") { text = this.splitLines(text); } updateDoc(this, {from: start, to: start, text: text}); setSelection(this, simpleSelection(start), sel_dontScroll); }; Doc.prototype = createObj(BranchChunk.prototype, { constructor: Doc, // Iterate over the document. Supports two forms -- with only one // argument, it calls that for each line in the document. With // three, it iterates over the range given by the first two (with // the second being non-inclusive). iter: function(from, to, op) { if (op) { this.iterN(from - this.first, to - from, op); } else { this.iterN(this.first, this.first + this.size, from); } }, // Non-public interface for adding and removing lines. insert: function(at, lines) { var height = 0; for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } this.insertInner(at - this.first, lines, height); }, remove: function(at, n) { this.removeInner(at - this.first, n); }, // From here, the methods are part of the public interface. Most // are also available from CodeMirror (editor) instances. getValue: function(lineSep) { var lines = getLines(this, this.first, this.first + this.size); if (lineSep === false) { return lines } return lines.join(lineSep || this.lineSeparator()) }, setValue: docMethodOp(function(code) { var top = Pos(this.first, 0), last = this.first + this.size - 1; makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), text: this.splitLines(code), origin: "setValue", full: true}, true); if (this.cm) { scrollToCoords(this.cm, 0, 0); } setSelection(this, simpleSelection(top), sel_dontScroll); }), replaceRange: function(code, from, to, origin) { from = clipPos(this, from); to = to ? clipPos(this, to) : from; replaceRange(this, code, from, to, origin); }, getRange: function(from, to, lineSep) { var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); if (lineSep === false) { return lines } return lines.join(lineSep || this.lineSeparator()) }, getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, getLineNumber: function(line) {return lineNo(line)}, getLineHandleVisualStart: function(line) { if (typeof line == "number") { line = getLine(this, line); } return visualLine(line) }, lineCount: function() {return this.size}, firstLine: function() {return this.first}, lastLine: function() {return this.first + this.size - 1}, clipPos: function(pos) {return clipPos(this, pos)}, getCursor: function(start) { var range = this.sel.primary(), pos; if (start == null || start == "head") { pos = range.head; } else if (start == "anchor") { pos = range.anchor; } else if (start == "end" || start == "to" || start === false) { pos = range.to(); } else { pos = range.from(); } return pos }, listSelections: function() { return this.sel.ranges }, somethingSelected: function() {return this.sel.somethingSelected()}, setCursor: docMethodOp(function(line, ch, options) { setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); }), setSelection: docMethodOp(function(anchor, head, options) { setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); }), extendSelection: docMethodOp(function(head, other, options) { extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); }), extendSelections: docMethodOp(function(heads, options) { extendSelections(this, clipPosArray(this, heads), options); }), extendSelectionsBy: docMethodOp(function(f, options) { var heads = map(this.sel.ranges, f); extendSelections(this, clipPosArray(this, heads), options); }), setSelections: docMethodOp(function(ranges, primary, options) { if (!ranges.length) { return } var out = []; for (var i = 0; i < ranges.length; i++) { out[i] = new Range(clipPos(this, ranges[i].anchor), clipPos(this, ranges[i].head)); } if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } setSelection(this, normalizeSelection(this.cm, out, primary), options); }), addSelection: docMethodOp(function(anchor, head, options) { var ranges = this.sel.ranges.slice(0); ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); }), getSelection: function(lineSep) { var ranges = this.sel.ranges, lines; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this, ranges[i].from(), ranges[i].to()); lines = lines ? lines.concat(sel) : sel; } if (lineSep === false) { return lines } else { return lines.join(lineSep || this.lineSeparator()) } }, getSelections: function(lineSep) { var parts = [], ranges = this.sel.ranges; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this, ranges[i].from(), ranges[i].to()); if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); } parts[i] = sel; } return parts }, replaceSelection: function(code, collapse, origin) { var dup = []; for (var i = 0; i < this.sel.ranges.length; i++) { dup[i] = code; } this.replaceSelections(dup, collapse, origin || "+input"); }, replaceSelections: docMethodOp(function(code, collapse, origin) { var changes = [], sel = this.sel; for (var i = 0; i < sel.ranges.length; i++) { var range = sel.ranges[i]; changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin}; } var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) { makeChange(this, changes[i$1]); } if (newSel) { setSelectionReplaceHistory(this, newSel); } else if (this.cm) { ensureCursorVisible(this.cm); } }), undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), setExtending: function(val) {this.extend = val;}, getExtending: function() {return this.extend}, historySize: function() { var hist = this.history, done = 0, undone = 0; for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } return {undo: done, redo: undone} }, clearHistory: function() { var this$1 = this; this.history = new History(this.history.maxGeneration); linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true); }, markClean: function() { this.cleanGeneration = this.changeGeneration(true); }, changeGeneration: function(forceSplit) { if (forceSplit) { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } return this.history.generation }, isClean: function (gen) { return this.history.generation == (gen || this.cleanGeneration) }, getHistory: function() { return {done: copyHistoryArray(this.history.done), undone: copyHistoryArray(this.history.undone)} }, setHistory: function(histData) { var hist = this.history = new History(this.history.maxGeneration); hist.done = copyHistoryArray(histData.done.slice(0), null, true); hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); }, setGutterMarker: docMethodOp(function(line, gutterID, value) { return changeLine(this, line, "gutter", function (line) { var markers = line.gutterMarkers || (line.gutterMarkers = {}); markers[gutterID] = value; if (!value && isEmpty(markers)) { line.gutterMarkers = null; } return true }) }), clearGutter: docMethodOp(function(gutterID) { var this$1 = this; this.iter(function (line) { if (line.gutterMarkers && line.gutterMarkers[gutterID]) { changeLine(this$1, line, "gutter", function () { line.gutterMarkers[gutterID] = null; if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } return true }); } }); }), lineInfo: function(line) { var n; if (typeof line == "number") { if (!isLine(this, line)) { return null } n = line; line = getLine(this, line); if (!line) { return null } } else { n = lineNo(line); if (n == null) { return null } } return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, widgets: line.widgets} }, addLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; if (!line[prop]) { line[prop] = cls; } else if (classTest(cls).test(line[prop])) { return false } else { line[prop] += " " + cls; } return true }) }), removeLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; var cur = line[prop]; if (!cur) { return false } else if (cls == null) { line[prop] = null; } else { var found = cur.match(classTest(cls)); if (!found) { return false } var end = found.index + found[0].length; line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; } return true }) }), addLineWidget: docMethodOp(function(handle, node, options) { return addLineWidget(this, handle, node, options) }), removeLineWidget: function(widget) { widget.clear(); }, markText: function(from, to, options) { return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") }, setBookmark: function(pos, options) { var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), insertLeft: options && options.insertLeft, clearWhenEmpty: false, shared: options && options.shared, handleMouseEvents: options && options.handleMouseEvents}; pos = clipPos(this, pos); return markText(this, pos, pos, realOpts, "bookmark") }, findMarksAt: function(pos) { pos = clipPos(this, pos); var markers = [], spans = getLine(this, pos.line).markedSpans; if (spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { markers.push(span.marker.parent || span.marker); } } } return markers }, findMarks: function(from, to, filter) { from = clipPos(this, from); to = clipPos(this, to); var found = [], lineNo = from.line; this.iter(from.line, to.line + 1, function (line) { var spans = line.markedSpans; if (spans) { for (var i = 0; i < spans.length; i++) { var span = spans[i]; if (!(span.to != null && lineNo == from.line && from.ch >= span.to || span.from == null && lineNo != from.line || span.from != null && lineNo == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { found.push(span.marker.parent || span.marker); } } } ++lineNo; }); return found }, getAllMarks: function() { var markers = []; this.iter(function (line) { var sps = line.markedSpans; if (sps) { for (var i = 0; i < sps.length; ++i) { if (sps[i].from != null) { markers.push(sps[i].marker); } } } }); return markers }, posFromIndex: function(off) { var ch, lineNo = this.first, sepSize = this.lineSeparator().length; this.iter(function (line) { var sz = line.text.length + sepSize; if (sz > off) { ch = off; return true } off -= sz; ++lineNo; }); return clipPos(this, Pos(lineNo, ch)) }, indexFromPos: function (coords) { coords = clipPos(this, coords); var index = coords.ch; if (coords.line < this.first || coords.ch < 0) { return 0 } var sepSize = this.lineSeparator().length; this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value index += line.text.length + sepSize; }); return index }, copy: function(copyHistory) { var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction); doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; doc.sel = this.sel; doc.extend = false; if (copyHistory) { doc.history.undoDepth = this.history.undoDepth; doc.setHistory(this.getHistory()); } return doc }, linkedDoc: function(options) { if (!options) { options = {}; } var from = this.first, to = this.first + this.size; if (options.from != null && options.from > from) { from = options.from; } if (options.to != null && options.to < to) { to = options.to; } var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); if (options.sharedHist) { copy.history = this.history ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; copySharedMarkers(copy, findSharedMarkers(this)); return copy }, unlinkDoc: function(other) { if (other instanceof CodeMirror) { other = other.doc; } if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { var link = this.linked[i]; if (link.doc != other) { continue } this.linked.splice(i, 1); other.unlinkDoc(this); detachSharedMarkers(findSharedMarkers(this)); break } } // If the histories were shared, split them again if (other.history == this.history) { var splitIds = [other.id]; linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); other.history = new History(null); other.history.done = copyHistoryArray(this.history.done, splitIds); other.history.undone = copyHistoryArray(this.history.undone, splitIds); } }, iterLinkedDocs: function(f) {linkedDocs(this, f);}, getMode: function() {return this.mode}, getEditor: function() {return this.cm}, splitLines: function(str) { if (this.lineSep) { return str.split(this.lineSep) } return splitLinesAuto(str) }, lineSeparator: function() { return this.lineSep || "\n" }, setDirection: docMethodOp(function (dir) { if (dir != "rtl") { dir = "ltr"; } if (dir == this.direction) { return } this.direction = dir; this.iter(function (line) { return line.order = null; }); if (this.cm) { directionChanged(this.cm); } }) }); // Public alias. Doc.prototype.eachLine = Doc.prototype.iter; // Kludge to work around strange IE behavior where it'll sometimes // re-fire a series of drag-related events right after the drop (#1551) var lastDrop = 0; function onDrop(e) { var cm = this; clearDragCursor(cm); if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } e_preventDefault(e); if (ie) { lastDrop = +new Date; } var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; if (!pos || cm.isReadOnly()) { return } // Might be a file drop, in which case we simply extract the text // and insert it. if (files && files.length && window.FileReader && window.File) { var n = files.length, text = Array(n), read = 0; var markAsReadAndPasteIfAllFilesAreRead = function () { if (++read == n) { operation(cm, function () { pos = clipPos(cm.doc, pos); var change = {from: pos, to: pos, text: cm.doc.splitLines( text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())), origin: "paste"}; makeChange(cm.doc, change); setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); })(); } }; var readTextFromFile = function (file, i) { if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { markAsReadAndPasteIfAllFilesAreRead(); return } var reader = new FileReader; reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); }; reader.onload = function () { var content = reader.result; if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { markAsReadAndPasteIfAllFilesAreRead(); return } text[i] = content; markAsReadAndPasteIfAllFilesAreRead(); }; reader.readAsText(file); }; for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); } } else { // Normal drop // Don't do a replace if the drop happened inside of the selected text. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { cm.state.draggingText(e); // Ensure the editor is re-focused setTimeout(function () { return cm.display.input.focus(); }, 20); return } try { var text$1 = e.dataTransfer.getData("Text"); if (text$1) { var selected; if (cm.state.draggingText && !cm.state.draggingText.copy) { selected = cm.listSelections(); } setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } cm.replaceSelection(text$1, "around", "paste"); cm.display.input.focus(); } } catch(e$1){} } } function onDragStart(cm, e) { if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } e.dataTransfer.setData("Text", cm.getSelection()); e.dataTransfer.effectAllowed = "copyMove"; // Use dummy image instead of default browsers image. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. if (e.dataTransfer.setDragImage && !safari) { var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; if (presto) { img.width = img.height = 1; cm.display.wrapper.appendChild(img); // Force a relayout, or Opera won't use our image for some obscure reason img._top = img.offsetTop; } e.dataTransfer.setDragImage(img, 0, 0); if (presto) { img.parentNode.removeChild(img); } } } function onDragOver(cm, e) { var pos = posFromMouse(cm, e); if (!pos) { return } var frag = document.createDocumentFragment(); drawSelectionCursor(cm, pos, frag); if (!cm.display.dragCursor) { cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); } removeChildrenAndAdd(cm.display.dragCursor, frag); } function clearDragCursor(cm) { if (cm.display.dragCursor) { cm.display.lineSpace.removeChild(cm.display.dragCursor); cm.display.dragCursor = null; } } // These must be handled carefully, because naively registering a // handler for each editor will cause the editors to never be // garbage collected. function forEachCodeMirror(f) { if (!document.getElementsByClassName) { return } var byClass = document.getElementsByClassName("CodeMirror"), editors = []; for (var i = 0; i < byClass.length; i++) { var cm = byClass[i].CodeMirror; if (cm) { editors.push(cm); } } if (editors.length) { editors[0].operation(function () { for (var i = 0; i < editors.length; i++) { f(editors[i]); } }); } } var globalsRegistered = false; function ensureGlobalHandlers() { if (globalsRegistered) { return } registerGlobalHandlers(); globalsRegistered = true; } function registerGlobalHandlers() { // When the window resizes, we need to refresh active editors. var resizeTimer; on(window, "resize", function () { if (resizeTimer == null) { resizeTimer = setTimeout(function () { resizeTimer = null; forEachCodeMirror(onResize); }, 100); } }); // When the window loses focus, we want to show the editor as blurred on(window, "blur", function () { return forEachCodeMirror(onBlur); }); } // Called when the window resizes function onResize(cm) { var d = cm.display; // Might be a text scaling operation, clear size caches. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; d.scrollbarsClipped = false; cm.setSize(); } var keyNames = { 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" }; // Number keys for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } // Alphabetic keys for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } // Function keys for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } var keyMap = {}; keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", "Esc": "singleSelection" }; // Note that the save and find-related commands aren't defined by // default. User code or addons can define them. Unknown commands // are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", "fallthrough": "basic" }; // Very basic readline/emacs-style bindings, which are standard on Mac. keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", "Ctrl-O": "openLine" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", "fallthrough": ["basic", "emacsy"] }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; // KEYMAP DISPATCH function normalizeKeyName(name) { var parts = name.split(/-(?!$)/); name = parts[parts.length - 1]; var alt, ctrl, shift, cmd; for (var i = 0; i < parts.length - 1; i++) { var mod = parts[i]; if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } else if (/^a(lt)?$/i.test(mod)) { alt = true; } else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } else if (/^s(hift)?$/i.test(mod)) { shift = true; } else { throw new Error("Unrecognized modifier name: " + mod) } } if (alt) { name = "Alt-" + name; } if (ctrl) { name = "Ctrl-" + name; } if (cmd) { name = "Cmd-" + name; } if (shift) { name = "Shift-" + name; } return name } // This is a kludge to keep keymaps mostly working as raw objects // (backwards compatibility) while at the same time support features // like normalization and multi-stroke key bindings. It compiles a // new normalized keymap, and then updates the old object to reflect // this. function normalizeKeyMap(keymap) { var copy = {}; for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { var value = keymap[keyname]; if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } if (value == "...") { delete keymap[keyname]; continue } var keys = map(keyname.split(" "), normalizeKeyName); for (var i = 0; i < keys.length; i++) { var val = (void 0), name = (void 0); if (i == keys.length - 1) { name = keys.join(" "); val = value; } else { name = keys.slice(0, i + 1).join(" "); val = "..."; } var prev = copy[name]; if (!prev) { copy[name] = val; } else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } } delete keymap[keyname]; } } for (var prop in copy) { keymap[prop] = copy[prop]; } return keymap } function lookupKey(key, map, handle, context) { map = getKeyMap(map); var found = map.call ? map.call(key, context) : map[key]; if (found === false) { return "nothing" } if (found === "...") { return "multi" } if (found != null && handle(found)) { return "handled" } if (map.fallthrough) { if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") { return lookupKey(key, map.fallthrough, handle, context) } for (var i = 0; i < map.fallthrough.length; i++) { var result = lookupKey(key, map.fallthrough[i], handle, context); if (result) { return result } } } } // Modifier key presses don't count as 'real' key presses for the // purpose of keymap fallthrough. function isModifierKey(value) { var name = typeof value == "string" ? value : keyNames[value.keyCode]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" } function addModifierNames(name, event, noShift) { var base = name; if (event.altKey && base != "Alt") { name = "Alt-" + name; } if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; } if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } return name } // Look up the name of a key as indicated by an event object. function keyName(event, noShift) { if (presto && event.keyCode == 34 && event["char"]) { return false } var name = keyNames[event.keyCode]; if (name == null || event.altGraphKey) { return false } // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) if (event.keyCode == 3 && event.code) { name = event.code; } return addModifierNames(name, event, noShift) } function getKeyMap(val) { return typeof val == "string" ? keyMap[val] : val } // Helper for deleting text near the selection(s), used to implement // backspace, delete, and similar functionality. function deleteNearSelection(cm, compute) { var ranges = cm.doc.sel.ranges, kill = []; // Build up a set of ranges to kill first, merging overlapping // ranges. for (var i = 0; i < ranges.length; i++) { var toKill = compute(ranges[i]); while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { var replaced = kill.pop(); if (cmp(replaced.from, toKill.from) < 0) { toKill.from = replaced.from; break } } kill.push(toKill); } // Next, remove those actual ranges. runInOp(cm, function () { for (var i = kill.length - 1; i >= 0; i--) { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } ensureCursorVisible(cm); }); } function moveCharLogically(line, ch, dir) { var target = skipExtendingChars(line.text, ch + dir, dir); return target < 0 || target > line.text.length ? null : target } function moveLogically(line, start, dir) { var ch = moveCharLogically(line, start.ch, dir); return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") } function endOfLine(visually, cm, lineObj, lineNo, dir) { if (visually) { if (cm.doc.direction == "rtl") { dir = -dir; } var order = getOrder(lineObj, cm.doc.direction); if (order) { var part = dir < 0 ? lst(order) : order[0]; var moveInStorageOrder = (dir < 0) == (part.level == 1); var sticky = moveInStorageOrder ? "after" : "before"; var ch; // With a wrapped rtl chunk (possibly spanning multiple bidi parts), // it could be that the last bidi part is not on the last visual line, // since visual lines contain content order-consecutive chunks. // Thus, in rtl, we are looking for the first (content-order) character // in the rtl chunk that is on the last line (that is, the same line // as the last (content-order) character). if (part.level > 0 || cm.doc.direction == "rtl") { var prep = prepareMeasureForLine(cm, lineObj); ch = dir < 0 ? lineObj.text.length - 1 : 0; var targetTop = measureCharPrepared(cm, prep, ch).top; ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } } else { ch = dir < 0 ? part.to : part.from; } return new Pos(lineNo, ch, sticky) } } return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") } function moveVisually(cm, line, start, dir) { var bidi = getOrder(line, cm.doc.direction); if (!bidi) { return moveLogically(line, start, dir) } if (start.ch >= line.text.length) { start.ch = line.text.length; start.sticky = "before"; } else if (start.ch <= 0) { start.ch = 0; start.sticky = "after"; } var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, // nothing interesting happens. return moveLogically(line, start, dir) } var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; var prep; var getWrappedLineExtent = function (ch) { if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } prep = prep || prepareMeasureForLine(cm, line); return wrappedLineExtentChar(cm, line, prep, ch) }; var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); if (cm.doc.direction == "rtl" || part.level == 1) { var moveInStorageOrder = (part.level == 1) == (dir < 0); var ch = mv(start, moveInStorageOrder ? 1 : -1); if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { // Case 2: We move within an rtl part or in an rtl editor on the same visual line var sticky = moveInStorageOrder ? "before" : "after"; return new Pos(start.line, ch, sticky) } } // Case 3: Could not move within this bidi part in this visual line, so leave // the current bidi part var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder ? new Pos(start.line, mv(ch, 1), "before") : new Pos(start.line, ch, "after"); }; for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { var part = bidi[partPos]; var moveInStorageOrder = (dir > 0) == (part.level != 1); var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } ch = moveInStorageOrder ? part.from : mv(part.to, -1); if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } } }; // Case 3a: Look for other bidi parts on the same visual line var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); if (res) { return res } // Case 3b: Look for other bidi parts on the next visual line var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); if (res) { return res } } // Case 4: Nowhere to move return null } // Commands are parameter-less actions that can be performed on an // editor, mostly used for keybindings. var commands = { selectAll: selectAll, singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, killLine: function (cm) { return deleteNearSelection(cm, function (range) { if (range.empty()) { var len = getLine(cm.doc, range.head.line).text.length; if (range.head.ch == len && range.head.line < cm.lastLine()) { return {from: range.head, to: Pos(range.head.line + 1, 0)} } else { return {from: range.head, to: Pos(range.head.line, len)} } } else { return {from: range.from(), to: range.to()} } }); }, deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ from: Pos(range.from().line, 0), to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) }); }); }, delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ from: Pos(range.from().line, 0), to: range.from() }); }); }, delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { var top = cm.charCoords(range.head, "div").top + 5; var leftPos = cm.coordsChar({left: 0, top: top}, "div"); return {from: leftPos, to: range.from()} }); }, delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { var top = cm.charCoords(range.head, "div").top + 5; var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); return {from: range.from(), to: rightPos } }); }, undo: function (cm) { return cm.undo(); }, redo: function (cm) { return cm.redo(); }, undoSelection: function (cm) { return cm.undoSelection(); }, redoSelection: function (cm) { return cm.redoSelection(); }, goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, {origin: "+move", bias: 1} ); }, goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, {origin: "+move", bias: 1} ); }, goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, {origin: "+move", bias: -1} ); }, goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") }, sel_move); }, goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; return cm.coordsChar({left: 0, top: top}, "div") }, sel_move); }, goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; var pos = cm.coordsChar({left: 0, top: top}, "div"); if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } return pos }, sel_move); }, goLineUp: function (cm) { return cm.moveV(-1, "line"); }, goLineDown: function (cm) { return cm.moveV(1, "line"); }, goPageUp: function (cm) { return cm.moveV(-1, "page"); }, goPageDown: function (cm) { return cm.moveV(1, "page"); }, goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, goCharRight: function (cm) { return cm.moveH(1, "char"); }, goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, goColumnRight: function (cm) { return cm.moveH(1, "column"); }, goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, goGroupRight: function (cm) { return cm.moveH(1, "group"); }, goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, goWordRight: function (cm) { return cm.moveH(1, "word"); }, delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); }, delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, indentAuto: function (cm) { return cm.indentSelection("smart"); }, indentMore: function (cm) { return cm.indentSelection("add"); }, indentLess: function (cm) { return cm.indentSelection("subtract"); }, insertTab: function (cm) { return cm.replaceSelection("\t"); }, insertSoftTab: function (cm) { var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; for (var i = 0; i < ranges.length; i++) { var pos = ranges[i].from(); var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); spaces.push(spaceStr(tabSize - col % tabSize)); } cm.replaceSelections(spaces); }, defaultTab: function (cm) { if (cm.somethingSelected()) { cm.indentSelection("add"); } else { cm.execCommand("insertTab"); } }, // Swap the two chars left and right of each selection's head. // Move cursor behind the two swapped characters afterwards. // // Doesn't consider line feeds a character. // Doesn't scan more than one line above to find a character. // Doesn't do anything on an empty line. // Doesn't do anything with non-empty selections. transposeChars: function (cm) { return runInOp(cm, function () { var ranges = cm.listSelections(), newSel = []; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) { continue } var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; if (line) { if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } if (cur.ch > 0) { cur = new Pos(cur.line, cur.ch + 1); cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); } else if (cur.line > cm.doc.first) { var prev = getLine(cm.doc, cur.line - 1).text; if (prev) { cur = new Pos(cur.line, 1); cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); } } } newSel.push(new Range(cur, cur)); } cm.setSelections(newSel); }); }, newlineAndIndent: function (cm) { return runInOp(cm, function () { var sels = cm.listSelections(); for (var i = sels.length - 1; i >= 0; i--) { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } sels = cm.listSelections(); for (var i$1 = 0; i$1 < sels.length; i$1++) { cm.indentLine(sels[i$1].from().line, null, true); } ensureCursorVisible(cm); }); }, openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } }; function lineStart(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLine(line); if (visual != line) { lineN = lineNo(visual); } return endOfLine(true, cm, visual, lineN, 1) } function lineEnd(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLineEnd(line); if (visual != line) { lineN = lineNo(visual); } return endOfLine(true, cm, line, lineN, -1) } function lineStartSmart(cm, pos) { var start = lineStart(cm, pos.line); var line = getLine(cm.doc, start.line); var order = getOrder(line, cm.doc.direction); if (!order || order[0].level == 0) { var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) } return start } // Run a handler that was bound to a key. function doHandleBinding(cm, bound, dropShift) { if (typeof bound == "string") { bound = commands[bound]; if (!bound) { return false } } // Ensure previous input has been read, so that the handler sees a // consistent view of the document cm.display.input.ensurePolled(); var prevShift = cm.display.shift, done = false; try { if (cm.isReadOnly()) { cm.state.suppressEdits = true; } if (dropShift) { cm.display.shift = false; } done = bound(cm) != Pass; } finally { cm.display.shift = prevShift; cm.state.suppressEdits = false; } return done } function lookupKeyForEditor(cm, name, handle) { for (var i = 0; i < cm.state.keyMaps.length; i++) { var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); if (result) { return result } } return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) || lookupKey(name, cm.options.keyMap, handle, cm) } // Note that, despite the name, this function is also used to check // for bound mouse clicks. var stopSeq = new Delayed; function dispatchKey(cm, name, e, handle) { var seq = cm.state.keySeq; if (seq) { if (isModifierKey(name)) { return "handled" } if (/\'$/.test(name)) { cm.state.keySeq = null; } else { stopSeq.set(50, function () { if (cm.state.keySeq == seq) { cm.state.keySeq = null; cm.display.input.reset(); } }); } if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } } return dispatchKeyInner(cm, name, e, handle) } function dispatchKeyInner(cm, name, e, handle) { var result = lookupKeyForEditor(cm, name, handle); if (result == "multi") { cm.state.keySeq = name; } if (result == "handled") { signalLater(cm, "keyHandled", cm, name, e); } if (result == "handled" || result == "multi") { e_preventDefault(e); restartBlink(cm); } return !!result } // Handle a key from the keydown event. function handleKeyBinding(cm, e) { var name = keyName(e, true); if (!name) { return false } if (e.shiftKey && !cm.state.keySeq) { // First try to resolve full name (including 'Shift-'). Failing // that, see if there is a cursor-motion command (starting with // 'go') bound to the keyname without 'Shift-'. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) || dispatchKey(cm, name, e, function (b) { if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { return doHandleBinding(cm, b) } }) } else { return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) } } // Handle a key from the keypress event function handleCharBinding(cm, e, ch) { return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) } var lastStoppedKey = null; function onKeyDown(e) { var cm = this; if (e.target && e.target != cm.display.input.getField()) { return } cm.curOp.focus = activeElt(); if (signalDOMEvent(cm, e)) { return } // IE does strange things with escape. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } var code = e.keyCode; cm.display.shift = code == 16 || e.shiftKey; var handled = handleKeyBinding(cm, e); if (presto) { lastStoppedKey = handled ? code : null; // Opera has no cut event... we try to at least catch the key combo if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { cm.replaceSelection("", null, "cut"); } } if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) { document.execCommand("cut"); } // Turn mouse into crosshair when Alt is held on Mac. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { showCrossHair(cm); } } function showCrossHair(cm) { var lineDiv = cm.display.lineDiv; addClass(lineDiv, "CodeMirror-crosshair"); function up(e) { if (e.keyCode == 18 || !e.altKey) { rmClass(lineDiv, "CodeMirror-crosshair"); off(document, "keyup", up); off(document, "mouseover", up); } } on(document, "keyup", up); on(document, "mouseover", up); } function onKeyUp(e) { if (e.keyCode == 16) { this.doc.sel.shift = false; } signalDOMEvent(this, e); } function onKeyPress(e) { var cm = this; if (e.target && e.target != cm.display.input.getField()) { return } if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } var keyCode = e.keyCode, charCode = e.charCode; if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } var ch = String.fromCharCode(charCode == null ? keyCode : charCode); // Some browsers fire keypress events for backspace if (ch == "\x08") { return } if (handleCharBinding(cm, e, ch)) { return } cm.display.input.onKeyPress(e); } var DOUBLECLICK_DELAY = 400; var PastClick = function(time, pos, button) { this.time = time; this.pos = pos; this.button = button; }; PastClick.prototype.compare = function (time, pos, button) { return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button }; var lastClick, lastDoubleClick; function clickRepeat(pos, button) { var now = +new Date; if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { lastClick = lastDoubleClick = null; return "triple" } else if (lastClick && lastClick.compare(now, pos, button)) { lastDoubleClick = new PastClick(now, pos, button); lastClick = null; return "double" } else { lastClick = new PastClick(now, pos, button); lastDoubleClick = null; return "single" } } // A mouse down can be a single click, double click, triple click, // start of selection drag, start of text drag, new cursor // (ctrl-click), rectangle drag (alt-drag), or xwin // middle-click-paste. Or it might be a click on something we should // not interfere with, such as a scrollbar or widget. function onMouseDown(e) { var cm = this, display = cm.display; if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } display.input.ensurePolled(); display.shift = e.shiftKey; if (eventInWidget(display, e)) { if (!webkit) { // Briefly turn off draggability, to allow widgets to do // normal dragging things. display.scroller.draggable = false; setTimeout(function () { return display.scroller.draggable = true; }, 100); } return } if (clickInGutter(cm, e)) { return } var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; window.focus(); // #3261: make sure, that we're not starting a second selection if (button == 1 && cm.state.selectingText) { cm.state.selectingText(e); } if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } if (button == 1) { if (pos) { leftButtonDown(cm, pos, repeat, e); } else if (e_target(e) == display.scroller) { e_preventDefault(e); } } else if (button == 2) { if (pos) { extendSelection(cm.doc, pos); } setTimeout(function () { return display.input.focus(); }, 20); } else if (button == 3) { if (captureRightClick) { cm.display.input.onContextMenu(e); } else { delayBlurEvent(cm); } } } function handleMappedButton(cm, button, pos, repeat, event) { var name = "Click"; if (repeat == "double") { name = "Double" + name; } else if (repeat == "triple") { name = "Triple" + name; } name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { if (typeof bound == "string") { bound = commands[bound]; } if (!bound) { return false } var done = false; try { if (cm.isReadOnly()) { cm.state.suppressEdits = true; } done = bound(cm, pos) != Pass; } finally { cm.state.suppressEdits = false; } return done }) } function configureMouse(cm, repeat, event) { var option = cm.getOption("configureMouse"); var value = option ? option(cm, repeat, event) : {}; if (value.unit == null) { var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; } if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } return value } function leftButtonDown(cm, pos, repeat, event) { if (ie) { setTimeout(bind(ensureFocus, cm), 0); } else { cm.curOp.focus = activeElt(); } var behavior = configureMouse(cm, repeat, event); var sel = cm.doc.sel, contained; if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { leftButtonStartDrag(cm, event, pos, behavior); } else { leftButtonSelect(cm, event, pos, behavior); } } // Start a text drag. When it ends, see if any dragging actually // happen, and treat as a click if it didn't. function leftButtonStartDrag(cm, event, pos, behavior) { var display = cm.display, moved = false; var dragEnd = operation(cm, function (e) { if (webkit) { display.scroller.draggable = false; } cm.state.draggingText = false; off(display.wrapper.ownerDocument, "mouseup", dragEnd); off(display.wrapper.ownerDocument, "mousemove", mouseMove); off(display.scroller, "dragstart", dragStart); off(display.scroller, "drop", dragEnd); if (!moved) { e_preventDefault(e); if (!behavior.addNew) { extendSelection(cm.doc, pos, null, null, behavior.extend); } // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) if ((webkit && !safari) || ie && ie_version == 9) { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); } else { display.input.focus(); } } }); var mouseMove = function(e2) { moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; }; var dragStart = function () { return moved = true; }; // Let the drag handler handle this. if (webkit) { display.scroller.draggable = true; } cm.state.draggingText = dragEnd; dragEnd.copy = !behavior.moveOnDrag; // IE's approach to draggable if (display.scroller.dragDrop) { display.scroller.dragDrop(); } on(display.wrapper.ownerDocument, "mouseup", dragEnd); on(display.wrapper.ownerDocument, "mousemove", mouseMove); on(display.scroller, "dragstart", dragStart); on(display.scroller, "drop", dragEnd); delayBlurEvent(cm); setTimeout(function () { return display.input.focus(); }, 20); } function rangeForUnit(cm, pos, unit) { if (unit == "char") { return new Range(pos, pos) } if (unit == "word") { return cm.findWordAt(pos) } if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } var result = unit(cm, pos); return new Range(result.from, result.to) } // Normal selection, as opposed to text dragging. function leftButtonSelect(cm, event, start, behavior) { var display = cm.display, doc = cm.doc; e_preventDefault(event); var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; if (behavior.addNew && !behavior.extend) { ourIndex = doc.sel.contains(start); if (ourIndex > -1) { ourRange = ranges[ourIndex]; } else { ourRange = new Range(start, start); } } else { ourRange = doc.sel.primary(); ourIndex = doc.sel.primIndex; } if (behavior.unit == "rectangle") { if (!behavior.addNew) { ourRange = new Range(start, start); } start = posFromMouse(cm, event, true, true); ourIndex = -1; } else { var range = rangeForUnit(cm, start, behavior.unit); if (behavior.extend) { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); } else { ourRange = range; } } if (!behavior.addNew) { ourIndex = 0; setSelection(doc, new Selection([ourRange], 0), sel_mouse); startSel = doc.sel; } else if (ourIndex == -1) { ourIndex = ranges.length; setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), {scroll: false, origin: "*mouse"}); } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), {scroll: false, origin: "*mouse"}); startSel = doc.sel; } else { replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); } var lastPos = start; function extendTo(pos) { if (cmp(lastPos, pos) == 0) { return } lastPos = pos; if (behavior.unit == "rectangle") { var ranges = [], tabSize = cm.options.tabSize; var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); if (left == right) { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } else if (text.length > leftPos) { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } } if (!ranges.length) { ranges.push(new Range(start, start)); } setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), {origin: "*mouse", scroll: false}); cm.scrollIntoView(pos); } else { var oldRange = ourRange; var range = rangeForUnit(cm, pos, behavior.unit); var anchor = oldRange.anchor, head; if (cmp(range.anchor, anchor) > 0) { head = range.head; anchor = minPos(oldRange.from(), range.anchor); } else { head = range.anchor; anchor = maxPos(oldRange.to(), range.head); } var ranges$1 = startSel.ranges.slice(0); ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); } } var editorSize = display.wrapper.getBoundingClientRect(); // Used to ensure timeout re-tries don't fire when another extend // happened in the meantime (clearTimeout isn't reliable -- at // least on Chrome, the timeouts still happen even when cleared, // if the clear happens after their scheduled firing time). var counter = 0; function extend(e) { var curCount = ++counter; var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); if (!cur) { return } if (cmp(cur, lastPos) != 0) { cm.curOp.focus = activeElt(); extendTo(cur); var visible = visibleLines(display, doc); if (cur.line >= visible.to || cur.line < visible.from) { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } } else { var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; if (outside) { setTimeout(operation(cm, function () { if (counter != curCount) { return } display.scroller.scrollTop += outside; extend(e); }), 50); } } } function done(e) { cm.state.selectingText = false; counter = Infinity; // If e is null or undefined we interpret this as someone trying // to explicitly cancel the selection rather than the user // letting go of the mouse button. if (e) { e_preventDefault(e); display.input.focus(); } off(display.wrapper.ownerDocument, "mousemove", move); off(display.wrapper.ownerDocument, "mouseup", up); doc.history.lastSelOrigin = null; } var move = operation(cm, function (e) { if (e.buttons === 0 || !e_button(e)) { done(e); } else { extend(e); } }); var up = operation(cm, done); cm.state.selectingText = up; on(display.wrapper.ownerDocument, "mousemove", move); on(display.wrapper.ownerDocument, "mouseup", up); } // Used when mouse-selecting to adjust the anchor to the proper side // of a bidi jump depending on the visual position of the head. function bidiSimplify(cm, range) { var anchor = range.anchor; var head = range.head; var anchorLine = getLine(cm.doc, anchor.line); if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range } var order = getOrder(anchorLine); if (!order) { return range } var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; if (part.from != anchor.ch && part.to != anchor.ch) { return range } var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); if (boundary == 0 || boundary == order.length) { return range } // Compute the relative visual position of the head compared to the // anchor (<0 is to the left, >0 to the right) var leftSide; if (head.line != anchor.line) { leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; } else { var headIndex = getBidiPartAt(order, head.ch, head.sticky); var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); if (headIndex == boundary - 1 || headIndex == boundary) { leftSide = dir < 0; } else { leftSide = dir > 0; } } var usePart = order[boundary + (leftSide ? -1 : 0)]; var from = leftSide == (usePart.level == 1); var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head) } // Determines whether an event happened in the gutter, and fires the // handlers for the corresponding event. function gutterEvent(cm, e, type, prevent) { var mX, mY; if (e.touches) { mX = e.touches[0].clientX; mY = e.touches[0].clientY; } else { try { mX = e.clientX; mY = e.clientY; } catch(e$1) { return false } } if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } if (prevent) { e_preventDefault(e); } var display = cm.display; var lineBox = display.lineDiv.getBoundingClientRect(); if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } mY -= lineBox.top - display.viewOffset; for (var i = 0; i < cm.display.gutterSpecs.length; ++i) { var g = display.gutters.childNodes[i]; if (g && g.getBoundingClientRect().right >= mX) { var line = lineAtHeight(cm.doc, mY); var gutter = cm.display.gutterSpecs[i]; signal(cm, type, cm, line, gutter.className, e); return e_defaultPrevented(e) } } } function clickInGutter(cm, e) { return gutterEvent(cm, e, "gutterClick", true) } // CONTEXT MENU HANDLING // To make the context menu work, we need to briefly unhide the // textarea (making it as unobtrusive as possible) to let the // right-click take effect on it. function onContextMenu(cm, e) { if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } if (signalDOMEvent(cm, e, "contextmenu")) { return } if (!captureRightClick) { cm.display.input.onContextMenu(e); } } function contextMenuInGutter(cm, e) { if (!hasHandler(cm, "gutterContextMenu")) { return false } return gutterEvent(cm, e, "gutterContextMenu", false) } function themeChanged(cm) { cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); clearCaches(cm); } var Init = {toString: function(){return "CodeMirror.Init"}}; var defaults = {}; var optionHandlers = {}; function defineOptions(CodeMirror) { var optionHandlers = CodeMirror.optionHandlers; function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt; if (handle) { optionHandlers[name] = notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } } CodeMirror.defineOption = option; // Passed to option handlers when there is no old value. CodeMirror.Init = Init; // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", function (cm, val) { return cm.setValue(val); }, true); option("mode", null, function (cm, val) { cm.doc.modeOption = val; loadMode(cm); }, true); option("indentUnit", 2, loadMode, true); option("indentWithTabs", false); option("smartIndent", true); option("tabSize", 4, function (cm) { resetModeState(cm); clearCaches(cm); regChange(cm); }, true); option("lineSeparator", null, function (cm, val) { cm.doc.lineSep = val; if (!val) { return } var newBreaks = [], lineNo = cm.doc.first; cm.doc.iter(function (line) { for (var pos = 0;;) { var found = line.text.indexOf(val, pos); if (found == -1) { break } pos = found + val.length; newBreaks.push(Pos(lineNo, found)); } lineNo++; }); for (var i = newBreaks.length - 1; i >= 0; i--) { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } }); option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); if (old != Init) { cm.refresh(); } }); option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); option("electricChars", true); option("inputStyle", mobile ? "contenteditable" : "textarea", function () { throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME }, true); option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true); option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true); option("rtlMoveVisually", !windows); option("wholeLineUpdateBefore", true); option("theme", "default", function (cm) { themeChanged(cm); updateGutters(cm); }, true); option("keyMap", "default", function (cm, val, old) { var next = getKeyMap(val); var prev = old != Init && getKeyMap(old); if (prev && prev.detach) { prev.detach(cm, next); } if (next.attach) { next.attach(cm, prev || null); } }); option("extraKeys", null); option("configureMouse", null); option("lineWrapping", false, wrappingChanged, true); option("gutters", [], function (cm, val) { cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); updateGutters(cm); }, true); option("fixedGutter", true, function (cm, val) { cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; cm.refresh(); }, true); option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); option("scrollbarStyle", "native", function (cm) { initScrollbars(cm); updateScrollbars(cm); cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); }, true); option("lineNumbers", false, function (cm, val) { cm.display.gutterSpecs = getGutters(cm.options.gutters, val); updateGutters(cm); }, true); option("firstLineNumber", 1, updateGutters, true); option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true); option("showCursorWhenSelecting", false, updateSelection, true); option("resetSelectionOnContextMenu", true); option("lineWiseCopyCut", true); option("pasteLinesPerSelection", true); option("selectionsMayTouch", false); option("readOnly", false, function (cm, val) { if (val == "nocursor") { onBlur(cm); cm.display.input.blur(); } cm.display.input.readOnlyChanged(val); }); option("screenReaderLabel", null, function (cm, val) { val = (val === '') ? null : val; cm.display.input.screenReaderLabelChanged(val); }); option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); option("dragDrop", true, dragDropChanged); option("allowDropFileTypes", null); option("cursorBlinkRate", 530); option("cursorScrollMargin", 0); option("cursorHeight", 1, updateSelection, true); option("singleCursorHeightPerLine", true, updateSelection, true); option("workTime", 100); option("workDelay", 100); option("flattenSpans", true, resetModeState, true); option("addModeClass", false, resetModeState, true); option("pollInterval", 100); option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); option("historyEventDelay", 1250); option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); option("maxHighlightLength", 10000, resetModeState, true); option("moveInputWithCursor", true, function (cm, val) { if (!val) { cm.display.input.resetPosition(); } }); option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); option("autofocus", null); option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); option("phrases", null); } function dragDropChanged(cm, value, old) { var wasOn = old && old != Init; if (!value != !wasOn) { var funcs = cm.display.dragFunctions; var toggle = value ? on : off; toggle(cm.display.scroller, "dragstart", funcs.start); toggle(cm.display.scroller, "dragenter", funcs.enter); toggle(cm.display.scroller, "dragover", funcs.over); toggle(cm.display.scroller, "dragleave", funcs.leave); toggle(cm.display.scroller, "drop", funcs.drop); } } function wrappingChanged(cm) { if (cm.options.lineWrapping) { addClass(cm.display.wrapper, "CodeMirror-wrap"); cm.display.sizer.style.minWidth = ""; cm.display.sizerWidth = null; } else { rmClass(cm.display.wrapper, "CodeMirror-wrap"); findMaxLine(cm); } estimateLineHeights(cm); regChange(cm); clearCaches(cm); setTimeout(function () { return updateScrollbars(cm); }, 100); } // A CodeMirror instance represents an editor. This is the object // that user code is usually dealing with. function CodeMirror(place, options) { var this$1 = this; if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } this.options = options = options ? copyObj(options) : {}; // Determine effective options based on given values and defaults. copyObj(defaults, options, false); var doc = options.value; if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } else if (options.mode) { doc.modeOption = options.mode; } this.doc = doc; var input = new CodeMirror.inputStyles[options.inputStyle](this); var display = this.display = new Display(place, doc, input, options); display.wrapper.CodeMirror = this; themeChanged(this); if (options.lineWrapping) { this.display.wrapper.className += " CodeMirror-wrap"; } initScrollbars(this); this.state = { keyMaps: [], // stores maps added by addKeyMap overlays: [], // highlighting overlays, as added by addOverlay modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info overwrite: false, delayingBlurEvent: false, focused: false, suppressEdits: false, // used to disable editing during key handlers when in readOnly mode pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll selectingText: false, draggingText: false, highlight: new Delayed(), // stores highlight worker timeout keySeq: null, // Unfinished key sequence specialChars: null }; if (options.autofocus && !mobile) { display.input.focus(); } // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } registerEventHandlers(this); ensureGlobalHandlers(); startOperation(this); this.curOp.forceUpdate = true; attachDoc(this, doc); if ((options.autofocus && !mobile) || this.hasFocus()) { setTimeout(function () { if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); } }, 20); } else { onBlur(this); } for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) { optionHandlers[opt](this, options[opt], Init); } } maybeUpdateLineNumberWidth(this); if (options.finishInit) { options.finishInit(this); } for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); } endOperation(this); // Suppress optimizelegibility in Webkit, since it breaks text // measuring on line wrapping boundaries. if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { display.lineDiv.style.textRendering = "auto"; } } // The default configuration options. CodeMirror.defaults = defaults; // Functions to run when options are changed. CodeMirror.optionHandlers = optionHandlers; // Attach the necessary event handlers when initializing the editor function registerEventHandlers(cm) { var d = cm.display; on(d.scroller, "mousedown", operation(cm, onMouseDown)); // Older IE's will not fire a second mousedown for a double click if (ie && ie_version < 11) { on(d.scroller, "dblclick", operation(cm, function (e) { if (signalDOMEvent(cm, e)) { return } var pos = posFromMouse(cm, e); if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } e_preventDefault(e); var word = cm.findWordAt(pos); extendSelection(cm.doc, word.anchor, word.head); })); } else { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } // Some browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for these browsers. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); on(d.input.getField(), "contextmenu", function (e) { if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); } }); // Used to suppress mouse event handling when a touch happens var touchFinished, prevTouch = {end: 0}; function finishTouch() { if (d.activeTouch) { touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); prevTouch = d.activeTouch; prevTouch.end = +new Date; } } function isMouseLikeTouchEvent(e) { if (e.touches.length != 1) { return false } var touch = e.touches[0]; return touch.radiusX <= 1 && touch.radiusY <= 1 } function farAway(touch, other) { if (other.left == null) { return true } var dx = other.left - touch.left, dy = other.top - touch.top; return dx * dx + dy * dy > 20 * 20 } on(d.scroller, "touchstart", function (e) { if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { d.input.ensurePolled(); clearTimeout(touchFinished); var now = +new Date; d.activeTouch = {start: now, moved: false, prev: now - prevTouch.end <= 300 ? prevTouch : null}; if (e.touches.length == 1) { d.activeTouch.left = e.touches[0].pageX; d.activeTouch.top = e.touches[0].pageY; } } }); on(d.scroller, "touchmove", function () { if (d.activeTouch) { d.activeTouch.moved = true; } }); on(d.scroller, "touchend", function (e) { var touch = d.activeTouch; if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && new Date - touch.start < 300) { var pos = cm.coordsChar(d.activeTouch, "page"), range; if (!touch.prev || farAway(touch, touch.prev)) // Single tap { range = new Range(pos, pos); } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap { range = cm.findWordAt(pos); } else // Triple tap { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } cm.setSelection(range.anchor, range.head); cm.focus(); e_preventDefault(e); } finishTouch(); }); on(d.scroller, "touchcancel", finishTouch); // Sync scrolling between fake scrollbars and real scrollable // area, ensure viewport is updated when scrolling. on(d.scroller, "scroll", function () { if (d.scroller.clientHeight) { updateScrollTop(cm, d.scroller.scrollTop); setScrollLeft(cm, d.scroller.scrollLeft, true); signal(cm, "scroll", cm); } }); // Listen to wheel events in order to try and update the viewport on time. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); // Prevent wrapper from ever scrolling on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); d.dragFunctions = { enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, start: function (e) { return onDragStart(cm, e); }, drop: operation(cm, onDrop), leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} }; var inp = d.input.getField(); on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); on(inp, "keydown", operation(cm, onKeyDown)); on(inp, "keypress", operation(cm, onKeyPress)); on(inp, "focus", function (e) { return onFocus(cm, e); }); on(inp, "blur", function (e) { return onBlur(cm, e); }); } var initHooks = []; CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }; // Indent the given line. The how parameter can be "smart", // "add"/null, "subtract", or "prev". When aggressive is false // (typically set to true for forced single-line indents), empty // lines are not indented, and places where the mode returns Pass // are left alone. function indentLine(cm, n, how, aggressive) { var doc = cm.doc, state; if (how == null) { how = "add"; } if (how == "smart") { // Fall back to "prev" when the mode doesn't have an indentation // method. if (!doc.mode.indent) { how = "prev"; } else { state = getContextBefore(cm, n).state; } } var tabSize = cm.options.tabSize; var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); if (line.stateAfter) { line.stateAfter = null; } var curSpaceString = line.text.match(/^\s*/)[0], indentation; if (!aggressive && !/\S/.test(line.text)) { indentation = 0; how = "not"; } else if (how == "smart") { indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); if (indentation == Pass || indentation > 150) { if (!aggressive) { return } how = "prev"; } } if (how == "prev") { if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } else { indentation = 0; } } else if (how == "add") { indentation = curSpace + cm.options.indentUnit; } else if (how == "subtract") { indentation = curSpace - cm.options.indentUnit; } else if (typeof how == "number") { indentation = curSpace + how; } indentation = Math.max(0, indentation); var indentString = "", pos = 0; if (cm.options.indentWithTabs) { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } if (pos < indentation) { indentString += spaceStr(indentation - pos); } if (indentString != curSpaceString) { replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); line.stateAfter = null; return true } else { // Ensure that, if the cursor was in the whitespace at the start // of the line, it is moved to the end of that space. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { var range = doc.sel.ranges[i$1]; if (range.head.line == n && range.head.ch < curSpaceString.length) { var pos$1 = Pos(n, curSpaceString.length); replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); break } } } } // This will be set to a {lineWise: bool, text: [string]} object, so // that, when pasting, we know what kind of selections the copied // text was made out of. var lastCopied = null; function setLastCopied(newLastCopied) { lastCopied = newLastCopied; } function applyTextInput(cm, inserted, deleted, sel, origin) { var doc = cm.doc; cm.display.shift = false; if (!sel) { sel = doc.sel; } var recent = +new Date - 200; var paste = origin == "paste" || cm.state.pasteIncoming > recent; var textLines = splitLinesAuto(inserted), multiPaste = null; // When pasting N lines into N selections, insert one line per selection if (paste && sel.ranges.length > 1) { if (lastCopied && lastCopied.text.join("\n") == inserted) { if (sel.ranges.length % lastCopied.text.length == 0) { multiPaste = []; for (var i = 0; i < lastCopied.text.length; i++) { multiPaste.push(doc.splitLines(lastCopied.text[i])); } } } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { multiPaste = map(textLines, function (l) { return [l]; }); } } var updateInput = cm.curOp.updateInput; // Normal behavior is to insert the new text into every selection for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { var range = sel.ranges[i$1]; var from = range.from(), to = range.to(); if (range.empty()) { if (deleted && deleted > 0) // Handle deletion { from = Pos(from.line, from.ch - deleted); } else if (cm.state.overwrite && !paste) // Handle overwrite { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) { from = to = Pos(from.line, 0); } } var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")}; makeChange(cm.doc, changeEvent); signalLater(cm, "inputRead", cm, changeEvent); } if (inserted && !paste) { triggerElectric(cm, inserted); } ensureCursorVisible(cm); if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; } cm.curOp.typing = true; cm.state.pasteIncoming = cm.state.cutIncoming = -1; } function handlePaste(e, cm) { var pasted = e.clipboardData && e.clipboardData.getData("Text"); if (pasted) { e.preventDefault(); if (!cm.isReadOnly() && !cm.options.disableInput) { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } return true } } function triggerElectric(cm, inserted) { // When an 'electric' character is inserted, immediately trigger a reindent if (!cm.options.electricChars || !cm.options.smartIndent) { return } var sel = cm.doc.sel; for (var i = sel.ranges.length - 1; i >= 0; i--) { var range = sel.ranges[i]; if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue } var mode = cm.getModeAt(range.head); var indented = false; if (mode.electricChars) { for (var j = 0; j < mode.electricChars.length; j++) { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { indented = indentLine(cm, range.head.line, "smart"); break } } } else if (mode.electricInput) { if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) { indented = indentLine(cm, range.head.line, "smart"); } } if (indented) { signalLater(cm, "electricInput", cm, range.head.line); } } } function copyableRanges(cm) { var text = [], ranges = []; for (var i = 0; i < cm.doc.sel.ranges.length; i++) { var line = cm.doc.sel.ranges[i].head.line; var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; ranges.push(lineRange); text.push(cm.getRange(lineRange.anchor, lineRange.head)); } return {text: text, ranges: ranges} } function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { field.setAttribute("autocorrect", autocorrect ? "" : "off"); field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); field.setAttribute("spellcheck", !!spellcheck); } function hiddenTextarea() { var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); // The textarea is kept positioned near the cursor to prevent the // fact that it'll be scrolled into view on input from scrolling // our fake cursor out of view. On webkit, when wrap=off, paste is // very slow. So make the area wide instead. if (webkit) { te.style.width = "1000px"; } else { te.setAttribute("wrap", "off"); } // If border: 0; -- iOS fails to open keyboard (issue #1287) if (ios) { te.style.border = "1px solid black"; } disableBrowserMagic(te); return div } // The publicly visible API. Note that methodOp(f) means // 'wrap f in an operation, performed on its `this` parameter'. // This is not the complete set of editor methods. Most of the // methods defined on the Doc type are also injected into // CodeMirror.prototype, for backwards compatibility and // convenience. function addEditorMethods(CodeMirror) { var optionHandlers = CodeMirror.optionHandlers; var helpers = CodeMirror.helpers = {}; CodeMirror.prototype = { constructor: CodeMirror, focus: function(){window.focus(); this.display.input.focus();}, setOption: function(option, value) { var options = this.options, old = options[option]; if (options[option] == value && option != "mode") { return } options[option] = value; if (optionHandlers.hasOwnProperty(option)) { operation(this, optionHandlers[option])(this, value, old); } signal(this, "optionChange", this, option); }, getOption: function(option) {return this.options[option]}, getDoc: function() {return this.doc}, addKeyMap: function(map, bottom) { this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); }, removeKeyMap: function(map) { var maps = this.state.keyMaps; for (var i = 0; i < maps.length; ++i) { if (maps[i] == map || maps[i].name == map) { maps.splice(i, 1); return true } } }, addOverlay: methodOp(function(spec, options) { var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); if (mode.startState) { throw new Error("Overlays may not be stateful.") } insertSorted(this.state.overlays, {mode: mode, modeSpec: spec, opaque: options && options.opaque, priority: (options && options.priority) || 0}, function (overlay) { return overlay.priority; }); this.state.modeGen++; regChange(this); }), removeOverlay: methodOp(function(spec) { var overlays = this.state.overlays; for (var i = 0; i < overlays.length; ++i) { var cur = overlays[i].modeSpec; if (cur == spec || typeof spec == "string" && cur.name == spec) { overlays.splice(i, 1); this.state.modeGen++; regChange(this); return } } }), indentLine: methodOp(function(n, dir, aggressive) { if (typeof dir != "string" && typeof dir != "number") { if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } else { dir = dir ? "add" : "subtract"; } } if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } }), indentSelection: methodOp(function(how) { var ranges = this.doc.sel.ranges, end = -1; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (!range.empty()) { var from = range.from(), to = range.to(); var start = Math.max(end, from.line); end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; for (var j = start; j < end; ++j) { indentLine(this, j, how); } var newRanges = this.doc.sel.ranges; if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } } else if (range.head.line > end) { indentLine(this, range.head.line, how, true); end = range.head.line; if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); } } } }), // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). getTokenAt: function(pos, precise) { return takeToken(this, pos, precise) }, getLineTokens: function(line, precise) { return takeToken(this, Pos(line), precise, true) }, getTokenTypeAt: function(pos) { pos = clipPos(this.doc, pos); var styles = getLineStyles(this, getLine(this.doc, pos.line)); var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; var type; if (ch == 0) { type = styles[2]; } else { for (;;) { var mid = (before + after) >> 1; if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } else { type = styles[mid * 2 + 2]; break } } } var cut = type ? type.indexOf("overlay ") : -1; return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) }, getModeAt: function(pos) { var mode = this.doc.mode; if (!mode.innerMode) { return mode } return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode }, getHelper: function(pos, type) { return this.getHelpers(pos, type)[0] }, getHelpers: function(pos, type) { var found = []; if (!helpers.hasOwnProperty(type)) { return found } var help = helpers[type], mode = this.getModeAt(pos); if (typeof mode[type] == "string") { if (help[mode[type]]) { found.push(help[mode[type]]); } } else if (mode[type]) { for (var i = 0; i < mode[type].length; i++) { var val = help[mode[type][i]]; if (val) { found.push(val); } } } else if (mode.helperType && help[mode.helperType]) { found.push(help[mode.helperType]); } else if (help[mode.name]) { found.push(help[mode.name]); } for (var i$1 = 0; i$1 < help._global.length; i$1++) { var cur = help._global[i$1]; if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) { found.push(cur.val); } } return found }, getStateAfter: function(line, precise) { var doc = this.doc; line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); return getContextBefore(this, line + 1, precise).state }, cursorCoords: function(start, mode) { var pos, range = this.doc.sel.primary(); if (start == null) { pos = range.head; } else if (typeof start == "object") { pos = clipPos(this.doc, start); } else { pos = start ? range.from() : range.to(); } return cursorCoords(this, pos, mode || "page") }, charCoords: function(pos, mode) { return charCoords(this, clipPos(this.doc, pos), mode || "page") }, coordsChar: function(coords, mode) { coords = fromCoordSystem(this, coords, mode || "page"); return coordsChar(this, coords.left, coords.top) }, lineAtHeight: function(height, mode) { height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; return lineAtHeight(this.doc, height + this.display.viewOffset) }, heightAtLine: function(line, mode, includeWidgets) { var end = false, lineObj; if (typeof line == "number") { var last = this.doc.first + this.doc.size - 1; if (line < this.doc.first) { line = this.doc.first; } else if (line > last) { line = last; end = true; } lineObj = getLine(this.doc, line); } else { lineObj = line; } return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0) }, defaultTextHeight: function() { return textHeight(this.display) }, defaultCharWidth: function() { return charWidth(this.display) }, getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, addWidget: function(pos, node, scroll, vert, horiz) { var display = this.display; pos = cursorCoords(this, clipPos(this.doc, pos)); var top = pos.bottom, left = pos.left; node.style.position = "absolute"; node.setAttribute("cm-ignore-events", "true"); this.display.input.setUneditable(node); display.sizer.appendChild(node); if (vert == "over") { top = pos.top; } else if (vert == "above" || vert == "near") { var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); // Default to positioning above (if specified and possible); otherwise default to positioning below if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { top = pos.top - node.offsetHeight; } else if (pos.bottom + node.offsetHeight <= vspace) { top = pos.bottom; } if (left + node.offsetWidth > hspace) { left = hspace - node.offsetWidth; } } node.style.top = top + "px"; node.style.left = node.style.right = ""; if (horiz == "right") { left = display.sizer.clientWidth - node.offsetWidth; node.style.right = "0px"; } else { if (horiz == "left") { left = 0; } else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } node.style.left = left + "px"; } if (scroll) { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } }, triggerOnKeyDown: methodOp(onKeyDown), triggerOnKeyPress: methodOp(onKeyPress), triggerOnKeyUp: onKeyUp, triggerOnMouseDown: methodOp(onMouseDown), execCommand: function(cmd) { if (commands.hasOwnProperty(cmd)) { return commands[cmd].call(null, this) } }, triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), findPosH: function(from, amount, unit, visually) { var dir = 1; if (amount < 0) { dir = -1; amount = -amount; } var cur = clipPos(this.doc, from); for (var i = 0; i < amount; ++i) { cur = findPosH(this.doc, cur, dir, unit, visually); if (cur.hitSide) { break } } return cur }, moveH: methodOp(function(dir, unit) { var this$1 = this; this.extendSelectionsBy(function (range) { if (this$1.display.shift || this$1.doc.extend || range.empty()) { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) } else { return dir < 0 ? range.from() : range.to() } }, sel_move); }), deleteH: methodOp(function(dir, unit) { var sel = this.doc.sel, doc = this.doc; if (sel.somethingSelected()) { doc.replaceSelection("", null, "+delete"); } else { deleteNearSelection(this, function (range) { var other = findPosH(doc, range.head, dir, unit, false); return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other} }); } }), findPosV: function(from, amount, unit, goalColumn) { var dir = 1, x = goalColumn; if (amount < 0) { dir = -1; amount = -amount; } var cur = clipPos(this.doc, from); for (var i = 0; i < amount; ++i) { var coords = cursorCoords(this, cur, "div"); if (x == null) { x = coords.left; } else { coords.left = x; } cur = findPosV(this, coords, dir, unit); if (cur.hitSide) { break } } return cur }, moveV: methodOp(function(dir, unit) { var this$1 = this; var doc = this.doc, goals = []; var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); doc.extendSelectionsBy(function (range) { if (collapse) { return dir < 0 ? range.from() : range.to() } var headPos = cursorCoords(this$1, range.head, "div"); if (range.goalColumn != null) { headPos.left = range.goalColumn; } goals.push(headPos.left); var pos = findPosV(this$1, headPos, dir, unit); if (unit == "page" && range == doc.sel.primary()) { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } return pos }, sel_move); if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) { doc.sel.ranges[i].goalColumn = goals[i]; } } }), // Find the word at the given position (as returned by coordsChar). findWordAt: function(pos) { var doc = this.doc, line = getLine(doc, pos.line).text; var start = pos.ch, end = pos.ch; if (line) { var helper = this.getHelper(pos, "wordChars"); if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } var startChar = line.charAt(start); var check = isWordChar(startChar, helper) ? function (ch) { return isWordChar(ch, helper); } : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; while (start > 0 && check(line.charAt(start - 1))) { --start; } while (end < line.length && check(line.charAt(end))) { ++end; } } return new Range(Pos(pos.line, start), Pos(pos.line, end)) }, toggleOverwrite: function(value) { if (value != null && value == this.state.overwrite) { return } if (this.state.overwrite = !this.state.overwrite) { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } else { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } signal(this, "overwriteToggle", this, this.state.overwrite); }, hasFocus: function() { return this.display.input.getField() == activeElt() }, isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), getScrollInfo: function() { var scroller = this.display.scroller; return {left: scroller.scrollLeft, top: scroller.scrollTop, height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, clientHeight: displayHeight(this), clientWidth: displayWidth(this)} }, scrollIntoView: methodOp(function(range, margin) { if (range == null) { range = {from: this.doc.sel.primary().head, to: null}; if (margin == null) { margin = this.options.cursorScrollMargin; } } else if (typeof range == "number") { range = {from: Pos(range, 0), to: null}; } else if (range.from == null) { range = {from: range, to: null}; } if (!range.to) { range.to = range.from; } range.margin = margin || 0; if (range.from.line != null) { scrollToRange(this, range); } else { scrollToCoordsRange(this, range.from, range.to, range.margin); } }), setSize: methodOp(function(width, height) { var this$1 = this; var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; if (width != null) { this.display.wrapper.style.width = interpret(width); } if (height != null) { this.display.wrapper.style.height = interpret(height); } if (this.options.lineWrapping) { clearLineMeasurementCache(this); } var lineNo = this.display.viewFrom; this.doc.iter(lineNo, this.display.viewTo, function (line) { if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } } ++lineNo; }); this.curOp.forceUpdate = true; signal(this, "refresh", this); }), operation: function(f){return runInOp(this, f)}, startOperation: function(){return startOperation(this)}, endOperation: function(){return endOperation(this)}, refresh: methodOp(function() { var oldHeight = this.display.cachedTextHeight; regChange(this); this.curOp.forceUpdate = true; clearCaches(this); scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); updateGutterSpace(this.display); if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping) { estimateLineHeights(this); } signal(this, "refresh", this); }), swapDoc: methodOp(function(doc) { var old = this.doc; old.cm = null; // Cancel the current text selection if any (#5821) if (this.state.selectingText) { this.state.selectingText(); } attachDoc(this, doc); clearCaches(this); this.display.input.reset(); scrollToCoords(this, doc.scrollLeft, doc.scrollTop); this.curOp.forceScroll = true; signalLater(this, "swapDoc", this, old); return old }), phrase: function(phraseText) { var phrases = this.options.phrases; return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText }, getInputField: function(){return this.display.input.getField()}, getWrapperElement: function(){return this.display.wrapper}, getScrollerElement: function(){return this.display.scroller}, getGutterElement: function(){return this.display.gutters} }; eventMixin(CodeMirror); CodeMirror.registerHelper = function(type, name, value) { if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } helpers[type][name] = value; }; CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { CodeMirror.registerHelper(type, name, value); helpers[type]._global.push({pred: predicate, val: value}); }; } // Used for horizontal relative motion. Dir is -1 or 1 (left or // right), unit can be "codepoint", "char", "column" (like char, but // doesn't cross line boundaries), "word" (across next word), or // "group" (to the start of next group of word or // non-word-non-whitespace chars). The visually param controls // whether, in right-to-left text, direction 1 means to move towards // the next index in the string, or towards the character to the right // of the current position. The resulting position will have a // hitSide=true property if it reached the end of the document. function findPosH(doc, pos, dir, unit, visually) { var oldPos = pos; var origDir = dir; var lineObj = getLine(doc, pos.line); var lineDir = visually && doc.direction == "rtl" ? -dir : dir; function findNextLine() { var l = pos.line + lineDir; if (l < doc.first || l >= doc.first + doc.size) { return false } pos = new Pos(l, pos.ch, pos.sticky); return lineObj = getLine(doc, l) } function moveOnce(boundToLine) { var next; if (unit == "codepoint") { var ch = lineObj.text.charCodeAt(pos.ch + (unit > 0 ? 0 : -1)); if (isNaN(ch)) { next = null; } else { next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (ch >= 0xD800 && ch < 0xDC00 ? 2 : 1))), -dir); } } else if (visually) { next = moveVisually(doc.cm, lineObj, pos, dir); } else { next = moveLogically(lineObj, pos, dir); } if (next == null) { if (!boundToLine && findNextLine()) { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); } else { return false } } else { pos = next; } return true } if (unit == "char" || unit == "codepoint") { moveOnce(); } else if (unit == "column") { moveOnce(true); } else if (unit == "word" || unit == "group") { var sawType = null, group = unit == "group"; var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); for (var first = true;; first = false) { if (dir < 0 && !moveOnce(!first)) { break } var cur = lineObj.text.charAt(pos.ch) || "\n"; var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; if (group && !first && !type) { type = "s"; } if (sawType && sawType != type) { if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} break } if (type) { sawType = type; } if (dir > 0 && !moveOnce(!first)) { break } } } var result = skipAtomic(doc, pos, oldPos, origDir, true); if (equalCursorPos(oldPos, result)) { result.hitSide = true; } return result } // For relative vertical movement. Dir may be -1 or 1. Unit can be // "page" or "line". The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosV(cm, pos, dir, unit) { var doc = cm.doc, x = pos.left, y; if (unit == "page") { var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; } else if (unit == "line") { y = dir > 0 ? pos.bottom + 3 : pos.top - 3; } var target; for (;;) { target = coordsChar(cm, x, y); if (!target.outside) { break } if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } y += dir * 5; } return target } // CONTENTEDITABLE INPUT STYLE var ContentEditableInput = function(cm) { this.cm = cm; this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; this.polling = new Delayed(); this.composing = null; this.gracePeriod = false; this.readDOMTimeout = null; }; ContentEditableInput.prototype.init = function (display) { var this$1 = this; var input = this, cm = input.cm; var div = input.div = display.lineDiv; disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); function belongsToInput(e) { for (var t = e.target; t; t = t.parentNode) { if (t == div) { return true } if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break } } return false } on(div, "paste", function (e) { if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } // IE doesn't fire input events, so we schedule a read for the pasted content in this way if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } }); on(div, "compositionstart", function (e) { this$1.composing = {data: e.data, done: false}; }); on(div, "compositionupdate", function (e) { if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } }); on(div, "compositionend", function (e) { if (this$1.composing) { if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } this$1.composing.done = true; } }); on(div, "touchstart", function () { return input.forceCompositionEnd(); }); on(div, "input", function () { if (!this$1.composing) { this$1.readFromDOMSoon(); } }); function onCopyCut(e) { if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return } if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}); if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } } else if (!cm.options.lineWiseCopyCut) { return } else { var ranges = copyableRanges(cm); setLastCopied({lineWise: true, text: ranges.text}); if (e.type == "cut") { cm.operation(function () { cm.setSelections(ranges.ranges, 0, sel_dontScroll); cm.replaceSelection("", null, "cut"); }); } } if (e.clipboardData) { e.clipboardData.clearData(); var content = lastCopied.text.join("\n"); // iOS exposes the clipboard API, but seems to discard content inserted into it e.clipboardData.setData("Text", content); if (e.clipboardData.getData("Text") == content) { e.preventDefault(); return } } // Old-fashioned briefly-focus-a-textarea hack var kludge = hiddenTextarea(), te = kludge.firstChild; cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); te.value = lastCopied.text.join("\n"); var hadFocus = document.activeElement; selectInput(te); setTimeout(function () { cm.display.lineSpace.removeChild(kludge); hadFocus.focus(); if (hadFocus == div) { input.showPrimarySelection(); } }, 50); } on(div, "copy", onCopyCut); on(div, "cut", onCopyCut); }; ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { // Label for screenreaders, accessibility if(label) { this.div.setAttribute('aria-label', label); } else { this.div.removeAttribute('aria-label'); } }; ContentEditableInput.prototype.prepareSelection = function () { var result = prepareSelection(this.cm, false); result.focus = document.activeElement == this.div; return result }; ContentEditableInput.prototype.showSelection = function (info, takeFocus) { if (!info || !this.cm.display.view.length) { return } if (info.focus || takeFocus) { this.showPrimarySelection(); } this.showMultipleSelections(info); }; ContentEditableInput.prototype.getSelection = function () { return this.cm.display.wrapper.ownerDocument.getSelection() }; ContentEditableInput.prototype.showPrimarySelection = function () { var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); var from = prim.from(), to = prim.to(); if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { sel.removeAllRanges(); return } var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { return } var view = cm.display.view; var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || {node: view[0].measure.map[2], offset: 0}; var end = to.line < cm.display.viewTo && posToDOM(cm, to); if (!end) { var measure = view[view.length - 1].measure; var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; } if (!start || !end) { sel.removeAllRanges(); return } var old = sel.rangeCount && sel.getRangeAt(0), rng; try { rng = range(start.node, start.offset, end.offset, end.node); } catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible if (rng) { if (!gecko && cm.state.focused) { sel.collapse(start.node, start.offset); if (!rng.collapsed) { sel.removeAllRanges(); sel.addRange(rng); } } else { sel.removeAllRanges(); sel.addRange(rng); } if (old && sel.anchorNode == null) { sel.addRange(old); } else if (gecko) { this.startGracePeriod(); } } this.rememberSelection(); }; ContentEditableInput.prototype.startGracePeriod = function () { var this$1 = this; clearTimeout(this.gracePeriod); this.gracePeriod = setTimeout(function () { this$1.gracePeriod = false; if (this$1.selectionChanged()) { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } }, 20); }; ContentEditableInput.prototype.showMultipleSelections = function (info) { removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); }; ContentEditableInput.prototype.rememberSelection = function () { var sel = this.getSelection(); this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; }; ContentEditableInput.prototype.selectionInEditor = function () { var sel = this.getSelection(); if (!sel.rangeCount) { return false } var node = sel.getRangeAt(0).commonAncestorContainer; return contains(this.div, node) }; ContentEditableInput.prototype.focus = function () { if (this.cm.options.readOnly != "nocursor") { if (!this.selectionInEditor() || document.activeElement != this.div) { this.showSelection(this.prepareSelection(), true); } this.div.focus(); } }; ContentEditableInput.prototype.blur = function () { this.div.blur(); }; ContentEditableInput.prototype.getField = function () { return this.div }; ContentEditableInput.prototype.supportsTouch = function () { return true }; ContentEditableInput.prototype.receivedFocus = function () { var input = this; if (this.selectionInEditor()) { this.pollSelection(); } else { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } function poll() { if (input.cm.state.focused) { input.pollSelection(); input.polling.set(input.cm.options.pollInterval, poll); } } this.polling.set(this.cm.options.pollInterval, poll); }; ContentEditableInput.prototype.selectionChanged = function () { var sel = this.getSelection(); return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset }; ContentEditableInput.prototype.pollSelection = function () { if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } var sel = this.getSelection(), cm = this.cm; // On Android Chrome (version 56, at least), backspacing into an // uneditable block element will put the cursor in that element, // and then, because it's not editable, hide the virtual keyboard. // Because Android doesn't allow us to actually detect backspace // presses in a sane way, this code checks for when that happens // and simulates a backspace press in this case. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); this.blur(); this.focus(); return } if (this.composing) { return } this.rememberSelection(); var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); var head = domToPos(cm, sel.focusNode, sel.focusOffset); if (anchor && head) { runInOp(cm, function () { setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } }); } }; ContentEditableInput.prototype.pollContent = function () { if (this.readDOMTimeout != null) { clearTimeout(this.readDOMTimeout); this.readDOMTimeout = null; } var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); var from = sel.from(), to = sel.to(); if (from.ch == 0 && from.line > cm.firstLine()) { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { to = Pos(to.line + 1, 0); } if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } var fromIndex, fromLine, fromNode; if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { fromLine = lineNo(display.view[0].line); fromNode = display.view[0].node; } else { fromLine = lineNo(display.view[fromIndex].line); fromNode = display.view[fromIndex - 1].node.nextSibling; } var toIndex = findViewIndex(cm, to.line); var toLine, toNode; if (toIndex == display.view.length - 1) { toLine = display.viewTo - 1; toNode = display.lineDiv.lastChild; } else { toLine = lineNo(display.view[toIndex + 1].line) - 1; toNode = display.view[toIndex + 1].node.previousSibling; } if (!fromNode) { return false } var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); while (newText.length > 1 && oldText.length > 1) { if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } else { break } } var cutFront = 0, cutEnd = 0; var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { ++cutFront; } var newBot = lst(newText), oldBot = lst(oldText); var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)); while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { ++cutEnd; } // Try to move start of change to start of selection if ambiguous if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { cutFront--; cutEnd++; } } newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); var chFrom = Pos(fromLine, cutFront); var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { replaceRange(cm.doc, newText, chFrom, chTo, "+input"); return true } }; ContentEditableInput.prototype.ensurePolled = function () { this.forceCompositionEnd(); }; ContentEditableInput.prototype.reset = function () { this.forceCompositionEnd(); }; ContentEditableInput.prototype.forceCompositionEnd = function () { if (!this.composing) { return } clearTimeout(this.readDOMTimeout); this.composing = null; this.updateFromDOM(); this.div.blur(); this.div.focus(); }; ContentEditableInput.prototype.readFromDOMSoon = function () { var this$1 = this; if (this.readDOMTimeout != null) { return } this.readDOMTimeout = setTimeout(function () { this$1.readDOMTimeout = null; if (this$1.composing) { if (this$1.composing.done) { this$1.composing = null; } else { return } } this$1.updateFromDOM(); }, 80); }; ContentEditableInput.prototype.updateFromDOM = function () { var this$1 = this; if (this.cm.isReadOnly() || !this.pollContent()) { runInOp(this.cm, function () { return regChange(this$1.cm); }); } }; ContentEditableInput.prototype.setUneditable = function (node) { node.contentEditable = "false"; }; ContentEditableInput.prototype.onKeyPress = function (e) { if (e.charCode == 0 || this.composing) { return } e.preventDefault(); if (!this.cm.isReadOnly()) { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } }; ContentEditableInput.prototype.readOnlyChanged = function (val) { this.div.contentEditable = String(val != "nocursor"); }; ContentEditableInput.prototype.onContextMenu = function () {}; ContentEditableInput.prototype.resetPosition = function () {}; ContentEditableInput.prototype.needsContentAttribute = true; function posToDOM(cm, pos) { var view = findViewForLine(cm, pos.line); if (!view || view.hidden) { return null } var line = getLine(cm.doc, pos.line); var info = mapFromLineView(view, line, pos.line); var order = getOrder(line, cm.doc.direction), side = "left"; if (order) { var partPos = getBidiPartAt(order, pos.ch); side = partPos % 2 ? "right" : "left"; } var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); result.offset = result.collapse == "right" ? result.end : result.start; return result } function isInGutter(node) { for (var scan = node; scan; scan = scan.parentNode) { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } return false } function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } function domTextBetween(cm, from, to, fromLine, toLine) { var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false; function recognizeMarker(id) { return function (marker) { return marker.id == id; } } function close() { if (closing) { text += lineSep; if (extraLinebreak) { text += lineSep; } closing = extraLinebreak = false; } } function addText(str) { if (str) { close(); text += str; } } function walk(node) { if (node.nodeType == 1) { var cmText = node.getAttribute("cm-text"); if (cmText) { addText(cmText); return } var markerID = node.getAttribute("cm-marker"), range; if (markerID) { var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); if (found.length && (range = found[0].find(0))) { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); } return } if (node.getAttribute("contenteditable") == "false") { return } var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return } if (isBlock) { close(); } for (var i = 0; i < node.childNodes.length; i++) { walk(node.childNodes[i]); } if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; } if (isBlock) { closing = true; } } else if (node.nodeType == 3) { addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); } } for (;;) { walk(from); if (from == to) { break } from = from.nextSibling; extraLinebreak = false; } return text } function domToPos(cm, node, offset) { var lineNode; if (node == cm.display.lineDiv) { lineNode = cm.display.lineDiv.childNodes[offset]; if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } node = null; offset = 0; } else { for (lineNode = node;; lineNode = lineNode.parentNode) { if (!lineNode || lineNode == cm.display.lineDiv) { return null } if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } } } for (var i = 0; i < cm.display.view.length; i++) { var lineView = cm.display.view[i]; if (lineView.node == lineNode) { return locateNodeInLineView(lineView, node, offset) } } } function locateNodeInLineView(lineView, node, offset) { var wrapper = lineView.text.firstChild, bad = false; if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } if (node == wrapper) { bad = true; node = wrapper.childNodes[offset]; offset = 0; if (!node) { var line = lineView.rest ? lst(lineView.rest) : lineView.line; return badPos(Pos(lineNo(line), line.text.length), bad) } } var textNode = node.nodeType == 3 ? node : null, topNode = node; if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { textNode = node.firstChild; if (offset) { offset = textNode.nodeValue.length; } } while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } var measure = lineView.measure, maps = measure.maps; function find(textNode, topNode, offset) { for (var i = -1; i < (maps ? maps.length : 0); i++) { var map = i < 0 ? measure.map : maps[i]; for (var j = 0; j < map.length; j += 3) { var curNode = map[j + 2]; if (curNode == textNode || curNode == topNode) { var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); var ch = map[j] + offset; if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; } return Pos(line, ch) } } } } var found = find(textNode, topNode, offset); if (found) { return badPos(found, bad) } // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { found = find(after, after.firstChild, 0); if (found) { return badPos(Pos(found.line, found.ch - dist), bad) } else { dist += after.textContent.length; } } for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { found = find(before, before.firstChild, -1); if (found) { return badPos(Pos(found.line, found.ch + dist$1), bad) } else { dist$1 += before.textContent.length; } } } // TEXTAREA INPUT STYLE var TextareaInput = function(cm) { this.cm = cm; // See input.poll and input.reset this.prevInput = ""; // Flag that indicates whether we expect input to appear real soon // now (after some event like 'keypress' or 'input') and are // polling intensively. this.pollingFast = false; // Self-resetting timeout for the poller this.polling = new Delayed(); // Used to work around IE issue with selection being forgotten when focus moves away from textarea this.hasSelection = false; this.composing = null; }; TextareaInput.prototype.init = function (display) { var this$1 = this; var input = this, cm = this.cm; this.createField(display); var te = this.textarea; display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) if (ios) { te.style.width = "0px"; } on(te, "input", function () { if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } input.poll(); }); on(te, "paste", function (e) { if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } cm.state.pasteIncoming = +new Date; input.fastPoll(); }); function prepareCopyCut(e) { if (signalDOMEvent(cm, e)) { return } if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}); } else if (!cm.options.lineWiseCopyCut) { return } else { var ranges = copyableRanges(cm); setLastCopied({lineWise: true, text: ranges.text}); if (e.type == "cut") { cm.setSelections(ranges.ranges, null, sel_dontScroll); } else { input.prevInput = ""; te.value = ranges.text.join("\n"); selectInput(te); } } if (e.type == "cut") { cm.state.cutIncoming = +new Date; } } on(te, "cut", prepareCopyCut); on(te, "copy", prepareCopyCut); on(display.scroller, "paste", function (e) { if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } if (!te.dispatchEvent) { cm.state.pasteIncoming = +new Date; input.focus(); return } // Pass the `paste` event to the textarea so it's handled by its event listener. var event = new Event("paste"); event.clipboardData = e.clipboardData; te.dispatchEvent(event); }); // Prevent normal selection in the editor (we handle our own) on(display.lineSpace, "selectstart", function (e) { if (!eventInWidget(display, e)) { e_preventDefault(e); } }); on(te, "compositionstart", function () { var start = cm.getCursor("from"); if (input.composing) { input.composing.range.clear(); } input.composing = { start: start, range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) }; }); on(te, "compositionend", function () { if (input.composing) { input.poll(); input.composing.range.clear(); input.composing = null; } }); }; TextareaInput.prototype.createField = function (_display) { // Wraps and hides input textarea this.wrapper = hiddenTextarea(); // The semihidden textarea that is focused when the editor is // focused, and receives input. this.textarea = this.wrapper.firstChild; }; TextareaInput.prototype.screenReaderLabelChanged = function (label) { // Label for screenreaders, accessibility if(label) { this.textarea.setAttribute('aria-label', label); } else { this.textarea.removeAttribute('aria-label'); } }; TextareaInput.prototype.prepareSelection = function () { // Redraw the selection and/or cursor var cm = this.cm, display = cm.display, doc = cm.doc; var result = prepareSelection(cm); // Move the hidden textarea near the cursor to prevent scrolling artifacts if (cm.options.moveInputWithCursor) { var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); } return result }; TextareaInput.prototype.showSelection = function (drawn) { var cm = this.cm, display = cm.display; removeChildrenAndAdd(display.cursorDiv, drawn.cursors); removeChildrenAndAdd(display.selectionDiv, drawn.selection); if (drawn.teTop != null) { this.wrapper.style.top = drawn.teTop + "px"; this.wrapper.style.left = drawn.teLeft + "px"; } }; // Reset the input to correspond to the selection (or to be empty, // when not typing and nothing is selected) TextareaInput.prototype.reset = function (typing) { if (this.contextMenuPending || this.composing) { return } var cm = this.cm; if (cm.somethingSelected()) { this.prevInput = ""; var content = cm.getSelection(); this.textarea.value = content; if (cm.state.focused) { selectInput(this.textarea); } if (ie && ie_version >= 9) { this.hasSelection = content; } } else if (!typing) { this.prevInput = this.textarea.value = ""; if (ie && ie_version >= 9) { this.hasSelection = null; } } }; TextareaInput.prototype.getField = function () { return this.textarea }; TextareaInput.prototype.supportsTouch = function () { return false }; TextareaInput.prototype.focus = function () { if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { try { this.textarea.focus(); } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM } }; TextareaInput.prototype.blur = function () { this.textarea.blur(); }; TextareaInput.prototype.resetPosition = function () { this.wrapper.style.top = this.wrapper.style.left = 0; }; TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; // Poll for input changes, using the normal rate of polling. This // runs as long as the editor is focused. TextareaInput.prototype.slowPoll = function () { var this$1 = this; if (this.pollingFast) { return } this.polling.set(this.cm.options.pollInterval, function () { this$1.poll(); if (this$1.cm.state.focused) { this$1.slowPoll(); } }); }; // When an event has just come in that is likely to add or change // something in the input textarea, we poll faster, to ensure that // the change appears on the screen quickly. TextareaInput.prototype.fastPoll = function () { var missed = false, input = this; input.pollingFast = true; function p() { var changed = input.poll(); if (!changed && !missed) {missed = true; input.polling.set(60, p);} else {input.pollingFast = false; input.slowPoll();} } input.polling.set(20, p); }; // Read input from the textarea, and update the document to match. // When something is selected, it is present in the textarea, and // selected (unless it is huge, in which case a placeholder is // used). When nothing is selected, the cursor sits after previously // seen text (can be empty), which is stored in prevInput (we must // not reset the textarea when typing, because that breaks IME). TextareaInput.prototype.poll = function () { var this$1 = this; var cm = this.cm, input = this.textarea, prevInput = this.prevInput; // Since this is called a *lot*, try to bail out as cheaply as // possible when it is clear that nothing happened. hasSelection // will be the case when there is a lot of text in the textarea, // in which case reading its value would be expensive. if (this.contextMenuPending || !cm.state.focused || (hasSelection(input) && !prevInput && !this.composing) || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { return false } var text = input.value; // If nothing changed, bail. if (text == prevInput && !cm.somethingSelected()) { return false } // Work around nonsensical selection resetting in IE9/10, and // inexplicable appearance of private area unicode characters on // some key combos in Mac (#2689). if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { cm.display.input.reset(); return false } if (cm.doc.sel == cm.display.selForContextMenu) { var first = text.charCodeAt(0); if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } } // Find the part of the input that is actually new var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } runInOp(cm, function () { applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1.composing ? "*compose" : null); // Don't leave long text in the textarea, since it makes further polling slow if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } else { this$1.prevInput = text; } if (this$1.composing) { this$1.composing.range.clear(); this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), {className: "CodeMirror-composing"}); } }); return true }; TextareaInput.prototype.ensurePolled = function () { if (this.pollingFast && this.poll()) { this.pollingFast = false; } }; TextareaInput.prototype.onKeyPress = function () { if (ie && ie_version >= 9) { this.hasSelection = null; } this.fastPoll(); }; TextareaInput.prototype.onContextMenu = function (e) { var input = this, cm = input.cm, display = cm.display, te = input.textarea; if (input.contextMenuPending) { input.contextMenuPending(); } var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; if (!pos || presto) { return } // Opera is difficult. // Reset the current text selection only if the click is done outside of the selection // and 'resetSelectionOnContextMenu' option is true. var reset = cm.options.resetSelectionOnContextMenu; if (reset && cm.doc.sel.contains(pos) == -1) { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); input.wrapper.style.cssText = "position: static"; te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; var oldScrollY; if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) display.input.focus(); if (webkit) { window.scrollTo(null, oldScrollY); } display.input.reset(); // Adds "Select all" to context menu in FF if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } input.contextMenuPending = rehide; display.selForContextMenu = cm.doc.sel; clearTimeout(display.detectingSelectAll); // Select-all will be greyed out if there's nothing to select, so // this adds a zero-width space so that we can later check whether // it got selected. function prepareSelectAllHack() { if (te.selectionStart != null) { var selected = cm.somethingSelected(); var extval = "\u200b" + (selected ? te.value : ""); te.value = "\u21da"; // Used to catch context-menu undo te.value = extval; input.prevInput = selected ? "" : "\u200b"; te.selectionStart = 1; te.selectionEnd = extval.length; // Re-set this, in case some other handler touched the // selection in the meantime. display.selForContextMenu = cm.doc.sel; } } function rehide() { if (input.contextMenuPending != rehide) { return } input.contextMenuPending = false; input.wrapper.style.cssText = oldWrapperCSS; te.style.cssText = oldCSS; if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } // Try to detect the user choosing select-all if (te.selectionStart != null) { if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } var i = 0, poll = function () { if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "\u200b") { operation(cm, selectAll)(cm); } else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500); } else { display.selForContextMenu = null; display.input.reset(); } }; display.detectingSelectAll = setTimeout(poll, 200); } } if (ie && ie_version >= 9) { prepareSelectAllHack(); } if (captureRightClick) { e_stop(e); var mouseup = function () { off(window, "mouseup", mouseup); setTimeout(rehide, 20); }; on(window, "mouseup", mouseup); } else { setTimeout(rehide, 50); } }; TextareaInput.prototype.readOnlyChanged = function (val) { if (!val) { this.reset(); } this.textarea.disabled = val == "nocursor"; this.textarea.readOnly = !!val; }; TextareaInput.prototype.setUneditable = function () {}; TextareaInput.prototype.needsContentAttribute = false; function fromTextArea(textarea, options) { options = options ? copyObj(options) : {}; options.value = textarea.value; if (!options.tabindex && textarea.tabIndex) { options.tabindex = textarea.tabIndex; } if (!options.placeholder && textarea.placeholder) { options.placeholder = textarea.placeholder; } // Set autofocus to true if this textarea is focused, or if it has // autofocus and no other element is focused. if (options.autofocus == null) { var hasFocus = activeElt(); options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; } function save() {textarea.value = cm.getValue();} var realSubmit; if (textarea.form) { on(textarea.form, "submit", save); // Deplorable hack to make the submit method do the right thing. if (!options.leaveSubmitMethodAlone) { var form = textarea.form; realSubmit = form.submit; try { var wrappedSubmit = form.submit = function () { save(); form.submit = realSubmit; form.submit(); form.submit = wrappedSubmit; }; } catch(e) {} } } options.finishInit = function (cm) { cm.save = save; cm.getTextArea = function () { return textarea; }; cm.toTextArea = function () { cm.toTextArea = isNaN; // Prevent this from being ran twice save(); textarea.parentNode.removeChild(cm.getWrapperElement()); textarea.style.display = ""; if (textarea.form) { off(textarea.form, "submit", save); if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") { textarea.form.submit = realSubmit; } } }; }; textarea.style.display = "none"; var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); return cm } function addLegacyProps(CodeMirror) { CodeMirror.off = off; CodeMirror.on = on; CodeMirror.wheelEventPixels = wheelEventPixels; CodeMirror.Doc = Doc; CodeMirror.splitLines = splitLinesAuto; CodeMirror.countColumn = countColumn; CodeMirror.findColumn = findColumn; CodeMirror.isWordChar = isWordCharBasic; CodeMirror.Pass = Pass; CodeMirror.signal = signal; CodeMirror.Line = Line; CodeMirror.changeEnd = changeEnd; CodeMirror.scrollbarModel = scrollbarModel; CodeMirror.Pos = Pos; CodeMirror.cmpPos = cmp; CodeMirror.modes = modes; CodeMirror.mimeModes = mimeModes; CodeMirror.resolveMode = resolveMode; CodeMirror.getMode = getMode; CodeMirror.modeExtensions = modeExtensions; CodeMirror.extendMode = extendMode; CodeMirror.copyState = copyState; CodeMirror.startState = startState; CodeMirror.innerMode = innerMode; CodeMirror.commands = commands; CodeMirror.keyMap = keyMap; CodeMirror.keyName = keyName; CodeMirror.isModifierKey = isModifierKey; CodeMirror.lookupKey = lookupKey; CodeMirror.normalizeKeyMap = normalizeKeyMap; CodeMirror.StringStream = StringStream; CodeMirror.SharedTextMarker = SharedTextMarker; CodeMirror.TextMarker = TextMarker; CodeMirror.LineWidget = LineWidget; CodeMirror.e_preventDefault = e_preventDefault; CodeMirror.e_stopPropagation = e_stopPropagation; CodeMirror.e_stop = e_stop; CodeMirror.addClass = addClass; CodeMirror.contains = contains; CodeMirror.rmClass = rmClass; CodeMirror.keyNames = keyNames; } // EDITOR CONSTRUCTOR defineOptions(CodeMirror); addEditorMethods(CodeMirror); // Set up methods on CodeMirror's prototype to redirect to the editor's document. var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { CodeMirror.prototype[prop] = (function(method) { return function() {return method.apply(this.doc, arguments)} })(Doc.prototype[prop]); } } eventMixin(Doc); CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) CodeMirror.defineMode = function(name/*, mode, …*/) { if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; } defineMode.apply(this, arguments); }; CodeMirror.defineMIME = defineMIME; // Minimal default mode. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); CodeMirror.defineMIME("text/plain", "null"); // EXTENSIONS CodeMirror.defineExtension = function (name, func) { CodeMirror.prototype[name] = func; }; CodeMirror.defineDocExtension = function (name, func) { Doc.prototype[name] = func; }; CodeMirror.fromTextArea = fromTextArea; addLegacyProps(CodeMirror); CodeMirror.version = "5.58.1"; return CodeMirror; }))); },{}],112:[function(require,module,exports){ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; var jsonldMode = parserConfig.jsonld; var jsonMode = parserConfig.json || jsonldMode; var isTS = parserConfig.typescript; var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; // Tokenizer var keywords = function(){ function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}; return { "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, "this": kw("this"), "class": kw("class"), "super": kw("atom"), "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, "await": C }; }(); var isOperatorChar = /[+\-*&%=<>!?|~^@]/; var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; function readRegexp(stream) { var escaped = false, next, inSet = false; while ((next = stream.next()) != null) { if (!escaped) { if (next == "/" && !inSet) return; if (next == "[") inSet = true; else if (inSet && next == "]") inSet = false; } escaped = !escaped && next == "\\"; } } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { return ret("number", "number"); } else if (ch == "." && stream.match("..")) { return ret("spread", "meta"); } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "=" && stream.eat(">")) { return ret("=>", "operator"); } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (expressionAllowed(stream, state, 1)) { readRegexp(stream); stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); return ret("regexp", "string-2"); } else { stream.eat("="); return ret("operator", "operator", stream.current()); } } else if (ch == "`") { state.tokenize = tokenQuasi; return tokenQuasi(stream, state); } else if (ch == "#" && stream.peek() == "!") { stream.skipToEnd(); return ret("meta", "meta"); } else if (ch == "#" && stream.eatWhile(wordRE)) { return ret("variable", "property") } else if (ch == "<" && stream.match("!--") || (ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start)))) { stream.skipToEnd() return ret("comment", "comment") } else if (isOperatorChar.test(ch)) { if (ch != ">" || !state.lexical || state.lexical.type != ">") { if (stream.eat("=")) { if (ch == "!" || ch == "=") stream.eat("=") } else if (/[<>*+\-|&?]/.test(ch)) { stream.eat(ch) if (ch == ">") stream.eat(ch) } } if (ch == "?" && stream.eat(".")) return ret(".") return ret("operator", "operator", stream.current()); } else if (wordRE.test(ch)) { stream.eatWhile(wordRE); var word = stream.current() if (state.lastType != ".") { if (keywords.propertyIsEnumerable(word)) { var kw = keywords[word] return ret(kw.type, kw.style, word) } if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word) } return ret("variable", "variable", word) } } function tokenString(quote) { return function(stream, state) { var escaped = false, next; if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ state.tokenize = tokenBase; return ret("jsonld-keyword", "meta"); } while ((next = stream.next()) != null) { if (next == quote && !escaped) break; escaped = !escaped && next == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenQuasi(stream, state) { var escaped = false, next; while ((next = stream.next()) != null) { if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { state.tokenize = tokenBase; break; } escaped = !escaped && next == "\\"; } return ret("quasi", "string-2", stream.current()); } var brackets = "([{}])"; // This is a crude lookahead trick to try and notice that we're // parsing the argument patterns for a fat-arrow function before we // actually hit the arrow token. It only works if the arrow is on // the same line as the arguments and there's no strange noise // (comments) in between. Fallback is to only notice when we hit the // arrow, and not declare the arguments as locals for the arrow // body. function findFatArrow(stream, state) { if (state.fatArrowAt) state.fatArrowAt = null; var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; if (isTS) { // Try to skip TypeScript return type declarations after the arguments var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) if (m) arrow = m.index } var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); var bracket = brackets.indexOf(ch); if (bracket >= 0 && bracket < 3) { if (!depth) { ++pos; break; } if (--depth == 0) { if (ch == "(") sawSomething = true; break; } } else if (bracket >= 3 && bracket < 6) { ++depth; } else if (wordRE.test(ch)) { sawSomething = true; } else if (/["'\/`]/.test(ch)) { for (;; --pos) { if (pos == 0) return var next = stream.string.charAt(pos - 1) if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break } } } else if (sawSomething && !depth) { ++pos; break; } } if (sawSomething && !depth) state.fatArrowAt = pos; } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; for (var cx = state.context; cx; cx = cx.prev) { for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true; } } function parseJS(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; return style; } } } // Combinator utils var cx = {state: null, column: null, marked: null, cc: null}; function pass() { for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function inList(name, list) { for (var v = list; v; v = v.next) if (v.name == name) return true return false; } function register(varname) { var state = cx.state; cx.marked = "def"; if (state.context) { if (state.lexical.info == "var" && state.context && state.context.block) { // FIXME function decls are also not block scoped var newContext = registerVarScoped(varname, state.context) if (newContext != null) { state.context = newContext return } } else if (!inList(varname, state.localVars)) { state.localVars = new Var(varname, state.localVars) return } } // Fall through means this is global if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars) } function registerVarScoped(varname, context) { if (!context) { return null } else if (context.block) { var inner = registerVarScoped(varname, context.prev) if (!inner) return null if (inner == context.prev) return context return new Context(inner, context.vars, true) } else if (inList(varname, context.vars)) { return context } else { return new Context(context.prev, new Var(varname, context.vars), false) } } function isModifier(name) { return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" } // Combinators function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block } function Var(name, next) { this.name = name; this.next = next } var defaultVars = new Var("this", new Var("arguments", null)) function pushcontext() { cx.state.context = new Context(cx.state.context, cx.state.localVars, false) cx.state.localVars = defaultVars } function pushblockcontext() { cx.state.context = new Context(cx.state.context, cx.state.localVars, true) cx.state.localVars = null } function popcontext() { cx.state.localVars = cx.state.context.vars cx.state.context = cx.state.context.prev } popcontext.lex = true function pushlex(type, info) { var result = function() { var state = cx.state, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { function exp(type) { if (type == wanted) return cont(); else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass(); else return cont(exp); }; return exp; } function statement(type, value) { if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); if (type == "debugger") return cont(expect(";")); if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); if (type == ";") return cont(); if (type == "if") { if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); } if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword" return cont(pushlex("form", type == "class" ? type : value), className, poplex) } if (type == "variable") { if (isTS && value == "declare") { cx.marked = "keyword" return cont(statement) } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { cx.marked = "keyword" if (value == "enum") return cont(enumdef); else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";")); else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) } else if (isTS && value == "namespace") { cx.marked = "keyword" return cont(pushlex("form"), expression, statement, poplex) } else if (isTS && value == "abstract") { cx.marked = "keyword" return cont(statement) } else { return cont(pushlex("stat"), maybelabel); } } if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); if (type == "export") return cont(pushlex("stat"), afterExport, poplex); if (type == "import") return cont(pushlex("stat"), afterImport, poplex); if (type == "async") return cont(statement) if (value == "@") return cont(expression, statement) return pass(pushlex("stat"), expression, expect(";"), poplex); } function maybeCatchBinding(type) { if (type == "(") return cont(funarg, expect(")")) } function expression(type, value) { return expressionInner(type, value, false); } function expressionNoComma(type, value) { return expressionInner(type, value, true); } function parenExpr(type) { if (type != "(") return pass() return cont(pushlex(")"), maybeexpression, expect(")"), poplex) } function expressionInner(type, value, noComma) { if (cx.state.fatArrowAt == cx.stream.start) { var body = noComma ? arrowBodyNoComma : arrowBody; if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); } var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef, maybeop); if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); if (type == "{") return contCommasep(objprop, "}", null, maybeop); if (type == "quasi") return pass(quasi, maybeop); if (type == "new") return cont(maybeTarget(noComma)); if (type == "import") return cont(expression); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeoperatorComma(type, value) { if (type == ",") return cont(maybeexpression); return maybeoperatorNoComma(type, value, false); } function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); if (type == "operator") { if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } if (type == "quasi") { return pass(quasi, me); } if (type == ";") return; if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } if (type == "regexp") { cx.state.lastType = cx.marked = "operator" cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) return cont(expr) } } function quasi(type, value) { if (type != "quasi") return pass(); if (value.slice(value.length - 2) != "${") return cont(quasi); return cont(expression, continueQuasi); } function continueQuasi(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; return cont(quasi); } } function arrowBody(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expression); } function arrowBodyNoComma(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expressionNoComma); } function maybeTarget(noComma) { return function(type) { if (type == ".") return cont(noComma ? targetNoComma : target); else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) else return pass(noComma ? expressionNoComma : expression); }; } function target(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } } function targetNoComma(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperatorComma, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { if (type == "async") { cx.marked = "property"; return cont(objprop); } else if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length return cont(afterprop); } else if (type == "number" || type == "string") { cx.marked = jsonldMode ? "property" : (cx.style + " property"); return cont(afterprop); } else if (type == "jsonld-keyword") { return cont(afterprop); } else if (isTS && isModifier(value)) { cx.marked = "keyword" return cont(objprop) } else if (type == "[") { return cont(expression, maybetype, expect("]"), afterprop); } else if (type == "spread") { return cont(expressionNoComma, afterprop); } else if (value == "*") { cx.marked = "keyword"; return cont(objprop); } else if (type == ":") { return pass(afterprop) } } function getterSetter(type) { if (type != "variable") return pass(afterprop); cx.marked = "property"; return cont(functiondef); } function afterprop(type) { if (type == ":") return cont(expressionNoComma); if (type == "(") return pass(functiondef); } function commasep(what, end, sep) { function proceed(type, value) { if (sep ? sep.indexOf(type) > -1 : type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; return cont(function(type, value) { if (type == end || value == end) return pass() return pass(what) }, proceed); } if (type == end || value == end) return cont(); if (sep && sep.indexOf(";") > -1) return pass(what) return cont(expect(end)); } return function(type, value) { if (type == end || value == end) return cont(); return pass(what, proceed); }; } function contCommasep(what, end, info) { for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); return cont(pushlex(end, info), commasep(what, end), poplex); } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function maybetype(type, value) { if (isTS) { if (type == ":") return cont(typeexpr); if (value == "?") return cont(maybetype); } } function maybetypeOrIn(type, value) { if (isTS && (type == ":" || value == "in")) return cont(typeexpr) } function mayberettype(type) { if (isTS && type == ":") { if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) else return cont(typeexpr) } } function isKW(_, value) { if (value == "is") { cx.marked = "keyword" return cont() } } function typeexpr(type, value) { if (value == "keyof" || value == "typeof" || value == "infer") { cx.marked = "keyword" return cont(value == "typeof" ? expressionNoComma : typeexpr) } if (type == "variable" || value == "void") { cx.marked = "type" return cont(afterType) } if (value == "|" || value == "&") return cont(typeexpr) if (type == "string" || type == "number" || type == "atom") return cont(afterType); if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType) if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType) if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) } function maybeReturnType(type) { if (type == "=>") return cont(typeexpr) } function typeprop(type, value) { if (type == "variable" || cx.style == "keyword") { cx.marked = "property" return cont(typeprop) } else if (value == "?" || type == "number" || type == "string") { return cont(typeprop) } else if (type == ":") { return cont(typeexpr) } else if (type == "[") { return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop) } else if (type == "(") { return pass(functiondecl, typeprop) } } function typearg(type, value) { if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) if (type == ":") return cont(typeexpr) if (type == "spread") return cont(typearg) return pass(typeexpr) } function afterType(type, value) { if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) if (value == "|" || type == "." || value == "&") return cont(typeexpr) if (type == "[") return cont(typeexpr, expect("]"), afterType) if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } if (value == "?") return cont(typeexpr, expect(":"), typeexpr) } function maybeTypeArgs(_, value) { if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) } function typeparam() { return pass(typeexpr, maybeTypeDefault) } function maybeTypeDefault(_, value) { if (value == "=") return cont(typeexpr) } function vardef(_, value) { if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} return pass(pattern, maybetype, maybeAssign, vardefCont); } function pattern(type, value) { if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) } if (type == "variable") { register(value); return cont(); } if (type == "spread") return cont(pattern); if (type == "[") return contCommasep(eltpattern, "]"); if (type == "{") return contCommasep(proppattern, "}"); } function proppattern(type, value) { if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { register(value); return cont(maybeAssign); } if (type == "variable") cx.marked = "property"; if (type == "spread") return cont(pattern); if (type == "}") return pass(); if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern); return cont(expect(":"), pattern, maybeAssign); } function eltpattern() { return pass(pattern, maybeAssign) } function maybeAssign(_type, value) { if (value == "=") return cont(expressionNoComma); } function vardefCont(type) { if (type == ",") return cont(vardef); } function maybeelse(type, value) { if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); } function forspec(type, value) { if (value == "await") return cont(forspec); if (type == "(") return cont(pushlex(")"), forspec1, poplex); } function forspec1(type) { if (type == "var") return cont(vardef, forspec2); if (type == "variable") return cont(forspec2); return pass(forspec2) } function forspec2(type, value) { if (type == ")") return cont() if (type == ";") return cont(forspec2) if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) } return pass(expression, forspec2) } function functiondef(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) } function functiondecl(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);} if (type == "variable") {register(value); return cont(functiondecl);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl) } function typename(type, value) { if (type == "keyword" || type == "variable") { cx.marked = "type" return cont(typename) } else if (value == "<") { return cont(pushlex(">"), commasep(typeparam, ">"), poplex) } } function funarg(type, value) { if (value == "@") cont(expression, funarg) if (type == "spread") return cont(funarg); if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); } if (isTS && type == "this") return cont(maybetype, maybeAssign) return pass(pattern, maybetype, maybeAssign); } function classExpression(type, value) { // Class expressions may have an optional name. if (type == "variable") return className(type, value); return classNameAfter(type, value); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } function classNameAfter(type, value) { if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter) if (value == "extends" || value == "implements" || (isTS && type == ",")) { if (value == "implements") cx.marked = "keyword"; return cont(isTS ? typeexpr : expression, classNameAfter); } if (type == "{") return cont(pushlex("}"), classBody, poplex); } function classBody(type, value) { if (type == "async" || (type == "variable" && (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) { cx.marked = "keyword"; return cont(classBody); } if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; return cont(classfield, classBody); } if (type == "number" || type == "string") return cont(classfield, classBody); if (type == "[") return cont(expression, maybetype, expect("]"), classfield, classBody) if (value == "*") { cx.marked = "keyword"; return cont(classBody); } if (isTS && type == "(") return pass(functiondecl, classBody) if (type == ";" || type == ",") return cont(classBody); if (type == "}") return cont(); if (value == "@") return cont(expression, classBody) } function classfield(type, value) { if (value == "?") return cont(classfield) if (type == ":") return cont(typeexpr, maybeAssign) if (value == "=") return cont(expressionNoComma) var context = cx.state.lexical.prev, isInterface = context && context.info == "interface" return pass(isInterface ? functiondecl : functiondef) } function afterExport(type, value) { if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); return pass(statement); } function exportField(type, value) { if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } if (type == "variable") return pass(expressionNoComma, exportField); } function afterImport(type) { if (type == "string") return cont(); if (type == "(") return pass(expression); return pass(importSpec, maybeMoreImports, maybeFrom); } function importSpec(type, value) { if (type == "{") return contCommasep(importSpec, "}"); if (type == "variable") register(value); if (value == "*") cx.marked = "keyword"; return cont(maybeAs); } function maybeMoreImports(type) { if (type == ",") return cont(importSpec, maybeMoreImports) } function maybeAs(_type, value) { if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } } function maybeFrom(_type, value) { if (value == "from") { cx.marked = "keyword"; return cont(expression); } } function arrayLiteral(type) { if (type == "]") return cont(); return pass(commasep(expressionNoComma, "]")); } function enumdef() { return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) } function enummember() { return pass(pattern, maybeAssign); } function isContinuedStatement(state, textAfter) { return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); } function expressionAllowed(stream, state, backUp) { return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) } // Interface return { startState: function(basecolumn) { var state = { tokenize: tokenBase, lastType: "sof", cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && new Context(null, null, false), indented: basecolumn || 0 }; if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; return state; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); findFatArrow(stream, state); } if (state.tokenize != tokenComment && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize == tokenComment) return CodeMirror.Pass; if (state.tokenize != tokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top // Kludge to prevent 'maybelse' from blocking lexical scope pops if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse) break; } while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter)))) lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", blockCommentContinue: jsonMode ? null : " * ", lineComment: jsonMode ? null : "//", fold: "brace", closeBrackets: "()[]{}''\"\"``", helperType: jsonMode ? "json" : "javascript", jsonldMode: jsonldMode, jsonMode: jsonMode, expressionAllowed: expressionAllowed, skipExpression: function(state) { var top = state.cc[state.cc.length - 1] if (top == expression || top == expressionNoComma) state.cc.pop() } }; }); CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("text/ecmascript", "javascript"); CodeMirror.defineMIME("application/javascript", "javascript"); CodeMirror.defineMIME("application/x-javascript", "javascript"); CodeMirror.defineMIME("application/ecmascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); }); },{"../../lib/codemirror":111}],113:[function(require,module,exports){ var getNative = require('./_getNative'), root = require('./_root'); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; },{"./_getNative":196,"./_root":239}],114:[function(require,module,exports){ var hashClear = require('./_hashClear'), hashDelete = require('./_hashDelete'), hashGet = require('./_hashGet'), hashHas = require('./_hashHas'), hashSet = require('./_hashSet'); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; module.exports = Hash; },{"./_hashClear":204,"./_hashDelete":205,"./_hashGet":206,"./_hashHas":207,"./_hashSet":208}],115:[function(require,module,exports){ var listCacheClear = require('./_listCacheClear'), listCacheDelete = require('./_listCacheDelete'), listCacheGet = require('./_listCacheGet'), listCacheHas = require('./_listCacheHas'), listCacheSet = require('./_listCacheSet'); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; },{"./_listCacheClear":219,"./_listCacheDelete":220,"./_listCacheGet":221,"./_listCacheHas":222,"./_listCacheSet":223}],116:[function(require,module,exports){ var getNative = require('./_getNative'), root = require('./_root'); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; },{"./_getNative":196,"./_root":239}],117:[function(require,module,exports){ var mapCacheClear = require('./_mapCacheClear'), mapCacheDelete = require('./_mapCacheDelete'), mapCacheGet = require('./_mapCacheGet'), mapCacheHas = require('./_mapCacheHas'), mapCacheSet = require('./_mapCacheSet'); /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; module.exports = MapCache; },{"./_mapCacheClear":224,"./_mapCacheDelete":225,"./_mapCacheGet":226,"./_mapCacheHas":227,"./_mapCacheSet":228}],118:[function(require,module,exports){ var getNative = require('./_getNative'), root = require('./_root'); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; },{"./_getNative":196,"./_root":239}],119:[function(require,module,exports){ var getNative = require('./_getNative'), root = require('./_root'); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; },{"./_getNative":196,"./_root":239}],120:[function(require,module,exports){ var MapCache = require('./_MapCache'), setCacheAdd = require('./_setCacheAdd'), setCacheHas = require('./_setCacheHas'); /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; module.exports = SetCache; },{"./_MapCache":117,"./_setCacheAdd":241,"./_setCacheHas":242}],121:[function(require,module,exports){ var ListCache = require('./_ListCache'), stackClear = require('./_stackClear'), stackDelete = require('./_stackDelete'), stackGet = require('./_stackGet'), stackHas = require('./_stackHas'), stackSet = require('./_stackSet'); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack; },{"./_ListCache":115,"./_stackClear":246,"./_stackDelete":247,"./_stackGet":248,"./_stackHas":249,"./_stackSet":250}],122:[function(require,module,exports){ var root = require('./_root'); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; },{"./_root":239}],123:[function(require,module,exports){ var root = require('./_root'); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; },{"./_root":239}],124:[function(require,module,exports){ var getNative = require('./_getNative'), root = require('./_root'); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; },{"./_getNative":196,"./_root":239}],125:[function(require,module,exports){ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; },{}],126:[function(require,module,exports){ /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; },{}],127:[function(require,module,exports){ /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; },{}],128:[function(require,module,exports){ var baseTimes = require('./_baseTimes'), isArguments = require('./isArguments'), isArray = require('./isArray'), isBuffer = require('./isBuffer'), isIndex = require('./_isIndex'), isTypedArray = require('./isTypedArray'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } module.exports = arrayLikeKeys; },{"./_baseTimes":167,"./_isIndex":212,"./isArguments":264,"./isArray":265,"./isBuffer":268,"./isTypedArray":278}],129:[function(require,module,exports){ /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; },{}],130:[function(require,module,exports){ /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; },{}],131:[function(require,module,exports){ /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; },{}],132:[function(require,module,exports){ var baseAssignValue = require('./_baseAssignValue'), eq = require('./eq'); /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignMergeValue; },{"./_baseAssignValue":137,"./eq":258}],133:[function(require,module,exports){ var baseAssignValue = require('./_baseAssignValue'), eq = require('./eq'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignValue; },{"./_baseAssignValue":137,"./eq":258}],134:[function(require,module,exports){ var eq = require('./eq'); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; },{"./eq":258}],135:[function(require,module,exports){ var copyObject = require('./_copyObject'), keys = require('./keys'); /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } module.exports = baseAssign; },{"./_copyObject":180,"./keys":280}],136:[function(require,module,exports){ var copyObject = require('./_copyObject'), keysIn = require('./keysIn'); /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } module.exports = baseAssignIn; },{"./_copyObject":180,"./keysIn":281}],137:[function(require,module,exports){ var defineProperty = require('./_defineProperty'); /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } module.exports = baseAssignValue; },{"./_defineProperty":187}],138:[function(require,module,exports){ var Stack = require('./_Stack'), arrayEach = require('./_arrayEach'), assignValue = require('./_assignValue'), baseAssign = require('./_baseAssign'), baseAssignIn = require('./_baseAssignIn'), cloneBuffer = require('./_cloneBuffer'), copyArray = require('./_copyArray'), copySymbols = require('./_copySymbols'), copySymbolsIn = require('./_copySymbolsIn'), getAllKeys = require('./_getAllKeys'), getAllKeysIn = require('./_getAllKeysIn'), getTag = require('./_getTag'), initCloneArray = require('./_initCloneArray'), initCloneByTag = require('./_initCloneByTag'), initCloneObject = require('./_initCloneObject'), isArray = require('./isArray'), isBuffer = require('./isBuffer'), isMap = require('./isMap'), isObject = require('./isObject'), isSet = require('./isSet'), keys = require('./keys'), keysIn = require('./keysIn'); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } module.exports = baseClone; },{"./_Stack":121,"./_arrayEach":126,"./_assignValue":133,"./_baseAssign":135,"./_baseAssignIn":136,"./_cloneBuffer":174,"./_copyArray":179,"./_copySymbols":181,"./_copySymbolsIn":182,"./_getAllKeys":192,"./_getAllKeysIn":193,"./_getTag":201,"./_initCloneArray":209,"./_initCloneByTag":210,"./_initCloneObject":211,"./isArray":265,"./isBuffer":268,"./isMap":271,"./isObject":272,"./isSet":275,"./keys":280,"./keysIn":281}],139:[function(require,module,exports){ var isObject = require('./isObject'); /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); module.exports = baseCreate; },{"./isObject":272}],140:[function(require,module,exports){ var baseForOwn = require('./_baseForOwn'), createBaseEach = require('./_createBaseEach'); /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; },{"./_baseForOwn":142,"./_createBaseEach":185}],141:[function(require,module,exports){ var createBaseFor = require('./_createBaseFor'); /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; },{"./_createBaseFor":186}],142:[function(require,module,exports){ var baseFor = require('./_baseFor'), keys = require('./keys'); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } module.exports = baseForOwn; },{"./_baseFor":141,"./keys":280}],143:[function(require,module,exports){ var castPath = require('./_castPath'), toKey = require('./_toKey'); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; },{"./_castPath":172,"./_toKey":252}],144:[function(require,module,exports){ var arrayPush = require('./_arrayPush'), isArray = require('./isArray'); /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } module.exports = baseGetAllKeys; },{"./_arrayPush":130,"./isArray":265}],145:[function(require,module,exports){ var Symbol = require('./_Symbol'), getRawTag = require('./_getRawTag'), objectToString = require('./_objectToString'); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; },{"./_Symbol":122,"./_getRawTag":198,"./_objectToString":236}],146:[function(require,module,exports){ /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } module.exports = baseHasIn; },{}],147:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isObjectLike = require('./isObjectLike'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } module.exports = baseIsArguments; },{"./_baseGetTag":145,"./isObjectLike":273}],148:[function(require,module,exports){ var baseIsEqualDeep = require('./_baseIsEqualDeep'), isObjectLike = require('./isObjectLike'); /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } module.exports = baseIsEqual; },{"./_baseIsEqualDeep":149,"./isObjectLike":273}],149:[function(require,module,exports){ var Stack = require('./_Stack'), equalArrays = require('./_equalArrays'), equalByTag = require('./_equalByTag'), equalObjects = require('./_equalObjects'), getTag = require('./_getTag'), isArray = require('./isArray'), isBuffer = require('./isBuffer'), isTypedArray = require('./isTypedArray'); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } module.exports = baseIsEqualDeep; },{"./_Stack":121,"./_equalArrays":188,"./_equalByTag":189,"./_equalObjects":190,"./_getTag":201,"./isArray":265,"./isBuffer":268,"./isTypedArray":278}],150:[function(require,module,exports){ var getTag = require('./_getTag'), isObjectLike = require('./isObjectLike'); /** `Object#toString` result references. */ var mapTag = '[object Map]'; /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } module.exports = baseIsMap; },{"./_getTag":201,"./isObjectLike":273}],151:[function(require,module,exports){ var Stack = require('./_Stack'), baseIsEqual = require('./_baseIsEqual'); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; },{"./_Stack":121,"./_baseIsEqual":148}],152:[function(require,module,exports){ var isFunction = require('./isFunction'), isMasked = require('./_isMasked'), isObject = require('./isObject'), toSource = require('./_toSource'); /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } module.exports = baseIsNative; },{"./_isMasked":216,"./_toSource":253,"./isFunction":269,"./isObject":272}],153:[function(require,module,exports){ var getTag = require('./_getTag'), isObjectLike = require('./isObjectLike'); /** `Object#toString` result references. */ var setTag = '[object Set]'; /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } module.exports = baseIsSet; },{"./_getTag":201,"./isObjectLike":273}],154:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isLength = require('./isLength'), isObjectLike = require('./isObjectLike'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } module.exports = baseIsTypedArray; },{"./_baseGetTag":145,"./isLength":270,"./isObjectLike":273}],155:[function(require,module,exports){ var baseMatches = require('./_baseMatches'), baseMatchesProperty = require('./_baseMatchesProperty'), identity = require('./identity'), isArray = require('./isArray'), property = require('./property'); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; },{"./_baseMatches":159,"./_baseMatchesProperty":160,"./identity":263,"./isArray":265,"./property":286}],156:[function(require,module,exports){ var isPrototype = require('./_isPrototype'), nativeKeys = require('./_nativeKeys'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } module.exports = baseKeys; },{"./_isPrototype":217,"./_nativeKeys":233}],157:[function(require,module,exports){ var isObject = require('./isObject'), isPrototype = require('./_isPrototype'), nativeKeysIn = require('./_nativeKeysIn'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = baseKeysIn; },{"./_isPrototype":217,"./_nativeKeysIn":234,"./isObject":272}],158:[function(require,module,exports){ var baseEach = require('./_baseEach'), isArrayLike = require('./isArrayLike'); /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } module.exports = baseMap; },{"./_baseEach":140,"./isArrayLike":266}],159:[function(require,module,exports){ var baseIsMatch = require('./_baseIsMatch'), getMatchData = require('./_getMatchData'), matchesStrictComparable = require('./_matchesStrictComparable'); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; },{"./_baseIsMatch":151,"./_getMatchData":195,"./_matchesStrictComparable":230}],160:[function(require,module,exports){ var baseIsEqual = require('./_baseIsEqual'), get = require('./get'), hasIn = require('./hasIn'), isKey = require('./_isKey'), isStrictComparable = require('./_isStrictComparable'), matchesStrictComparable = require('./_matchesStrictComparable'), toKey = require('./_toKey'); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } module.exports = baseMatchesProperty; },{"./_baseIsEqual":148,"./_isKey":214,"./_isStrictComparable":218,"./_matchesStrictComparable":230,"./_toKey":252,"./get":261,"./hasIn":262}],161:[function(require,module,exports){ var Stack = require('./_Stack'), assignMergeValue = require('./_assignMergeValue'), baseFor = require('./_baseFor'), baseMergeDeep = require('./_baseMergeDeep'), isObject = require('./isObject'), keysIn = require('./keysIn'), safeGet = require('./_safeGet'); /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { stack || (stack = new Stack); if (isObject(srcValue)) { baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } module.exports = baseMerge; },{"./_Stack":121,"./_assignMergeValue":132,"./_baseFor":141,"./_baseMergeDeep":162,"./_safeGet":240,"./isObject":272,"./keysIn":281}],162:[function(require,module,exports){ var assignMergeValue = require('./_assignMergeValue'), cloneBuffer = require('./_cloneBuffer'), cloneTypedArray = require('./_cloneTypedArray'), copyArray = require('./_copyArray'), initCloneObject = require('./_initCloneObject'), isArguments = require('./isArguments'), isArray = require('./isArray'), isArrayLikeObject = require('./isArrayLikeObject'), isBuffer = require('./isBuffer'), isFunction = require('./isFunction'), isObject = require('./isObject'), isPlainObject = require('./isPlainObject'), isTypedArray = require('./isTypedArray'), safeGet = require('./_safeGet'), toPlainObject = require('./toPlainObject'); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } module.exports = baseMergeDeep; },{"./_assignMergeValue":132,"./_cloneBuffer":174,"./_cloneTypedArray":178,"./_copyArray":179,"./_initCloneObject":211,"./_safeGet":240,"./isArguments":264,"./isArray":265,"./isArrayLikeObject":267,"./isBuffer":268,"./isFunction":269,"./isObject":272,"./isPlainObject":274,"./isTypedArray":278,"./toPlainObject":291}],163:[function(require,module,exports){ /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; },{}],164:[function(require,module,exports){ var baseGet = require('./_baseGet'); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; },{"./_baseGet":143}],165:[function(require,module,exports){ var identity = require('./identity'), overRest = require('./_overRest'), setToString = require('./_setToString'); /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } module.exports = baseRest; },{"./_overRest":238,"./_setToString":244,"./identity":263}],166:[function(require,module,exports){ var constant = require('./constant'), defineProperty = require('./_defineProperty'), identity = require('./identity'); /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; module.exports = baseSetToString; },{"./_defineProperty":187,"./constant":255,"./identity":263}],167:[function(require,module,exports){ /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; },{}],168:[function(require,module,exports){ var Symbol = require('./_Symbol'), arrayMap = require('./_arrayMap'), isArray = require('./isArray'), isSymbol = require('./isSymbol'); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; },{"./_Symbol":122,"./_arrayMap":129,"./isArray":265,"./isSymbol":277}],169:[function(require,module,exports){ /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; },{}],170:[function(require,module,exports){ /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } module.exports = cacheHas; },{}],171:[function(require,module,exports){ var identity = require('./identity'); /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } module.exports = castFunction; },{"./identity":263}],172:[function(require,module,exports){ var isArray = require('./isArray'), isKey = require('./_isKey'), stringToPath = require('./_stringToPath'), toString = require('./toString'); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } module.exports = castPath; },{"./_isKey":214,"./_stringToPath":251,"./isArray":265,"./toString":292}],173:[function(require,module,exports){ var Uint8Array = require('./_Uint8Array'); /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } module.exports = cloneArrayBuffer; },{"./_Uint8Array":123}],174:[function(require,module,exports){ var root = require('./_root'); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; },{"./_root":239}],175:[function(require,module,exports){ var cloneArrayBuffer = require('./_cloneArrayBuffer'); /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } module.exports = cloneDataView; },{"./_cloneArrayBuffer":173}],176:[function(require,module,exports){ /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } module.exports = cloneRegExp; },{}],177:[function(require,module,exports){ var Symbol = require('./_Symbol'); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } module.exports = cloneSymbol; },{"./_Symbol":122}],178:[function(require,module,exports){ var cloneArrayBuffer = require('./_cloneArrayBuffer'); /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } module.exports = cloneTypedArray; },{"./_cloneArrayBuffer":173}],179:[function(require,module,exports){ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = copyArray; },{}],180:[function(require,module,exports){ var assignValue = require('./_assignValue'), baseAssignValue = require('./_baseAssignValue'); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; },{"./_assignValue":133,"./_baseAssignValue":137}],181:[function(require,module,exports){ var copyObject = require('./_copyObject'), getSymbols = require('./_getSymbols'); /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } module.exports = copySymbols; },{"./_copyObject":180,"./_getSymbols":199}],182:[function(require,module,exports){ var copyObject = require('./_copyObject'), getSymbolsIn = require('./_getSymbolsIn'); /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } module.exports = copySymbolsIn; },{"./_copyObject":180,"./_getSymbolsIn":200}],183:[function(require,module,exports){ var root = require('./_root'); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; },{"./_root":239}],184:[function(require,module,exports){ var baseRest = require('./_baseRest'), isIterateeCall = require('./_isIterateeCall'); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } module.exports = createAssigner; },{"./_baseRest":165,"./_isIterateeCall":213}],185:[function(require,module,exports){ var isArrayLike = require('./isArrayLike'); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; },{"./isArrayLike":266}],186:[function(require,module,exports){ /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; },{}],187:[function(require,module,exports){ var getNative = require('./_getNative'); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; },{"./_getNative":196}],188:[function(require,module,exports){ var SetCache = require('./_SetCache'), arraySome = require('./_arraySome'), cacheHas = require('./_cacheHas'); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Check that cyclic values are equal. var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } module.exports = equalArrays; },{"./_SetCache":120,"./_arraySome":131,"./_cacheHas":170}],189:[function(require,module,exports){ var Symbol = require('./_Symbol'), Uint8Array = require('./_Uint8Array'), eq = require('./eq'), equalArrays = require('./_equalArrays'), mapToArray = require('./_mapToArray'), setToArray = require('./_setToArray'); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; },{"./_Symbol":122,"./_Uint8Array":123,"./_equalArrays":188,"./_mapToArray":229,"./_setToArray":243,"./eq":258}],190:[function(require,module,exports){ var getAllKeys = require('./_getAllKeys'); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Check that cyclic values are equal. var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } module.exports = equalObjects; },{"./_getAllKeys":192}],191:[function(require,module,exports){ (function (global){ /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],192:[function(require,module,exports){ var baseGetAllKeys = require('./_baseGetAllKeys'), getSymbols = require('./_getSymbols'), keys = require('./keys'); /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } module.exports = getAllKeys; },{"./_baseGetAllKeys":144,"./_getSymbols":199,"./keys":280}],193:[function(require,module,exports){ var baseGetAllKeys = require('./_baseGetAllKeys'), getSymbolsIn = require('./_getSymbolsIn'), keysIn = require('./keysIn'); /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } module.exports = getAllKeysIn; },{"./_baseGetAllKeys":144,"./_getSymbolsIn":200,"./keysIn":281}],194:[function(require,module,exports){ var isKeyable = require('./_isKeyable'); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } module.exports = getMapData; },{"./_isKeyable":215}],195:[function(require,module,exports){ var isStrictComparable = require('./_isStrictComparable'), keys = require('./keys'); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } module.exports = getMatchData; },{"./_isStrictComparable":218,"./keys":280}],196:[function(require,module,exports){ var baseIsNative = require('./_baseIsNative'), getValue = require('./_getValue'); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } module.exports = getNative; },{"./_baseIsNative":152,"./_getValue":202}],197:[function(require,module,exports){ var overArg = require('./_overArg'); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; },{"./_overArg":237}],198:[function(require,module,exports){ var Symbol = require('./_Symbol'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; },{"./_Symbol":122}],199:[function(require,module,exports){ var arrayFilter = require('./_arrayFilter'), stubArray = require('./stubArray'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; module.exports = getSymbols; },{"./_arrayFilter":127,"./stubArray":287}],200:[function(require,module,exports){ var arrayPush = require('./_arrayPush'), getPrototype = require('./_getPrototype'), getSymbols = require('./_getSymbols'), stubArray = require('./stubArray'); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; module.exports = getSymbolsIn; },{"./_arrayPush":130,"./_getPrototype":197,"./_getSymbols":199,"./stubArray":287}],201:[function(require,module,exports){ var DataView = require('./_DataView'), Map = require('./_Map'), Promise = require('./_Promise'), Set = require('./_Set'), WeakMap = require('./_WeakMap'), baseGetTag = require('./_baseGetTag'), toSource = require('./_toSource'); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; },{"./_DataView":113,"./_Map":116,"./_Promise":118,"./_Set":119,"./_WeakMap":124,"./_baseGetTag":145,"./_toSource":253}],202:[function(require,module,exports){ /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } module.exports = getValue; },{}],203:[function(require,module,exports){ var castPath = require('./_castPath'), isArguments = require('./isArguments'), isArray = require('./isArray'), isIndex = require('./_isIndex'), isLength = require('./isLength'), toKey = require('./_toKey'); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } module.exports = hasPath; },{"./_castPath":172,"./_isIndex":212,"./_toKey":252,"./isArguments":264,"./isArray":265,"./isLength":270}],204:[function(require,module,exports){ var nativeCreate = require('./_nativeCreate'); /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } module.exports = hashClear; },{"./_nativeCreate":232}],205:[function(require,module,exports){ /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } module.exports = hashDelete; },{}],206:[function(require,module,exports){ var nativeCreate = require('./_nativeCreate'); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } module.exports = hashGet; },{"./_nativeCreate":232}],207:[function(require,module,exports){ var nativeCreate = require('./_nativeCreate'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } module.exports = hashHas; },{"./_nativeCreate":232}],208:[function(require,module,exports){ var nativeCreate = require('./_nativeCreate'); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } module.exports = hashSet; },{"./_nativeCreate":232}],209:[function(require,module,exports){ /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } module.exports = initCloneArray; },{}],210:[function(require,module,exports){ var cloneArrayBuffer = require('./_cloneArrayBuffer'), cloneDataView = require('./_cloneDataView'), cloneRegExp = require('./_cloneRegExp'), cloneSymbol = require('./_cloneSymbol'), cloneTypedArray = require('./_cloneTypedArray'); /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } module.exports = initCloneByTag; },{"./_cloneArrayBuffer":173,"./_cloneDataView":175,"./_cloneRegExp":176,"./_cloneSymbol":177,"./_cloneTypedArray":178}],211:[function(require,module,exports){ var baseCreate = require('./_baseCreate'), getPrototype = require('./_getPrototype'), isPrototype = require('./_isPrototype'); /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } module.exports = initCloneObject; },{"./_baseCreate":139,"./_getPrototype":197,"./_isPrototype":217}],212:[function(require,module,exports){ /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } module.exports = isIndex; },{}],213:[function(require,module,exports){ var eq = require('./eq'), isArrayLike = require('./isArrayLike'), isIndex = require('./_isIndex'), isObject = require('./isObject'); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; },{"./_isIndex":212,"./eq":258,"./isArrayLike":266,"./isObject":272}],214:[function(require,module,exports){ var isArray = require('./isArray'), isSymbol = require('./isSymbol'); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; },{"./isArray":265,"./isSymbol":277}],215:[function(require,module,exports){ /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } module.exports = isKeyable; },{}],216:[function(require,module,exports){ var coreJsData = require('./_coreJsData'); /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } module.exports = isMasked; },{"./_coreJsData":183}],217:[function(require,module,exports){ /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; },{}],218:[function(require,module,exports){ var isObject = require('./isObject'); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; },{"./isObject":272}],219:[function(require,module,exports){ /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } module.exports = listCacheClear; },{}],220:[function(require,module,exports){ var assocIndexOf = require('./_assocIndexOf'); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } module.exports = listCacheDelete; },{"./_assocIndexOf":134}],221:[function(require,module,exports){ var assocIndexOf = require('./_assocIndexOf'); /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } module.exports = listCacheGet; },{"./_assocIndexOf":134}],222:[function(require,module,exports){ var assocIndexOf = require('./_assocIndexOf'); /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } module.exports = listCacheHas; },{"./_assocIndexOf":134}],223:[function(require,module,exports){ var assocIndexOf = require('./_assocIndexOf'); /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } module.exports = listCacheSet; },{"./_assocIndexOf":134}],224:[function(require,module,exports){ var Hash = require('./_Hash'), ListCache = require('./_ListCache'), Map = require('./_Map'); /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } module.exports = mapCacheClear; },{"./_Hash":114,"./_ListCache":115,"./_Map":116}],225:[function(require,module,exports){ var getMapData = require('./_getMapData'); /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } module.exports = mapCacheDelete; },{"./_getMapData":194}],226:[function(require,module,exports){ var getMapData = require('./_getMapData'); /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } module.exports = mapCacheGet; },{"./_getMapData":194}],227:[function(require,module,exports){ var getMapData = require('./_getMapData'); /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } module.exports = mapCacheHas; },{"./_getMapData":194}],228:[function(require,module,exports){ var getMapData = require('./_getMapData'); /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } module.exports = mapCacheSet; },{"./_getMapData":194}],229:[function(require,module,exports){ /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } module.exports = mapToArray; },{}],230:[function(require,module,exports){ /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } module.exports = matchesStrictComparable; },{}],231:[function(require,module,exports){ var memoize = require('./memoize'); /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } module.exports = memoizeCapped; },{"./memoize":283}],232:[function(require,module,exports){ var getNative = require('./_getNative'); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; },{"./_getNative":196}],233:[function(require,module,exports){ var overArg = require('./_overArg'); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; },{"./_overArg":237}],234:[function(require,module,exports){ /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } module.exports = nativeKeysIn; },{}],235:[function(require,module,exports){ var freeGlobal = require('./_freeGlobal'); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; },{"./_freeGlobal":191}],236:[function(require,module,exports){ /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; },{}],237:[function(require,module,exports){ /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; },{}],238:[function(require,module,exports){ var apply = require('./_apply'); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } module.exports = overRest; },{"./_apply":125}],239:[function(require,module,exports){ var freeGlobal = require('./_freeGlobal'); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; },{"./_freeGlobal":191}],240:[function(require,module,exports){ /** * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key === 'constructor' && typeof object[key] === 'function') { return; } if (key == '__proto__') { return; } return object[key]; } module.exports = safeGet; },{}],241:[function(require,module,exports){ /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } module.exports = setCacheAdd; },{}],242:[function(require,module,exports){ /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } module.exports = setCacheHas; },{}],243:[function(require,module,exports){ /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } module.exports = setToArray; },{}],244:[function(require,module,exports){ var baseSetToString = require('./_baseSetToString'), shortOut = require('./_shortOut'); /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); module.exports = setToString; },{"./_baseSetToString":166,"./_shortOut":245}],245:[function(require,module,exports){ /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } module.exports = shortOut; },{}],246:[function(require,module,exports){ var ListCache = require('./_ListCache'); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } module.exports = stackClear; },{"./_ListCache":115}],247:[function(require,module,exports){ /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } module.exports = stackDelete; },{}],248:[function(require,module,exports){ /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } module.exports = stackGet; },{}],249:[function(require,module,exports){ /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } module.exports = stackHas; },{}],250:[function(require,module,exports){ var ListCache = require('./_ListCache'), Map = require('./_Map'), MapCache = require('./_MapCache'); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } module.exports = stackSet; },{"./_ListCache":115,"./_Map":116,"./_MapCache":117}],251:[function(require,module,exports){ var memoizeCapped = require('./_memoizeCapped'); /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; },{"./_memoizeCapped":231}],252:[function(require,module,exports){ var isSymbol = require('./isSymbol'); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; },{"./isSymbol":277}],253:[function(require,module,exports){ /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } module.exports = toSource; },{}],254:[function(require,module,exports){ var baseClone = require('./_baseClone'); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_SYMBOLS_FLAG = 4; /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } module.exports = cloneDeep; },{"./_baseClone":138}],255:[function(require,module,exports){ /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } module.exports = constant; },{}],256:[function(require,module,exports){ var isObject = require('./isObject'), now = require('./now'), toNumber = require('./toNumber'); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max, nativeMin = Math.min; /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } module.exports = debounce; },{"./isObject":272,"./now":285,"./toNumber":290}],257:[function(require,module,exports){ module.exports = require('./forEach'); },{"./forEach":259}],258:[function(require,module,exports){ /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; },{}],259:[function(require,module,exports){ var arrayEach = require('./_arrayEach'), baseEach = require('./_baseEach'), castFunction = require('./_castFunction'), isArray = require('./isArray'); /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, castFunction(iteratee)); } module.exports = forEach; },{"./_arrayEach":126,"./_baseEach":140,"./_castFunction":171,"./isArray":265}],260:[function(require,module,exports){ var baseForOwn = require('./_baseForOwn'), castFunction = require('./_castFunction'); /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, castFunction(iteratee)); } module.exports = forOwn; },{"./_baseForOwn":142,"./_castFunction":171}],261:[function(require,module,exports){ var baseGet = require('./_baseGet'); /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; },{"./_baseGet":143}],262:[function(require,module,exports){ var baseHasIn = require('./_baseHasIn'), hasPath = require('./_hasPath'); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } module.exports = hasIn; },{"./_baseHasIn":146,"./_hasPath":203}],263:[function(require,module,exports){ /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; },{}],264:[function(require,module,exports){ var baseIsArguments = require('./_baseIsArguments'), isObjectLike = require('./isObjectLike'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; module.exports = isArguments; },{"./_baseIsArguments":147,"./isObjectLike":273}],265:[function(require,module,exports){ /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; },{}],266:[function(require,module,exports){ var isFunction = require('./isFunction'), isLength = require('./isLength'); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } module.exports = isArrayLike; },{"./isFunction":269,"./isLength":270}],267:[function(require,module,exports){ var isArrayLike = require('./isArrayLike'), isObjectLike = require('./isObjectLike'); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; },{"./isArrayLike":266,"./isObjectLike":273}],268:[function(require,module,exports){ var root = require('./_root'), stubFalse = require('./stubFalse'); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; module.exports = isBuffer; },{"./_root":239,"./stubFalse":288}],269:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isObject = require('./isObject'); /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } module.exports = isFunction; },{"./_baseGetTag":145,"./isObject":272}],270:[function(require,module,exports){ /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; },{}],271:[function(require,module,exports){ var baseIsMap = require('./_baseIsMap'), baseUnary = require('./_baseUnary'), nodeUtil = require('./_nodeUtil'); /* Node.js helper references. */ var nodeIsMap = nodeUtil && nodeUtil.isMap; /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; module.exports = isMap; },{"./_baseIsMap":150,"./_baseUnary":169,"./_nodeUtil":235}],272:[function(require,module,exports){ /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; },{}],273:[function(require,module,exports){ /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; },{}],274:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), getPrototype = require('./_getPrototype'), isObjectLike = require('./isObjectLike'); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; },{"./_baseGetTag":145,"./_getPrototype":197,"./isObjectLike":273}],275:[function(require,module,exports){ var baseIsSet = require('./_baseIsSet'), baseUnary = require('./_baseUnary'), nodeUtil = require('./_nodeUtil'); /* Node.js helper references. */ var nodeIsSet = nodeUtil && nodeUtil.isSet; /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; module.exports = isSet; },{"./_baseIsSet":153,"./_baseUnary":169,"./_nodeUtil":235}],276:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isArray = require('./isArray'), isObjectLike = require('./isObjectLike'); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } module.exports = isString; },{"./_baseGetTag":145,"./isArray":265,"./isObjectLike":273}],277:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isObjectLike = require('./isObjectLike'); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; },{"./_baseGetTag":145,"./isObjectLike":273}],278:[function(require,module,exports){ var baseIsTypedArray = require('./_baseIsTypedArray'), baseUnary = require('./_baseUnary'), nodeUtil = require('./_nodeUtil'); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; module.exports = isTypedArray; },{"./_baseIsTypedArray":154,"./_baseUnary":169,"./_nodeUtil":235}],279:[function(require,module,exports){ /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } module.exports = isUndefined; },{}],280:[function(require,module,exports){ var arrayLikeKeys = require('./_arrayLikeKeys'), baseKeys = require('./_baseKeys'), isArrayLike = require('./isArrayLike'); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } module.exports = keys; },{"./_arrayLikeKeys":128,"./_baseKeys":156,"./isArrayLike":266}],281:[function(require,module,exports){ var arrayLikeKeys = require('./_arrayLikeKeys'), baseKeysIn = require('./_baseKeysIn'), isArrayLike = require('./isArrayLike'); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } module.exports = keysIn; },{"./_arrayLikeKeys":128,"./_baseKeysIn":157,"./isArrayLike":266}],282:[function(require,module,exports){ var arrayMap = require('./_arrayMap'), baseIteratee = require('./_baseIteratee'), baseMap = require('./_baseMap'), isArray = require('./isArray'); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, baseIteratee(iteratee, 3)); } module.exports = map; },{"./_arrayMap":129,"./_baseIteratee":155,"./_baseMap":158,"./isArray":265}],283:[function(require,module,exports){ var MapCache = require('./_MapCache'); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; module.exports = memoize; },{"./_MapCache":117}],284:[function(require,module,exports){ var baseMerge = require('./_baseMerge'), createAssigner = require('./_createAssigner'); /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); module.exports = merge; },{"./_baseMerge":161,"./_createAssigner":184}],285:[function(require,module,exports){ var root = require('./_root'); /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = function() { return root.Date.now(); }; module.exports = now; },{"./_root":239}],286:[function(require,module,exports){ var baseProperty = require('./_baseProperty'), basePropertyDeep = require('./_basePropertyDeep'), isKey = require('./_isKey'), toKey = require('./_toKey'); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = property; },{"./_baseProperty":163,"./_basePropertyDeep":164,"./_isKey":214,"./_toKey":252}],287:[function(require,module,exports){ /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } module.exports = stubArray; },{}],288:[function(require,module,exports){ /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; },{}],289:[function(require,module,exports){ var debounce = require('./debounce'), isObject = require('./isObject'); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } module.exports = throttle; },{"./debounce":256,"./isObject":272}],290:[function(require,module,exports){ var isObject = require('./isObject'), isSymbol = require('./isSymbol'); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; },{"./isObject":272,"./isSymbol":277}],291:[function(require,module,exports){ var copyObject = require('./_copyObject'), keysIn = require('./keysIn'); /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } module.exports = toPlainObject; },{"./_copyObject":180,"./keysIn":281}],292:[function(require,module,exports){ var baseToString = require('./_baseToString'); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; },{"./_baseToString":168}],293:[function(require,module,exports){ (function(root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.materialColors = factory(); } })(this, function() { return {"red":{"50":"#ffebee","100":"#ffcdd2","200":"#ef9a9a","300":"#e57373","400":"#ef5350","500":"#f44336","600":"#e53935","700":"#d32f2f","800":"#c62828","900":"#b71c1c","a100":"#ff8a80","a200":"#ff5252","a400":"#ff1744","a700":"#d50000"},"pink":{"50":"#fce4ec","100":"#f8bbd0","200":"#f48fb1","300":"#f06292","400":"#ec407a","500":"#e91e63","600":"#d81b60","700":"#c2185b","800":"#ad1457","900":"#880e4f","a100":"#ff80ab","a200":"#ff4081","a400":"#f50057","a700":"#c51162"},"purple":{"50":"#f3e5f5","100":"#e1bee7","200":"#ce93d8","300":"#ba68c8","400":"#ab47bc","500":"#9c27b0","600":"#8e24aa","700":"#7b1fa2","800":"#6a1b9a","900":"#4a148c","a100":"#ea80fc","a200":"#e040fb","a400":"#d500f9","a700":"#aa00ff"},"deepPurple":{"50":"#ede7f6","100":"#d1c4e9","200":"#b39ddb","300":"#9575cd","400":"#7e57c2","500":"#673ab7","600":"#5e35b1","700":"#512da8","800":"#4527a0","900":"#311b92","a100":"#b388ff","a200":"#7c4dff","a400":"#651fff","a700":"#6200ea"},"indigo":{"50":"#e8eaf6","100":"#c5cae9","200":"#9fa8da","300":"#7986cb","400":"#5c6bc0","500":"#3f51b5","600":"#3949ab","700":"#303f9f","800":"#283593","900":"#1a237e","a100":"#8c9eff","a200":"#536dfe","a400":"#3d5afe","a700":"#304ffe"},"blue":{"50":"#e3f2fd","100":"#bbdefb","200":"#90caf9","300":"#64b5f6","400":"#42a5f5","500":"#2196f3","600":"#1e88e5","700":"#1976d2","800":"#1565c0","900":"#0d47a1","a100":"#82b1ff","a200":"#448aff","a400":"#2979ff","a700":"#2962ff"},"lightBlue":{"50":"#e1f5fe","100":"#b3e5fc","200":"#81d4fa","300":"#4fc3f7","400":"#29b6f6","500":"#03a9f4","600":"#039be5","700":"#0288d1","800":"#0277bd","900":"#01579b","a100":"#80d8ff","a200":"#40c4ff","a400":"#00b0ff","a700":"#0091ea"},"cyan":{"50":"#e0f7fa","100":"#b2ebf2","200":"#80deea","300":"#4dd0e1","400":"#26c6da","500":"#00bcd4","600":"#00acc1","700":"#0097a7","800":"#00838f","900":"#006064","a100":"#84ffff","a200":"#18ffff","a400":"#00e5ff","a700":"#00b8d4"},"teal":{"50":"#e0f2f1","100":"#b2dfdb","200":"#80cbc4","300":"#4db6ac","400":"#26a69a","500":"#009688","600":"#00897b","700":"#00796b","800":"#00695c","900":"#004d40","a100":"#a7ffeb","a200":"#64ffda","a400":"#1de9b6","a700":"#00bfa5"},"green":{"50":"#e8f5e9","100":"#c8e6c9","200":"#a5d6a7","300":"#81c784","400":"#66bb6a","500":"#4caf50","600":"#43a047","700":"#388e3c","800":"#2e7d32","900":"#1b5e20","a100":"#b9f6ca","a200":"#69f0ae","a400":"#00e676","a700":"#00c853"},"lightGreen":{"50":"#f1f8e9","100":"#dcedc8","200":"#c5e1a5","300":"#aed581","400":"#9ccc65","500":"#8bc34a","600":"#7cb342","700":"#689f38","800":"#558b2f","900":"#33691e","a100":"#ccff90","a200":"#b2ff59","a400":"#76ff03","a700":"#64dd17"},"lime":{"50":"#f9fbe7","100":"#f0f4c3","200":"#e6ee9c","300":"#dce775","400":"#d4e157","500":"#cddc39","600":"#c0ca33","700":"#afb42b","800":"#9e9d24","900":"#827717","a100":"#f4ff81","a200":"#eeff41","a400":"#c6ff00","a700":"#aeea00"},"yellow":{"50":"#fffde7","100":"#fff9c4","200":"#fff59d","300":"#fff176","400":"#ffee58","500":"#ffeb3b","600":"#fdd835","700":"#fbc02d","800":"#f9a825","900":"#f57f17","a100":"#ffff8d","a200":"#ffff00","a400":"#ffea00","a700":"#ffd600"},"amber":{"50":"#fff8e1","100":"#ffecb3","200":"#ffe082","300":"#ffd54f","400":"#ffca28","500":"#ffc107","600":"#ffb300","700":"#ffa000","800":"#ff8f00","900":"#ff6f00","a100":"#ffe57f","a200":"#ffd740","a400":"#ffc400","a700":"#ffab00"},"orange":{"50":"#fff3e0","100":"#ffe0b2","200":"#ffcc80","300":"#ffb74d","400":"#ffa726","500":"#ff9800","600":"#fb8c00","700":"#f57c00","800":"#ef6c00","900":"#e65100","a100":"#ffd180","a200":"#ffab40","a400":"#ff9100","a700":"#ff6d00"},"deepOrange":{"50":"#fbe9e7","100":"#ffccbc","200":"#ffab91","300":"#ff8a65","400":"#ff7043","500":"#ff5722","600":"#f4511e","700":"#e64a19","800":"#d84315","900":"#bf360c","a100":"#ff9e80","a200":"#ff6e40","a400":"#ff3d00","a700":"#dd2c00"},"brown":{"50":"#efebe9","100":"#d7ccc8","200":"#bcaaa4","300":"#a1887f","400":"#8d6e63","500":"#795548","600":"#6d4c41","700":"#5d4037","800":"#4e342e","900":"#3e2723"},"grey":{"50":"#fafafa","100":"#f5f5f5","200":"#eeeeee","300":"#e0e0e0","400":"#bdbdbd","500":"#9e9e9e","600":"#757575","700":"#616161","800":"#424242","900":"#212121"},"blueGrey":{"50":"#eceff1","100":"#cfd8dc","200":"#b0bec5","300":"#90a4ae","400":"#78909c","500":"#607d8b","600":"#546e7a","700":"#455a64","800":"#37474f","900":"#263238"},"darkText":{"primary":"rgba(0, 0, 0, 0.87)","secondary":"rgba(0, 0, 0, 0.54)","disabled":"rgba(0, 0, 0, 0.38)","dividers":"rgba(0, 0, 0, 0.12)"},"lightText":{"primary":"rgba(255, 255, 255, 1)","secondary":"rgba(255, 255, 255, 0.7)","disabled":"rgba(255, 255, 255, 0.5)","dividers":"rgba(255, 255, 255, 0.12)"},"darkIcons":{"active":"rgba(0, 0, 0, 0.54)","inactive":"rgba(0, 0, 0, 0.38)"},"lightIcons":{"active":"rgba(255, 255, 255, 1)","inactive":"rgba(255, 255, 255, 0.5)"},"white":"#ffffff","black":"#000000"}; }); },{}],294:[function(require,module,exports){ /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}],295:[function(require,module,exports){ (function (process){ /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var printWarning = function() {}; if (process.env.NODE_ENV !== 'production') { var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); var loggedTypeFailures = {}; var has = Function.call.bind(Object.prototype.hasOwnProperty); printWarning = function(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } } /** * Resets warning cache when testing. * * @private */ checkPropTypes.resetWarningCache = function() { if (process.env.NODE_ENV !== 'production') { loggedTypeFailures = {}; } } module.exports = checkPropTypes; }).call(this,require('_process')) },{"./lib/ReactPropTypesSecret":299,"_process":1}],296:[function(require,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); function emptyFunction() {} function emptyFunctionWithReset() {} emptyFunctionWithReset.resetWarningCache = emptyFunction; module.exports = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } var err = new Error( 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); err.name = 'Invariant Violation'; throw err; }; shim.isRequired = shim; function getShim() { return shim; }; // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, elementType: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim, checkPropTypes: emptyFunctionWithReset, resetWarningCache: emptyFunction }; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; },{"./lib/ReactPropTypesSecret":299}],297:[function(require,module,exports){ (function (process){ /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var ReactIs = require('react-is'); var assign = require('object-assign'); var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); var checkPropTypes = require('./checkPropTypes'); var has = Function.call.bind(Object.prototype.hasOwnProperty); var printWarning = function() {}; if (process.env.NODE_ENV !== 'production') { printWarning = function(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } function emptyFunctionThatReturnsNull() { return null; } module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), elementType: createElementTypeTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker, }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (process.env.NODE_ENV !== 'production') { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package var err = new Error( 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); err.name = 'Invariant Violation'; throw err; } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { printWarning( 'You are manually calling a React.PropTypes validation ' + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createElementTypeTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!ReactIs.isValidElementType(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { if (process.env.NODE_ENV !== 'production') { if (arguments.length > 1) { printWarning( 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' + 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).' ); } else { printWarning('Invalid argument supplied to oneOf, expected an array.'); } } return emptyFunctionThatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues, function replacer(key, value) { var type = getPreciseType(value); if (type === 'symbol') { return String(value); } return value; }); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (has(propValue, key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { process.env.NODE_ENV !== 'production' ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunctionThatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { printWarning( 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.' ); return emptyFunctionThatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } // We need to check all keys in case some are required but missing from // props. var allKeys = assign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // falsy value can't be a Symbol if (!propValue) { return false; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; }).call(this,require('_process')) },{"./checkPropTypes":295,"./lib/ReactPropTypesSecret":299,"_process":1,"object-assign":294,"react-is":357}],298:[function(require,module,exports){ (function (process){ /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (process.env.NODE_ENV !== 'production') { var ReactIs = require('react-is'); // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = require('./factoryWithThrowingShims')(); } }).call(this,require('_process')) },{"./factoryWithThrowingShims":296,"./factoryWithTypeCheckers":297,"_process":1,"react-is":357}],299:[function(require,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; },{}],300:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.AlphaPicker = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _common = require('../common'); var _AlphaPointer = require('./AlphaPointer'); var _AlphaPointer2 = _interopRequireDefault(_AlphaPointer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var AlphaPicker = exports.AlphaPicker = function AlphaPicker(_ref) { var rgb = _ref.rgb, hsl = _ref.hsl, width = _ref.width, height = _ref.height, onChange = _ref.onChange, direction = _ref.direction, style = _ref.style, renderers = _ref.renderers, pointer = _ref.pointer, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)({ 'default': { picker: { position: 'relative', width: width, height: height }, alpha: { radius: '2px', style: style } } }); return _react2.default.createElement( 'div', { style: styles.picker, className: 'alpha-picker ' + className }, _react2.default.createElement(_common.Alpha, _extends({}, styles.alpha, { rgb: rgb, hsl: hsl, pointer: pointer, renderers: renderers, onChange: onChange, direction: direction })) ); }; AlphaPicker.defaultProps = { width: '316px', height: '16px', direction: 'horizontal', pointer: _AlphaPointer2.default }; exports.default = (0, _common.ColorWrap)(AlphaPicker); },{"../common":318,"./AlphaPointer":301,"react":"react","reactcss":363}],301:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.AlphaPointer = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var AlphaPointer = exports.AlphaPointer = function AlphaPointer(_ref) { var direction = _ref.direction; var styles = (0, _reactcss2.default)({ 'default': { picker: { width: '18px', height: '18px', borderRadius: '50%', transform: 'translate(-9px, -1px)', backgroundColor: 'rgb(248, 248, 248)', boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)' } }, 'vertical': { picker: { transform: 'translate(-3px, -9px)' } } }, { vertical: direction === 'vertical' }); return _react2.default.createElement('div', { style: styles.picker }); }; exports.default = AlphaPointer; },{"react":"react","reactcss":363}],302:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Block = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _color = require('../../helpers/color'); var color = _interopRequireWildcard(_color); var _common = require('../common'); var _BlockSwatches = require('./BlockSwatches'); var _BlockSwatches2 = _interopRequireDefault(_BlockSwatches); 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 }; } var Block = exports.Block = function Block(_ref) { var onChange = _ref.onChange, onSwatchHover = _ref.onSwatchHover, hex = _ref.hex, colors = _ref.colors, width = _ref.width, triangle = _ref.triangle, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var transparent = hex === 'transparent'; var handleChange = function handleChange(hexCode, e) { color.isValidHex(hexCode) && onChange({ hex: hexCode, source: 'hex' }, e); }; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { card: { width: width, background: '#fff', boxShadow: '0 1px rgba(0,0,0,.1)', borderRadius: '6px', position: 'relative' }, head: { height: '110px', background: hex, borderRadius: '6px 6px 0 0', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }, body: { padding: '10px' }, label: { fontSize: '18px', color: color.getContrastingColor(hex), position: 'relative' }, triangle: { width: '0px', height: '0px', borderStyle: 'solid', borderWidth: '0 10px 10px 10px', borderColor: 'transparent transparent ' + hex + ' transparent', position: 'absolute', top: '-10px', left: '50%', marginLeft: '-10px' }, input: { width: '100%', fontSize: '12px', color: '#666', border: '0px', outline: 'none', height: '22px', boxShadow: 'inset 0 0 0 1px #ddd', borderRadius: '4px', padding: '0 7px', boxSizing: 'border-box' } }, 'hide-triangle': { triangle: { display: 'none' } } }, passedStyles), { 'hide-triangle': triangle === 'hide' }); return _react2.default.createElement( 'div', { style: styles.card, className: 'block-picker ' + className }, _react2.default.createElement('div', { style: styles.triangle }), _react2.default.createElement( 'div', { style: styles.head }, transparent && _react2.default.createElement(_common.Checkboard, { borderRadius: '6px 6px 0 0' }), _react2.default.createElement( 'div', { style: styles.label }, hex ) ), _react2.default.createElement( 'div', { style: styles.body }, _react2.default.createElement(_BlockSwatches2.default, { colors: colors, onClick: handleChange, onSwatchHover: onSwatchHover }), _react2.default.createElement(_common.EditableInput, { style: { input: styles.input }, value: hex, onChange: handleChange }) ) ); }; Block.propTypes = { width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), colors: _propTypes2.default.arrayOf(_propTypes2.default.string), triangle: _propTypes2.default.oneOf(['top', 'hide']), styles: _propTypes2.default.object }; Block.defaultProps = { width: 170, colors: ['#D9E3F0', '#F47373', '#697689', '#37D67A', '#2CCCE4', '#555555', '#dce775', '#ff8a65', '#ba68c8'], triangle: 'top', styles: {} }; exports.default = (0, _common.ColorWrap)(Block); },{"../../helpers/color":350,"../common":318,"./BlockSwatches":303,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],303:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.BlockSwatches = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _map = require('lodash/map'); var _map2 = _interopRequireDefault(_map); var _common = require('../common'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var BlockSwatches = exports.BlockSwatches = function BlockSwatches(_ref) { var colors = _ref.colors, onClick = _ref.onClick, onSwatchHover = _ref.onSwatchHover; var styles = (0, _reactcss2.default)({ 'default': { swatches: { marginRight: '-10px' }, swatch: { width: '22px', height: '22px', float: 'left', marginRight: '10px', marginBottom: '10px', borderRadius: '4px' }, clear: { clear: 'both' } } }); return _react2.default.createElement( 'div', { style: styles.swatches }, (0, _map2.default)(colors, function (c) { return _react2.default.createElement(_common.Swatch, { key: c, color: c, style: styles.swatch, onClick: onClick, onHover: onSwatchHover, focusStyle: { boxShadow: '0 0 4px ' + c } }); }), _react2.default.createElement('div', { style: styles.clear }) ); }; exports.default = BlockSwatches; },{"../common":318,"lodash/map":282,"react":"react","reactcss":363}],304:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Chrome = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _common = require('../common'); var _ChromeFields = require('./ChromeFields'); var _ChromeFields2 = _interopRequireDefault(_ChromeFields); var _ChromePointer = require('./ChromePointer'); var _ChromePointer2 = _interopRequireDefault(_ChromePointer); var _ChromePointerCircle = require('./ChromePointerCircle'); var _ChromePointerCircle2 = _interopRequireDefault(_ChromePointerCircle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Chrome = exports.Chrome = function Chrome(_ref) { var width = _ref.width, onChange = _ref.onChange, disableAlpha = _ref.disableAlpha, rgb = _ref.rgb, hsl = _ref.hsl, hsv = _ref.hsv, hex = _ref.hex, renderers = _ref.renderers, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className, defaultView = _ref.defaultView; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { picker: { width: width, background: '#fff', borderRadius: '2px', boxShadow: '0 0 2px rgba(0,0,0,.3), 0 4px 8px rgba(0,0,0,.3)', boxSizing: 'initial', fontFamily: 'Menlo' }, saturation: { width: '100%', paddingBottom: '55%', position: 'relative', borderRadius: '2px 2px 0 0', overflow: 'hidden' }, Saturation: { radius: '2px 2px 0 0' }, body: { padding: '16px 16px 12px' }, controls: { display: 'flex' }, color: { width: '32px' }, swatch: { marginTop: '6px', width: '16px', height: '16px', borderRadius: '8px', position: 'relative', overflow: 'hidden' }, active: { absolute: '0px 0px 0px 0px', borderRadius: '8px', boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.1)', background: 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + rgb.a + ')', zIndex: '2' }, toggles: { flex: '1' }, hue: { height: '10px', position: 'relative', marginBottom: '8px' }, Hue: { radius: '2px' }, alpha: { height: '10px', position: 'relative' }, Alpha: { radius: '2px' } }, 'disableAlpha': { color: { width: '22px' }, alpha: { display: 'none' }, hue: { marginBottom: '0px' }, swatch: { width: '10px', height: '10px', marginTop: '0px' } } }, passedStyles), { disableAlpha: disableAlpha }); return _react2.default.createElement( 'div', { style: styles.picker, className: 'chrome-picker ' + className }, _react2.default.createElement( 'div', { style: styles.saturation }, _react2.default.createElement(_common.Saturation, { style: styles.Saturation, hsl: hsl, hsv: hsv, pointer: _ChromePointerCircle2.default, onChange: onChange }) ), _react2.default.createElement( 'div', { style: styles.body }, _react2.default.createElement( 'div', { style: styles.controls, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.color }, _react2.default.createElement( 'div', { style: styles.swatch }, _react2.default.createElement('div', { style: styles.active }), _react2.default.createElement(_common.Checkboard, { renderers: renderers }) ) ), _react2.default.createElement( 'div', { style: styles.toggles }, _react2.default.createElement( 'div', { style: styles.hue }, _react2.default.createElement(_common.Hue, { style: styles.Hue, hsl: hsl, pointer: _ChromePointer2.default, onChange: onChange }) ), _react2.default.createElement( 'div', { style: styles.alpha }, _react2.default.createElement(_common.Alpha, { style: styles.Alpha, rgb: rgb, hsl: hsl, pointer: _ChromePointer2.default, renderers: renderers, onChange: onChange }) ) ) ), _react2.default.createElement(_ChromeFields2.default, { rgb: rgb, hsl: hsl, hex: hex, view: defaultView, onChange: onChange, disableAlpha: disableAlpha }) ) ); }; Chrome.propTypes = { width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), disableAlpha: _propTypes2.default.bool, styles: _propTypes2.default.object, defaultView: _propTypes2.default.oneOf(["hex", "rgb", "hsl"]) }; Chrome.defaultProps = { width: 225, disableAlpha: false, styles: {} }; exports.default = (0, _common.ColorWrap)(Chrome); },{"../common":318,"./ChromeFields":305,"./ChromePointer":306,"./ChromePointerCircle":307,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],305:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ChromeFields = undefined; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _color = require('../../helpers/color'); var color = _interopRequireWildcard(_color); var _isUndefined = require('lodash/isUndefined'); var _isUndefined2 = _interopRequireDefault(_isUndefined); var _common = require('../common'); var _UnfoldMoreHorizontalIcon = require('@icons/material/UnfoldMoreHorizontalIcon'); var _UnfoldMoreHorizontalIcon2 = _interopRequireDefault(_UnfoldMoreHorizontalIcon); 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; } /* eslint-disable react/no-did-mount-set-state, no-param-reassign */ var ChromeFields = exports.ChromeFields = function (_React$Component) { _inherits(ChromeFields, _React$Component); function ChromeFields(props) { _classCallCheck(this, ChromeFields); var _this = _possibleConstructorReturn(this, (ChromeFields.__proto__ || Object.getPrototypeOf(ChromeFields)).call(this)); _this.toggleViews = function () { if (_this.state.view === 'hex') { _this.setState({ view: 'rgb' }); } else if (_this.state.view === 'rgb') { _this.setState({ view: 'hsl' }); } else if (_this.state.view === 'hsl') { if (_this.props.hsl.a === 1) { _this.setState({ view: 'hex' }); } else { _this.setState({ view: 'rgb' }); } } }; _this.handleChange = function (data, e) { if (data.hex) { color.isValidHex(data.hex) && _this.props.onChange({ hex: data.hex, source: 'hex' }, e); } else if (data.r || data.g || data.b) { _this.props.onChange({ r: data.r || _this.props.rgb.r, g: data.g || _this.props.rgb.g, b: data.b || _this.props.rgb.b, source: 'rgb' }, e); } else if (data.a) { if (data.a < 0) { data.a = 0; } else if (data.a > 1) { data.a = 1; } _this.props.onChange({ h: _this.props.hsl.h, s: _this.props.hsl.s, l: _this.props.hsl.l, a: Math.round(data.a * 100) / 100, source: 'rgb' }, e); } else if (data.h || data.s || data.l) { // Remove any occurances of '%'. if (typeof data.s === 'string' && data.s.includes('%')) { data.s = data.s.replace('%', ''); } if (typeof data.l === 'string' && data.l.includes('%')) { data.l = data.l.replace('%', ''); } // We store HSL as a unit interval so we need to override the 1 input to 0.01 if (data.s == 1) { data.s = 0.01; } else if (data.l == 1) { data.l = 0.01; } _this.props.onChange({ h: data.h || _this.props.hsl.h, s: Number(!(0, _isUndefined2.default)(data.s) ? data.s : _this.props.hsl.s), l: Number(!(0, _isUndefined2.default)(data.l) ? data.l : _this.props.hsl.l), source: 'hsl' }, e); } }; _this.showHighlight = function (e) { e.currentTarget.style.background = '#eee'; }; _this.hideHighlight = function (e) { e.currentTarget.style.background = 'transparent'; }; if (props.hsl.a !== 1 && props.view === "hex") { _this.state = { view: "rgb" }; } else { _this.state = { view: props.view }; } return _this; } _createClass(ChromeFields, [{ key: 'render', value: function render() { var _this2 = this; var styles = (0, _reactcss2.default)({ 'default': { wrap: { paddingTop: '16px', display: 'flex' }, fields: { flex: '1', display: 'flex', marginLeft: '-6px' }, field: { paddingLeft: '6px', width: '100%' }, alpha: { paddingLeft: '6px', width: '100%' }, toggle: { width: '32px', textAlign: 'right', position: 'relative' }, icon: { marginRight: '-4px', marginTop: '12px', cursor: 'pointer', position: 'relative' }, iconHighlight: { position: 'absolute', width: '24px', height: '28px', background: '#eee', borderRadius: '4px', top: '10px', left: '12px', display: 'none' }, input: { fontSize: '11px', color: '#333', width: '100%', borderRadius: '2px', border: 'none', boxShadow: 'inset 0 0 0 1px #dadada', height: '21px', textAlign: 'center' }, label: { textTransform: 'uppercase', fontSize: '11px', lineHeight: '11px', color: '#969696', textAlign: 'center', display: 'block', marginTop: '12px' }, svg: { fill: '#333', width: '24px', height: '24px', border: '1px transparent solid', borderRadius: '5px' } }, 'disableAlpha': { alpha: { display: 'none' } } }, this.props, this.state); var fields = void 0; if (this.state.view === 'hex') { fields = _react2.default.createElement( 'div', { style: styles.fields, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.field }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'hex', value: this.props.hex, onChange: this.handleChange }) ) ); } else if (this.state.view === 'rgb') { fields = _react2.default.createElement( 'div', { style: styles.fields, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.field }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'r', value: this.props.rgb.r, onChange: this.handleChange }) ), _react2.default.createElement( 'div', { style: styles.field }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'g', value: this.props.rgb.g, onChange: this.handleChange }) ), _react2.default.createElement( 'div', { style: styles.field }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'b', value: this.props.rgb.b, onChange: this.handleChange }) ), _react2.default.createElement( 'div', { style: styles.alpha }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'a', value: this.props.rgb.a, arrowOffset: 0.01, onChange: this.handleChange }) ) ); } else if (this.state.view === 'hsl') { fields = _react2.default.createElement( 'div', { style: styles.fields, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.field }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'h', value: Math.round(this.props.hsl.h), onChange: this.handleChange }) ), _react2.default.createElement( 'div', { style: styles.field }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 's', value: Math.round(this.props.hsl.s * 100) + '%', onChange: this.handleChange }) ), _react2.default.createElement( 'div', { style: styles.field }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'l', value: Math.round(this.props.hsl.l * 100) + '%', onChange: this.handleChange }) ), _react2.default.createElement( 'div', { style: styles.alpha }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'a', value: this.props.hsl.a, arrowOffset: 0.01, onChange: this.handleChange }) ) ); } return _react2.default.createElement( 'div', { style: styles.wrap, className: 'flexbox-fix' }, fields, _react2.default.createElement( 'div', { style: styles.toggle }, _react2.default.createElement( 'div', { style: styles.icon, onClick: this.toggleViews, ref: function ref(icon) { return _this2.icon = icon; } }, _react2.default.createElement(_UnfoldMoreHorizontalIcon2.default, { style: styles.svg, onMouseOver: this.showHighlight, onMouseEnter: this.showHighlight, onMouseOut: this.hideHighlight }) ) ) ); } }], [{ key: 'getDerivedStateFromProps', value: function getDerivedStateFromProps(nextProps, state) { if (nextProps.hsl.a !== 1 && state.view === 'hex') { return { view: 'rgb' }; } return null; } }]); return ChromeFields; }(_react2.default.Component); ChromeFields.defaultProps = { view: "hex" }; exports.default = ChromeFields; },{"../../helpers/color":350,"../common":318,"@icons/material/UnfoldMoreHorizontalIcon":82,"lodash/isUndefined":279,"react":"react","reactcss":363}],306:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ChromePointer = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ChromePointer = exports.ChromePointer = function ChromePointer() { var styles = (0, _reactcss2.default)({ 'default': { picker: { width: '12px', height: '12px', borderRadius: '6px', transform: 'translate(-6px, -1px)', backgroundColor: 'rgb(248, 248, 248)', boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)' } } }); return _react2.default.createElement('div', { style: styles.picker }); }; exports.default = ChromePointer; },{"react":"react","reactcss":363}],307:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ChromePointerCircle = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ChromePointerCircle = exports.ChromePointerCircle = function ChromePointerCircle() { var styles = (0, _reactcss2.default)({ 'default': { picker: { width: '12px', height: '12px', borderRadius: '6px', boxShadow: 'inset 0 0 0 1px #fff', transform: 'translate(-6px, -6px)' } } }); return _react2.default.createElement('div', { style: styles.picker }); }; exports.default = ChromePointerCircle; },{"react":"react","reactcss":363}],308:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Circle = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _map = require('lodash/map'); var _map2 = _interopRequireDefault(_map); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _materialColors = require('material-colors'); var material = _interopRequireWildcard(_materialColors); var _common = require('../common'); var _CircleSwatch = require('./CircleSwatch'); var _CircleSwatch2 = _interopRequireDefault(_CircleSwatch); 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 }; } var Circle = exports.Circle = function Circle(_ref) { var width = _ref.width, onChange = _ref.onChange, onSwatchHover = _ref.onSwatchHover, colors = _ref.colors, hex = _ref.hex, circleSize = _ref.circleSize, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, circleSpacing = _ref.circleSpacing, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { card: { width: width, display: 'flex', flexWrap: 'wrap', marginRight: -circleSpacing, marginBottom: -circleSpacing } } }, passedStyles)); var handleChange = function handleChange(hexCode, e) { return onChange({ hex: hexCode, source: 'hex' }, e); }; return _react2.default.createElement( 'div', { style: styles.card, className: 'circle-picker ' + className }, (0, _map2.default)(colors, function (c) { return _react2.default.createElement(_CircleSwatch2.default, { key: c, color: c, onClick: handleChange, onSwatchHover: onSwatchHover, active: hex === c.toLowerCase(), circleSize: circleSize, circleSpacing: circleSpacing }); }) ); }; Circle.propTypes = { width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), circleSize: _propTypes2.default.number, circleSpacing: _propTypes2.default.number, styles: _propTypes2.default.object }; Circle.defaultProps = { width: 252, circleSize: 28, circleSpacing: 14, colors: [material.red['500'], material.pink['500'], material.purple['500'], material.deepPurple['500'], material.indigo['500'], material.blue['500'], material.lightBlue['500'], material.cyan['500'], material.teal['500'], material.green['500'], material.lightGreen['500'], material.lime['500'], material.yellow['500'], material.amber['500'], material.orange['500'], material.deepOrange['500'], material.brown['500'], material.blueGrey['500']], styles: {} }; exports.default = (0, _common.ColorWrap)(Circle); },{"../common":318,"./CircleSwatch":309,"lodash/map":282,"lodash/merge":284,"material-colors":293,"prop-types":298,"react":"react","reactcss":363}],309:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.CircleSwatch = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _common = require('../common'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var CircleSwatch = exports.CircleSwatch = function CircleSwatch(_ref) { var color = _ref.color, onClick = _ref.onClick, onSwatchHover = _ref.onSwatchHover, hover = _ref.hover, active = _ref.active, circleSize = _ref.circleSize, circleSpacing = _ref.circleSpacing; var styles = (0, _reactcss2.default)({ 'default': { swatch: { width: circleSize, height: circleSize, marginRight: circleSpacing, marginBottom: circleSpacing, transform: 'scale(1)', transition: '100ms transform ease' }, Swatch: { borderRadius: '50%', background: 'transparent', boxShadow: 'inset 0 0 0 ' + (circleSize / 2 + 1) + 'px ' + color, transition: '100ms box-shadow ease' } }, 'hover': { swatch: { transform: 'scale(1.2)' } }, 'active': { Swatch: { boxShadow: 'inset 0 0 0 3px ' + color } } }, { hover: hover, active: active }); return _react2.default.createElement( 'div', { style: styles.swatch }, _react2.default.createElement(_common.Swatch, { style: styles.Swatch, color: color, onClick: onClick, onHover: onSwatchHover, focusStyle: { boxShadow: styles.Swatch.boxShadow + ', 0 0 5px ' + color } }) ); }; CircleSwatch.defaultProps = { circleSize: 28, circleSpacing: 14 }; exports.default = (0, _reactcss.handleHover)(CircleSwatch); },{"../common":318,"react":"react","reactcss":363}],310:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Alpha = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _alpha = require('../../helpers/alpha'); var alpha = _interopRequireWildcard(_alpha); var _Checkboard = require('./Checkboard'); var _Checkboard2 = _interopRequireDefault(_Checkboard); 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; } var Alpha = exports.Alpha = function (_ref) { _inherits(Alpha, _ref); function Alpha() { var _ref2; var _temp, _this, _ret; _classCallCheck(this, Alpha); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref2 = Alpha.__proto__ || Object.getPrototypeOf(Alpha)).call.apply(_ref2, [this].concat(args))), _this), _this.handleChange = function (e) { var change = alpha.calculateChange(e, _this.props.hsl, _this.props.direction, _this.props.a, _this.container); change && typeof _this.props.onChange === 'function' && _this.props.onChange(change, e); }, _this.handleMouseDown = function (e) { _this.handleChange(e); window.addEventListener('mousemove', _this.handleChange); window.addEventListener('mouseup', _this.handleMouseUp); }, _this.handleMouseUp = function () { _this.unbindEventListeners(); }, _this.unbindEventListeners = function () { window.removeEventListener('mousemove', _this.handleChange); window.removeEventListener('mouseup', _this.handleMouseUp); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Alpha, [{ key: 'componentWillUnmount', value: function componentWillUnmount() { this.unbindEventListeners(); } }, { key: 'render', value: function render() { var _this2 = this; var rgb = this.props.rgb; var styles = (0, _reactcss2.default)({ 'default': { alpha: { absolute: '0px 0px 0px 0px', borderRadius: this.props.radius }, checkboard: { absolute: '0px 0px 0px 0px', overflow: 'hidden', borderRadius: this.props.radius }, gradient: { absolute: '0px 0px 0px 0px', background: 'linear-gradient(to right, rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 0) 0%,\n rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 1) 100%)', boxShadow: this.props.shadow, borderRadius: this.props.radius }, container: { position: 'relative', height: '100%', margin: '0 3px' }, pointer: { position: 'absolute', left: rgb.a * 100 + '%' }, slider: { width: '4px', borderRadius: '1px', height: '8px', boxShadow: '0 0 2px rgba(0, 0, 0, .6)', background: '#fff', marginTop: '1px', transform: 'translateX(-2px)' } }, 'vertical': { gradient: { background: 'linear-gradient(to bottom, rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 0) 0%,\n rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 1) 100%)' }, pointer: { left: 0, top: rgb.a * 100 + '%' } }, 'overwrite': _extends({}, this.props.style) }, { vertical: this.props.direction === 'vertical', overwrite: true }); return _react2.default.createElement( 'div', { style: styles.alpha }, _react2.default.createElement( 'div', { style: styles.checkboard }, _react2.default.createElement(_Checkboard2.default, { renderers: this.props.renderers }) ), _react2.default.createElement('div', { style: styles.gradient }), _react2.default.createElement( 'div', { style: styles.container, ref: function ref(container) { return _this2.container = container; }, onMouseDown: this.handleMouseDown, onTouchMove: this.handleChange, onTouchStart: this.handleChange }, _react2.default.createElement( 'div', { style: styles.pointer }, this.props.pointer ? _react2.default.createElement(this.props.pointer, this.props) : _react2.default.createElement('div', { style: styles.slider }) ) ) ); } }]); return Alpha; }(_react.PureComponent || _react.Component); exports.default = Alpha; },{"../../helpers/alpha":348,"./Checkboard":311,"react":"react","reactcss":363}],311:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Checkboard = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _checkboard = require('../../helpers/checkboard'); var checkboard = _interopRequireWildcard(_checkboard); 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 }; } var Checkboard = exports.Checkboard = function Checkboard(_ref) { var white = _ref.white, grey = _ref.grey, size = _ref.size, renderers = _ref.renderers, borderRadius = _ref.borderRadius, boxShadow = _ref.boxShadow, children = _ref.children; var styles = (0, _reactcss2.default)({ 'default': { grid: { borderRadius: borderRadius, boxShadow: boxShadow, absolute: '0px 0px 0px 0px', background: 'url(' + checkboard.get(white, grey, size, renderers.canvas) + ') center left' } } }); return (0, _react.isValidElement)(children) ? _react2.default.cloneElement(children, _extends({}, children.props, { style: _extends({}, children.props.style, styles.grid) })) : _react2.default.createElement('div', { style: styles.grid }); }; Checkboard.defaultProps = { size: 8, white: 'transparent', grey: 'rgba(0,0,0,.08)', renderers: {} }; exports.default = Checkboard; },{"../../helpers/checkboard":349,"react":"react","reactcss":363}],312:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ColorWrap = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _debounce = require('lodash/debounce'); var _debounce2 = _interopRequireDefault(_debounce); var _color = require('../../helpers/color'); var color = _interopRequireWildcard(_color); 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; } var ColorWrap = exports.ColorWrap = function ColorWrap(Picker) { var ColorPicker = function (_ref) { _inherits(ColorPicker, _ref); function ColorPicker(props) { _classCallCheck(this, ColorPicker); var _this = _possibleConstructorReturn(this, (ColorPicker.__proto__ || Object.getPrototypeOf(ColorPicker)).call(this)); _this.handleChange = function (data, event) { var isValidColor = color.simpleCheckForValidColor(data); if (isValidColor) { var colors = color.toState(data, data.h || _this.state.oldHue); _this.setState(colors); _this.props.onChangeComplete && _this.debounce(_this.props.onChangeComplete, colors, event); _this.props.onChange && _this.props.onChange(colors, event); } }; _this.handleSwatchHover = function (data, event) { var isValidColor = color.simpleCheckForValidColor(data); if (isValidColor) { var colors = color.toState(data, data.h || _this.state.oldHue); _this.props.onSwatchHover && _this.props.onSwatchHover(colors, event); } }; _this.state = _extends({}, color.toState(props.color, 0)); _this.debounce = (0, _debounce2.default)(function (fn, data, event) { fn(data, event); }, 100); return _this; } _createClass(ColorPicker, [{ key: 'render', value: function render() { var optionalEvents = {}; if (this.props.onSwatchHover) { optionalEvents.onSwatchHover = this.handleSwatchHover; } return _react2.default.createElement(Picker, _extends({}, this.props, this.state, { onChange: this.handleChange }, optionalEvents)); } }], [{ key: 'getDerivedStateFromProps', value: function getDerivedStateFromProps(nextProps, state) { return _extends({}, color.toState(nextProps.color, state.oldHue)); } }]); return ColorPicker; }(_react.PureComponent || _react.Component); ColorPicker.propTypes = _extends({}, Picker.propTypes); ColorPicker.defaultProps = _extends({}, Picker.defaultProps, { color: { h: 250, s: 0.50, l: 0.20, a: 1 } }); return ColorPicker; }; exports.default = ColorWrap; },{"../../helpers/color":350,"lodash/debounce":256,"react":"react"}],313:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.EditableInput = undefined; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return 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; } var DEFAULT_ARROW_OFFSET = 1; var UP_KEY_CODE = 38; var DOWN_KEY_CODE = 40; var VALID_KEY_CODES = [UP_KEY_CODE, DOWN_KEY_CODE]; var isValidKeyCode = function isValidKeyCode(keyCode) { return VALID_KEY_CODES.indexOf(keyCode) > -1; }; var getNumberValue = function getNumberValue(value) { return Number(String(value).replace(/%/g, '')); }; var idCounter = 1; var EditableInput = exports.EditableInput = function (_ref) { _inherits(EditableInput, _ref); function EditableInput(props) { _classCallCheck(this, EditableInput); var _this = _possibleConstructorReturn(this, (EditableInput.__proto__ || Object.getPrototypeOf(EditableInput)).call(this)); _this.handleBlur = function () { if (_this.state.blurValue) { _this.setState({ value: _this.state.blurValue, blurValue: null }); } }; _this.handleChange = function (e) { _this.setUpdatedValue(e.target.value, e); }; _this.handleKeyDown = function (e) { // In case `e.target.value` is a percentage remove the `%` character // and update accordingly with a percentage // https://github.com/casesandberg/react-color/issues/383 var value = getNumberValue(e.target.value); if (!isNaN(value) && isValidKeyCode(e.keyCode)) { var offset = _this.getArrowOffset(); var updatedValue = e.keyCode === UP_KEY_CODE ? value + offset : value - offset; _this.setUpdatedValue(updatedValue, e); } }; _this.handleDrag = function (e) { if (_this.props.dragLabel) { var newValue = Math.round(_this.props.value + e.movementX); if (newValue >= 0 && newValue <= _this.props.dragMax) { _this.props.onChange && _this.props.onChange(_this.getValueObjectWithLabel(newValue), e); } } }; _this.handleMouseDown = function (e) { if (_this.props.dragLabel) { e.preventDefault(); _this.handleDrag(e); window.addEventListener('mousemove', _this.handleDrag); window.addEventListener('mouseup', _this.handleMouseUp); } }; _this.handleMouseUp = function () { _this.unbindEventListeners(); }; _this.unbindEventListeners = function () { window.removeEventListener('mousemove', _this.handleDrag); window.removeEventListener('mouseup', _this.handleMouseUp); }; _this.state = { value: String(props.value).toUpperCase(), blurValue: String(props.value).toUpperCase() }; _this.inputId = 'rc-editable-input-' + idCounter++; return _this; } _createClass(EditableInput, [{ key: 'componentDidUpdate', value: function componentDidUpdate(prevProps, prevState) { if (this.props.value !== this.state.value && (prevProps.value !== this.props.value || prevState.value !== this.state.value)) { if (this.input === document.activeElement) { this.setState({ blurValue: String(this.props.value).toUpperCase() }); } else { this.setState({ value: String(this.props.value).toUpperCase(), blurValue: !this.state.blurValue && String(this.props.value).toUpperCase() }); } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unbindEventListeners(); } }, { key: 'getValueObjectWithLabel', value: function getValueObjectWithLabel(value) { return _defineProperty({}, this.props.label, value); } }, { key: 'getArrowOffset', value: function getArrowOffset() { return this.props.arrowOffset || DEFAULT_ARROW_OFFSET; } }, { key: 'setUpdatedValue', value: function setUpdatedValue(value, e) { var onChangeValue = this.props.label ? this.getValueObjectWithLabel(value) : value; this.props.onChange && this.props.onChange(onChangeValue, e); this.setState({ value: value }); } }, { key: 'render', value: function render() { var _this2 = this; var styles = (0, _reactcss2.default)({ 'default': { wrap: { position: 'relative' } }, 'user-override': { wrap: this.props.style && this.props.style.wrap ? this.props.style.wrap : {}, input: this.props.style && this.props.style.input ? this.props.style.input : {}, label: this.props.style && this.props.style.label ? this.props.style.label : {} }, 'dragLabel-true': { label: { cursor: 'ew-resize' } } }, { 'user-override': true }, this.props); return _react2.default.createElement( 'div', { style: styles.wrap }, _react2.default.createElement('input', { id: this.inputId, style: styles.input, ref: function ref(input) { return _this2.input = input; }, value: this.state.value, onKeyDown: this.handleKeyDown, onChange: this.handleChange, onBlur: this.handleBlur, placeholder: this.props.placeholder, spellCheck: 'false' }), this.props.label && !this.props.hideLabel ? _react2.default.createElement( 'label', { htmlFor: this.inputId, style: styles.label, onMouseDown: this.handleMouseDown }, this.props.label ) : null ); } }]); return EditableInput; }(_react.PureComponent || _react.Component); exports.default = EditableInput; },{"react":"react","reactcss":363}],314:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Hue = undefined; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _hue = require('../../helpers/hue'); var hue = _interopRequireWildcard(_hue); 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; } var Hue = exports.Hue = function (_ref) { _inherits(Hue, _ref); function Hue() { var _ref2; var _temp, _this, _ret; _classCallCheck(this, Hue); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref2 = Hue.__proto__ || Object.getPrototypeOf(Hue)).call.apply(_ref2, [this].concat(args))), _this), _this.handleChange = function (e) { var change = hue.calculateChange(e, _this.props.direction, _this.props.hsl, _this.container); change && typeof _this.props.onChange === 'function' && _this.props.onChange(change, e); }, _this.handleMouseDown = function (e) { _this.handleChange(e); window.addEventListener('mousemove', _this.handleChange); window.addEventListener('mouseup', _this.handleMouseUp); }, _this.handleMouseUp = function () { _this.unbindEventListeners(); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Hue, [{ key: 'componentWillUnmount', value: function componentWillUnmount() { this.unbindEventListeners(); } }, { key: 'unbindEventListeners', value: function unbindEventListeners() { window.removeEventListener('mousemove', this.handleChange); window.removeEventListener('mouseup', this.handleMouseUp); } }, { key: 'render', value: function render() { var _this2 = this; var _props$direction = this.props.direction, direction = _props$direction === undefined ? 'horizontal' : _props$direction; var styles = (0, _reactcss2.default)({ 'default': { hue: { absolute: '0px 0px 0px 0px', borderRadius: this.props.radius, boxShadow: this.props.shadow }, container: { padding: '0 2px', position: 'relative', height: '100%', borderRadius: this.props.radius }, pointer: { position: 'absolute', left: this.props.hsl.h * 100 / 360 + '%' }, slider: { marginTop: '1px', width: '4px', borderRadius: '1px', height: '8px', boxShadow: '0 0 2px rgba(0, 0, 0, .6)', background: '#fff', transform: 'translateX(-2px)' } }, 'vertical': { pointer: { left: '0px', top: -(this.props.hsl.h * 100 / 360) + 100 + '%' } } }, { vertical: direction === 'vertical' }); return _react2.default.createElement( 'div', { style: styles.hue }, _react2.default.createElement( 'div', { className: 'hue-' + direction, style: styles.container, ref: function ref(container) { return _this2.container = container; }, onMouseDown: this.handleMouseDown, onTouchMove: this.handleChange, onTouchStart: this.handleChange }, _react2.default.createElement( 'style', null, '\n .hue-horizontal {\n background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0\n 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n background: -webkit-linear-gradient(to right, #f00 0%, #ff0\n 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n }\n\n .hue-vertical {\n background: linear-gradient(to top, #f00 0%, #ff0 17%, #0f0 33%,\n #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n background: -webkit-linear-gradient(to top, #f00 0%, #ff0 17%,\n #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n }\n ' ), _react2.default.createElement( 'div', { style: styles.pointer }, this.props.pointer ? _react2.default.createElement(this.props.pointer, this.props) : _react2.default.createElement('div', { style: styles.slider }) ) ) ); } }]); return Hue; }(_react.PureComponent || _react.Component); exports.default = Hue; },{"../../helpers/hue":351,"react":"react","reactcss":363}],315:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Raised = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Raised = exports.Raised = function Raised(_ref) { var zDepth = _ref.zDepth, radius = _ref.radius, background = _ref.background, children = _ref.children, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { wrap: { position: 'relative', display: 'inline-block' }, content: { position: 'relative' }, bg: { absolute: '0px 0px 0px 0px', boxShadow: '0 ' + zDepth + 'px ' + zDepth * 4 + 'px rgba(0,0,0,.24)', borderRadius: radius, background: background } }, 'zDepth-0': { bg: { boxShadow: 'none' } }, 'zDepth-1': { bg: { boxShadow: '0 2px 10px rgba(0,0,0,.12), 0 2px 5px rgba(0,0,0,.16)' } }, 'zDepth-2': { bg: { boxShadow: '0 6px 20px rgba(0,0,0,.19), 0 8px 17px rgba(0,0,0,.2)' } }, 'zDepth-3': { bg: { boxShadow: '0 17px 50px rgba(0,0,0,.19), 0 12px 15px rgba(0,0,0,.24)' } }, 'zDepth-4': { bg: { boxShadow: '0 25px 55px rgba(0,0,0,.21), 0 16px 28px rgba(0,0,0,.22)' } }, 'zDepth-5': { bg: { boxShadow: '0 40px 77px rgba(0,0,0,.22), 0 27px 24px rgba(0,0,0,.2)' } }, 'square': { bg: { borderRadius: '0' } }, 'circle': { bg: { borderRadius: '50%' } } }, passedStyles), { 'zDepth-1': zDepth === 1 }); return _react2.default.createElement( 'div', { style: styles.wrap }, _react2.default.createElement('div', { style: styles.bg }), _react2.default.createElement( 'div', { style: styles.content }, children ) ); }; Raised.propTypes = { background: _propTypes2.default.string, zDepth: _propTypes2.default.oneOf([0, 1, 2, 3, 4, 5]), radius: _propTypes2.default.number, styles: _propTypes2.default.object }; Raised.defaultProps = { background: '#fff', zDepth: 1, radius: 2, styles: {} }; exports.default = Raised; },{"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],316:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Saturation = undefined; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _throttle = require('lodash/throttle'); var _throttle2 = _interopRequireDefault(_throttle); var _saturation = require('../../helpers/saturation'); var saturation = _interopRequireWildcard(_saturation); 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; } var Saturation = exports.Saturation = function (_ref) { _inherits(Saturation, _ref); function Saturation(props) { _classCallCheck(this, Saturation); var _this = _possibleConstructorReturn(this, (Saturation.__proto__ || Object.getPrototypeOf(Saturation)).call(this, props)); _this.handleChange = function (e) { typeof _this.props.onChange === 'function' && _this.throttle(_this.props.onChange, saturation.calculateChange(e, _this.props.hsl, _this.container), e); }; _this.handleMouseDown = function (e) { _this.handleChange(e); var renderWindow = _this.getContainerRenderWindow(); renderWindow.addEventListener('mousemove', _this.handleChange); renderWindow.addEventListener('mouseup', _this.handleMouseUp); }; _this.handleMouseUp = function () { _this.unbindEventListeners(); }; _this.throttle = (0, _throttle2.default)(function (fn, data, e) { fn(data, e); }, 50); return _this; } _createClass(Saturation, [{ key: 'componentWillUnmount', value: function componentWillUnmount() { this.throttle.cancel(); this.unbindEventListeners(); } }, { key: 'getContainerRenderWindow', value: function getContainerRenderWindow() { var container = this.container; var renderWindow = window; while (!renderWindow.document.contains(container) && renderWindow.parent !== renderWindow) { renderWindow = renderWindow.parent; } return renderWindow; } }, { key: 'unbindEventListeners', value: function unbindEventListeners() { var renderWindow = this.getContainerRenderWindow(); renderWindow.removeEventListener('mousemove', this.handleChange); renderWindow.removeEventListener('mouseup', this.handleMouseUp); } }, { key: 'render', value: function render() { var _this2 = this; var _ref2 = this.props.style || {}, color = _ref2.color, white = _ref2.white, black = _ref2.black, pointer = _ref2.pointer, circle = _ref2.circle; var styles = (0, _reactcss2.default)({ 'default': { color: { absolute: '0px 0px 0px 0px', background: 'hsl(' + this.props.hsl.h + ',100%, 50%)', borderRadius: this.props.radius }, white: { absolute: '0px 0px 0px 0px', borderRadius: this.props.radius }, black: { absolute: '0px 0px 0px 0px', boxShadow: this.props.shadow, borderRadius: this.props.radius }, pointer: { position: 'absolute', top: -(this.props.hsv.v * 100) + 100 + '%', left: this.props.hsv.s * 100 + '%', cursor: 'default' }, circle: { width: '4px', height: '4px', boxShadow: '0 0 0 1.5px #fff, inset 0 0 1px 1px rgba(0,0,0,.3),\n 0 0 1px 2px rgba(0,0,0,.4)', borderRadius: '50%', cursor: 'hand', transform: 'translate(-2px, -2px)' } }, 'custom': { color: color, white: white, black: black, pointer: pointer, circle: circle } }, { 'custom': !!this.props.style }); return _react2.default.createElement( 'div', { style: styles.color, ref: function ref(container) { return _this2.container = container; }, onMouseDown: this.handleMouseDown, onTouchMove: this.handleChange, onTouchStart: this.handleChange }, _react2.default.createElement( 'style', null, '\n .saturation-white {\n background: -webkit-linear-gradient(to right, #fff, rgba(255,255,255,0));\n background: linear-gradient(to right, #fff, rgba(255,255,255,0));\n }\n .saturation-black {\n background: -webkit-linear-gradient(to top, #000, rgba(0,0,0,0));\n background: linear-gradient(to top, #000, rgba(0,0,0,0));\n }\n ' ), _react2.default.createElement( 'div', { style: styles.white, className: 'saturation-white' }, _react2.default.createElement('div', { style: styles.black, className: 'saturation-black' }), _react2.default.createElement( 'div', { style: styles.pointer }, this.props.pointer ? _react2.default.createElement(this.props.pointer, this.props) : _react2.default.createElement('div', { style: styles.circle }) ) ) ); } }]); return Saturation; }(_react.PureComponent || _react.Component); exports.default = Saturation; },{"../../helpers/saturation":353,"lodash/throttle":289,"react":"react","reactcss":363}],317:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Swatch = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _interaction = require('../../helpers/interaction'); var _Checkboard = require('./Checkboard'); var _Checkboard2 = _interopRequireDefault(_Checkboard); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ENTER = 13; var Swatch = exports.Swatch = function Swatch(_ref) { var color = _ref.color, style = _ref.style, _ref$onClick = _ref.onClick, onClick = _ref$onClick === undefined ? function () {} : _ref$onClick, onHover = _ref.onHover, _ref$title = _ref.title, title = _ref$title === undefined ? color : _ref$title, children = _ref.children, focus = _ref.focus, _ref$focusStyle = _ref.focusStyle, focusStyle = _ref$focusStyle === undefined ? {} : _ref$focusStyle; var transparent = color === 'transparent'; var styles = (0, _reactcss2.default)({ default: { swatch: _extends({ background: color, height: '100%', width: '100%', cursor: 'pointer', position: 'relative', outline: 'none' }, style, focus ? focusStyle : {}) } }); var handleClick = function handleClick(e) { return onClick(color, e); }; var handleKeyDown = function handleKeyDown(e) { return e.keyCode === ENTER && onClick(color, e); }; var handleHover = function handleHover(e) { return onHover(color, e); }; var optionalEvents = {}; if (onHover) { optionalEvents.onMouseOver = handleHover; } return _react2.default.createElement( 'div', _extends({ style: styles.swatch, onClick: handleClick, title: title, tabIndex: 0, onKeyDown: handleKeyDown }, optionalEvents), children, transparent && _react2.default.createElement(_Checkboard2.default, { borderRadius: styles.swatch.borderRadius, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.1)' }) ); }; exports.default = (0, _interaction.handleFocus)(Swatch); },{"../../helpers/interaction":352,"./Checkboard":311,"react":"react","reactcss":363}],318:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Alpha = require('./Alpha'); Object.defineProperty(exports, 'Alpha', { enumerable: true, get: function get() { return _interopRequireDefault(_Alpha).default; } }); var _Checkboard = require('./Checkboard'); Object.defineProperty(exports, 'Checkboard', { enumerable: true, get: function get() { return _interopRequireDefault(_Checkboard).default; } }); var _EditableInput = require('./EditableInput'); Object.defineProperty(exports, 'EditableInput', { enumerable: true, get: function get() { return _interopRequireDefault(_EditableInput).default; } }); var _Hue = require('./Hue'); Object.defineProperty(exports, 'Hue', { enumerable: true, get: function get() { return _interopRequireDefault(_Hue).default; } }); var _Raised = require('./Raised'); Object.defineProperty(exports, 'Raised', { enumerable: true, get: function get() { return _interopRequireDefault(_Raised).default; } }); var _Saturation = require('./Saturation'); Object.defineProperty(exports, 'Saturation', { enumerable: true, get: function get() { return _interopRequireDefault(_Saturation).default; } }); var _ColorWrap = require('./ColorWrap'); Object.defineProperty(exports, 'ColorWrap', { enumerable: true, get: function get() { return _interopRequireDefault(_ColorWrap).default; } }); var _Swatch = require('./Swatch'); Object.defineProperty(exports, 'Swatch', { enumerable: true, get: function get() { return _interopRequireDefault(_Swatch).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } },{"./Alpha":310,"./Checkboard":311,"./ColorWrap":312,"./EditableInput":313,"./Hue":314,"./Raised":315,"./Saturation":316,"./Swatch":317}],319:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Compact = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _map = require('lodash/map'); var _map2 = _interopRequireDefault(_map); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _color = require('../../helpers/color'); var color = _interopRequireWildcard(_color); var _common = require('../common'); var _CompactColor = require('./CompactColor'); var _CompactColor2 = _interopRequireDefault(_CompactColor); var _CompactFields = require('./CompactFields'); var _CompactFields2 = _interopRequireDefault(_CompactFields); 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 }; } var Compact = exports.Compact = function Compact(_ref) { var onChange = _ref.onChange, onSwatchHover = _ref.onSwatchHover, colors = _ref.colors, hex = _ref.hex, rgb = _ref.rgb, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { Compact: { background: '#f6f6f6', radius: '4px' }, compact: { paddingTop: '5px', paddingLeft: '5px', boxSizing: 'initial', width: '240px' }, clear: { clear: 'both' } } }, passedStyles)); var handleChange = function handleChange(data, e) { if (data.hex) { color.isValidHex(data.hex) && onChange({ hex: data.hex, source: 'hex' }, e); } else { onChange(data, e); } }; return _react2.default.createElement( _common.Raised, { style: styles.Compact, styles: passedStyles }, _react2.default.createElement( 'div', { style: styles.compact, className: 'compact-picker ' + className }, _react2.default.createElement( 'div', null, (0, _map2.default)(colors, function (c) { return _react2.default.createElement(_CompactColor2.default, { key: c, color: c, active: c.toLowerCase() === hex, onClick: handleChange, onSwatchHover: onSwatchHover }); }), _react2.default.createElement('div', { style: styles.clear }) ), _react2.default.createElement(_CompactFields2.default, { hex: hex, rgb: rgb, onChange: handleChange }) ) ); }; Compact.propTypes = { colors: _propTypes2.default.arrayOf(_propTypes2.default.string), styles: _propTypes2.default.object }; Compact.defaultProps = { colors: ['#4D4D4D', '#999999', '#FFFFFF', '#F44E3B', '#FE9200', '#FCDC00', '#DBDF00', '#A4DD00', '#68CCCA', '#73D8FF', '#AEA1FF', '#FDA1FF', '#333333', '#808080', '#cccccc', '#D33115', '#E27300', '#FCC400', '#B0BC00', '#68BC00', '#16A5A5', '#009CE0', '#7B64FF', '#FA28FF', '#000000', '#666666', '#B3B3B3', '#9F0500', '#C45100', '#FB9E00', '#808900', '#194D33', '#0C797D', '#0062B1', '#653294', '#AB149E'], styles: {} }; exports.default = (0, _common.ColorWrap)(Compact); },{"../../helpers/color":350,"../common":318,"./CompactColor":320,"./CompactFields":321,"lodash/map":282,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],320:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.CompactColor = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _color = require('../../helpers/color'); var colorUtils = _interopRequireWildcard(_color); var _common = require('../common'); 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 }; } var CompactColor = exports.CompactColor = function CompactColor(_ref) { var color = _ref.color, _ref$onClick = _ref.onClick, onClick = _ref$onClick === undefined ? function () {} : _ref$onClick, onSwatchHover = _ref.onSwatchHover, active = _ref.active; var styles = (0, _reactcss2.default)({ 'default': { color: { background: color, width: '15px', height: '15px', float: 'left', marginRight: '5px', marginBottom: '5px', position: 'relative', cursor: 'pointer' }, dot: { absolute: '5px 5px 5px 5px', background: colorUtils.getContrastingColor(color), borderRadius: '50%', opacity: '0' } }, 'active': { dot: { opacity: '1' } }, 'color-#FFFFFF': { color: { boxShadow: 'inset 0 0 0 1px #ddd' }, dot: { background: '#000' } }, 'transparent': { dot: { background: '#000' } } }, { active: active, 'color-#FFFFFF': color === '#FFFFFF', 'transparent': color === 'transparent' }); return _react2.default.createElement( _common.Swatch, { style: styles.color, color: color, onClick: onClick, onHover: onSwatchHover, focusStyle: { boxShadow: '0 0 4px ' + color } }, _react2.default.createElement('div', { style: styles.dot }) ); }; exports.default = CompactColor; },{"../../helpers/color":350,"../common":318,"react":"react","reactcss":363}],321:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.CompactFields = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _common = require('../common'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var CompactFields = exports.CompactFields = function CompactFields(_ref) { var hex = _ref.hex, rgb = _ref.rgb, onChange = _ref.onChange; var styles = (0, _reactcss2.default)({ 'default': { fields: { display: 'flex', paddingBottom: '6px', paddingRight: '5px', position: 'relative' }, active: { position: 'absolute', top: '6px', left: '5px', height: '9px', width: '9px', background: hex }, HEXwrap: { flex: '6', position: 'relative' }, HEXinput: { width: '80%', padding: '0px', paddingLeft: '20%', border: 'none', outline: 'none', background: 'none', fontSize: '12px', color: '#333', height: '16px' }, HEXlabel: { display: 'none' }, RGBwrap: { flex: '3', position: 'relative' }, RGBinput: { width: '70%', padding: '0px', paddingLeft: '30%', border: 'none', outline: 'none', background: 'none', fontSize: '12px', color: '#333', height: '16px' }, RGBlabel: { position: 'absolute', top: '3px', left: '0px', lineHeight: '16px', textTransform: 'uppercase', fontSize: '12px', color: '#999' } } }); var handleChange = function handleChange(data, e) { if (data.r || data.g || data.b) { onChange({ r: data.r || rgb.r, g: data.g || rgb.g, b: data.b || rgb.b, source: 'rgb' }, e); } else { onChange({ hex: data.hex, source: 'hex' }, e); } }; return _react2.default.createElement( 'div', { style: styles.fields, className: 'flexbox-fix' }, _react2.default.createElement('div', { style: styles.active }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.HEXwrap, input: styles.HEXinput, label: styles.HEXlabel }, label: 'hex', value: hex, onChange: handleChange }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'r', value: rgb.r, onChange: handleChange }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'g', value: rgb.g, onChange: handleChange }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'b', value: rgb.b, onChange: handleChange }) ); }; exports.default = CompactFields; },{"../common":318,"react":"react","reactcss":363}],322:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Github = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _map = require('lodash/map'); var _map2 = _interopRequireDefault(_map); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _common = require('../common'); var _GithubSwatch = require('./GithubSwatch'); var _GithubSwatch2 = _interopRequireDefault(_GithubSwatch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Github = exports.Github = function Github(_ref) { var width = _ref.width, colors = _ref.colors, onChange = _ref.onChange, onSwatchHover = _ref.onSwatchHover, triangle = _ref.triangle, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { card: { width: width, background: '#fff', border: '1px solid rgba(0,0,0,0.2)', boxShadow: '0 3px 12px rgba(0,0,0,0.15)', borderRadius: '4px', position: 'relative', padding: '5px', display: 'flex', flexWrap: 'wrap' }, triangle: { position: 'absolute', border: '7px solid transparent', borderBottomColor: '#fff' }, triangleShadow: { position: 'absolute', border: '8px solid transparent', borderBottomColor: 'rgba(0,0,0,0.15)' } }, 'hide-triangle': { triangle: { display: 'none' }, triangleShadow: { display: 'none' } }, 'top-left-triangle': { triangle: { top: '-14px', left: '10px' }, triangleShadow: { top: '-16px', left: '9px' } }, 'top-right-triangle': { triangle: { top: '-14px', right: '10px' }, triangleShadow: { top: '-16px', right: '9px' } }, 'bottom-left-triangle': { triangle: { top: '35px', left: '10px', transform: 'rotate(180deg)' }, triangleShadow: { top: '37px', left: '9px', transform: 'rotate(180deg)' } }, 'bottom-right-triangle': { triangle: { top: '35px', right: '10px', transform: 'rotate(180deg)' }, triangleShadow: { top: '37px', right: '9px', transform: 'rotate(180deg)' } } }, passedStyles), { 'hide-triangle': triangle === 'hide', 'top-left-triangle': triangle === 'top-left', 'top-right-triangle': triangle === 'top-right', 'bottom-left-triangle': triangle === 'bottom-left', 'bottom-right-triangle': triangle === 'bottom-right' }); var handleChange = function handleChange(hex, e) { return onChange({ hex: hex, source: 'hex' }, e); }; return _react2.default.createElement( 'div', { style: styles.card, className: 'github-picker ' + className }, _react2.default.createElement('div', { style: styles.triangleShadow }), _react2.default.createElement('div', { style: styles.triangle }), (0, _map2.default)(colors, function (c) { return _react2.default.createElement(_GithubSwatch2.default, { color: c, key: c, onClick: handleChange, onSwatchHover: onSwatchHover }); }) ); }; Github.propTypes = { width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), colors: _propTypes2.default.arrayOf(_propTypes2.default.string), triangle: _propTypes2.default.oneOf(['hide', 'top-left', 'top-right', 'bottom-left', 'bottom-right']), styles: _propTypes2.default.object }; Github.defaultProps = { width: 200, colors: ['#B80000', '#DB3E00', '#FCCB00', '#008B02', '#006B76', '#1273DE', '#004DCF', '#5300EB', '#EB9694', '#FAD0C3', '#FEF3BD', '#C1E1C5', '#BEDADC', '#C4DEF6', '#BED3F3', '#D4C4FB'], triangle: 'top-left', styles: {} }; exports.default = (0, _common.ColorWrap)(Github); },{"../common":318,"./GithubSwatch":323,"lodash/map":282,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],323:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.GithubSwatch = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _common = require('../common'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var GithubSwatch = exports.GithubSwatch = function GithubSwatch(_ref) { var hover = _ref.hover, color = _ref.color, onClick = _ref.onClick, onSwatchHover = _ref.onSwatchHover; var hoverSwatch = { position: 'relative', zIndex: '2', outline: '2px solid #fff', boxShadow: '0 0 5px 2px rgba(0,0,0,0.25)' }; var styles = (0, _reactcss2.default)({ 'default': { swatch: { width: '25px', height: '25px', fontSize: '0' } }, 'hover': { swatch: hoverSwatch } }, { hover: hover }); return _react2.default.createElement( 'div', { style: styles.swatch }, _react2.default.createElement(_common.Swatch, { color: color, onClick: onClick, onHover: onSwatchHover, focusStyle: hoverSwatch }) ); }; exports.default = (0, _reactcss.handleHover)(GithubSwatch); },{"../common":318,"react":"react","reactcss":363}],324:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Google = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _common = require('../common'); var _GooglePointerCircle = require('./GooglePointerCircle'); var _GooglePointerCircle2 = _interopRequireDefault(_GooglePointerCircle); var _GooglePointer = require('./GooglePointer'); var _GooglePointer2 = _interopRequireDefault(_GooglePointer); var _GoogleFields = require('./GoogleFields'); var _GoogleFields2 = _interopRequireDefault(_GoogleFields); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Google = exports.Google = function Google(_ref) { var width = _ref.width, onChange = _ref.onChange, rgb = _ref.rgb, hsl = _ref.hsl, hsv = _ref.hsv, hex = _ref.hex, header = _ref.header, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { picker: { width: width, background: '#fff', border: '1px solid #dfe1e5', boxSizing: 'initial', display: 'flex', flexWrap: 'wrap', borderRadius: '8px 8px 0px 0px' }, head: { height: '57px', width: '100%', paddingTop: '16px', paddingBottom: '16px', paddingLeft: '16px', fontSize: '20px', boxSizing: 'border-box', fontFamily: 'Roboto-Regular,HelveticaNeue,Arial,sans-serif' }, saturation: { width: '70%', padding: '0px', position: 'relative', overflow: 'hidden' }, swatch: { width: '30%', height: '228px', padding: '0px', background: 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', 1)', position: 'relative', overflow: 'hidden' }, body: { margin: 'auto', width: '95%' }, controls: { display: 'flex', boxSizing: 'border-box', height: '52px', paddingTop: '22px' }, color: { width: '32px' }, hue: { height: '8px', position: 'relative', margin: '0px 16px 0px 16px', width: '100%' }, Hue: { radius: '2px' } } }, passedStyles)); return _react2.default.createElement( 'div', { style: styles.picker, className: 'google-picker ' + className }, _react2.default.createElement( 'div', { style: styles.head }, header ), _react2.default.createElement('div', { style: styles.swatch }), _react2.default.createElement( 'div', { style: styles.saturation }, _react2.default.createElement(_common.Saturation, { hsl: hsl, hsv: hsv, pointer: _GooglePointerCircle2.default, onChange: onChange }) ), _react2.default.createElement( 'div', { style: styles.body }, _react2.default.createElement( 'div', { style: styles.controls, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.hue }, _react2.default.createElement(_common.Hue, { style: styles.Hue, hsl: hsl, radius: '4px', pointer: _GooglePointer2.default, onChange: onChange }) ) ), _react2.default.createElement(_GoogleFields2.default, { rgb: rgb, hsl: hsl, hex: hex, hsv: hsv, onChange: onChange }) ) ); }; Google.propTypes = { width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), styles: _propTypes2.default.object, header: _propTypes2.default.string }; Google.defaultProps = { width: 652, styles: {}, header: 'Color picker' }; exports.default = (0, _common.ColorWrap)(Google); },{"../common":318,"./GoogleFields":325,"./GooglePointer":326,"./GooglePointerCircle":327,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],325:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.GoogleFields = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _color = require('../../helpers/color'); var color = _interopRequireWildcard(_color); var _common = require('../common'); 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 }; } var GoogleFields = exports.GoogleFields = function GoogleFields(_ref) { var onChange = _ref.onChange, rgb = _ref.rgb, hsl = _ref.hsl, hex = _ref.hex, hsv = _ref.hsv; var handleChange = function handleChange(data, e) { if (data.hex) { color.isValidHex(data.hex) && onChange({ hex: data.hex, source: 'hex' }, e); } else if (data.rgb) { var values = data.rgb.split(','); color.isvalidColorString(data.rgb, 'rgb') && onChange({ r: values[0], g: values[1], b: values[2], a: 1, source: 'rgb' }, e); } else if (data.hsv) { var _values = data.hsv.split(','); if (color.isvalidColorString(data.hsv, 'hsv')) { _values[2] = _values[2].replace('%', ''); _values[1] = _values[1].replace('%', ''); _values[0] = _values[0].replace('°', ''); if (_values[1] == 1) { _values[1] = 0.01; } else if (_values[2] == 1) { _values[2] = 0.01; } onChange({ h: Number(_values[0]), s: Number(_values[1]), v: Number(_values[2]), source: 'hsv' }, e); } } else if (data.hsl) { var _values2 = data.hsl.split(','); if (color.isvalidColorString(data.hsl, 'hsl')) { _values2[2] = _values2[2].replace('%', ''); _values2[1] = _values2[1].replace('%', ''); _values2[0] = _values2[0].replace('°', ''); if (hsvValue[1] == 1) { hsvValue[1] = 0.01; } else if (hsvValue[2] == 1) { hsvValue[2] = 0.01; } onChange({ h: Number(_values2[0]), s: Number(_values2[1]), v: Number(_values2[2]), source: 'hsl' }, e); } } }; var styles = (0, _reactcss2.default)({ 'default': { wrap: { display: 'flex', height: '100px', marginTop: '4px' }, fields: { width: '100%' }, column: { paddingTop: '10px', display: 'flex', justifyContent: 'space-between' }, double: { padding: '0px 4.4px', boxSizing: 'border-box' }, input: { width: '100%', height: '38px', boxSizing: 'border-box', padding: '4px 10% 3px', textAlign: 'center', border: '1px solid #dadce0', fontSize: '11px', textTransform: 'lowercase', borderRadius: '5px', outline: 'none', fontFamily: 'Roboto,Arial,sans-serif' }, input2: { height: '38px', width: '100%', border: '1px solid #dadce0', boxSizing: 'border-box', fontSize: '11px', textTransform: 'lowercase', borderRadius: '5px', outline: 'none', paddingLeft: '10px', fontFamily: 'Roboto,Arial,sans-serif' }, label: { textAlign: 'center', fontSize: '12px', background: '#fff', position: 'absolute', textTransform: 'uppercase', color: '#3c4043', width: '35px', top: '-6px', left: '0', right: '0', marginLeft: 'auto', marginRight: 'auto', fontFamily: 'Roboto,Arial,sans-serif' }, label2: { left: '10px', textAlign: 'center', fontSize: '12px', background: '#fff', position: 'absolute', textTransform: 'uppercase', color: '#3c4043', width: '32px', top: '-6px', fontFamily: 'Roboto,Arial,sans-serif' }, single: { flexGrow: '1', margin: '0px 4.4px' } } }); var rgbValue = rgb.r + ', ' + rgb.g + ', ' + rgb.b; var hslValue = Math.round(hsl.h) + '\xB0, ' + Math.round(hsl.s * 100) + '%, ' + Math.round(hsl.l * 100) + '%'; var hsvValue = Math.round(hsv.h) + '\xB0, ' + Math.round(hsv.s * 100) + '%, ' + Math.round(hsv.v * 100) + '%'; return _react2.default.createElement( 'div', { style: styles.wrap, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.fields }, _react2.default.createElement( 'div', { style: styles.double }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'hex', value: hex, onChange: handleChange }) ), _react2.default.createElement( 'div', { style: styles.column }, _react2.default.createElement( 'div', { style: styles.single }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input2, label: styles.label2 }, label: 'rgb', value: rgbValue, onChange: handleChange }) ), _react2.default.createElement( 'div', { style: styles.single }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input2, label: styles.label2 }, label: 'hsv', value: hsvValue, onChange: handleChange }) ), _react2.default.createElement( 'div', { style: styles.single }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input2, label: styles.label2 }, label: 'hsl', value: hslValue, onChange: handleChange }) ) ) ) ); }; exports.default = GoogleFields; },{"../../helpers/color":350,"../common":318,"react":"react","reactcss":363}],326:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.GooglePointer = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var GooglePointer = exports.GooglePointer = function GooglePointer(props) { var styles = (0, _reactcss2.default)({ 'default': { picker: { width: '20px', height: '20px', borderRadius: '22px', transform: 'translate(-10px, -7px)', background: 'hsl(' + Math.round(props.hsl.h) + ', 100%, 50%)', border: '2px white solid' } } }); return _react2.default.createElement('div', { style: styles.picker }); }; GooglePointer.propTypes = { hsl: _propTypes2.default.shape({ h: _propTypes2.default.number, s: _propTypes2.default.number, l: _propTypes2.default.number, a: _propTypes2.default.number }) }; GooglePointer.defaultProps = { hsl: { a: 1, h: 249.94, l: 0.2, s: 0.50 } }; exports.default = GooglePointer; },{"prop-types":298,"react":"react","reactcss":363}],327:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.GooglePointerCircle = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var GooglePointerCircle = exports.GooglePointerCircle = function GooglePointerCircle(props) { var styles = (0, _reactcss2.default)({ 'default': { picker: { width: '20px', height: '20px', borderRadius: '22px', border: '2px #fff solid', transform: 'translate(-12px, -13px)', background: 'hsl(' + Math.round(props.hsl.h) + ', ' + Math.round(props.hsl.s * 100) + '%, ' + Math.round(props.hsl.l * 100) + '%)' } } }); return _react2.default.createElement('div', { style: styles.picker }); }; GooglePointerCircle.propTypes = { hsl: _propTypes2.default.shape({ h: _propTypes2.default.number, s: _propTypes2.default.number, l: _propTypes2.default.number, a: _propTypes2.default.number }) }; GooglePointerCircle.defaultProps = { hsl: { a: 1, h: 249.94, l: 0.2, s: 0.50 } }; exports.default = GooglePointerCircle; },{"prop-types":298,"react":"react","reactcss":363}],328:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.HuePicker = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _common = require('../common'); var _HuePointer = require('./HuePointer'); var _HuePointer2 = _interopRequireDefault(_HuePointer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var HuePicker = exports.HuePicker = function HuePicker(_ref) { var width = _ref.width, height = _ref.height, onChange = _ref.onChange, hsl = _ref.hsl, direction = _ref.direction, pointer = _ref.pointer, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { picker: { position: 'relative', width: width, height: height }, hue: { radius: '2px' } } }, passedStyles)); // Overwrite to provide pure hue color var handleChange = function handleChange(data) { return onChange({ a: 1, h: data.h, l: 0.5, s: 1 }); }; return _react2.default.createElement( 'div', { style: styles.picker, className: 'hue-picker ' + className }, _react2.default.createElement(_common.Hue, _extends({}, styles.hue, { hsl: hsl, pointer: pointer, onChange: handleChange, direction: direction })) ); }; HuePicker.propTypes = { styles: _propTypes2.default.object }; HuePicker.defaultProps = { width: '316px', height: '16px', direction: 'horizontal', pointer: _HuePointer2.default, styles: {} }; exports.default = (0, _common.ColorWrap)(HuePicker); },{"../common":318,"./HuePointer":329,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],329:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.SliderPointer = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SliderPointer = exports.SliderPointer = function SliderPointer(_ref) { var direction = _ref.direction; var styles = (0, _reactcss2.default)({ 'default': { picker: { width: '18px', height: '18px', borderRadius: '50%', transform: 'translate(-9px, -1px)', backgroundColor: 'rgb(248, 248, 248)', boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)' } }, 'vertical': { picker: { transform: 'translate(-3px, -9px)' } } }, { vertical: direction === 'vertical' }); return _react2.default.createElement('div', { style: styles.picker }); }; exports.default = SliderPointer; },{"react":"react","reactcss":363}],330:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Material = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _color = require('../../helpers/color'); var color = _interopRequireWildcard(_color); var _common = require('../common'); 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 }; } var Material = exports.Material = function Material(_ref) { var onChange = _ref.onChange, hex = _ref.hex, rgb = _ref.rgb, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { material: { width: '98px', height: '98px', padding: '16px', fontFamily: 'Roboto' }, HEXwrap: { position: 'relative' }, HEXinput: { width: '100%', marginTop: '12px', fontSize: '15px', color: '#333', padding: '0px', border: '0px', borderBottom: '2px solid ' + hex, outline: 'none', height: '30px' }, HEXlabel: { position: 'absolute', top: '0px', left: '0px', fontSize: '11px', color: '#999999', textTransform: 'capitalize' }, Hex: { style: {} }, RGBwrap: { position: 'relative' }, RGBinput: { width: '100%', marginTop: '12px', fontSize: '15px', color: '#333', padding: '0px', border: '0px', borderBottom: '1px solid #eee', outline: 'none', height: '30px' }, RGBlabel: { position: 'absolute', top: '0px', left: '0px', fontSize: '11px', color: '#999999', textTransform: 'capitalize' }, split: { display: 'flex', marginRight: '-10px', paddingTop: '11px' }, third: { flex: '1', paddingRight: '10px' } } }, passedStyles)); var handleChange = function handleChange(data, e) { if (data.hex) { color.isValidHex(data.hex) && onChange({ hex: data.hex, source: 'hex' }, e); } else if (data.r || data.g || data.b) { onChange({ r: data.r || rgb.r, g: data.g || rgb.g, b: data.b || rgb.b, source: 'rgb' }, e); } }; return _react2.default.createElement( _common.Raised, { styles: passedStyles }, _react2.default.createElement( 'div', { style: styles.material, className: 'material-picker ' + className }, _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.HEXwrap, input: styles.HEXinput, label: styles.HEXlabel }, label: 'hex', value: hex, onChange: handleChange }), _react2.default.createElement( 'div', { style: styles.split, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.third }, _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'r', value: rgb.r, onChange: handleChange }) ), _react2.default.createElement( 'div', { style: styles.third }, _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'g', value: rgb.g, onChange: handleChange }) ), _react2.default.createElement( 'div', { style: styles.third }, _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'b', value: rgb.b, onChange: handleChange }) ) ) ) ); }; exports.default = (0, _common.ColorWrap)(Material); },{"../../helpers/color":350,"../common":318,"lodash/merge":284,"react":"react","reactcss":363}],331:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Photoshop = undefined; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _common = require('../common'); var _PhotoshopFields = require('./PhotoshopFields'); var _PhotoshopFields2 = _interopRequireDefault(_PhotoshopFields); var _PhotoshopPointerCircle = require('./PhotoshopPointerCircle'); var _PhotoshopPointerCircle2 = _interopRequireDefault(_PhotoshopPointerCircle); var _PhotoshopPointer = require('./PhotoshopPointer'); var _PhotoshopPointer2 = _interopRequireDefault(_PhotoshopPointer); var _PhotoshopButton = require('./PhotoshopButton'); var _PhotoshopButton2 = _interopRequireDefault(_PhotoshopButton); var _PhotoshopPreviews = require('./PhotoshopPreviews'); var _PhotoshopPreviews2 = _interopRequireDefault(_PhotoshopPreviews); 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; } var Photoshop = exports.Photoshop = function (_React$Component) { _inherits(Photoshop, _React$Component); function Photoshop(props) { _classCallCheck(this, Photoshop); var _this = _possibleConstructorReturn(this, (Photoshop.__proto__ || Object.getPrototypeOf(Photoshop)).call(this)); _this.state = { currentColor: props.hex }; return _this; } _createClass(Photoshop, [{ key: 'render', value: function render() { var _props = this.props, _props$styles = _props.styles, passedStyles = _props$styles === undefined ? {} : _props$styles, _props$className = _props.className, className = _props$className === undefined ? '' : _props$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { picker: { background: '#DCDCDC', borderRadius: '4px', boxShadow: '0 0 0 1px rgba(0,0,0,.25), 0 8px 16px rgba(0,0,0,.15)', boxSizing: 'initial', width: '513px' }, head: { backgroundImage: 'linear-gradient(-180deg, #F0F0F0 0%, #D4D4D4 100%)', borderBottom: '1px solid #B1B1B1', boxShadow: 'inset 0 1px 0 0 rgba(255,255,255,.2), inset 0 -1px 0 0 rgba(0,0,0,.02)', height: '23px', lineHeight: '24px', borderRadius: '4px 4px 0 0', fontSize: '13px', color: '#4D4D4D', textAlign: 'center' }, body: { padding: '15px 15px 0', display: 'flex' }, saturation: { width: '256px', height: '256px', position: 'relative', border: '2px solid #B3B3B3', borderBottom: '2px solid #F0F0F0', overflow: 'hidden' }, hue: { position: 'relative', height: '256px', width: '19px', marginLeft: '10px', border: '2px solid #B3B3B3', borderBottom: '2px solid #F0F0F0' }, controls: { width: '180px', marginLeft: '10px' }, top: { display: 'flex' }, previews: { width: '60px' }, actions: { flex: '1', marginLeft: '20px' } } }, passedStyles)); return _react2.default.createElement( 'div', { style: styles.picker, className: 'photoshop-picker ' + className }, _react2.default.createElement( 'div', { style: styles.head }, this.props.header ), _react2.default.createElement( 'div', { style: styles.body, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.saturation }, _react2.default.createElement(_common.Saturation, { hsl: this.props.hsl, hsv: this.props.hsv, pointer: _PhotoshopPointerCircle2.default, onChange: this.props.onChange }) ), _react2.default.createElement( 'div', { style: styles.hue }, _react2.default.createElement(_common.Hue, { direction: 'vertical', hsl: this.props.hsl, pointer: _PhotoshopPointer2.default, onChange: this.props.onChange }) ), _react2.default.createElement( 'div', { style: styles.controls }, _react2.default.createElement( 'div', { style: styles.top, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.previews }, _react2.default.createElement(_PhotoshopPreviews2.default, { rgb: this.props.rgb, currentColor: this.state.currentColor }) ), _react2.default.createElement( 'div', { style: styles.actions }, _react2.default.createElement(_PhotoshopButton2.default, { label: 'OK', onClick: this.props.onAccept, active: true }), _react2.default.createElement(_PhotoshopButton2.default, { label: 'Cancel', onClick: this.props.onCancel }), _react2.default.createElement(_PhotoshopFields2.default, { onChange: this.props.onChange, rgb: this.props.rgb, hsv: this.props.hsv, hex: this.props.hex }) ) ) ) ) ); } }]); return Photoshop; }(_react2.default.Component); Photoshop.propTypes = { header: _propTypes2.default.string, styles: _propTypes2.default.object }; Photoshop.defaultProps = { header: 'Color Picker', styles: {} }; exports.default = (0, _common.ColorWrap)(Photoshop); },{"../common":318,"./PhotoshopButton":332,"./PhotoshopFields":333,"./PhotoshopPointer":334,"./PhotoshopPointerCircle":335,"./PhotoshopPreviews":336,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],332:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.PhotoshopButton = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PhotoshopButton = exports.PhotoshopButton = function PhotoshopButton(_ref) { var onClick = _ref.onClick, label = _ref.label, children = _ref.children, active = _ref.active; var styles = (0, _reactcss2.default)({ 'default': { button: { backgroundImage: 'linear-gradient(-180deg, #FFFFFF 0%, #E6E6E6 100%)', border: '1px solid #878787', borderRadius: '2px', height: '20px', boxShadow: '0 1px 0 0 #EAEAEA', fontSize: '14px', color: '#000', lineHeight: '20px', textAlign: 'center', marginBottom: '10px', cursor: 'pointer' } }, 'active': { button: { boxShadow: '0 0 0 1px #878787' } } }, { active: active }); return _react2.default.createElement( 'div', { style: styles.button, onClick: onClick }, label || children ); }; exports.default = PhotoshopButton; },{"react":"react","reactcss":363}],333:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.PhotoshopPicker = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _color = require('../../helpers/color'); var color = _interopRequireWildcard(_color); var _common = require('../common'); 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 }; } var PhotoshopPicker = exports.PhotoshopPicker = function PhotoshopPicker(_ref) { var onChange = _ref.onChange, rgb = _ref.rgb, hsv = _ref.hsv, hex = _ref.hex; var styles = (0, _reactcss2.default)({ 'default': { fields: { paddingTop: '5px', paddingBottom: '9px', width: '80px', position: 'relative' }, divider: { height: '5px' }, RGBwrap: { position: 'relative' }, RGBinput: { marginLeft: '40%', width: '40%', height: '18px', border: '1px solid #888888', boxShadow: 'inset 0 1px 1px rgba(0,0,0,.1), 0 1px 0 0 #ECECEC', marginBottom: '5px', fontSize: '13px', paddingLeft: '3px', marginRight: '10px' }, RGBlabel: { left: '0px', top: '0px', width: '34px', textTransform: 'uppercase', fontSize: '13px', height: '18px', lineHeight: '22px', position: 'absolute' }, HEXwrap: { position: 'relative' }, HEXinput: { marginLeft: '20%', width: '80%', height: '18px', border: '1px solid #888888', boxShadow: 'inset 0 1px 1px rgba(0,0,0,.1), 0 1px 0 0 #ECECEC', marginBottom: '6px', fontSize: '13px', paddingLeft: '3px' }, HEXlabel: { position: 'absolute', top: '0px', left: '0px', width: '14px', textTransform: 'uppercase', fontSize: '13px', height: '18px', lineHeight: '22px' }, fieldSymbols: { position: 'absolute', top: '5px', right: '-7px', fontSize: '13px' }, symbol: { height: '20px', lineHeight: '22px', paddingBottom: '7px' } } }); var handleChange = function handleChange(data, e) { if (data['#']) { color.isValidHex(data['#']) && onChange({ hex: data['#'], source: 'hex' }, e); } else if (data.r || data.g || data.b) { onChange({ r: data.r || rgb.r, g: data.g || rgb.g, b: data.b || rgb.b, source: 'rgb' }, e); } else if (data.h || data.s || data.v) { onChange({ h: data.h || hsv.h, s: data.s || hsv.s, v: data.v || hsv.v, source: 'hsv' }, e); } }; return _react2.default.createElement( 'div', { style: styles.fields }, _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'h', value: Math.round(hsv.h), onChange: handleChange }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 's', value: Math.round(hsv.s * 100), onChange: handleChange }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'v', value: Math.round(hsv.v * 100), onChange: handleChange }), _react2.default.createElement('div', { style: styles.divider }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'r', value: rgb.r, onChange: handleChange }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'g', value: rgb.g, onChange: handleChange }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel }, label: 'b', value: rgb.b, onChange: handleChange }), _react2.default.createElement('div', { style: styles.divider }), _react2.default.createElement(_common.EditableInput, { style: { wrap: styles.HEXwrap, input: styles.HEXinput, label: styles.HEXlabel }, label: '#', value: hex.replace('#', ''), onChange: handleChange }), _react2.default.createElement( 'div', { style: styles.fieldSymbols }, _react2.default.createElement( 'div', { style: styles.symbol }, '\xB0' ), _react2.default.createElement( 'div', { style: styles.symbol }, '%' ), _react2.default.createElement( 'div', { style: styles.symbol }, '%' ) ) ); }; exports.default = PhotoshopPicker; },{"../../helpers/color":350,"../common":318,"react":"react","reactcss":363}],334:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.PhotoshopPointerCircle = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PhotoshopPointerCircle = exports.PhotoshopPointerCircle = function PhotoshopPointerCircle() { var styles = (0, _reactcss2.default)({ 'default': { triangle: { width: 0, height: 0, borderStyle: 'solid', borderWidth: '4px 0 4px 6px', borderColor: 'transparent transparent transparent #fff', position: 'absolute', top: '1px', left: '1px' }, triangleBorder: { width: 0, height: 0, borderStyle: 'solid', borderWidth: '5px 0 5px 8px', borderColor: 'transparent transparent transparent #555' }, left: { Extend: 'triangleBorder', transform: 'translate(-13px, -4px)' }, leftInside: { Extend: 'triangle', transform: 'translate(-8px, -5px)' }, right: { Extend: 'triangleBorder', transform: 'translate(20px, -14px) rotate(180deg)' }, rightInside: { Extend: 'triangle', transform: 'translate(-8px, -5px)' } } }); return _react2.default.createElement( 'div', { style: styles.pointer }, _react2.default.createElement( 'div', { style: styles.left }, _react2.default.createElement('div', { style: styles.leftInside }) ), _react2.default.createElement( 'div', { style: styles.right }, _react2.default.createElement('div', { style: styles.rightInside }) ) ); }; exports.default = PhotoshopPointerCircle; },{"react":"react","reactcss":363}],335:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.PhotoshopPointerCircle = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PhotoshopPointerCircle = exports.PhotoshopPointerCircle = function PhotoshopPointerCircle(_ref) { var hsl = _ref.hsl; var styles = (0, _reactcss2.default)({ 'default': { picker: { width: '12px', height: '12px', borderRadius: '6px', boxShadow: 'inset 0 0 0 1px #fff', transform: 'translate(-6px, -6px)' } }, 'black-outline': { picker: { boxShadow: 'inset 0 0 0 1px #000' } } }, { 'black-outline': hsl.l > 0.5 }); return _react2.default.createElement('div', { style: styles.picker }); }; exports.default = PhotoshopPointerCircle; },{"react":"react","reactcss":363}],336:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.PhotoshopPreviews = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PhotoshopPreviews = exports.PhotoshopPreviews = function PhotoshopPreviews(_ref) { var rgb = _ref.rgb, currentColor = _ref.currentColor; var styles = (0, _reactcss2.default)({ 'default': { swatches: { border: '1px solid #B3B3B3', borderBottom: '1px solid #F0F0F0', marginBottom: '2px', marginTop: '1px' }, new: { height: '34px', background: 'rgb(' + rgb.r + ',' + rgb.g + ', ' + rgb.b + ')', boxShadow: 'inset 1px 0 0 #000, inset -1px 0 0 #000, inset 0 1px 0 #000' }, current: { height: '34px', background: currentColor, boxShadow: 'inset 1px 0 0 #000, inset -1px 0 0 #000, inset 0 -1px 0 #000' }, label: { fontSize: '14px', color: '#000', textAlign: 'center' } } }); return _react2.default.createElement( 'div', null, _react2.default.createElement( 'div', { style: styles.label }, 'new' ), _react2.default.createElement( 'div', { style: styles.swatches }, _react2.default.createElement('div', { style: styles.new }), _react2.default.createElement('div', { style: styles.current }) ), _react2.default.createElement( 'div', { style: styles.label }, 'current' ) ); }; exports.default = PhotoshopPreviews; },{"react":"react","reactcss":363}],337:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Sketch = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _common = require('../common'); var _SketchFields = require('./SketchFields'); var _SketchFields2 = _interopRequireDefault(_SketchFields); var _SketchPresetColors = require('./SketchPresetColors'); var _SketchPresetColors2 = _interopRequireDefault(_SketchPresetColors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Sketch = exports.Sketch = function Sketch(_ref) { var width = _ref.width, rgb = _ref.rgb, hex = _ref.hex, hsv = _ref.hsv, hsl = _ref.hsl, onChange = _ref.onChange, onSwatchHover = _ref.onSwatchHover, disableAlpha = _ref.disableAlpha, presetColors = _ref.presetColors, renderers = _ref.renderers, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': _extends({ picker: { width: width, padding: '10px 10px 0', boxSizing: 'initial', background: '#fff', borderRadius: '4px', boxShadow: '0 0 0 1px rgba(0,0,0,.15), 0 8px 16px rgba(0,0,0,.15)' }, saturation: { width: '100%', paddingBottom: '75%', position: 'relative', overflow: 'hidden' }, Saturation: { radius: '3px', shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)' }, controls: { display: 'flex' }, sliders: { padding: '4px 0', flex: '1' }, color: { width: '24px', height: '24px', position: 'relative', marginTop: '4px', marginLeft: '4px', borderRadius: '3px' }, activeColor: { absolute: '0px 0px 0px 0px', borderRadius: '2px', background: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')', boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)' }, hue: { position: 'relative', height: '10px', overflow: 'hidden' }, Hue: { radius: '2px', shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)' }, alpha: { position: 'relative', height: '10px', marginTop: '4px', overflow: 'hidden' }, Alpha: { radius: '2px', shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)' } }, passedStyles), 'disableAlpha': { color: { height: '10px' }, hue: { height: '10px' }, alpha: { display: 'none' } } }, passedStyles), { disableAlpha: disableAlpha }); return _react2.default.createElement( 'div', { style: styles.picker, className: 'sketch-picker ' + className }, _react2.default.createElement( 'div', { style: styles.saturation }, _react2.default.createElement(_common.Saturation, { style: styles.Saturation, hsl: hsl, hsv: hsv, onChange: onChange }) ), _react2.default.createElement( 'div', { style: styles.controls, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.sliders }, _react2.default.createElement( 'div', { style: styles.hue }, _react2.default.createElement(_common.Hue, { style: styles.Hue, hsl: hsl, onChange: onChange }) ), _react2.default.createElement( 'div', { style: styles.alpha }, _react2.default.createElement(_common.Alpha, { style: styles.Alpha, rgb: rgb, hsl: hsl, renderers: renderers, onChange: onChange }) ) ), _react2.default.createElement( 'div', { style: styles.color }, _react2.default.createElement(_common.Checkboard, null), _react2.default.createElement('div', { style: styles.activeColor }) ) ), _react2.default.createElement(_SketchFields2.default, { rgb: rgb, hsl: hsl, hex: hex, onChange: onChange, disableAlpha: disableAlpha }), _react2.default.createElement(_SketchPresetColors2.default, { colors: presetColors, onClick: onChange, onSwatchHover: onSwatchHover }) ); }; Sketch.propTypes = { disableAlpha: _propTypes2.default.bool, width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), styles: _propTypes2.default.object }; Sketch.defaultProps = { disableAlpha: false, width: 200, styles: {}, presetColors: ['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#BD10E0', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF'] }; exports.default = (0, _common.ColorWrap)(Sketch); },{"../common":318,"./SketchFields":338,"./SketchPresetColors":339,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],338:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.SketchFields = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _color = require('../../helpers/color'); var color = _interopRequireWildcard(_color); var _common = require('../common'); 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 }; } /* eslint-disable no-param-reassign */ var SketchFields = exports.SketchFields = function SketchFields(_ref) { var onChange = _ref.onChange, rgb = _ref.rgb, hsl = _ref.hsl, hex = _ref.hex, disableAlpha = _ref.disableAlpha; var styles = (0, _reactcss2.default)({ 'default': { fields: { display: 'flex', paddingTop: '4px' }, single: { flex: '1', paddingLeft: '6px' }, alpha: { flex: '1', paddingLeft: '6px' }, double: { flex: '2' }, input: { width: '80%', padding: '4px 10% 3px', border: 'none', boxShadow: 'inset 0 0 0 1px #ccc', fontSize: '11px' }, label: { display: 'block', textAlign: 'center', fontSize: '11px', color: '#222', paddingTop: '3px', paddingBottom: '4px', textTransform: 'capitalize' } }, 'disableAlpha': { alpha: { display: 'none' } } }, { disableAlpha: disableAlpha }); var handleChange = function handleChange(data, e) { if (data.hex) { color.isValidHex(data.hex) && onChange({ hex: data.hex, source: 'hex' }, e); } else if (data.r || data.g || data.b) { onChange({ r: data.r || rgb.r, g: data.g || rgb.g, b: data.b || rgb.b, a: rgb.a, source: 'rgb' }, e); } else if (data.a) { if (data.a < 0) { data.a = 0; } else if (data.a > 100) { data.a = 100; } data.a /= 100; onChange({ h: hsl.h, s: hsl.s, l: hsl.l, a: data.a, source: 'rgb' }, e); } }; return _react2.default.createElement( 'div', { style: styles.fields, className: 'flexbox-fix' }, _react2.default.createElement( 'div', { style: styles.double }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'hex', value: hex.replace('#', ''), onChange: handleChange }) ), _react2.default.createElement( 'div', { style: styles.single }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'r', value: rgb.r, onChange: handleChange, dragLabel: 'true', dragMax: '255' }) ), _react2.default.createElement( 'div', { style: styles.single }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'g', value: rgb.g, onChange: handleChange, dragLabel: 'true', dragMax: '255' }) ), _react2.default.createElement( 'div', { style: styles.single }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'b', value: rgb.b, onChange: handleChange, dragLabel: 'true', dragMax: '255' }) ), _react2.default.createElement( 'div', { style: styles.alpha }, _react2.default.createElement(_common.EditableInput, { style: { input: styles.input, label: styles.label }, label: 'a', value: Math.round(rgb.a * 100), onChange: handleChange, dragLabel: 'true', dragMax: '100' }) ) ); }; exports.default = SketchFields; },{"../../helpers/color":350,"../common":318,"react":"react","reactcss":363}],339:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.SketchPresetColors = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _common = require('../common'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SketchPresetColors = exports.SketchPresetColors = function SketchPresetColors(_ref) { var colors = _ref.colors, _ref$onClick = _ref.onClick, onClick = _ref$onClick === undefined ? function () {} : _ref$onClick, onSwatchHover = _ref.onSwatchHover; var styles = (0, _reactcss2.default)({ 'default': { colors: { margin: '0 -10px', padding: '10px 0 0 10px', borderTop: '1px solid #eee', display: 'flex', flexWrap: 'wrap', position: 'relative' }, swatchWrap: { width: '16px', height: '16px', margin: '0 10px 10px 0' }, swatch: { borderRadius: '3px', boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15)' } }, 'no-presets': { colors: { display: 'none' } } }, { 'no-presets': !colors || !colors.length }); var handleClick = function handleClick(hex, e) { onClick({ hex: hex, source: 'hex' }, e); }; return _react2.default.createElement( 'div', { style: styles.colors, className: 'flexbox-fix' }, colors.map(function (colorObjOrString) { var c = typeof colorObjOrString === 'string' ? { color: colorObjOrString } : colorObjOrString; var key = '' + c.color + (c.title || ''); return _react2.default.createElement( 'div', { key: key, style: styles.swatchWrap }, _react2.default.createElement(_common.Swatch, _extends({}, c, { style: styles.swatch, onClick: handleClick, onHover: onSwatchHover, focusStyle: { boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15), 0 0 4px ' + c.color } })) ); }) ); }; SketchPresetColors.propTypes = { colors: _propTypes2.default.arrayOf(_propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.shape({ color: _propTypes2.default.string, title: _propTypes2.default.string })])).isRequired }; exports.default = SketchPresetColors; },{"../common":318,"prop-types":298,"react":"react","reactcss":363}],340:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Slider = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _common = require('../common'); var _SliderSwatches = require('./SliderSwatches'); var _SliderSwatches2 = _interopRequireDefault(_SliderSwatches); var _SliderPointer = require('./SliderPointer'); var _SliderPointer2 = _interopRequireDefault(_SliderPointer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Slider = exports.Slider = function Slider(_ref) { var hsl = _ref.hsl, onChange = _ref.onChange, pointer = _ref.pointer, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { hue: { height: '12px', position: 'relative' }, Hue: { radius: '2px' } } }, passedStyles)); return _react2.default.createElement( 'div', { style: styles.wrap || {}, className: 'slider-picker ' + className }, _react2.default.createElement( 'div', { style: styles.hue }, _react2.default.createElement(_common.Hue, { style: styles.Hue, hsl: hsl, pointer: pointer, onChange: onChange }) ), _react2.default.createElement( 'div', { style: styles.swatches }, _react2.default.createElement(_SliderSwatches2.default, { hsl: hsl, onClick: onChange }) ) ); }; Slider.propTypes = { styles: _propTypes2.default.object }; Slider.defaultProps = { pointer: _SliderPointer2.default, styles: {} }; exports.default = (0, _common.ColorWrap)(Slider); },{"../common":318,"./SliderPointer":341,"./SliderSwatches":343,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],341:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.SliderPointer = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SliderPointer = exports.SliderPointer = function SliderPointer() { var styles = (0, _reactcss2.default)({ 'default': { picker: { width: '14px', height: '14px', borderRadius: '6px', transform: 'translate(-7px, -1px)', backgroundColor: 'rgb(248, 248, 248)', boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)' } } }); return _react2.default.createElement('div', { style: styles.picker }); }; exports.default = SliderPointer; },{"react":"react","reactcss":363}],342:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.SliderSwatch = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SliderSwatch = exports.SliderSwatch = function SliderSwatch(_ref) { var hsl = _ref.hsl, offset = _ref.offset, _ref$onClick = _ref.onClick, onClick = _ref$onClick === undefined ? function () {} : _ref$onClick, active = _ref.active, first = _ref.first, last = _ref.last; var styles = (0, _reactcss2.default)({ 'default': { swatch: { height: '12px', background: 'hsl(' + hsl.h + ', 50%, ' + offset * 100 + '%)', cursor: 'pointer' } }, 'first': { swatch: { borderRadius: '2px 0 0 2px' } }, 'last': { swatch: { borderRadius: '0 2px 2px 0' } }, 'active': { swatch: { transform: 'scaleY(1.8)', borderRadius: '3.6px/2px' } } }, { active: active, first: first, last: last }); var handleClick = function handleClick(e) { return onClick({ h: hsl.h, s: 0.5, l: offset, source: 'hsl' }, e); }; return _react2.default.createElement('div', { style: styles.swatch, onClick: handleClick }); }; exports.default = SliderSwatch; },{"react":"react","reactcss":363}],343:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.SliderSwatches = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _SliderSwatch = require('./SliderSwatch'); var _SliderSwatch2 = _interopRequireDefault(_SliderSwatch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SliderSwatches = exports.SliderSwatches = function SliderSwatches(_ref) { var onClick = _ref.onClick, hsl = _ref.hsl; var styles = (0, _reactcss2.default)({ 'default': { swatches: { marginTop: '20px' }, swatch: { boxSizing: 'border-box', width: '20%', paddingRight: '1px', float: 'left' }, clear: { clear: 'both' } } }); // Acceptible difference in floating point equality var epsilon = 0.1; return _react2.default.createElement( 'div', { style: styles.swatches }, _react2.default.createElement( 'div', { style: styles.swatch }, _react2.default.createElement(_SliderSwatch2.default, { hsl: hsl, offset: '.80', active: Math.abs(hsl.l - 0.80) < epsilon && Math.abs(hsl.s - 0.50) < epsilon, onClick: onClick, first: true }) ), _react2.default.createElement( 'div', { style: styles.swatch }, _react2.default.createElement(_SliderSwatch2.default, { hsl: hsl, offset: '.65', active: Math.abs(hsl.l - 0.65) < epsilon && Math.abs(hsl.s - 0.50) < epsilon, onClick: onClick }) ), _react2.default.createElement( 'div', { style: styles.swatch }, _react2.default.createElement(_SliderSwatch2.default, { hsl: hsl, offset: '.50', active: Math.abs(hsl.l - 0.50) < epsilon && Math.abs(hsl.s - 0.50) < epsilon, onClick: onClick }) ), _react2.default.createElement( 'div', { style: styles.swatch }, _react2.default.createElement(_SliderSwatch2.default, { hsl: hsl, offset: '.35', active: Math.abs(hsl.l - 0.35) < epsilon && Math.abs(hsl.s - 0.50) < epsilon, onClick: onClick }) ), _react2.default.createElement( 'div', { style: styles.swatch }, _react2.default.createElement(_SliderSwatch2.default, { hsl: hsl, offset: '.20', active: Math.abs(hsl.l - 0.20) < epsilon && Math.abs(hsl.s - 0.50) < epsilon, onClick: onClick, last: true }) ), _react2.default.createElement('div', { style: styles.clear }) ); }; exports.default = SliderSwatches; },{"./SliderSwatch":342,"react":"react","reactcss":363}],344:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Swatches = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _map = require('lodash/map'); var _map2 = _interopRequireDefault(_map); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _materialColors = require('material-colors'); var material = _interopRequireWildcard(_materialColors); var _common = require('../common'); var _SwatchesGroup = require('./SwatchesGroup'); var _SwatchesGroup2 = _interopRequireDefault(_SwatchesGroup); 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 }; } var Swatches = exports.Swatches = function Swatches(_ref) { var width = _ref.width, height = _ref.height, onChange = _ref.onChange, onSwatchHover = _ref.onSwatchHover, colors = _ref.colors, hex = _ref.hex, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { picker: { width: width, height: height }, overflow: { height: height, overflowY: 'scroll' }, body: { padding: '16px 0 6px 16px' }, clear: { clear: 'both' } } }, passedStyles)); var handleChange = function handleChange(data, e) { return onChange({ hex: data, source: 'hex' }, e); }; return _react2.default.createElement( 'div', { style: styles.picker, className: 'swatches-picker ' + className }, _react2.default.createElement( _common.Raised, null, _react2.default.createElement( 'div', { style: styles.overflow }, _react2.default.createElement( 'div', { style: styles.body }, (0, _map2.default)(colors, function (group) { return _react2.default.createElement(_SwatchesGroup2.default, { key: group.toString(), group: group, active: hex, onClick: handleChange, onSwatchHover: onSwatchHover }); }), _react2.default.createElement('div', { style: styles.clear }) ) ) ) ); }; Swatches.propTypes = { width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), height: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), colors: _propTypes2.default.arrayOf(_propTypes2.default.arrayOf(_propTypes2.default.string)), styles: _propTypes2.default.object /* eslint-disable max-len */ };Swatches.defaultProps = { width: 320, height: 240, colors: [[material.red['900'], material.red['700'], material.red['500'], material.red['300'], material.red['100']], [material.pink['900'], material.pink['700'], material.pink['500'], material.pink['300'], material.pink['100']], [material.purple['900'], material.purple['700'], material.purple['500'], material.purple['300'], material.purple['100']], [material.deepPurple['900'], material.deepPurple['700'], material.deepPurple['500'], material.deepPurple['300'], material.deepPurple['100']], [material.indigo['900'], material.indigo['700'], material.indigo['500'], material.indigo['300'], material.indigo['100']], [material.blue['900'], material.blue['700'], material.blue['500'], material.blue['300'], material.blue['100']], [material.lightBlue['900'], material.lightBlue['700'], material.lightBlue['500'], material.lightBlue['300'], material.lightBlue['100']], [material.cyan['900'], material.cyan['700'], material.cyan['500'], material.cyan['300'], material.cyan['100']], [material.teal['900'], material.teal['700'], material.teal['500'], material.teal['300'], material.teal['100']], ['#194D33', material.green['700'], material.green['500'], material.green['300'], material.green['100']], [material.lightGreen['900'], material.lightGreen['700'], material.lightGreen['500'], material.lightGreen['300'], material.lightGreen['100']], [material.lime['900'], material.lime['700'], material.lime['500'], material.lime['300'], material.lime['100']], [material.yellow['900'], material.yellow['700'], material.yellow['500'], material.yellow['300'], material.yellow['100']], [material.amber['900'], material.amber['700'], material.amber['500'], material.amber['300'], material.amber['100']], [material.orange['900'], material.orange['700'], material.orange['500'], material.orange['300'], material.orange['100']], [material.deepOrange['900'], material.deepOrange['700'], material.deepOrange['500'], material.deepOrange['300'], material.deepOrange['100']], [material.brown['900'], material.brown['700'], material.brown['500'], material.brown['300'], material.brown['100']], [material.blueGrey['900'], material.blueGrey['700'], material.blueGrey['500'], material.blueGrey['300'], material.blueGrey['100']], ['#000000', '#525252', '#969696', '#D9D9D9', '#FFFFFF']], styles: {} }; exports.default = (0, _common.ColorWrap)(Swatches); },{"../common":318,"./SwatchesGroup":346,"lodash/map":282,"lodash/merge":284,"material-colors":293,"prop-types":298,"react":"react","reactcss":363}],345:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.SwatchesColor = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _color = require('../../helpers/color'); var colorUtils = _interopRequireWildcard(_color); var _common = require('../common'); var _CheckIcon = require('@icons/material/CheckIcon'); var _CheckIcon2 = _interopRequireDefault(_CheckIcon); 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 }; } var SwatchesColor = exports.SwatchesColor = function SwatchesColor(_ref) { var color = _ref.color, _ref$onClick = _ref.onClick, onClick = _ref$onClick === undefined ? function () {} : _ref$onClick, onSwatchHover = _ref.onSwatchHover, first = _ref.first, last = _ref.last, active = _ref.active; var styles = (0, _reactcss2.default)({ 'default': { color: { width: '40px', height: '24px', cursor: 'pointer', background: color, marginBottom: '1px' }, check: { color: colorUtils.getContrastingColor(color), marginLeft: '8px', display: 'none' } }, 'first': { color: { overflow: 'hidden', borderRadius: '2px 2px 0 0' } }, 'last': { color: { overflow: 'hidden', borderRadius: '0 0 2px 2px' } }, 'active': { check: { display: 'block' } }, 'color-#FFFFFF': { color: { boxShadow: 'inset 0 0 0 1px #ddd' }, check: { color: '#333' } }, 'transparent': { check: { color: '#333' } } }, { first: first, last: last, active: active, 'color-#FFFFFF': color === '#FFFFFF', 'transparent': color === 'transparent' }); return _react2.default.createElement( _common.Swatch, { color: color, style: styles.color, onClick: onClick, onHover: onSwatchHover, focusStyle: { boxShadow: '0 0 4px ' + color } }, _react2.default.createElement( 'div', { style: styles.check }, _react2.default.createElement(_CheckIcon2.default, null) ) ); }; exports.default = SwatchesColor; },{"../../helpers/color":350,"../common":318,"@icons/material/CheckIcon":81,"react":"react","reactcss":363}],346:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.SwatchesGroup = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _map = require('lodash/map'); var _map2 = _interopRequireDefault(_map); var _SwatchesColor = require('./SwatchesColor'); var _SwatchesColor2 = _interopRequireDefault(_SwatchesColor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SwatchesGroup = exports.SwatchesGroup = function SwatchesGroup(_ref) { var onClick = _ref.onClick, onSwatchHover = _ref.onSwatchHover, group = _ref.group, active = _ref.active; var styles = (0, _reactcss2.default)({ 'default': { group: { paddingBottom: '10px', width: '40px', float: 'left', marginRight: '10px' } } }); return _react2.default.createElement( 'div', { style: styles.group }, (0, _map2.default)(group, function (color, i) { return _react2.default.createElement(_SwatchesColor2.default, { key: color, color: color, active: color.toLowerCase() === active, first: i === 0, last: i === group.length - 1, onClick: onClick, onSwatchHover: onSwatchHover }); }) ); }; exports.default = SwatchesGroup; },{"./SwatchesColor":345,"lodash/map":282,"react":"react","reactcss":363}],347:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Twitter = undefined; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var _map = require('lodash/map'); var _map2 = _interopRequireDefault(_map); var _merge = require('lodash/merge'); var _merge2 = _interopRequireDefault(_merge); var _color = require('../../helpers/color'); var color = _interopRequireWildcard(_color); var _common = require('../common'); 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 }; } var Twitter = exports.Twitter = function Twitter(_ref) { var onChange = _ref.onChange, onSwatchHover = _ref.onSwatchHover, hex = _ref.hex, colors = _ref.colors, width = _ref.width, triangle = _ref.triangle, _ref$styles = _ref.styles, passedStyles = _ref$styles === undefined ? {} : _ref$styles, _ref$className = _ref.className, className = _ref$className === undefined ? '' : _ref$className; var styles = (0, _reactcss2.default)((0, _merge2.default)({ 'default': { card: { width: width, background: '#fff', border: '0 solid rgba(0,0,0,0.25)', boxShadow: '0 1px 4px rgba(0,0,0,0.25)', borderRadius: '4px', position: 'relative' }, body: { padding: '15px 9px 9px 15px' }, label: { fontSize: '18px', color: '#fff' }, triangle: { width: '0px', height: '0px', borderStyle: 'solid', borderWidth: '0 9px 10px 9px', borderColor: 'transparent transparent #fff transparent', position: 'absolute' }, triangleShadow: { width: '0px', height: '0px', borderStyle: 'solid', borderWidth: '0 9px 10px 9px', borderColor: 'transparent transparent rgba(0,0,0,.1) transparent', position: 'absolute' }, hash: { background: '#F0F0F0', height: '30px', width: '30px', borderRadius: '4px 0 0 4px', float: 'left', color: '#98A1A4', display: 'flex', alignItems: 'center', justifyContent: 'center' }, input: { width: '100px', fontSize: '14px', color: '#666', border: '0px', outline: 'none', height: '28px', boxShadow: 'inset 0 0 0 1px #F0F0F0', boxSizing: 'content-box', borderRadius: '0 4px 4px 0', float: 'left', paddingLeft: '8px' }, swatch: { width: '30px', height: '30px', float: 'left', borderRadius: '4px', margin: '0 6px 6px 0' }, clear: { clear: 'both' } }, 'hide-triangle': { triangle: { display: 'none' }, triangleShadow: { display: 'none' } }, 'top-left-triangle': { triangle: { top: '-10px', left: '12px' }, triangleShadow: { top: '-11px', left: '12px' } }, 'top-right-triangle': { triangle: { top: '-10px', right: '12px' }, triangleShadow: { top: '-11px', right: '12px' } } }, passedStyles), { 'hide-triangle': triangle === 'hide', 'top-left-triangle': triangle === 'top-left', 'top-right-triangle': triangle === 'top-right' }); var handleChange = function handleChange(hexcode, e) { color.isValidHex(hexcode) && onChange({ hex: hexcode, source: 'hex' }, e); }; return _react2.default.createElement( 'div', { style: styles.card, className: 'twitter-picker ' + className }, _react2.default.createElement('div', { style: styles.triangleShadow }), _react2.default.createElement('div', { style: styles.triangle }), _react2.default.createElement( 'div', { style: styles.body }, (0, _map2.default)(colors, function (c, i) { return _react2.default.createElement(_common.Swatch, { key: i, color: c, hex: c, style: styles.swatch, onClick: handleChange, onHover: onSwatchHover, focusStyle: { boxShadow: '0 0 4px ' + c } }); }), _react2.default.createElement( 'div', { style: styles.hash }, '#' ), _react2.default.createElement(_common.EditableInput, { label: null, style: { input: styles.input }, value: hex.replace('#', ''), onChange: handleChange }), _react2.default.createElement('div', { style: styles.clear }) ) ); }; Twitter.propTypes = { width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), triangle: _propTypes2.default.oneOf(['hide', 'top-left', 'top-right']), colors: _propTypes2.default.arrayOf(_propTypes2.default.string), styles: _propTypes2.default.object }; Twitter.defaultProps = { width: 276, colors: ['#FF6900', '#FCB900', '#7BDCB5', '#00D084', '#8ED1FC', '#0693E3', '#ABB8C3', '#EB144C', '#F78DA7', '#9900EF'], triangle: 'top-left', styles: {} }; exports.default = (0, _common.ColorWrap)(Twitter); },{"../../helpers/color":350,"../common":318,"lodash/map":282,"lodash/merge":284,"prop-types":298,"react":"react","reactcss":363}],348:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var calculateChange = exports.calculateChange = function calculateChange(e, hsl, direction, initialA, container) { var containerWidth = container.clientWidth; var containerHeight = container.clientHeight; var x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX; var y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY; var left = x - (container.getBoundingClientRect().left + window.pageXOffset); var top = y - (container.getBoundingClientRect().top + window.pageYOffset); if (direction === 'vertical') { var a = void 0; if (top < 0) { a = 0; } else if (top > containerHeight) { a = 1; } else { a = Math.round(top * 100 / containerHeight) / 100; } if (hsl.a !== a) { return { h: hsl.h, s: hsl.s, l: hsl.l, a: a, source: 'rgb' }; } } else { var _a = void 0; if (left < 0) { _a = 0; } else if (left > containerWidth) { _a = 1; } else { _a = Math.round(left * 100 / containerWidth) / 100; } if (initialA !== _a) { return { h: hsl.h, s: hsl.s, l: hsl.l, a: _a, source: 'rgb' }; } } return null; }; },{}],349:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var checkboardCache = {}; var render = exports.render = function render(c1, c2, size, serverCanvas) { if (typeof document === 'undefined' && !serverCanvas) { return null; } var canvas = serverCanvas ? new serverCanvas() : document.createElement('canvas'); canvas.width = size * 2; canvas.height = size * 2; var ctx = canvas.getContext('2d'); if (!ctx) { return null; } // If no context can be found, return early. ctx.fillStyle = c1; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = c2; ctx.fillRect(0, 0, size, size); ctx.translate(size, size); ctx.fillRect(0, 0, size, size); return canvas.toDataURL(); }; var get = exports.get = function get(c1, c2, size, serverCanvas) { var key = c1 + '-' + c2 + '-' + size + (serverCanvas ? '-server' : ''); if (checkboardCache[key]) { return checkboardCache[key]; } var checkboard = render(c1, c2, size, serverCanvas); checkboardCache[key] = checkboard; return checkboard; }; },{}],350:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.isvalidColorString = exports.red = exports.getContrastingColor = exports.isValidHex = exports.toState = exports.simpleCheckForValidColor = undefined; var _each = require('lodash/each'); var _each2 = _interopRequireDefault(_each); var _tinycolor = require('tinycolor2'); var _tinycolor2 = _interopRequireDefault(_tinycolor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var simpleCheckForValidColor = exports.simpleCheckForValidColor = function simpleCheckForValidColor(data) { var keysToCheck = ['r', 'g', 'b', 'a', 'h', 's', 'l', 'v']; var checked = 0; var passed = 0; (0, _each2.default)(keysToCheck, function (letter) { if (data[letter]) { checked += 1; if (!isNaN(data[letter])) { passed += 1; } if (letter === 's' || letter === 'l') { var percentPatt = /^\d+%$/; if (percentPatt.test(data[letter])) { passed += 1; } } } }); return checked === passed ? data : false; }; var toState = exports.toState = function toState(data, oldHue) { var color = data.hex ? (0, _tinycolor2.default)(data.hex) : (0, _tinycolor2.default)(data); var hsl = color.toHsl(); var hsv = color.toHsv(); var rgb = color.toRgb(); var hex = color.toHex(); if (hsl.s === 0) { hsl.h = oldHue || 0; hsv.h = oldHue || 0; } var transparent = hex === '000000' && rgb.a === 0; return { hsl: hsl, hex: transparent ? 'transparent' : '#' + hex, rgb: rgb, hsv: hsv, oldHue: data.h || oldHue || hsl.h, source: data.source }; }; var isValidHex = exports.isValidHex = function isValidHex(hex) { if (hex === 'transparent') { return true; } // disable hex4 and hex8 var lh = String(hex).charAt(0) === '#' ? 1 : 0; return hex.length !== 4 + lh && hex.length < 7 + lh && (0, _tinycolor2.default)(hex).isValid(); }; var getContrastingColor = exports.getContrastingColor = function getContrastingColor(data) { if (!data) { return '#fff'; } var col = toState(data); if (col.hex === 'transparent') { return 'rgba(0,0,0,0.4)'; } var yiq = (col.rgb.r * 299 + col.rgb.g * 587 + col.rgb.b * 114) / 1000; return yiq >= 128 ? '#000' : '#fff'; }; var red = exports.red = { hsl: { a: 1, h: 0, l: 0.5, s: 1 }, hex: '#ff0000', rgb: { r: 255, g: 0, b: 0, a: 1 }, hsv: { h: 0, s: 1, v: 1, a: 1 } }; var isvalidColorString = exports.isvalidColorString = function isvalidColorString(string, type) { var stringWithoutDegree = string.replace('°', ''); return (0, _tinycolor2.default)(type + ' (' + stringWithoutDegree + ')')._ok; }; },{"lodash/each":257,"tinycolor2":367}],351:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var calculateChange = exports.calculateChange = function calculateChange(e, direction, hsl, container) { var containerWidth = container.clientWidth; var containerHeight = container.clientHeight; var x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX; var y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY; var left = x - (container.getBoundingClientRect().left + window.pageXOffset); var top = y - (container.getBoundingClientRect().top + window.pageYOffset); if (direction === 'vertical') { var h = void 0; if (top < 0) { h = 359; } else if (top > containerHeight) { h = 0; } else { var percent = -(top * 100 / containerHeight) + 100; h = 360 * percent / 100; } if (hsl.h !== h) { return { h: h, s: hsl.s, l: hsl.l, a: hsl.a, source: 'hsl' }; } } else { var _h = void 0; if (left < 0) { _h = 0; } else if (left > containerWidth) { _h = 359; } else { var _percent = left * 100 / containerWidth; _h = 360 * _percent / 100; } if (hsl.h !== _h) { return { h: _h, s: hsl.s, l: hsl.l, a: hsl.a, source: 'hsl' }; } } return null; }; },{}],352:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.handleFocus = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); 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; } /* eslint-disable no-invalid-this */ var handleFocus = exports.handleFocus = function handleFocus(Component) { var Span = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'span'; return function (_React$Component) { _inherits(Focus, _React$Component); function Focus() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Focus); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Focus.__proto__ || Object.getPrototypeOf(Focus)).call.apply(_ref, [this].concat(args))), _this), _this.state = { focus: false }, _this.handleFocus = function () { return _this.setState({ focus: true }); }, _this.handleBlur = function () { return _this.setState({ focus: false }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Focus, [{ key: 'render', value: function render() { return _react2.default.createElement( Span, { onFocus: this.handleFocus, onBlur: this.handleBlur }, _react2.default.createElement(Component, _extends({}, this.props, this.state)) ); } }]); return Focus; }(_react2.default.Component); }; },{"react":"react"}],353:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var calculateChange = exports.calculateChange = function calculateChange(e, hsl, container) { var _container$getBoundin = container.getBoundingClientRect(), containerWidth = _container$getBoundin.width, containerHeight = _container$getBoundin.height; var x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX; var y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY; var left = x - (container.getBoundingClientRect().left + window.pageXOffset); var top = y - (container.getBoundingClientRect().top + window.pageYOffset); if (left < 0) { left = 0; } else if (left > containerWidth) { left = containerWidth; } if (top < 0) { top = 0; } else if (top > containerHeight) { top = containerHeight; } var saturation = left / containerWidth; var bright = 1 - top / containerHeight; return { h: hsl.h, s: saturation, v: bright, a: hsl.a, source: 'hsv' }; }; },{}],354:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.CustomPicker = exports.GooglePicker = exports.TwitterPicker = exports.SwatchesPicker = exports.SliderPicker = exports.SketchPicker = exports.PhotoshopPicker = exports.MaterialPicker = exports.HuePicker = exports.GithubPicker = exports.CompactPicker = exports.ChromePicker = exports.default = exports.CirclePicker = exports.BlockPicker = exports.AlphaPicker = undefined; var _Alpha = require('./components/alpha/Alpha'); Object.defineProperty(exports, 'AlphaPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Alpha).default; } }); var _Block = require('./components/block/Block'); Object.defineProperty(exports, 'BlockPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Block).default; } }); var _Circle = require('./components/circle/Circle'); Object.defineProperty(exports, 'CirclePicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Circle).default; } }); var _Chrome = require('./components/chrome/Chrome'); Object.defineProperty(exports, 'ChromePicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Chrome).default; } }); var _Compact = require('./components/compact/Compact'); Object.defineProperty(exports, 'CompactPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Compact).default; } }); var _Github = require('./components/github/Github'); Object.defineProperty(exports, 'GithubPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Github).default; } }); var _Hue = require('./components/hue/Hue'); Object.defineProperty(exports, 'HuePicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Hue).default; } }); var _Material = require('./components/material/Material'); Object.defineProperty(exports, 'MaterialPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Material).default; } }); var _Photoshop = require('./components/photoshop/Photoshop'); Object.defineProperty(exports, 'PhotoshopPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Photoshop).default; } }); var _Sketch = require('./components/sketch/Sketch'); Object.defineProperty(exports, 'SketchPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Sketch).default; } }); var _Slider = require('./components/slider/Slider'); Object.defineProperty(exports, 'SliderPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Slider).default; } }); var _Swatches = require('./components/swatches/Swatches'); Object.defineProperty(exports, 'SwatchesPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Swatches).default; } }); var _Twitter = require('./components/twitter/Twitter'); Object.defineProperty(exports, 'TwitterPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Twitter).default; } }); var _Google = require('./components/google/Google'); Object.defineProperty(exports, 'GooglePicker', { enumerable: true, get: function get() { return _interopRequireDefault(_Google).default; } }); var _ColorWrap = require('./components/common/ColorWrap'); Object.defineProperty(exports, 'CustomPicker', { enumerable: true, get: function get() { return _interopRequireDefault(_ColorWrap).default; } }); var _Chrome2 = _interopRequireDefault(_Chrome); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _Chrome2.default; },{"./components/alpha/Alpha":300,"./components/block/Block":302,"./components/chrome/Chrome":304,"./components/circle/Circle":308,"./components/common/ColorWrap":312,"./components/compact/Compact":319,"./components/github/Github":322,"./components/google/Google":324,"./components/hue/Hue":328,"./components/material/Material":330,"./components/photoshop/Photoshop":331,"./components/sketch/Sketch":337,"./components/slider/Slider":340,"./components/swatches/Swatches":344,"./components/twitter/Twitter":347}],355:[function(require,module,exports){ (function (process){ /** @license React v16.13.1 * react-is.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary // (unstable) APIs that have been removed. Can we remove the symbols? var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf; var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9; var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6; var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7; function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE); } function typeOf(object) { if (typeof object === 'object' && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type = object.type; switch (type) { case REACT_ASYNC_MODE_TYPE: case REACT_CONCURRENT_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: return type; default: var $$typeofType = type && type.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } return undefined; } // AsyncMode is deprecated along with isAsyncMode var AsyncMode = REACT_ASYNC_MODE_TYPE; var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Lazy = REACT_LAZY_TYPE; var Memo = REACT_MEMO_TYPE; var Portal = REACT_PORTAL_TYPE; var Profiler = REACT_PROFILER_TYPE; var StrictMode = REACT_STRICT_MODE_TYPE; var Suspense = REACT_SUSPENSE_TYPE; var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated function isAsyncMode(object) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.'); } } return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE; } function isConcurrentMode(object) { return typeOf(object) === REACT_CONCURRENT_MODE_TYPE; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isLazy(object) { return typeOf(object) === REACT_LAZY_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } function isSuspense(object) { return typeOf(object) === REACT_SUSPENSE_TYPE; } exports.AsyncMode = AsyncMode; exports.ConcurrentMode = ConcurrentMode; exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Lazy = Lazy; exports.Memo = Memo; exports.Portal = Portal; exports.Profiler = Profiler; exports.StrictMode = StrictMode; exports.Suspense = Suspense; exports.isAsyncMode = isAsyncMode; exports.isConcurrentMode = isConcurrentMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isLazy = isLazy; exports.isMemo = isMemo; exports.isPortal = isPortal; exports.isProfiler = isProfiler; exports.isStrictMode = isStrictMode; exports.isSuspense = isSuspense; exports.isValidElementType = isValidElementType; exports.typeOf = typeOf; })(); } }).call(this,require('_process')) },{"_process":1}],356:[function(require,module,exports){ /** @license React v16.13.1 * react-is.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b? Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119; function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d; exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t}; exports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p}; exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z; },{}],357:[function(require,module,exports){ (function (process){ 'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-is.production.min.js'); } else { module.exports = require('./cjs/react-is.development.js'); } }).call(this,require('_process')) },{"./cjs/react-is.development.js":355,"./cjs/react-is.production.min.js":356,"_process":1}],358:[function(require,module,exports){ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("prop-types"),require("react"),require("signature_pad"),require("trim-canvas")):"function"==typeof define&&define.amd?define(["prop-types","react","signature_pad","trim-canvas"],t):"object"==typeof exports?exports.SignatureCanvas=t(require("prop-types"),require("react"),require("signature_pad"),require("trim-canvas")):e.SignatureCanvas=t(e["prop-types"],e.react,e.signature_pad,e["trim-canvas"])}(this,function(e,t,n,r){return function(e){function t(r){if(n[r])return n[r].exports;var a=n[r]={exports:{},id:r,loaded:!1};return e[r].call(a.exports,a,a.exports,t),a.loaded=!0,a.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t 1 && arguments[1] !== undefined ? arguments[1] : 'span'; return function (_React$Component) { _inherits(Active, _React$Component); function Active() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Active); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Active.__proto__ || Object.getPrototypeOf(Active)).call.apply(_ref, [this].concat(args))), _this), _this.state = { active: false }, _this.handleMouseDown = function () { return _this.setState({ active: true }); }, _this.handleMouseUp = function () { return _this.setState({ active: false }); }, _this.render = function () { return _react2.default.createElement( Span, { onMouseDown: _this.handleMouseDown, onMouseUp: _this.handleMouseUp }, _react2.default.createElement(Component, _extends({}, _this.props, _this.state)) ); }, _temp), _possibleConstructorReturn(_this, _ret); } return Active; }(_react2.default.Component); }; exports.default = active; },{"react":"react"}],361:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.hover = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); 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; } var hover = exports.hover = function hover(Component) { var Span = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'span'; return function (_React$Component) { _inherits(Hover, _React$Component); function Hover() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Hover); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Hover.__proto__ || Object.getPrototypeOf(Hover)).call.apply(_ref, [this].concat(args))), _this), _this.state = { hover: false }, _this.handleMouseOver = function () { return _this.setState({ hover: true }); }, _this.handleMouseOut = function () { return _this.setState({ hover: false }); }, _this.render = function () { return _react2.default.createElement( Span, { onMouseOver: _this.handleMouseOver, onMouseOut: _this.handleMouseOut }, _react2.default.createElement(Component, _extends({}, _this.props, _this.state)) ); }, _temp), _possibleConstructorReturn(_this, _ret); } return Hover; }(_react2.default.Component); }; exports.default = hover; },{"react":"react"}],362:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.flattenNames = undefined; var _isString2 = require('lodash/isString'); var _isString3 = _interopRequireDefault(_isString2); var _forOwn2 = require('lodash/forOwn'); var _forOwn3 = _interopRequireDefault(_forOwn2); var _isPlainObject2 = require('lodash/isPlainObject'); var _isPlainObject3 = _interopRequireDefault(_isPlainObject2); var _map2 = require('lodash/map'); var _map3 = _interopRequireDefault(_map2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var flattenNames = exports.flattenNames = function flattenNames() { var things = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var names = []; (0, _map3.default)(things, function (thing) { if (Array.isArray(thing)) { flattenNames(thing).map(function (name) { return names.push(name); }); } else if ((0, _isPlainObject3.default)(thing)) { (0, _forOwn3.default)(thing, function (value, key) { value === true && names.push(key); names.push(key + '-' + value); }); } else if ((0, _isString3.default)(thing)) { names.push(thing); } }); return names; }; exports.default = flattenNames; },{"lodash/forOwn":260,"lodash/isPlainObject":274,"lodash/isString":276,"lodash/map":282}],363:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ReactCSS = exports.loop = exports.handleActive = exports.handleHover = exports.hover = undefined; var _flattenNames = require('./flattenNames'); var _flattenNames2 = _interopRequireDefault(_flattenNames); var _mergeClasses = require('./mergeClasses'); var _mergeClasses2 = _interopRequireDefault(_mergeClasses); var _autoprefix = require('./autoprefix'); var _autoprefix2 = _interopRequireDefault(_autoprefix); var _hover2 = require('./components/hover'); var _hover3 = _interopRequireDefault(_hover2); var _active = require('./components/active'); var _active2 = _interopRequireDefault(_active); var _loop2 = require('./loop'); var _loop3 = _interopRequireDefault(_loop2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.hover = _hover3.default; exports.handleHover = _hover3.default; exports.handleActive = _active2.default; exports.loop = _loop3.default; var ReactCSS = exports.ReactCSS = function ReactCSS(classes) { for (var _len = arguments.length, activations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { activations[_key - 1] = arguments[_key]; } var activeNames = (0, _flattenNames2.default)(activations); var merged = (0, _mergeClasses2.default)(classes, activeNames); return (0, _autoprefix2.default)(merged); }; exports.default = ReactCSS; },{"./autoprefix":359,"./components/active":360,"./components/hover":361,"./flattenNames":362,"./loop":364,"./mergeClasses":365}],364:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var loopable = function loopable(i, length) { var props = {}; var setProp = function setProp(name) { var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; props[name] = value; }; i === 0 && setProp('first-child'); i === length - 1 && setProp('last-child'); (i === 0 || i % 2 === 0) && setProp('even'); Math.abs(i % 2) === 1 && setProp('odd'); setProp('nth-child', i); return props; }; exports.default = loopable; },{}],365:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.mergeClasses = undefined; var _forOwn2 = require('lodash/forOwn'); var _forOwn3 = _interopRequireDefault(_forOwn2); var _cloneDeep2 = require('lodash/cloneDeep'); var _cloneDeep3 = _interopRequireDefault(_cloneDeep2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var mergeClasses = exports.mergeClasses = function mergeClasses(classes) { var activeNames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var styles = classes.default && (0, _cloneDeep3.default)(classes.default) || {}; activeNames.map(function (name) { var toMerge = classes[name]; if (toMerge) { (0, _forOwn3.default)(toMerge, function (value, key) { if (!styles[key]) { styles[key] = {}; } styles[key] = _extends({}, styles[key], toMerge[key]); }); } return name; }); return styles; }; exports.default = mergeClasses; },{"lodash/cloneDeep":254,"lodash/forOwn":260}],366:[function(require,module,exports){ /*! * Signature Pad v2.3.2 * https://github.com/szimek/signature_pad * * Copyright 2017 Szymon Nowak * Released under the MIT license * * The main idea and some parts of the code (e.g. drawing variable width Bézier curve) are taken from: * http://corner.squareup.com/2012/07/smoother-signatures.html * * Implementation of interpolation using cubic Bézier curves is taken from: * http://benknowscode.wordpress.com/2012/09/14/path-interpolation-using-cubic-bezier-and-control-point-estimation-in-javascript * * Algorithm for approximated length of a Bézier curve is taken from: * http://www.lemoda.net/maths/bezier-length/index.html * */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.SignaturePad = factory()); }(this, (function () { 'use strict'; function Point(x, y, time) { this.x = x; this.y = y; this.time = time || new Date().getTime(); } Point.prototype.velocityFrom = function (start) { return this.time !== start.time ? this.distanceTo(start) / (this.time - start.time) : 1; }; Point.prototype.distanceTo = function (start) { return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2)); }; Point.prototype.equals = function (other) { return this.x === other.x && this.y === other.y && this.time === other.time; }; function Bezier(startPoint, control1, control2, endPoint) { this.startPoint = startPoint; this.control1 = control1; this.control2 = control2; this.endPoint = endPoint; } // Returns approximated length. Bezier.prototype.length = function () { var steps = 10; var length = 0; var px = void 0; var py = void 0; for (var i = 0; i <= steps; i += 1) { var t = i / steps; var cx = this._point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x); var cy = this._point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y); if (i > 0) { var xdiff = cx - px; var ydiff = cy - py; length += Math.sqrt(xdiff * xdiff + ydiff * ydiff); } px = cx; py = cy; } return length; }; /* eslint-disable no-multi-spaces, space-in-parens */ Bezier.prototype._point = function (t, start, c1, c2, end) { return start * (1.0 - t) * (1.0 - t) * (1.0 - t) + 3.0 * c1 * (1.0 - t) * (1.0 - t) * t + 3.0 * c2 * (1.0 - t) * t * t + end * t * t * t; }; /* eslint-disable */ // http://stackoverflow.com/a/27078401/815507 function throttle(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function later() { previous = options.leading === false ? 0 : Date.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function () { var now = Date.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; } function SignaturePad(canvas, options) { var self = this; var opts = options || {}; this.velocityFilterWeight = opts.velocityFilterWeight || 0.7; this.minWidth = opts.minWidth || 0.5; this.maxWidth = opts.maxWidth || 2.5; this.throttle = 'throttle' in opts ? opts.throttle : 16; // in miliseconds this.minDistance = 'minDistance' in opts ? opts.minDistance : 5; if (this.throttle) { this._strokeMoveUpdate = throttle(SignaturePad.prototype._strokeUpdate, this.throttle); } else { this._strokeMoveUpdate = SignaturePad.prototype._strokeUpdate; } this.dotSize = opts.dotSize || function () { return (this.minWidth + this.maxWidth) / 2; }; this.penColor = opts.penColor || 'black'; this.backgroundColor = opts.backgroundColor || 'rgba(0,0,0,0)'; this.onBegin = opts.onBegin; this.onEnd = opts.onEnd; this._canvas = canvas; this._ctx = canvas.getContext('2d'); this.clear(); // We need add these inline so they are available to unbind while still having // access to 'self' we could use _.bind but it's not worth adding a dependency. this._handleMouseDown = function (event) { if (event.which === 1) { self._mouseButtonDown = true; self._strokeBegin(event); } }; this._handleMouseMove = function (event) { if (self._mouseButtonDown) { self._strokeMoveUpdate(event); } }; this._handleMouseUp = function (event) { if (event.which === 1 && self._mouseButtonDown) { self._mouseButtonDown = false; self._strokeEnd(event); } }; this._handleTouchStart = function (event) { if (event.targetTouches.length === 1) { var touch = event.changedTouches[0]; self._strokeBegin(touch); } }; this._handleTouchMove = function (event) { // Prevent scrolling. event.preventDefault(); var touch = event.targetTouches[0]; self._strokeMoveUpdate(touch); }; this._handleTouchEnd = function (event) { var wasCanvasTouched = event.target === self._canvas; if (wasCanvasTouched) { event.preventDefault(); self._strokeEnd(event); } }; // Enable mouse and touch event handlers this.on(); } // Public methods SignaturePad.prototype.clear = function () { var ctx = this._ctx; var canvas = this._canvas; ctx.fillStyle = this.backgroundColor; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillRect(0, 0, canvas.width, canvas.height); this._data = []; this._reset(); this._isEmpty = true; }; SignaturePad.prototype.fromDataURL = function (dataUrl) { var _this = this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var image = new Image(); var ratio = options.ratio || window.devicePixelRatio || 1; var width = options.width || this._canvas.width / ratio; var height = options.height || this._canvas.height / ratio; this._reset(); image.src = dataUrl; image.onload = function () { _this._ctx.drawImage(image, 0, 0, width, height); }; this._isEmpty = false; }; SignaturePad.prototype.toDataURL = function (type) { var _canvas; switch (type) { case 'image/svg+xml': return this._toSVG(); default: for (var _len = arguments.length, options = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { options[_key - 1] = arguments[_key]; } return (_canvas = this._canvas).toDataURL.apply(_canvas, [type].concat(options)); } }; SignaturePad.prototype.on = function () { this._handleMouseEvents(); this._handleTouchEvents(); }; SignaturePad.prototype.off = function () { this._canvas.removeEventListener('mousedown', this._handleMouseDown); this._canvas.removeEventListener('mousemove', this._handleMouseMove); document.removeEventListener('mouseup', this._handleMouseUp); this._canvas.removeEventListener('touchstart', this._handleTouchStart); this._canvas.removeEventListener('touchmove', this._handleTouchMove); this._canvas.removeEventListener('touchend', this._handleTouchEnd); }; SignaturePad.prototype.isEmpty = function () { return this._isEmpty; }; // Private methods SignaturePad.prototype._strokeBegin = function (event) { this._data.push([]); this._reset(); this._strokeUpdate(event); if (typeof this.onBegin === 'function') { this.onBegin(event); } }; SignaturePad.prototype._strokeUpdate = function (event) { var x = event.clientX; var y = event.clientY; var point = this._createPoint(x, y); var lastPointGroup = this._data[this._data.length - 1]; var lastPoint = lastPointGroup && lastPointGroup[lastPointGroup.length - 1]; var isLastPointTooClose = lastPoint && point.distanceTo(lastPoint) < this.minDistance; // Skip this point if it's too close to the previous one if (!(lastPoint && isLastPointTooClose)) { var _addPoint = this._addPoint(point), curve = _addPoint.curve, widths = _addPoint.widths; if (curve && widths) { this._drawCurve(curve, widths.start, widths.end); } this._data[this._data.length - 1].push({ x: point.x, y: point.y, time: point.time, color: this.penColor }); } }; SignaturePad.prototype._strokeEnd = function (event) { var canDrawCurve = this.points.length > 2; var point = this.points[0]; // Point instance if (!canDrawCurve && point) { this._drawDot(point); } if (point) { var lastPointGroup = this._data[this._data.length - 1]; var lastPoint = lastPointGroup[lastPointGroup.length - 1]; // plain object // When drawing a dot, there's only one point in a group, so without this check // such group would end up with exactly the same 2 points. if (!point.equals(lastPoint)) { lastPointGroup.push({ x: point.x, y: point.y, time: point.time, color: this.penColor }); } } if (typeof this.onEnd === 'function') { this.onEnd(event); } }; SignaturePad.prototype._handleMouseEvents = function () { this._mouseButtonDown = false; this._canvas.addEventListener('mousedown', this._handleMouseDown); this._canvas.addEventListener('mousemove', this._handleMouseMove); document.addEventListener('mouseup', this._handleMouseUp); }; SignaturePad.prototype._handleTouchEvents = function () { // Pass touch events to canvas element on mobile IE11 and Edge. this._canvas.style.msTouchAction = 'none'; this._canvas.style.touchAction = 'none'; this._canvas.addEventListener('touchstart', this._handleTouchStart); this._canvas.addEventListener('touchmove', this._handleTouchMove); this._canvas.addEventListener('touchend', this._handleTouchEnd); }; SignaturePad.prototype._reset = function () { this.points = []; this._lastVelocity = 0; this._lastWidth = (this.minWidth + this.maxWidth) / 2; this._ctx.fillStyle = this.penColor; }; SignaturePad.prototype._createPoint = function (x, y, time) { var rect = this._canvas.getBoundingClientRect(); return new Point(x - rect.left, y - rect.top, time || new Date().getTime()); }; SignaturePad.prototype._addPoint = function (point) { var points = this.points; var tmp = void 0; points.push(point); if (points.length > 2) { // To reduce the initial lag make it work with 3 points // by copying the first point to the beginning. if (points.length === 3) points.unshift(points[0]); tmp = this._calculateCurveControlPoints(points[0], points[1], points[2]); var c2 = tmp.c2; tmp = this._calculateCurveControlPoints(points[1], points[2], points[3]); var c3 = tmp.c1; var curve = new Bezier(points[1], c2, c3, points[2]); var widths = this._calculateCurveWidths(curve); // Remove the first element from the list, // so that we always have no more than 4 points in points array. points.shift(); return { curve: curve, widths: widths }; } return {}; }; SignaturePad.prototype._calculateCurveControlPoints = function (s1, s2, s3) { var dx1 = s1.x - s2.x; var dy1 = s1.y - s2.y; var dx2 = s2.x - s3.x; var dy2 = s2.y - s3.y; var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 }; var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 }; var l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1); var l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2); var dxm = m1.x - m2.x; var dym = m1.y - m2.y; var k = l2 / (l1 + l2); var cm = { x: m2.x + dxm * k, y: m2.y + dym * k }; var tx = s2.x - cm.x; var ty = s2.y - cm.y; return { c1: new Point(m1.x + tx, m1.y + ty), c2: new Point(m2.x + tx, m2.y + ty) }; }; SignaturePad.prototype._calculateCurveWidths = function (curve) { var startPoint = curve.startPoint; var endPoint = curve.endPoint; var widths = { start: null, end: null }; var velocity = this.velocityFilterWeight * endPoint.velocityFrom(startPoint) + (1 - this.velocityFilterWeight) * this._lastVelocity; var newWidth = this._strokeWidth(velocity); widths.start = this._lastWidth; widths.end = newWidth; this._lastVelocity = velocity; this._lastWidth = newWidth; return widths; }; SignaturePad.prototype._strokeWidth = function (velocity) { return Math.max(this.maxWidth / (velocity + 1), this.minWidth); }; SignaturePad.prototype._drawPoint = function (x, y, size) { var ctx = this._ctx; ctx.moveTo(x, y); ctx.arc(x, y, size, 0, 2 * Math.PI, false); this._isEmpty = false; }; SignaturePad.prototype._drawCurve = function (curve, startWidth, endWidth) { var ctx = this._ctx; var widthDelta = endWidth - startWidth; var drawSteps = Math.floor(curve.length()); ctx.beginPath(); for (var i = 0; i < drawSteps; i += 1) { // Calculate the Bezier (x, y) coordinate for this step. var t = i / drawSteps; var tt = t * t; var ttt = tt * t; var u = 1 - t; var uu = u * u; var uuu = uu * u; var x = uuu * curve.startPoint.x; x += 3 * uu * t * curve.control1.x; x += 3 * u * tt * curve.control2.x; x += ttt * curve.endPoint.x; var y = uuu * curve.startPoint.y; y += 3 * uu * t * curve.control1.y; y += 3 * u * tt * curve.control2.y; y += ttt * curve.endPoint.y; var width = startWidth + ttt * widthDelta; this._drawPoint(x, y, width); } ctx.closePath(); ctx.fill(); }; SignaturePad.prototype._drawDot = function (point) { var ctx = this._ctx; var width = typeof this.dotSize === 'function' ? this.dotSize() : this.dotSize; ctx.beginPath(); this._drawPoint(point.x, point.y, width); ctx.closePath(); ctx.fill(); }; SignaturePad.prototype._fromData = function (pointGroups, drawCurve, drawDot) { for (var i = 0; i < pointGroups.length; i += 1) { var group = pointGroups[i]; if (group.length > 1) { for (var j = 0; j < group.length; j += 1) { var rawPoint = group[j]; var point = new Point(rawPoint.x, rawPoint.y, rawPoint.time); var color = rawPoint.color; if (j === 0) { // First point in a group. Nothing to draw yet. // All points in the group have the same color, so it's enough to set // penColor just at the beginning. this.penColor = color; this._reset(); this._addPoint(point); } else if (j !== group.length - 1) { // Middle point in a group. var _addPoint2 = this._addPoint(point), curve = _addPoint2.curve, widths = _addPoint2.widths; if (curve && widths) { drawCurve(curve, widths, color); } } else { // Last point in a group. Do nothing. } } } else { this._reset(); var _rawPoint = group[0]; drawDot(_rawPoint); } } }; SignaturePad.prototype._toSVG = function () { var _this2 = this; var pointGroups = this._data; var canvas = this._canvas; var ratio = Math.max(window.devicePixelRatio || 1, 1); var minX = 0; var minY = 0; var maxX = canvas.width / ratio; var maxY = canvas.height / ratio; var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttributeNS(null, 'width', canvas.width); svg.setAttributeNS(null, 'height', canvas.height); this._fromData(pointGroups, function (curve, widths, color) { var path = document.createElement('path'); // Need to check curve for NaN values, these pop up when drawing // lines on the canvas that are not continuous. E.g. Sharp corners // or stopping mid-stroke and than continuing without lifting mouse. if (!isNaN(curve.control1.x) && !isNaN(curve.control1.y) && !isNaN(curve.control2.x) && !isNaN(curve.control2.y)) { var attr = 'M ' + curve.startPoint.x.toFixed(3) + ',' + curve.startPoint.y.toFixed(3) + ' ' + ('C ' + curve.control1.x.toFixed(3) + ',' + curve.control1.y.toFixed(3) + ' ') + (curve.control2.x.toFixed(3) + ',' + curve.control2.y.toFixed(3) + ' ') + (curve.endPoint.x.toFixed(3) + ',' + curve.endPoint.y.toFixed(3)); path.setAttribute('d', attr); path.setAttribute('stroke-width', (widths.end * 2.25).toFixed(3)); path.setAttribute('stroke', color); path.setAttribute('fill', 'none'); path.setAttribute('stroke-linecap', 'round'); svg.appendChild(path); } }, function (rawPoint) { var circle = document.createElement('circle'); var dotSize = typeof _this2.dotSize === 'function' ? _this2.dotSize() : _this2.dotSize; circle.setAttribute('r', dotSize); circle.setAttribute('cx', rawPoint.x); circle.setAttribute('cy', rawPoint.y); circle.setAttribute('fill', rawPoint.color); svg.appendChild(circle); }); var prefix = 'data:image/svg+xml;base64,'; var header = ''; var body = svg.innerHTML; // IE hack for missing innerHTML property on SVGElement if (body === undefined) { var dummy = document.createElement('dummy'); var nodes = svg.childNodes; dummy.innerHTML = ''; for (var i = 0; i < nodes.length; i += 1) { dummy.appendChild(nodes[i].cloneNode(true)); } body = dummy.innerHTML; } var footer = ''; var data = header + body + footer; return prefix + btoa(data); }; SignaturePad.prototype.fromData = function (pointGroups) { var _this3 = this; this.clear(); this._fromData(pointGroups, function (curve, widths) { return _this3._drawCurve(curve, widths.start, widths.end); }, function (rawPoint) { return _this3._drawDot(rawPoint); }); this._data = pointGroups; }; SignaturePad.prototype.toData = function () { return this._data; }; return SignaturePad; }))); },{}],367:[function(require,module,exports){ // TinyColor v1.4.2 // https://github.com/bgrins/TinyColor // Brian Grinstead, MIT License (function(Math) { var trimLeft = /^\s+/, trimRight = /\s+$/, tinyCounter = 0, mathRound = Math.round, mathMin = Math.min, mathMax = Math.max, mathRandom = Math.random; function tinycolor (color, opts) { color = (color) ? color : ''; opts = opts || { }; // If input is already a tinycolor, return itself if (color instanceof tinycolor) { return color; } // If we are called as a function, call using new instead if (!(this instanceof tinycolor)) { return new tinycolor(color, opts); } var rgb = inputToRGB(color); this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = mathRound(100*this._a) / 100, this._format = opts.format || rgb.format; this._gradientType = opts.gradientType; // Don't let the range of [0,255] come back in [0,1]. // Potentially lose a little bit of precision here, but will fix issues where // .5 gets interpreted as half of the total, instead of half of 1 // If it was supposed to be 128, this was already taken care of by `inputToRgb` if (this._r < 1) { this._r = mathRound(this._r); } if (this._g < 1) { this._g = mathRound(this._g); } if (this._b < 1) { this._b = mathRound(this._b); } this._ok = rgb.ok; this._tc_id = tinyCounter++; } tinycolor.prototype = { isDark: function() { return this.getBrightness() < 128; }, isLight: function() { return !this.isDark(); }, isValid: function() { return this._ok; }, getOriginalInput: function() { return this._originalInput; }, getFormat: function() { return this._format; }, getAlpha: function() { return this._a; }, getBrightness: function() { //http://www.w3.org/TR/AERT#color-contrast var rgb = this.toRgb(); return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; }, getLuminance: function() { //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef var rgb = this.toRgb(); var RsRGB, GsRGB, BsRGB, R, G, B; RsRGB = rgb.r/255; GsRGB = rgb.g/255; BsRGB = rgb.b/255; if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);} if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);} if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);} return (0.2126 * R) + (0.7152 * G) + (0.0722 * B); }, setAlpha: function(value) { this._a = boundAlpha(value); this._roundA = mathRound(100*this._a) / 100; return this; }, toHsv: function() { var hsv = rgbToHsv(this._r, this._g, this._b); return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; }, toHsvString: function() { var hsv = rgbToHsv(this._r, this._g, this._b); var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); return (this._a == 1) ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")"; }, toHsl: function() { var hsl = rgbToHsl(this._r, this._g, this._b); return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; }, toHslString: function() { var hsl = rgbToHsl(this._r, this._g, this._b); var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); return (this._a == 1) ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")"; }, toHex: function(allow3Char) { return rgbToHex(this._r, this._g, this._b, allow3Char); }, toHexString: function(allow3Char) { return '#' + this.toHex(allow3Char); }, toHex8: function(allow4Char) { return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); }, toHex8String: function(allow4Char) { return '#' + this.toHex8(allow4Char); }, toRgb: function() { return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a }; }, toRgbString: function() { return (this._a == 1) ? "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" : "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")"; }, toPercentageRgb: function() { return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a }; }, toPercentageRgbString: function() { return (this._a == 1) ? "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" : "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; }, toName: function() { if (this._a === 0) { return "transparent"; } if (this._a < 1) { return false; } return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; }, toFilter: function(secondColor) { var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a); var secondHex8String = hex8String; var gradientType = this._gradientType ? "GradientType = 1, " : ""; if (secondColor) { var s = tinycolor(secondColor); secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a); } return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")"; }, toString: function(format) { var formatSet = !!format; format = format || this._format; var formattedString = false; var hasAlpha = this._a < 1 && this._a >= 0; var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); if (needsAlphaFormat) { // Special case for "transparent", all other non-alpha formats // will return rgba when there is transparency. if (format === "name" && this._a === 0) { return this.toName(); } return this.toRgbString(); } if (format === "rgb") { formattedString = this.toRgbString(); } if (format === "prgb") { formattedString = this.toPercentageRgbString(); } if (format === "hex" || format === "hex6") { formattedString = this.toHexString(); } if (format === "hex3") { formattedString = this.toHexString(true); } if (format === "hex4") { formattedString = this.toHex8String(true); } if (format === "hex8") { formattedString = this.toHex8String(); } if (format === "name") { formattedString = this.toName(); } if (format === "hsl") { formattedString = this.toHslString(); } if (format === "hsv") { formattedString = this.toHsvString(); } return formattedString || this.toHexString(); }, clone: function() { return tinycolor(this.toString()); }, _applyModification: function(fn, args) { var color = fn.apply(null, [this].concat([].slice.call(args))); this._r = color._r; this._g = color._g; this._b = color._b; this.setAlpha(color._a); return this; }, lighten: function() { return this._applyModification(lighten, arguments); }, brighten: function() { return this._applyModification(brighten, arguments); }, darken: function() { return this._applyModification(darken, arguments); }, desaturate: function() { return this._applyModification(desaturate, arguments); }, saturate: function() { return this._applyModification(saturate, arguments); }, greyscale: function() { return this._applyModification(greyscale, arguments); }, spin: function() { return this._applyModification(spin, arguments); }, _applyCombination: function(fn, args) { return fn.apply(null, [this].concat([].slice.call(args))); }, analogous: function() { return this._applyCombination(analogous, arguments); }, complement: function() { return this._applyCombination(complement, arguments); }, monochromatic: function() { return this._applyCombination(monochromatic, arguments); }, splitcomplement: function() { return this._applyCombination(splitcomplement, arguments); }, triad: function() { return this._applyCombination(triad, arguments); }, tetrad: function() { return this._applyCombination(tetrad, arguments); } }; // If input is an object, force 1 into "1.0" to handle ratios properly // String input requires "1.0" as input, so 1 will be treated as 1 tinycolor.fromRatio = function(color, opts) { if (typeof color == "object") { var newColor = {}; for (var i in color) { if (color.hasOwnProperty(i)) { if (i === "a") { newColor[i] = color[i]; } else { newColor[i] = convertToPercentage(color[i]); } } } color = newColor; } return tinycolor(color, opts); }; // Given a string or object, convert that input to RGB // Possible string inputs: // // "red" // "#f00" or "f00" // "#ff0000" or "ff0000" // "#ff000000" or "ff000000" // "rgb 255 0 0" or "rgb (255, 0, 0)" // "rgb 1.0 0 0" or "rgb (1, 0, 0)" // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" // function inputToRGB(color) { var rgb = { r: 0, g: 0, b: 0 }; var a = 1; var s = null; var v = null; var l = null; var ok = false; var format = false; if (typeof color == "string") { color = stringInputToObject(color); } if (typeof color == "object") { if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { rgb = rgbToRgb(color.r, color.g, color.b); ok = true; format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { s = convertToPercentage(color.s); v = convertToPercentage(color.v); rgb = hsvToRgb(color.h, s, v); ok = true; format = "hsv"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { s = convertToPercentage(color.s); l = convertToPercentage(color.l); rgb = hslToRgb(color.h, s, l); ok = true; format = "hsl"; } if (color.hasOwnProperty("a")) { a = color.a; } } a = boundAlpha(a); return { ok: ok, format: color.format || format, r: mathMin(255, mathMax(rgb.r, 0)), g: mathMin(255, mathMax(rgb.g, 0)), b: mathMin(255, mathMax(rgb.b, 0)), a: a }; } // Conversion Functions // -------------------- // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: // // `rgbToRgb` // Handle bounds / percentage checking to conform to CSS color spec // // *Assumes:* r, g, b in [0, 255] or [0, 1] // *Returns:* { r, g, b } in [0, 255] function rgbToRgb(r, g, b){ return { r: bound01(r, 255) * 255, g: bound01(g, 255) * 255, b: bound01(b, 255) * 255 }; } // `rgbToHsl` // Converts an RGB color value to HSL. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] // *Returns:* { h, s, l } in [0,1] function rgbToHsl(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, l = (max + min) / 2; if(max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, l: l }; } // `hslToRgb` // Converts an HSL color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hslToRgb(h, s, l) { var r, g, b; h = bound01(h, 360); s = bound01(s, 100); l = bound01(l, 100); function hue2rgb(p, q, t) { if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1/6) return p + (q - p) * 6 * t; if(t < 1/2) return q; if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } if(s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHsv` // Converts an RGB color value to HSV // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] // *Returns:* { h, s, v } in [0,1] function rgbToHsv(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, v = max; var d = max - min; s = max === 0 ? 0 : d / max; if(max == min) { h = 0; // achromatic } else { switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, v: v }; } // `hsvToRgb` // Converts an HSV color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hsvToRgb(h, s, v) { h = bound01(h, 360) * 6; s = bound01(s, 100); v = bound01(v, 100); var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod]; return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHex` // Converts an RGB color to hex // Assumes r, g, and b are contained in the set [0, 255] // Returns a 3 or 6 character hex function rgbToHex(r, g, b, allow3Char) { var hex = [ pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)) ]; // Return a 3 character hex if possible if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } return hex.join(""); } // `rgbaToHex` // Converts an RGBA color plus alpha transparency to hex // Assumes r, g, b are contained in the set [0, 255] and // a in [0, 1]. Returns a 4 or 8 character rgba hex function rgbaToHex(r, g, b, a, allow4Char) { var hex = [ pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)), pad2(convertDecimalToHex(a)) ]; // Return a 4 character hex if possible if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); } return hex.join(""); } // `rgbaToArgbHex` // Converts an RGBA color to an ARGB Hex8 string // Rarely used, but required for "toFilter()" function rgbaToArgbHex(r, g, b, a) { var hex = [ pad2(convertDecimalToHex(a)), pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)) ]; return hex.join(""); } // `equals` // Can be called with any tinycolor input tinycolor.equals = function (color1, color2) { if (!color1 || !color2) { return false; } return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); }; tinycolor.random = function() { return tinycolor.fromRatio({ r: mathRandom(), g: mathRandom(), b: mathRandom() }); }; // Modification Functions // ---------------------- // Thanks to less.js for some of the basics here // function desaturate(color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.s -= amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function saturate(color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.s += amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function greyscale(color) { return tinycolor(color).desaturate(100); } function lighten (color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.l += amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } function brighten(color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var rgb = tinycolor(color).toRgb(); rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); return tinycolor(rgb); } function darken (color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.l -= amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. // Values outside of this range will be wrapped into this range. function spin(color, amount) { var hsl = tinycolor(color).toHsl(); var hue = (hsl.h + amount) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return tinycolor(hsl); } // Combination Functions // --------------------- // Thanks to jQuery xColor for some of the ideas behind these // function complement(color) { var hsl = tinycolor(color).toHsl(); hsl.h = (hsl.h + 180) % 360; return tinycolor(hsl); } function triad(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) ]; } function tetrad(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) ]; } function splitcomplement(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) ]; } function analogous(color, results, slices) { results = results || 6; slices = slices || 30; var hsl = tinycolor(color).toHsl(); var part = 360 / slices; var ret = [tinycolor(color)]; for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { hsl.h = (hsl.h + part) % 360; ret.push(tinycolor(hsl)); } return ret; } function monochromatic(color, results) { results = results || 6; var hsv = tinycolor(color).toHsv(); var h = hsv.h, s = hsv.s, v = hsv.v; var ret = []; var modification = 1 / results; while (results--) { ret.push(tinycolor({ h: h, s: s, v: v})); v = (v + modification) % 1; } return ret; } // Utility Functions // --------------------- tinycolor.mix = function(color1, color2, amount) { amount = (amount === 0) ? 0 : (amount || 50); var rgb1 = tinycolor(color1).toRgb(); var rgb2 = tinycolor(color2).toRgb(); var p = amount / 100; var rgba = { r: ((rgb2.r - rgb1.r) * p) + rgb1.r, g: ((rgb2.g - rgb1.g) * p) + rgb1.g, b: ((rgb2.b - rgb1.b) * p) + rgb1.b, a: ((rgb2.a - rgb1.a) * p) + rgb1.a }; return tinycolor(rgba); }; // Readability Functions // --------------------- // false // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false tinycolor.isReadable = function(color1, color2, wcag2) { var readability = tinycolor.readability(color1, color2); var wcag2Parms, out; out = false; wcag2Parms = validateWCAG2Parms(wcag2); switch (wcag2Parms.level + wcag2Parms.size) { case "AAsmall": case "AAAlarge": out = readability >= 4.5; break; case "AAlarge": out = readability >= 3; break; case "AAAsmall": out = readability >= 7; break; } return out; }; // `mostReadable` // Given a base color and a list of possible foreground or background // colors for that base, returns the most readable color. // Optionally returns Black or White if the most readable color is unreadable. // *Example* // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" tinycolor.mostReadable = function(baseColor, colorList, args) { var bestColor = null; var bestScore = 0; var readability; var includeFallbackColors, level, size ; args = args || {}; includeFallbackColors = args.includeFallbackColors ; level = args.level; size = args.size; for (var i= 0; i < colorList.length ; i++) { readability = tinycolor.readability(baseColor, colorList[i]); if (readability > bestScore) { bestScore = readability; bestColor = tinycolor(colorList[i]); } } if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { return bestColor; } else { args.includeFallbackColors=false; return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); } }; // Big List of Colors // ------------------ // var names = tinycolor.names = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "0ff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000", blanchedalmond: "ffebcd", blue: "00f", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", burntsienna: "ea7e5d", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "0ff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "f0f", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslategray: "789", lightslategrey: "789", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "0f0", limegreen: "32cd32", linen: "faf0e6", magenta: "f0f", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "f00", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", wheat: "f5deb3", white: "fff", whitesmoke: "f5f5f5", yellow: "ff0", yellowgreen: "9acd32" }; // Make it easy to access colors via `hexNames[hex]` var hexNames = tinycolor.hexNames = flip(names); // Utilities // --------- // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` function flip(o) { var flipped = { }; for (var i in o) { if (o.hasOwnProperty(i)) { flipped[o[i]] = i; } } return flipped; } // Return a valid alpha value [0,1] with all invalid values being set to 1 function boundAlpha(a) { a = parseFloat(a); if (isNaN(a) || a < 0 || a > 1) { a = 1; } return a; } // Take input from [0, n] and return it as [0, 1] function bound01(n, max) { if (isOnePointZero(n)) { n = "100%"; } var processPercent = isPercentage(n); n = mathMin(max, mathMax(0, parseFloat(n))); // Automatically convert percentage into number if (processPercent) { n = parseInt(n * max, 10) / 100; } // Handle floating point rounding errors if ((Math.abs(n - max) < 0.000001)) { return 1; } // Convert into [0, 1] range if it isn't already return (n % max) / parseFloat(max); } // Force a number between 0 and 1 function clamp01(val) { return mathMin(1, mathMax(0, val)); } // Parse a base-16 hex value into a base-10 integer function parseIntFromHex(val) { return parseInt(val, 16); } // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 // function isOnePointZero(n) { return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; } // Check to see if string passed in is a percentage function isPercentage(n) { return typeof n === "string" && n.indexOf('%') != -1; } // Force a hex value to have 2 characters function pad2(c) { return c.length == 1 ? '0' + c : '' + c; } // Replace a decimal with it's percentage value function convertToPercentage(n) { if (n <= 1) { n = (n * 100) + "%"; } return n; } // Converts a decimal to a hex value function convertDecimalToHex(d) { return Math.round(parseFloat(d) * 255).toString(16); } // Converts a hex value to a decimal function convertHexToDecimal(h) { return (parseIntFromHex(h) / 255); } var matchers = (function() { // var CSS_INTEGER = "[-\\+]?\\d+%?"; // var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; // Actual matching. // Parentheses and commas are optional, but not required. // Whitespace can take the place of commas or opening paren var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; return { CSS_UNIT: new RegExp(CSS_UNIT), rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ }; })(); // `isValidCSSUnit` // Take in a single string / number and check to see if it looks like a CSS unit // (see `matchers` above for definition). function isValidCSSUnit(color) { return !!matchers.CSS_UNIT.exec(color); } // `stringInputToObject` // Permissive string parsing. Take in a number of formats, and output an object // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` function stringInputToObject(color) { color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); var named = false; if (names[color]) { color = names[color]; named = true; } else if (color == 'transparent') { return { r: 0, g: 0, b: 0, a: 0, format: "name" }; } // Try to match string input using regular expressions. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] // Just return an object and let the conversion functions handle that. // This way the result will be the same whether the tinycolor is initialized with string or object. var match; if ((match = matchers.rgb.exec(color))) { return { r: match[1], g: match[2], b: match[3] }; } if ((match = matchers.rgba.exec(color))) { return { r: match[1], g: match[2], b: match[3], a: match[4] }; } if ((match = matchers.hsl.exec(color))) { return { h: match[1], s: match[2], l: match[3] }; } if ((match = matchers.hsla.exec(color))) { return { h: match[1], s: match[2], l: match[3], a: match[4] }; } if ((match = matchers.hsv.exec(color))) { return { h: match[1], s: match[2], v: match[3] }; } if ((match = matchers.hsva.exec(color))) { return { h: match[1], s: match[2], v: match[3], a: match[4] }; } if ((match = matchers.hex8.exec(color))) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), a: convertHexToDecimal(match[4]), format: named ? "name" : "hex8" }; } if ((match = matchers.hex6.exec(color))) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), format: named ? "name" : "hex" }; } if ((match = matchers.hex4.exec(color))) { return { r: parseIntFromHex(match[1] + '' + match[1]), g: parseIntFromHex(match[2] + '' + match[2]), b: parseIntFromHex(match[3] + '' + match[3]), a: convertHexToDecimal(match[4] + '' + match[4]), format: named ? "name" : "hex8" }; } if ((match = matchers.hex3.exec(color))) { return { r: parseIntFromHex(match[1] + '' + match[1]), g: parseIntFromHex(match[2] + '' + match[2]), b: parseIntFromHex(match[3] + '' + match[3]), format: named ? "name" : "hex" }; } return false; } function validateWCAG2Parms(parms) { // return valid WCAG2 parms for isReadable. // If input parms are invalid, return {"level":"AA", "size":"small"} var level, size; parms = parms || {"level":"AA", "size":"small"}; level = (parms.level || "AA").toUpperCase(); size = (parms.size || "small").toLowerCase(); if (level !== "AA" && level !== "AAA") { level = "AA"; } if (size !== "small" && size !== "large") { size = "small"; } return {"level":level, "size":size}; } // Node: Export function if (typeof module !== "undefined" && module.exports) { module.exports = tinycolor; } // AMD/requirejs: Define the module else if (typeof define === 'function' && define.amd) { define(function () {return tinycolor;}); } // Browser: Expose to window else { window.tinycolor = tinycolor; } })(Math); },{}],368:[function(require,module,exports){ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.trimCanvas=t():e.trimCanvas=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t){"use strict";function r(e){var t=e.getContext("2d"),r=e.width,n=e.height,o=t.getImageData(0,0,r,n).data,f=a(!0,r,n,o),i=a(!1,r,n,o),c=u(!0,r,n,o),d=u(!1,r,n,o),p=d-c+1,l=i-f+1,s=t.getImageData(c,f,p,l);return e.width=p,e.height=l,t.clearRect(0,0,p,l),t.putImageData(s,0,0),e}function n(e,t,r,n){return{red:n[4*(r*t+e)],green:n[4*(r*t+e)+1],blue:n[4*(r*t+e)+2],alpha:n[4*(r*t+e)+3]}}function o(e,t,r,o){return n(e,t,r,o).alpha}function a(e,t,r,n){for(var a=e?1:-1,u=e?0:r-1,f=u;e?f-1;f+=a)for(var i=0;i-1;f+=a)for(var i=0;i