UNPKG

@eform/ng-formio-builder

Version:

The Angular.js form builder component.

1,591 lines (1,406 loc) 5.91 MB
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.formioBuilder = f()}})(function(){var define,module,exports;return (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<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){ (function (global){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _utils = _dereq_('./utils'); var FormioUtils = _interopRequireWildcard(_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } if ((typeof global === 'undefined' ? 'undefined' : _typeof(global)) === 'object') { global.FormioUtils = FormioUtils; } exports.default = FormioUtils; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./utils":3}],2:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // Use only immutable useful functions from Lodash. // Visit https://lodash.com/docs for more info. var lodashOperators = exports.lodashOperators = [ // Array 'chunk', 'compact', 'concat', 'difference', 'differenceBy', 'differenceWith', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'findIndex', 'findLastIndex', 'first', 'flatten', 'flattenDeep', 'flattenDepth', 'fromPairs', 'head', 'indexOf', 'initial', 'intersection', 'intersectionBy', 'intersectionWith', 'join', 'last', 'lastIndexOf', 'nth', 'slice', 'sortedIndex', 'sortedIndexBy', 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexBy', 'sortedLastIndexOf', 'sortedUniq', 'sortedUniqBy', 'tail', 'take', 'takeRight', 'takeRightWhile', 'takeWhile', 'union', 'unionBy', 'unionWith', 'uniq', 'uniqBy', 'uniqWith', 'unzip', 'unzipWith', 'without', 'xor', 'xorBy', 'xorWith', 'zip', 'zipObject', 'zipObjectDeep', 'zipWith', // Collection 'countBy', 'every', 'filter', 'find', 'findLast', 'flatMap', 'flatMapDeep', 'flatMapDepth', 'groupBy', 'includes', 'invokeMap', 'keyBy', 'map', 'orderBy', 'partition', 'reduce', 'reduceRight', 'reject', 'sample', 'sampleSize', 'shuffle', 'size', 'some', 'sortBy', // Date 'now', // Function 'flip', 'negate', 'overArgs', 'partial', 'partialRight', 'rearg', 'rest', 'spread', // Lang 'castArray', 'clone', 'cloneDeep', 'cloneDeepWith', 'cloneDeep', 'conformsTo', 'eq', 'gt', 'gte', 'isArguments', 'isArray', 'isArrayBuffer', 'isArrayLike', 'isArrayLikeObject', 'isBoolean', 'isBuffer', 'isDate', 'isElement', 'isEmpty', 'isEqual', 'isEqualWith', 'isError', 'isFinite', 'isFunction', 'isInteger', 'isLength', 'isMap', 'isMatch', 'isMatchWith', 'isNaN', 'isNative', 'isNil', 'isNull', 'isNumber', 'isObject', 'isObjectLike', 'isPlainObject', 'isRegExp', 'isSafeInteger', 'isSet', 'isString', 'isSymbol', 'isTypedArray', 'isUndefined', 'isWeakMap', 'isWeakSet', 'lt', 'lte', 'toArray', 'toFinite', 'toInteger', 'toLength', 'toNumber', 'toPlainObject', 'toSafeInteger', 'toString', // Math 'add', 'ceil', 'divide', 'floor', 'max', 'maxBy', 'mean', 'meanBy', 'min', 'minBy', 'multiply', 'round', 'subtract', 'sum', 'sumBy', // Number 'clamp', 'inRange', 'random', // Object 'at', 'entries', 'entriesIn', 'findKey', 'findLastKey', 'functions', 'functionsIn', 'get', 'has', 'hasIn', 'invert', 'invertBy', 'invoke', 'keys', 'keysIn', 'mapKeys', 'mapValues', 'omit', 'omitBy', 'pick', 'pickBy', 'result', 'toPairs', 'toPairsIn', 'transform', 'values', 'valuesIn', // String 'camelCase', 'capitalize', 'deburr', 'endsWith', 'escape', 'escapeRegExp', 'kebabCase', 'lowerCase', 'lowerFirst', 'pad', 'padEnd', 'padStart', 'parseInt', 'repeat', 'replace', 'snakeCase', 'split', 'startCase', 'startsWith', 'toLower', 'toUpper', 'trim', 'trimEnd', 'trimStart', 'truncate', 'unescape', 'upperCase', 'upperFirst', 'words', // Util 'cond', 'conforms', 'constant', 'defaultTo', 'flow', 'flowRight', 'identity', 'iteratee', 'matches', 'matchesProperty', 'method', 'methodOf', 'nthArg', 'over', 'overEvery', 'overSome', 'property', 'propertyOf', 'range', 'rangeRight', 'stubArray', 'stubFalse', 'stubObject', 'stubString', 'stubTrue', 'times', 'toPath', 'uniqueId']; },{}],3:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.jsonLogic = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.evaluate = evaluate; exports.getRandomComponentId = getRandomComponentId; exports.getPropertyValue = getPropertyValue; exports.getElementRect = getElementRect; exports.boolValue = boolValue; exports.isMongoId = isMongoId; exports.isLayoutComponent = isLayoutComponent; exports.eachComponent = eachComponent; exports.matchComponent = matchComponent; exports.getComponent = getComponent; exports.findComponents = findComponents; exports.flattenComponents = flattenComponents; exports.hasCondition = hasCondition; exports.parseFloatExt = parseFloatExt; exports.formatAsCurrency = formatAsCurrency; exports.escapeRegExCharacters = escapeRegExCharacters; exports.checkCalculated = checkCalculated; exports.checkSimpleConditional = checkSimpleConditional; exports.checkCustomConditional = checkCustomConditional; exports.checkJsonConditional = checkJsonConditional; exports.checkCondition = checkCondition; exports.checkTrigger = checkTrigger; exports.setActionProperty = setActionProperty; exports.getValue = getValue; exports.interpolate = interpolate; exports.uniqueName = uniqueName; exports.guid = guid; exports.getDateSetting = getDateSetting; exports.isValidDate = isValidDate; exports.getLocaleDateFormatInfo = getLocaleDateFormatInfo; exports.convertFormatToFlatpickr = convertFormatToFlatpickr; exports.convertFormatToMoment = convertFormatToMoment; exports.getInputMask = getInputMask; exports.matchInputMask = matchInputMask; exports.getNumberSeparators = getNumberSeparators; exports.getNumberDecimalLimit = getNumberDecimalLimit; exports.getCurrencyAffixes = getCurrencyAffixes; exports.fieldData = fieldData; exports.delay = delay; var _lodash = _dereq_('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _jsonLogicJs = _dereq_('json-logic-js'); var _jsonLogicJs2 = _interopRequireDefault(_jsonLogicJs); var _moment = _dereq_('moment'); var _moment2 = _interopRequireDefault(_moment); var _operators = _dereq_('./jsonlogic/operators'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } // Configure JsonLogic _operators.lodashOperators.forEach(function (name) { return _jsonLogicJs2.default.add_operation('_' + name, _lodash2.default[name]); }); // Retrieve Any Date _jsonLogicJs2.default.add_operation('getDate', function (date) { return (0, _moment2.default)(date).toISOString(); }); // Set Relative Minimum Date _jsonLogicJs2.default.add_operation('relativeMinDate', function (relativeMinDate) { return (0, _moment2.default)().subtract(relativeMinDate, 'days').toISOString(); }); // Set Relative Maximum Date _jsonLogicJs2.default.add_operation('relativeMaxDate', function (relativeMaxDate) { return (0, _moment2.default)().add(relativeMaxDate, 'days').toISOString(); }); exports.jsonLogic = _jsonLogicJs2.default; /** * Evaluate a method. * * @param func * @param args * @return {*} */ function evaluate(func, args, ret, tokenize) { var returnVal = null; var component = args.component ? args.component : { key: 'unknown' }; if (!args.form && args.instance) { args.form = _lodash2.default.get(args.instance, 'root._form', {}); } if (typeof func === 'string') { if (ret) { func += ';return ' + ret; } var params = _lodash2.default.keys(args); if (tokenize) { // Replace all {{ }} references with actual data. func = func.replace(/({{\s+(.*)\s+}})/, function (match, $1, $2) { if ($2.indexOf('data.') === 0) { return _lodash2.default.get(args.data, $2.replace('data.', '')); } else if ($2.indexOf('row.') === 0) { return _lodash2.default.get(args.row, $2.replace('row.', '')); } // Support legacy... return _lodash2.default.get(args.data, $2); }); } try { func = new (Function.prototype.bind.apply(Function, [null].concat(_toConsumableArray(params), [func])))(); } catch (err) { console.warn('An error occured within the custom function for ' + component.key, err); returnVal = null; func = false; } } if (typeof func === 'function') { var values = _lodash2.default.values(args); try { returnVal = func.apply(undefined, _toConsumableArray(values)); } catch (err) { returnVal = null; console.warn('An error occured within custom function for ' + component.key, err); } } else if ((typeof func === 'undefined' ? 'undefined' : _typeof(func)) === 'object') { try { returnVal = _jsonLogicJs2.default.apply(func, args); } catch (err) { returnVal = null; console.warn('An error occured within custom function for ' + component.key, err); } } else if (func) { console.warn('Unknown function type for ' + component.key); } return returnVal; } function getRandomComponentId() { return 'e' + Math.random().toString(36).substring(7); } /** * Get a property value of an element. * * @param style * @param prop * @return {number} */ function getPropertyValue(style, prop) { var value = style.getPropertyValue(prop); value = value ? value.replace(/[^0-9.]/g, '') : '0'; return parseFloat(value); } /** * Get an elements bounding rectagle. * * @param element * @return {{x: string, y: string, width: string, height: string}} */ function getElementRect(element) { var style = window.getComputedStyle(element, null); return { x: getPropertyValue(style, 'left'), y: getPropertyValue(style, 'top'), width: getPropertyValue(style, 'width'), height: getPropertyValue(style, 'height') }; } /** * Determines the boolean value of a setting. * * @param value * @return {boolean} */ function boolValue(value) { if (_lodash2.default.isBoolean(value)) { return value; } else if (_lodash2.default.isString(value)) { return value.toLowerCase() === 'true'; } else { return !!value; } } /** * Check to see if an ID is a mongoID. * @param text * @return {Array|{index: number, input: string}|Boolean|*} */ function isMongoId(text) { return text.toString().match(/^[0-9a-fA-F]{24}$/); } /** * Determine if a component is a layout component or not. * * @param {Object} component * The component to check. * * @returns {Boolean} * Whether or not the component is a layout component. */ function isLayoutComponent(component) { return Boolean(component.columns && Array.isArray(component.columns) || component.rows && Array.isArray(component.rows) || component.components && Array.isArray(component.components)); } /** * Iterate through each component within a form. * * @param {Object} components * The components to iterate. * @param {Function} fn * The iteration function to invoke for each component. * @param {Boolean} includeAll * Whether or not to include layout components. * @param {String} path * The current data path of the element. Example: data.user.firstName * @param {Object} parent * The parent object. */ function eachComponent(components, fn, includeAll, path, parent) { if (!components) return; path = path || ''; components.forEach(function (component) { var hasColumns = component.columns && Array.isArray(component.columns); var hasRows = component.rows && Array.isArray(component.rows); var hasComps = component.components && Array.isArray(component.components); var noRecurse = false; var newPath = component.key ? path ? path + '.' + component.key : component.key : ''; // Keep track of parent references. if (parent) { // Ensure we don't create infinite JSON structures. component.parent = _lodash2.default.clone(parent); delete component.parent.components; delete component.parent.componentMap; delete component.parent.columns; delete component.parent.rows; } if (includeAll || component.tree || !hasColumns && !hasRows && !hasComps) { noRecurse = fn(component, newPath); } var subPath = function subPath() { if (component.key && !(['panel', 'table', 'well', 'columns', 'fieldset', 'tabs', 'form'].indexOf(component.type) !== -1) && (['datagrid', 'container', 'editgrid'].indexOf(component.type) !== -1 || component.tree)) { return newPath; } else if (component.key && component.type === 'form') { return newPath + '.data'; } return path; }; if (!noRecurse) { if (hasColumns) { component.columns.forEach(function (column) { return eachComponent(column.components, fn, includeAll, subPath(), parent ? component : null); }); } else if (hasRows) { component.rows.forEach(function (row) { if (Array.isArray(row)) { row.forEach(function (column) { return eachComponent(column.components, fn, includeAll, subPath(), parent ? component : null); }); } }); } else if (hasComps) { eachComponent(component.components, fn, includeAll, subPath(), parent ? component : null); } } }); } /** * Matches if a component matches the query. * * @param component * @param query * @return {boolean} */ function matchComponent(component, query) { if (_lodash2.default.isString(query)) { return component.key === query; } else { var matches = false; _lodash2.default.forOwn(query, function (value, key) { matches = _lodash2.default.get(component, key) === value; if (!matches) { return false; } }); return matches; } } /** * Get a component by its key * * @param {Object} components * The components to iterate. * @param {String|Object} key * The key of the component to get, or a query of the component to search. * * @returns {Object} * The component that matches the given key, or undefined if not found. */ function getComponent(components, key, includeAll) { var result = void 0; eachComponent(components, function (component, path) { if (path === key) { component.path = path; result = component; return true; } }, includeAll); return result; } /** * Finds a component provided a query of properties of that component. * * @param components * @param query * @return {*} */ function findComponents(components, query) { var results = []; eachComponent(components, function (component, path) { if (matchComponent(component, query)) { component.path = path; results.push(component); } }, true); return results; } /** * Flatten the form components for data manipulation. * * @param {Object} components * The components to iterate. * @param {Boolean} includeAll * Whether or not to include layout components. * * @returns {Object} * The flattened components map. */ function flattenComponents(components, includeAll) { var flattened = {}; eachComponent(components, function (component, path) { flattened[path] = component; }, includeAll); return flattened; } /** * Returns if this component has a conditional statement. * * @param component - The component JSON schema. * * @returns {boolean} - TRUE - This component has a conditional, FALSE - No conditional provided. */ function hasCondition(component) { return Boolean(component.customConditional || component.conditional && component.conditional.when || component.conditional && component.conditional.json); } /** * Extension of standard #parseFloat(value) function, that also clears input string. * * @param {any} value * The value to parse. * * @returns {Number} * Parsed value. */ function parseFloatExt(value) { return parseFloat(_lodash2.default.isString(value) ? value.replace(/[^\de.+-]/gi, '') : value); } /** * Formats provided value in way how Currency component uses it. * * @param {any} value * The value to format. * * @returns {String} * Value formatted for Currency component. */ function formatAsCurrency(value) { var parsedValue = parseFloatExt(value); if (_lodash2.default.isNaN(parsedValue)) { return ''; } var parts = _lodash2.default.round(parsedValue, 2).toString().split('.'); parts[0] = _lodash2.default.chunk(Array.from(parts[0]).reverse(), 3).reverse().map(function (part) { return part.reverse().join(''); }).join(','); parts[1] = _lodash2.default.pad(parts[1], 2, '0'); return parts.join('.'); } /** * Escapes RegEx characters in provided String value. * * @param {String} value * String for escaping RegEx characters. * @returns {string} * String with escaped RegEx characters. */ function escapeRegExCharacters(value) { return value.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'); } /** * Checks the calculated value for a provided component and data. * * @param {Object} component * The component to check for the calculated value. * @param {Object} submission * A submission object. * @param data * The full submission data. */ function checkCalculated(component, submission, rowData) { // Process calculated value stuff if present. if (component.calculateValue) { _lodash2.default.set(rowData, component.key, evaluate(component.calculateValue, { value: undefined, data: submission ? submission.data : rowData, row: rowData, util: this, component: component }, 'value')); } } /** * Check if a simple conditional evaluates to true. * * @param condition * @param condition * @param row * @param data * @returns {boolean} */ function checkSimpleConditional(component, condition, row, data) { var value = null; if (row) { value = getValue({ data: row }, condition.when); } if (data && _lodash2.default.isNil(value)) { value = getValue({ data: data }, condition.when); } // FOR-400 - Fix issue where falsey values were being evaluated as show=true if (_lodash2.default.isNil(value)) { value = ''; } // Special check for selectboxes component. if (_lodash2.default.isObject(value) && _lodash2.default.has(value, condition.eq)) { return value[condition.eq].toString() === condition.show.toString(); } // FOR-179 - Check for multiple values. if (Array.isArray(value) && value.indexOf(condition.eq) !== -1) { return condition.show.toString() === 'true'; } return value.toString() === condition.eq.toString() === (condition.show.toString() === 'true'); } /** * Check custom javascript conditional. * * @param component * @param custom * @param row * @param data * @returns {*} */ function checkCustomConditional(component, custom, row, data, form, variable, onError, instance) { if (typeof custom === 'string') { custom = 'var ' + variable + ' = true; ' + custom + '; return ' + variable + ';'; } var value = instance && instance.evaluate ? instance.evaluate(custom) : evaluate(custom, { row: row, data: data, form: form }); if (value === null) { return onError; } return value; } function checkJsonConditional(component, json, row, data, form, onError) { try { return _jsonLogicJs2.default.apply(json, { data: data, row: row, form: form, _: _lodash2.default }); } catch (err) { console.warn('An error occurred in jsonLogic advanced condition for ' + component.key, err); return onError; } } /** * Checks the conditions for a provided component and data. * * @param component * The component to check for the condition. * @param row * The data within a row * @param data * The full submission data. * * @returns {boolean} */ function checkCondition(component, row, data, form, instance) { if (component.customConditional) { return checkCustomConditional(component, component.customConditional, row, data, form, 'show', true, instance); } else if (component.conditional && component.conditional.when) { return checkSimpleConditional(component, component.conditional, row, data, true); } else if (component.conditional && component.conditional.json) { return checkJsonConditional(component, component.conditional.json, row, data, form, instance); } // Default to show. return true; } /** * Test a trigger on a component. * * @param component * @param action * @param data * @param row * @returns {mixed} */ function checkTrigger(component, trigger, row, data, form, instance) { switch (trigger.type) { case 'simple': return checkSimpleConditional(component, trigger.simple, row, data); case 'javascript': return checkCustomConditional(component, trigger.javascript, row, data, form, 'result', false, instance); case 'json': return checkJsonConditional(component, trigger.json, row, data, form, false); } // If none of the types matched, don't fire the trigger. return false; } function setActionProperty(component, action, row, data, result, instance) { switch (action.property.type) { case 'boolean': if (_lodash2.default.get(component, action.property.value, false).toString() !== action.state.toString()) { _lodash2.default.set(component, action.property.value, action.state.toString() === 'true'); } break; case 'string': { var evalData = { data: data, row: row, component: component, result: result }; var newValue = instance && instance.interpolate ? instance.interpolate(action.text, evalData) : interpolate(action.text, evalData); if (newValue !== _lodash2.default.get(component, action.property.value, '')) { _lodash2.default.set(component, action.property.value, newValue); } break; } } return component; } /** * Get the value for a component key, in the given submission. * * @param {Object} submission * A submission object to search. * @param {String} key * A for components API key to search for. */ function getValue(submission, key) { var search = function search(data) { if (_lodash2.default.isPlainObject(data)) { if (_lodash2.default.has(data, key)) { return data[key]; } var value = null; _lodash2.default.forOwn(data, function (prop) { var result = search(prop); if (!_lodash2.default.isNil(result)) { value = result; return false; } }); return value; } else { return null; } }; return search(submission.data); } /** * Interpolate a string and add data replacements. * * @param string * @param data * @returns {XML|string|*|void} */ function interpolate(string, data) { var templateSettings = { evaluate: /\{%(.+?)%\}/g, interpolate: /\{\{(.+?)\}\}/g, escape: /\{\{\{(.+?)\}\}\}/g }; try { return _lodash2.default.template(string, templateSettings)(data); } catch (err) { console.warn('Error interpolating template', err, string, data); } } /** * Make a filename guaranteed to be unique. * @param name * @returns {string} */ function uniqueName(name) { var parts = name.toLowerCase().replace(/[^0-9a-z.]/g, '').split('.'); var fileName = parts[0]; var ext = parts.length > 1 ? '.' + _lodash2.default.last(parts) : ''; return fileName.substr(0, 10) + '-' + guid() + ext; } function guid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0; var v = c === 'x' ? r : r & 0x3 | 0x8; return v.toString(16); }); } /** * Return a translated date setting. * * @param date * @return {*} */ function getDateSetting(date) { if (_lodash2.default.isNil(date) || _lodash2.default.isNaN(date) || date === '') { return null; } if (date instanceof Date) { return date; } else if (typeof date.toDate === 'function') { return date.isValid() ? date.toDate() : null; } var dateSetting = typeof date !== 'string' || date.indexOf('moment(') === -1 ? (0, _moment2.default)(date) : null; if (dateSetting && dateSetting.isValid()) { return dateSetting.toDate(); } dateSetting = null; try { var value = new Function('moment', 'return ' + date + ';')(_moment2.default); if (typeof value === 'string') { dateSetting = (0, _moment2.default)(value); } else if (typeof value.toDate === 'function') { dateSetting = (0, _moment2.default)(value.toDate().toUTCString()); } else if (value instanceof Date) { dateSetting = (0, _moment2.default)(value); } } catch (e) { return null; } if (!dateSetting) { return null; } // Ensure this is a date. if (!dateSetting.isValid()) { return null; } return dateSetting.toDate(); } function isValidDate(date) { return _lodash2.default.isDate(date) && !_lodash2.default.isNaN(date.getDate()); } function getLocaleDateFormatInfo(locale) { var formatInfo = {}; var day = 21; var exampleDate = new Date(2017, 11, day); var localDateString = exampleDate.toLocaleDateString(locale); formatInfo.dayFirst = localDateString.slice(0, 2) === day.toString(); return formatInfo; } /** * Convert the format from the angular-datepicker module to flatpickr format. * @param format * @return {string} */ function convertFormatToFlatpickr(format) { return format // Year conversion. .replace(/y/g, 'Y').replace('YYYY', 'Y').replace('YY', 'y') // Month conversion. .replace('MMMM', 'F').replace(/M/g, 'n').replace('nnn', 'M').replace('nn', 'm') // Day in month. .replace(/d/g, 'j').replace('jj', 'd') // Day in week. .replace('EEEE', 'l').replace('EEE', 'D') // Hours, minutes, seconds .replace('HH', 'H').replace('hh', 'h').replace('mm', 'i').replace('ss', 'S').replace(/a/g, 'K'); } /** * Convert the format from the angular-datepicker module to moment format. * @param format * @return {string} */ function convertFormatToMoment(format) { return format // Year conversion. .replace(/y/g, 'Y') // Day in month. .replace(/d/g, 'D') // Day in week. .replace(/E/g, 'd') // AM/PM marker .replace(/a/g, 'A'); } /** * Returns an input mask that is compatible with the input mask library. * @param {string} mask - The eForm input mask. * @returns {Array} - The input mask for the mask library. */ function getInputMask(mask) { if (mask instanceof Array) { return mask; } var maskArray = []; maskArray.numeric = true; for (var i = 0; i < mask.length; i++) { switch (mask[i]) { case '9': maskArray.push(/\d/); break; case 'A': maskArray.numeric = false; maskArray.push(/[a-zA-Z]/); break; case 'a': maskArray.numeric = false; maskArray.push(/[a-z]/); break; case '*': maskArray.numeric = false; maskArray.push(/[a-zA-Z0-9]/); break; default: maskArray.push(mask[i]); break; } } return maskArray; } function matchInputMask(value, inputMask) { if (!inputMask) { return true; } for (var i = 0; i < inputMask.length; i++) { var char = value[i]; var charPart = inputMask[i]; if (!(_lodash2.default.isRegExp(charPart) && charPart.test(char) || charPart === char)) { return false; } } return true; } function getNumberSeparators() { var lang = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'en'; var formattedNumberString = 12345.6789.toLocaleString(lang); var delimeters = formattedNumberString.match(/..(.)...(.)../); if (!delimeters) { return { delimiter: ',', decimalSeparator: '.' }; } return { delimiter: delimeters.length > 1 ? delimeters[1] : ',', decimalSeparator: delimeters.length > 2 ? delimeters[2] : '.' }; } function getNumberDecimalLimit(component) { // Determine the decimal limit. Defaults to 20 but can be overridden by validate.step or decimalLimit settings. var decimalLimit = 20; var step = _lodash2.default.get(component, 'validate.step', 'any'); if (step !== 'any') { var parts = step.toString().split('.'); if (parts.length > 1) { decimalLimit = parts[1].length; } } return decimalLimit; } function getCurrencyAffixes(_ref) { var _ref$currency = _ref.currency, currency = _ref$currency === undefined ? 'USD' : _ref$currency, decimalLimit = _ref.decimalLimit, decimalSeparator = _ref.decimalSeparator, lang = _ref.lang; // Get the prefix and suffix from the localized string. var regex = '(.*)?100'; if (decimalLimit) { regex += (decimalSeparator === '.' ? '\\.' : decimalSeparator) + '0{' + decimalLimit + '}'; } regex += '(.*)?'; var parts = 100 .toLocaleString(lang, { style: 'currency', currency: currency, useGrouping: true, maximumFractionDigits: decimalLimit, minimumFractionDigits: decimalLimit }).replace('.', decimalSeparator).match(new RegExp(regex)); return { prefix: parts[1] || '', suffix: parts[2] || '' }; } /** * Fetch the field data provided a component. * * @param data * @param component * @return {*} */ function fieldData(data, component) { if (!data) { return ''; } if (!component || !component.key) { return data; } if (component.key.indexOf('.') !== -1) { var value = data; var parts = component.key.split('.'); var key = ''; for (var i = 0; i < parts.length; i++) { key = parts[i]; // Handle nested resources if (value.hasOwnProperty('_id')) { value = value.data; } // Return if the key is not found on the value. if (!value.hasOwnProperty(key)) { return; } // Convert old single field data in submissions to multiple if (key === parts[parts.length - 1] && component.multiple && !Array.isArray(value[key])) { value[key] = [value[key]]; } // Set the value of this key. value = value[key]; } return value; } else { // Convert old single field data in submissions to multiple if (component.multiple && !Array.isArray(data[component.key])) { data[component.key] = [data[component.key]]; } return data[component.key]; } } /** * Delays function execution with possibility to execute function synchronously or cancel it. * * @param fn Function to delay * @param delay Delay time * @return {*} */ function delay(fn) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var timer = setTimeout.apply(undefined, [fn, delay].concat(args)); function cancel() { clearTimeout(timer); } function earlyCall() { cancel(); return fn.apply(undefined, args); } earlyCall.timer = timer; earlyCall.cancel = cancel; return earlyCall; } },{"./jsonlogic/operators":2,"json-logic-js":8,"lodash":213,"moment":232}],4:[function(_dereq_,module,exports){ (function (global){ "use strict"; /*! ng-formio v2.35.6 | https://unpkg.com/ng-formio@2.35.6/LICENSE.txt */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.formio = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof _dereq_&&_dereq_;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 _dereq_&&_dereq_,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){ (function (root, factory) { // AMD if (typeof define === 'function' && define.amd) define(['angular'], factory); // Global else factory(angular); }(this, function (angular) { angular .module('ckeditor', []) .directive('ckeditor', ['$parse', ckeditorDirective]); // Polyfill setImmediate function. var setImmediate = window && window.setImmediate ? window.setImmediate : function (fn) { setTimeout(fn, 0); }; /** * CKEditor directive. * * @example * <div ckeditor="options" ng-model="content" ready="onReady()"></div> */ function ckeditorDirective($parse) { return { restrict: 'A', require: ['ckeditor', 'ngModel'], controller: [ '$scope', '$element', '$attrs', '$parse', '$q', ckeditorController ], link: function (scope, element, attrs, ctrls) { // get needed controllers var controller = ctrls[0]; // our own, see below var ngModelController = ctrls[1]; // Initialize the editor content when it is ready. controller.ready().then(function initialize() { // Sync view on specific events. ['dataReady', 'change', 'blur', 'saveSnapshot'].forEach(function (event) { controller.onCKEvent(event, function syncView() { ngModelController.$setViewValue(controller.instance.getData() || ''); }); }); controller.instance.setReadOnly(!! attrs.readonly); attrs.$observe('readonly', function (readonly) { controller.instance.setReadOnly(!! readonly); }); // Defer the ready handler calling to ensure that the editor is // completely ready and populated with data. setImmediate(function () { $parse(attrs.ready)(scope); }); }); // Set editor data when view data change. ngModelController.$render = function syncEditor() { controller.ready().then(function () { // "noSnapshot" prevent recording an undo snapshot controller.instance.setData(ngModelController.$viewValue || '', { noSnapshot: true, callback: function () { // Amends the top of the undo stack with the current DOM changes // ie: merge snapshot with the first empty one // http://docs.ckeditor.com/#!/api/CKEDITOR.editor-event-updateSnapshot controller.instance.fire('updateSnapshot'); } }); }); }; } }; } /** * CKEditor controller. */ function ckeditorController($scope, $element, $attrs, $parse, $q) { var config = $parse($attrs.ckeditor)($scope) || {}; var editorElement = $element[0]; var instance; var readyDeferred = $q.defer(); // a deferred to be resolved when the editor is ready // Create editor instance. if (editorElement.hasAttribute('contenteditable') && editorElement.getAttribute('contenteditable').toLowerCase() == 'true') { instance = this.instance = CKEDITOR.inline(editorElement, config); } else { instance = this.instance = CKEDITOR.replace(editorElement, config); } /** * Listen on events of a given type. * This make all event asynchronous and wrapped in $scope.$apply. * * @param {String} event * @param {Function} listener * @returns {Function} Deregistration function for this listener. */ this.onCKEvent = function (event, listener) { instance.on(event, asyncListener); function asyncListener() { var args = arguments; setImmediate(function () { applyListener.apply(null, args); }); } function applyListener() { var args = arguments; $scope.$apply(function () { listener.apply(null, args); }); } // Return the deregistration function return function $off() { instance.removeListener(event, applyListener); }; }; this.onCKEvent('instanceReady', function() { readyDeferred.resolve(true); }); /** * Check if the editor if ready. * * @returns {Promise} */ this.ready = function ready() { return readyDeferred.promise; }; // Destroy editor when the scope is destroyed. $scope.$on('$destroy', function onDestroy() { // do not delete too fast or pending events will throw errors readyDeferred.promise.then(function() { instance.destroy(false); }); }); } })); },{}],2:[function(_dereq_,module,exports){ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /* * * A AngularJS module that implements the HTML5 W3C saveAs() in browsers that * do not natively support it * * (c) 2015 Philipp Alferov * License: MIT * */ module.exports = 'ngFileSaver'; angular.module('ngFileSaver', []) .factory('FileSaver', ['Blob', 'SaveAs', 'FileSaverUtils', __webpack_require__(1)]) .factory('FileSaverUtils', [__webpack_require__(2)]) .factory('Blob', ['$window', __webpack_require__(3)]) .factory('SaveAs', [__webpack_require__(5)]); /***/ }, /* 1 */ /***/ function(module, exports) { 'use strict'; module.exports = function FileSaver(Blob, SaveAs, FileSaverUtils) { function save(blob, filename, disableAutoBOM) { try { SaveAs(blob, filename, disableAutoBOM); } catch(err) { FileSaverUtils.handleErrors(err.message); } } return { /** * saveAs * Immediately starts saving a file, returns undefined. * * @name saveAs * @function * @param {Blob} data A Blob instance * @param {Object} filename Custom filename (extension is optional) * @param {Boolean} disableAutoBOM Disable automatically provided Unicode * text encoding hints * * @return {Undefined} */ saveAs: function(data, filename, disableAutoBOM) { if (!FileSaverUtils.isBlobInstance(data)) { FileSaverUtils.handleErrors('Data argument should be a blob instance'); } if (!FileSaverUtils.isString(filename)) { FileSaverUtils.handleErrors('Filename argument should be a string'); } return save(data, filename, disableAutoBOM); } }; }; /***/ }, /* 2 */ /***/ function(module, exports) { 'use strict'; module.exports = function FileSaverUtils() { return { handleErrors: function(msg) { throw new Error(msg); }, isString: function(obj) { return typeof obj === 'string' || obj instanceof String; }, isUndefined: function(obj) { return typeof obj === 'undefined'; }, isBlobInstance: function(obj) { return obj instanceof Blob; } }; }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(4); module.exports = function Blob($window) { return $window.Blob; }; /***/ }, /* 4 */ /***/ function(module, exports) { /* Blob.js * A Blob implementation. * 2014-07-24 * * By Eli Grey, http://eligrey.com * By Devin Samarin, https://github.com/dsamarin * License: MIT * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md */ /*global self, unescape */ /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */ (function (view) { "use strict"; view.URL = view.URL || view.webkitURL; if (view.Blob && view.URL) { try { new Blob; return; } catch (e) {} } // Internally we use a BlobBuilder implementation to base Blob off of // in order to support older browsers that only have BlobBuilder var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) { var get_class = function(object) { return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1]; } , FakeBlobBuilder = function BlobBuilder() { this.data = []; } , FakeBlob = function Blob(data, type, encoding) { this.data = data; this.size = data.length; this.type = type; this.encoding = encoding; } , FBB_proto = FakeBlobBuilder.prototype , FB_proto = FakeBlob.prototype , FileReaderSync = view.FileReaderSync , FileException = function(type) { this.code = this[this.name = type]; } , file_ex_codes = ( "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR " + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR" ).split(" ") , file_ex_code = file_ex_codes.length , real_URL = view.URL || view.webkitURL || view , real_create_object_URL = real_URL.createObjectURL , real_revoke_object_URL = real_URL.revokeObjectURL , URL = real_URL , btoa = view.btoa , atob = view.atob , ArrayBuffer = view.ArrayBuffer , Uint8Array = view.Uint8Array , origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/ ; FakeBlob.fake = FB_proto.fake = true; while (file_ex_code--) { FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1; } // Polyfill URL if (!real_URL.createObjectURL) { URL = view.URL = function(uri) { var uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a") , uri_origin ; uri_info.href = uri; if (!("origin" in uri_info)) { if (uri_info.protocol.toLowerCase() === "data:") { uri_info.origin = null; } else { uri_origin = uri.match(origin); uri_info.origin = uri_origin && uri_origin[1]; } } return uri_info; }; } URL.createObjectURL = function(blob) { var type = blob.type , data_URI_header ; if (type === null) { type = "application/octet-stream"; } if (blob instanceof FakeBlob) { data_URI_header = "data:" + type; if (blob.encoding === "base64") { return data_URI_header + ";base64," + blob.data; } else if (blob.encoding === "URI") { return data_URI_header + "," + decodeURIComponent(blob.data); } if (btoa) { return data_URI_header + ";base64," + btoa(blob.data); } else { return data_URI_header + "," + encodeURIComponent(blob.data); } } else if (real_create_object_URL) { return real_create_object_URL.call(real_URL, blob); } }; URL.revokeObjectURL = function(object_URL) { if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) { real_revoke_object_URL.call(real_URL, object_URL); } }; FBB_proto.append = function(data/*, endings*/) { var bb = this.data; // decode data to a binary string if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) { var str = "" , buf = new Uint8Array(data) , i = 0 , buf_len = buf.length ; for (; i < buf_len; i++) { str += String.fromCharCode(buf[i]); } bb.push(str); } else if (get_class(data) === "Blob" || get_class(data) === "File") { if (FileReaderSync) { var fr = new FileReaderSync; bb.push(fr.readAsBinaryString(data)); } else { // async FileReader won't work as BlobBuilder is sync throw new FileException("NOT_READABLE_ERR"); } } else if (data instanceof FakeBlob) { if (data.encoding === "base64" && atob) { bb.push(atob(data.data)); } else if (data.encoding === "URI") { bb.push(decodeURIComponent(data.data)); } else if (data.encoding === "raw") { bb.push(data.data); } } else { if (typeof data !== "string") { data += ""; // convert unsupported types to strings } // decode UTF-16 to binary string bb.push(unescape(encodeURIComponent(data))); } }; FBB_proto.getBlob = function(type) { if (!arguments.length) { type = null; } return new FakeBlob(this.data.join(""), type, "raw"); }; FBB_proto.toString = function() { return "[object BlobBuilder]"; }; FB_proto.slice = function(start, end, type) { var args = arguments.length; if (args < 3) { type = null; } return new FakeBlob( this.data.slice(start, args > 1 ? end : this.data.length) , type , this.encoding ); }; FB_proto.toString = function() { return "[object Blob]"; }; FB_proto.close = function() { this.size = 0; delete this.data; }; return FakeBlobBuilder; }(view)); view.Blob = function(blobParts, options) { var type = options ? (options.type || "") : ""; var builder = new BlobBuilder(); if (blobParts) { for (var i = 0, len = blobParts.length; i < len; i++) { if (Uint8Array && blobParts[i] instanceof Uint8Array) { builder.append(blobParts[i].buffer); } else { builder.append(blobParts[i]); } } } var blob = builder.getBlob(type); if (!blob.slice && blob.webkitSlice) { blob.slice = blob.webkitSlice; } return blob; }; var getPrototypeOf = Object.getPrototypeOf || function(object) { return object.__proto__; }; view.Blob.prototype = getPrototypeOf(new view.Blob()); }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this)); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = function SaveAs() { return __webpack_require__(6).saveAs || function() {}; }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js * A saveAs() FileSaver implementation. * 1.3.2 * 2016-06-16 18:25:19 * * By Eli Grey, http://eligrey.com * License: MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ var saveAs = saveAs || (function(view) { "use strict"; // IE <10 is explicitly unsupported if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document // only get URL when necessary in case Blob.js hasn't overridden it yet , get_URL = function() { return view.URL || view.webk