text
stringlengths
2
1.05M
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('echarts/lib/echarts'), require('echarts/lib/component/tooltip'), require('echarts/lib/component/legend'), require('echarts/lib/chart/heatmap'), require('echarts/lib/component/visualMap'), require('echarts/extension/bmap/bmap'), require('echarts/lib/chart/map')) : typeof define === 'function' && define.amd ? define(['echarts/lib/echarts', 'echarts/lib/component/tooltip', 'echarts/lib/component/legend', 'echarts/lib/chart/heatmap', 'echarts/lib/component/visualMap', 'echarts/extension/bmap/bmap', 'echarts/lib/chart/map'], factory) : (global.Veheatmap = factory(global.echarts)); }(this, (function (echarts) { 'use strict'; echarts = 'default' in echarts ? echarts['default'] : echarts; echarts.registerTheme('ve-chart', { categoryAxis: { axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false } }, valueAxis: { axisLine: { show: false } }, line: { smooth: true }, grid: { containLabel: true, left: 10, right: 10 } }); var itemPoint = function itemPoint(color) { return ['<span style="', 'background-color:' + color + ';', 'display: inline-block;', 'width: 10px;', 'height: 10px;', 'border-radius: 50%;', 'margin-right:2px;', '"></span>'].join(''); }; var color = ['#19d4ae', '#5ab1ef', '#fa6e86', '#ffb980', '#0067a6', '#c4b4e4', '#d87a80', '#9cbbff', '#d9d0c7', '#87a997', '#d49ea2', '#5b4947', '#7ba3a8']; var HEAT_MAP_COLOR = ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']; var HEAT_BMAP_COLOR = ['blue', 'blue', 'green', 'yellow', 'red']; var numberFormat = function numberFormat(val) { var digits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; if (isNaN(+val)) return val; var symbolMap = [{ value: 1E18, symbol: 'E' }, { value: 1E15, symbol: 'P' }, { value: 1E12, symbol: 'T' }, { value: 1E9, symbol: 'B' }, { value: 1E6, symbol: 'M' }, { value: 1E3, symbol: 'k' }]; for (var i = 0; i < symbolMap.length; i++) { if (Math.abs(val) >= symbolMap[i].value) { return (val / symbolMap[i].value).toFixed(digits) + symbolMap[i].symbol; } } return val.toString(); }; var formatTausends = function formatTausends(num) { return String(num).replace(/^(\s+|-)?\d+(?=.?\d*($|\s))/g, function (m) { return m.replace(/(?=(?!\b)(\d{3})+$)/g, ','); }); }; var getFormated = function getFormated(val, type) { var digit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2; var defaultVal = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '-'; if (val == null || isNaN(val)) return defaultVal; switch (type) { case 'KMB': return numberFormat(val); case 'percent': return parseFloat((val * 100).toFixed(digit)) + '%'; case 'normal': return formatTausends(val); default: return val; } }; var $get = function $get(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.send(null); xhr.onload = function () { resolve(JSON.parse(xhr.responseText)); }; xhr.onerror = function () { reject(JSON.parse(xhr.responseText)); }; }); }; var mapPromise = {}; var getMapJSON = function getMapJSON(_ref) { var position = _ref.position, positionJsonLink = _ref.positionJsonLink, beforeRegisterMapOnce = _ref.beforeRegisterMapOnce, mapURLProfix = _ref.mapURLProfix; var link = positionJsonLink || '' + mapURLProfix + position + '.json'; if (!mapPromise[link]) { mapPromise[link] = $get(link).then(function (res) { if (beforeRegisterMapOnce) res = beforeRegisterMapOnce(res); return res; }); } return mapPromise[link]; }; var bmapPromise = null; var amapPromise = null; var getBmap = function getBmap(key, v) { if (!bmapPromise) { bmapPromise = new Promise(function (resolve, reject) { var callbackName = 'bmap' + Date.now(); window[callbackName] = resolve; var script = document.createElement('script'); script.src = ['https://api.map.baidu.com/api?v=' + (v || '2.0'), 'ak=' + key, 'callback=' + callbackName].join('&'); document.body.appendChild(script); }); } return bmapPromise; }; var getAmap = function getAmap(key, v) { if (!amapPromise) { amapPromise = new Promise(function (resolve, reject) { var callbackName = 'amap' + Date.now(); window[callbackName] = resolve; var script = document.createElement('script'); script.src = ['https://webapi.amap.com/maps?v=' + (v || '1.4.3'), 'key=' + key, 'callback=' + callbackName].join('&'); document.body.appendChild(script); }); } return amapPromise; }; var getType = function getType(v) { return Object.prototype.toString.call(v); }; var toKebab = function toKebab(v) { return v.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); }; var isArray = function isArray(v) { return getType(v) === '[object Array]'; }; var isObject = function isObject(v) { return getType(v) === '[object Object]'; }; 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 toArray = function (arr) { return Array.isArray(arr) ? arr : Array.from(arr); }; function getAxisList(rows, label) { var result = []; rows.forEach(function (row) { if (!~result.indexOf(row[label])) result.push(row[label]); }); return result; } function getData(args) { var rows = args.rows, innerXAxisList = args.innerXAxisList, innerYAxisList = args.innerYAxisList, xDim = args.xDim, yDim = args.yDim, metrics = args.metrics, type = args.type, extraMetrics = args.extraMetrics; var result = null; if (type === 'cartesian') { result = rows.map(function (row) { var xIndex = innerXAxisList.indexOf(row[xDim]); var yIndex = innerYAxisList.indexOf(row[yDim]); var value = metrics ? row[metrics] : 1; var extraData = extraMetrics.map(function (m) { return row[m] || '-'; }); return { value: [xIndex, yIndex, value].concat(extraData) }; }); } else { result = rows.map(function (row) { var value = metrics ? row[metrics] : 1; return { value: [row[xDim], row[yDim], value] }; }); } return result; } function getAxis(list, name) { return { type: 'category', data: list, name: name, nameLocation: 'end', splitArea: { show: true } }; } function getVisualMap(args) { var min = args.innerMin, max = args.innerMax, type = args.type, heatColor = args.heatColor; var result = { min: min, max: max, calculable: true }; var extra = null; if (type === 'map') { extra = { orient: 'vertical', left: 0, bottom: 0, inRange: { color: heatColor || HEAT_MAP_COLOR } }; } else if (type === 'bmap' || type === 'amap') { extra = { show: false, orient: 'vertical', left: 0, bottom: 0, inRange: { color: heatColor || HEAT_BMAP_COLOR } }; } else { extra = { orient: 'horizontal', left: 'center', bottom: 10, dimension: 2, inRange: heatColor && { color: heatColor } }; } return _extends(result, extra); } function getSeries(args) { var chartData = args.chartData; return [{ type: 'heatmap', data: chartData }]; } function getTooltip(args) { var dataType = args.dataType, innerXAxisList = args.innerXAxisList, innerYAxisList = args.innerYAxisList, digit = args.digit, extraMetrics = args.extraMetrics, metrics = args.metrics; return { trigger: 'item', formatter: function formatter(_ref) { var color$$1 = _ref.color, _ref$data$value = toArray(_ref.data.value), xDim = _ref$data$value[0], yDim = _ref$data$value[1], value = _ref$data$value[2], extraData = _ref$data$value.slice(3); var tpl = []; tpl.push(innerXAxisList[xDim] + ' ~ ' + innerYAxisList[yDim] + '<br>'); extraMetrics.forEach(function (m, index) { tpl.push(m + ': ' + extraData[index] + '<br>'); }); tpl.push(itemPoint(color$$1) + ' ' + metrics + ': ' + getFormated(value, dataType, digit) + '<br>'); return tpl.join(''); } }; } var heatmap = function heatmap(columns, rows, settings, status) { var _settings$type = settings.type, type = _settings$type === undefined ? 'cartesian' : _settings$type, xAxisList = settings.xAxisList, yAxisList = settings.yAxisList, _settings$dimension = settings.dimension, dimension = _settings$dimension === undefined ? [columns[0], columns[1]] : _settings$dimension, _settings$metrics = settings.metrics, metrics = _settings$metrics === undefined ? columns[2] : _settings$metrics, _settings$dataType = settings.dataType, dataType = _settings$dataType === undefined ? 'normal' : _settings$dataType, min = settings.min, max = settings.max, digit = settings.digit, bmap = settings.bmap, amap = settings.amap, geo = settings.geo, key = settings.key, _settings$v = settings.v, v = _settings$v === undefined ? '2.0' : _settings$v, position = settings.position, positionJsonLink = settings.positionJsonLink, beforeRegisterMap = settings.beforeRegisterMap, _settings$pointSize = settings.pointSize, pointSize = _settings$pointSize === undefined ? 10 : _settings$pointSize, _settings$blurSize = settings.blurSize, blurSize = _settings$blurSize === undefined ? 5 : _settings$blurSize, heatColor = settings.heatColor, yAxisName = settings.yAxisName, xAxisName = settings.xAxisName, beforeRegisterMapOnce = settings.beforeRegisterMapOnce, _settings$mapURLProfi = settings.mapURLProfix, mapURLProfix = _settings$mapURLProfi === undefined ? 'https://unpkg.com/echarts@3.6.2/map/json/' : _settings$mapURLProfi, _settings$specialArea = settings.specialAreas, specialAreas = _settings$specialArea === undefined ? {} : _settings$specialArea; var tooltipVisible = status.tooltipVisible; var innerXAxisList = xAxisList; var innerYAxisList = yAxisList; var chartData = []; // add extraMetrics prop for data which only display in tooltip var extraMetrics = []; var mainColumn = dimension.concat([metrics]); columns.forEach(function (column) { if (!~mainColumn.indexOf(column)) extraMetrics.push(column); }); if (type === 'cartesian') { if (!innerXAxisList || !innerXAxisList.length) { innerXAxisList = getAxisList(rows, dimension[0]); } if (!innerYAxisList || !innerYAxisList.length) { innerYAxisList = getAxisList(rows, dimension[1]); } chartData = getData({ rows: rows, innerXAxisList: innerXAxisList, innerYAxisList: innerYAxisList, xDim: dimension[0], yDim: dimension[1], metrics: metrics, type: type, extraMetrics: extraMetrics }); } else { chartData = getData({ rows: rows, xDim: dimension[0], yDim: dimension[1], metrics: metrics, type: type, extraMetrics: extraMetrics }); } var metricsList = metrics ? rows.map(function (row) { return row[metrics]; }) : [0, 5]; var innerMin = min || Math.min.apply(null, metricsList); var innerMax = max || Math.max.apply(null, metricsList); var xAxis = getAxis(innerXAxisList, xAxisName); var yAxis = getAxis(innerYAxisList, yAxisName); var visualMap = getVisualMap({ innerMin: innerMin, innerMax: innerMax, type: type, heatColor: heatColor }); var series = getSeries({ chartData: chartData }); var tooltip = tooltipVisible && getTooltip({ dataType: dataType, innerXAxisList: innerXAxisList, innerYAxisList: innerYAxisList, digit: digit, extraMetrics: extraMetrics, metrics: metrics }); var options = { visualMap: visualMap, series: series }; if (type === 'bmap') { _extends(options.series[0], { coordinateSystem: 'bmap', pointSize: pointSize, blurSize: blurSize }); return getBmap(key, v).then(function (_) { return _extends({ bmap: bmap }, options); }); } else if (type === 'map') { options.series[0].coordinateSystem = 'geo'; return getMapJSON({ position: position, positionJsonLink: positionJsonLink, beforeRegisterMapOnce: beforeRegisterMapOnce, mapURLProfix: mapURLProfix }).then(function (json) { var geoAttr = _extends({ map: position }, geo); if (beforeRegisterMap) json = beforeRegisterMap(json); echarts.registerMap(position, json, specialAreas); return _extends({ geo: geoAttr }, options); }); } else if (type === 'amap') { _extends(options.series[0], { coordinateSystem: 'amap', pointSize: pointSize, blurSize: blurSize }); return getAmap(key, v).then(function (_) { return _extends({ amap: amap }, options); }); } else { return _extends({ xAxis: xAxis, yAxis: yAxis, tooltip: tooltip }, options); } }; var Loading = { render: function render() { var _vm = this;var _h = _vm.$createElement;var _c = _vm._self._c || _h;return _c('div', { staticClass: "v-charts-component-loading" }, [_c('div', { staticClass: "loader" }, [_c('div', { staticClass: "loading-spinner" }, [_c('svg', { staticClass: "circular", attrs: { "viewBox": "25 25 50 50" } }, [_c('circle', { staticClass: "path", attrs: { "cx": "50", "cy": "50", "r": "20", "fill": "none" } })])])])]); }, staticRenderFns: [] }; var DataEmpty = { render: function render() { var _vm = this;var _h = _vm.$createElement;var _c = _vm._self._c || _h;return _c('div', { staticClass: "v-charts-data-empty" }, [_vm._v(" 暂无数据 ")]); }, staticRenderFns: [] }; /** * 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$1(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** 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')(); /** * 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(); }; /** Built-in value references. */ var Symbol$1 = root.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$1 = Symbol$1 ? Symbol$1.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$1), tag = value[symToStringTag$1]; try { value[symToStringTag$1] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag$1] = tag; } else { delete value[symToStringTag$1]; } } return result; } /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.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$1.call(value); } /** `Object#toString` result references. */ var nullTag = '[object Null]'; var undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol$1 ? Symbol$1.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); } /** * 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'; } /** `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); } /** 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$1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject$1(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); } /** 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; var 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$1(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, result = wait - timeSinceLastCall; return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; } 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. timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } var STATIC_PROPS = ['initOptions', 'loading', 'dataEmpty', 'judgeWidth', 'widthChangeDelay']; var Core = { render: function render(h) { return h('div', { class: [toKebab(this.$options.name || this.$options._componentTag)], style: this.canvasStyle }, [h('div', { style: this.canvasStyle, ref: 'canvas' }), h(Loading, { style: { display: this.loading ? '' : 'none' } }), h(DataEmpty, { style: { display: this.dataEmpty ? '' : 'none' } }), this.$slots.default]); }, props: { data: { type: [Object, Array], default: function _default() { return {}; } }, settings: { type: Object, default: function _default() { return {}; } }, width: { type: String, default: 'auto' }, height: { type: String, default: '400px' }, beforeConfig: { type: Function }, afterConfig: { type: Function }, afterSetOption: { type: Function }, afterSetOptionOnce: { type: Function }, events: { type: Object }, grid: { type: [Object, Array] }, colors: { type: Array }, tooltipVisible: { type: Boolean, default: true }, legendVisible: { type: Boolean, default: true }, legendPosition: { type: String }, markLine: { type: Object }, markArea: { type: Object }, markPoint: { type: Object }, visualMap: { type: [Object, Array] }, dataZoom: { type: [Object, Array] }, toolbox: { type: [Object, Array] }, initOptions: { type: Object, default: function _default() { return {}; } }, title: Object, legend: [Object, Array], xAxis: [Object, Array], yAxis: [Object, Array], radar: Object, tooltip: Object, axisPointer: Object, brush: [Object, Array], geo: Object, timeline: [Object, Array], graphic: [Object, Array], series: [Object, Array], backgroundColor: [Object, String], textStyle: Object, animation: Object, theme: Object, themeName: String, loading: Boolean, dataEmpty: Boolean, extend: Object, judgeWidth: { type: Boolean, default: false }, widthChangeDelay: { type: Number, default: 300 }, tooltipFormatter: { type: Function }, resizeable: { type: Boolean, default: true }, resizeDelay: { type: Number, default: 200 }, changeDelay: { type: Number, default: 0 }, setOptionOpts: { type: [Boolean, Object], default: true } }, watch: { data: { deep: true, handler: function handler(v) { if (v) { this.changeHandler(); } } }, settings: { deep: true, handler: function handler(v) { if (v.type && this.chartLib) this.chartHandler = this.chartLib[v.type]; this.changeHandler(); } }, events: { deep: true, handler: function handler() { this.createEventProxy(); } }, theme: { deep: true, handler: function handler(v) { this.themeChange(v); } }, themeName: function themeName(v) { this.themeChange(v); } }, computed: { canvasStyle: function canvasStyle() { return { width: this.width, height: this.height, position: 'relative' }; }, chartColor: function chartColor() { return this.colors || this.theme && this.theme.color || color; } }, methods: { dataHandler: function dataHandler() { if (!this.chartHandler) return; var data = this.data; var _data = data, _data$columns = _data.columns, columns = _data$columns === undefined ? [] : _data$columns, _data$rows = _data.rows, rows = _data$rows === undefined ? [] : _data$rows; var extra = { tooltipVisible: this.tooltipVisible, legendVisible: this.legendVisible, echarts: this.echarts, color: this.chartColor, tooltipFormatter: this.tooltipFormatter, _once: this._once }; if (this.beforeConfig) data = this.beforeConfig(data); var options = this.chartHandler(columns, rows, this.settings, extra); if (options) { if (typeof options.then === 'function') { options.then(this.optionsHandler); } else { this.optionsHandler(options); } } }, resize: function resize() { this.echarts.resize(); }, optionsHandler: function optionsHandler(options) { var _this = this; if (this.legendPosition && options.legend) { options.legend[this.legendPosition] = 10; if (~['left', 'right'].indexOf(this.legendPosition)) { options.legend.top = 'middle'; options.legend.orient = 'vertical'; } } if (!this.themeName) options.color = this.chartColor; var echartsSettings = ['grid', 'dataZoom', 'visualMap', 'toolbox', 'title', 'legend', 'xAxis', 'yAxis', 'radar', 'tooltip', 'axisPointer', 'brush', 'geo', 'timeline', 'graphic', 'series', 'backgroundColor', 'textStyle']; echartsSettings.forEach(function (setting) { if (_this[setting]) options[setting] = _this[setting]; }); if (this.animation) { Object.keys(this.animation).forEach(function (key) { options[key] = _this.animation[key]; }); } if (this.markArea || this.markLine || this.markPoint) { var marks = { markArea: this.markArea, markLine: this.markLine, markPoint: this.markPoint }; var series = options.series; if (getType(series) === '[object Array]') { series.forEach(function (item) { _this.addMark(item, marks); }); } else if (getType(series) === '[object Object]') { this.addMark(series, marks); } } // extend sub attribute if (this.extend) { Object.keys(this.extend).forEach(function (attr) { if (typeof _this.extend[attr] === 'function') { // get callback value options[attr] = _this.extend[attr](options[attr]); } else { // mixin extend value if (isArray(options[attr]) && isObject(options[attr][0])) { // eg: [{ xx: 1 }, { xx: 2 }] options[attr].forEach(function (option, index) { options[attr][index] = _extends({}, option, _this.extend[attr]); }); } else if (isObject(options[attr])) { // eg: { xx: 1, yy: 2 } options[attr] = _extends({}, options[attr], _this.extend[attr]); } else { options[attr] = _this.extend[attr]; } } }); } if (this.afterConfig) options = this.afterConfig(options); console.log(this.setOptionOpts); this.echarts.setOption(options, this.setOptionOpts); this.$emit('ready', this.echarts); if (!this._once['ready-once']) { this._once['ready-once'] = true; this.$emit('ready-once', this.echarts); } if (this.judgeWidth) this.judgeWidthHandler(options); if (this.afterSetOption) this.afterSetOption(this.echarts); if (this.afterSetOptionOnce && !this._once['afterSetOptionOnce']) { this._once['afterSetOptionOnce'] = true; this.afterSetOptionOnce(this.echarts); } }, judgeWidthHandler: function judgeWidthHandler(options) { var _this2 = this; var echarts$$1 = this.echarts, widthChangeDelay = this.widthChangeDelay; if (this.$el.clientWidth) { echarts$$1 && echarts$$1.resize(); } else { this.$nextTick(function (_) { if (_this2.$el.clientWidth) { echarts$$1 && echarts$$1.resize(); } else { setTimeout(function (_) { echarts$$1 && echarts$$1.resize(); if (!_this2.$el.clientWidth) { console.warn(' Can\'t get dom width or height '); } }, widthChangeDelay); } }); } }, addMark: function addMark(seriesItem, marks) { Object.keys(marks).forEach(function (key) { if (marks[key]) { seriesItem[key] = marks[key]; } }); }, init: function init() { if (this.echarts) return; var themeName = this.themeName || this.theme || 've-chart'; this.echarts = this.echartsLib.init(this.$refs.canvas, themeName, this.initOptions); if (this.data) this.changeHandler(); this.createEventProxy(); if (this.resizeable) window.addEventListener('resize', this.resizeHandler); }, addWatchToProps: function addWatchToProps() { var _this3 = this; var watchedVariable = this._watchers.map(function (watcher) { return watcher.expression; }); Object.keys(this.$props).forEach(function (prop) { if (!~watchedVariable.indexOf(prop) && !~STATIC_PROPS.indexOf(prop)) { var opts = {}; if (~['[object Object]', '[object Array]'].indexOf(getType(_this3.$props[prop]))) { opts.deep = true; } _this3.$watch(prop, function () { _this3.changeHandler(); }, opts); } }); }, createEventProxy: function createEventProxy() { var _this4 = this; // 只要用户使用 on 方法绑定的事件都做一层代理, // 是否真正执行相应的事件方法取决于该方法是否仍然存在 events 中 // 实现 events 的动态响应 var self = this; var keys = Object.keys(this.events || {}); keys.length && keys.forEach(function (ev) { if (_this4.registeredEvents.indexOf(ev) === -1) { _this4.registeredEvents.push(ev); _this4.echarts.on(ev, function (ev) { return function () { if (ev in self.events) { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } self.events[ev].apply(null, args); } }; }(ev)); } }); }, themeChange: function themeChange(theme) { this.clean(); this.echarts = null; this.init(); }, clean: function clean() { if (this.resizeable) window.removeEventListener('resize', this.resizeHandler); this.echarts.dispose(); } }, created: function created() { var _this5 = this; this.echarts = null; this.registeredEvents = []; this._once = {}; this.resizeHandler = debounce(function (_) { _this5.echarts && _this5.echarts.resize(); }, this.resizeDelay); this.changeHandler = debounce(function (_) { _this5.dataHandler(); }, this.changeDelay); this.addWatchToProps(); }, mounted: function mounted() { this.init(); }, beforeDestroy: function beforeDestroy() { this.clean(); } }; var index = { name: 'VeHeatmap', mixins: [Core], created: function created() { this.chartHandler = heatmap; this.echartsLib = echarts; } }; return index; })));
// @flow import * as React from 'react'; import type { HigherOrderComponent, ClassComponentWithDefaultProps, } from '../index'; // This is a valid functional react component that we'll use to test our HigherOrderComponents later const ValidFunctionalComponent = (props: {string1: string, number1: number}) => <div />; // This is an invalid functional component. HigherOrderComponents shouldn't accept this as input const InvalidFunctionalComponent = (props: {string1: string, number1: number}) => 'hi'; // This is a valid class-based component. We'll use it to test HigherOrderComponents later class ValidClassComponent extends React.Component<{string1: string, number1: number}, void> { static defaultProps = {number1: 10} render() { return <div />; } }; // tests for ClassComponentWithDefaultProps (function(){ // should pass (ValidClassComponent: ClassComponentWithDefaultProps<{number1: number}, {string1: string, number1: number}, void>); // $FlowExpectError (ValidClassComponent: ClassComponentWithDefaultProps<{number1: string}, {string1: string, number1: number}, void>); // $FlowExpectError (ValidClassComponent: ClassComponentWithDefaultProps<{}, {string1: string, number1: number}, void>); // $FlowExpectError (ValidClassComponent: ClassComponentWithDefaultProps<{number1: number}, {number1: number}, void>); (class extends React.PureComponent<{b: string}, {c: string}> {static defaultProps = {a: 'foo'}} :ClassComponentWithDefaultProps<{a: string}, {b: string}, {c: string}>) })(); // Now, the tests for HigherOrderComponent: (function() { // Let's start with only the ProvidedProps part: declare var provideString1: HigherOrderComponent<{}, {string1: string}>; (function(){ // ... and test it with our functional component: const ProvideString1OfValidFunctionalComponent = provideString1(ValidFunctionalComponent); // should pass: (<ProvideString1OfValidFunctionalComponent number1={10} />: React.Element<any>); })(); (function(){ // Now with the class-based component: const ProvideString1OfValidClassComponent = provideString1(ValidClassComponent); // should pass: (<ProvideString1OfValidClassComponent />: React.Element<any>); // $FlowExpectError (<ProvideString1OfValidClassComponent number1="foo" />: React.Element<any>); })(); // now both ProvidedProps and RequiredProps: declare var provideString1AndRequireObject1: HigherOrderComponent<{object1: Object}, {string1: string}>; (function(){ // with the functional component: const ProvideString1AndRequireObject1OfValidFunctionalComponent = provideString1AndRequireObject1(ValidFunctionalComponent); // should pass: <ProvideString1AndRequireObject1OfValidFunctionalComponent object1={{}} number1={10} />; // $FlowExpectError <ProvideString1AndRequireObject1OfValidFunctionalComponent number1={10} />; })(); (function(){ // with the class component: const ProvideString1AndRequireObject1OfValidClassComponent = provideString1AndRequireObject1(ValidClassComponent); // should pass: <ProvideString1AndRequireObject1OfValidClassComponent object1={{}} />; // $FlowExpectError <ProvideString1AndRequireObject1OfValidClassComponent />; })(); // Composition: (function(){ declare var provideNumber1AndRequireNumber2: HigherOrderComponent<{number2: number}, {number1: number}>; declare var requireNumber3: HigherOrderComponent<{number3: number}, {}>; const ComposedComponent = provideString1(provideNumber1AndRequireNumber2(requireNumber3(ValidFunctionalComponent))); <ComposedComponent number2={1} number3={1} />; // $FlowExpectError <ComposedComponent number2={1} number3={1} number1="hi" />; // $FlowExpectError <ComposedComponent number1={1} number3={1} />; // $FlowExpectError <ComposedComponent number1={1} number2={1} />; // using ramda's compose: type FN<A,R> = (a: A) => R; declare var compose: ((end: void) => (<T>(x: T) => T)) & (<A,B>(m1: FN<A,B>, end: void) => FN<A,B>) & (<A,B,C>(m1: FN<B,C>, m2: FN<A,B>, end: void) => FN<A,C>) & (<A,B,C,D>(m1: FN<C,D>, m2: FN<B,C>, m3: FN<A,B>, end: void) => FN<A,D>) & (<A,B,C,D,E>(m1: FN<D,E>, m2: FN<C,D>, m3: FN<B,C>, m4: FN<A,B>, end: void) => FN<A,E>) & (<A,B,C,D,E,F>(m1: FN<E,F>, m2: FN<D,E>, m3: FN<C,D>, m4: FN<B,C>, m5: FN<A,B>, end: void) => FN<A,F>) & (<A,B,C,D,E,F,G>(m1: FN<F,G>, m2: FN<E,F>, m3: FN<D,E>, m4: FN<C,D>, m5: FN<B,C>, m6: FN<A,B>, end: void) => FN<A,G>) & (<A,B,C,D,E,F,G,H>(m1: FN<G,H>, m2: FN<F,G>, m3: FN<E,F>, m4: FN<D,E>, m5: FN<C,D>, m6: FN<B,C>, m7: FN<A,B>, end: void) => FN<A,H>) & (<A,B,C,D,E,F,G,H,J>(m1: FN<G,J>, m2: FN<G,H>, m3: FN<F,G>, m4: FN<E,F>, m5: FN<D,E>, m6: FN<C,D>, m7: FN<B,C>, m8: FN<A,B>, end: void) => FN<A,J>) & (<A,B,C,D,E,F,G,H,J,K>(m1: FN<J,K>, m2: FN<G,J>, m3: FN<G,H>, m4: FN<F,G>, m5: FN<E,F>, m6: FN<D,E>, m7: FN<C,D>, m8: FN<B,C>, m9: FN<A,B>, end: void) => FN<A,K>) & (<A,B,C,D,E,F,G,H,J,K,L>(m1: FN<K,L>, m2: FN<J,K>, m3: FN<G,J>, m4: FN<G,H>, m5: FN<F,G>, m6: FN<E,F>, m7: FN<D,E>, m8: FN<C,D>, m9: FN<B,C>, m10: FN<A,B>, end: void) => FN<A,L>) & (<A,R>(...funcs: Array<FN<A,R>>) => FN<A,R>); const ComposedComponent2 = compose( requireNumber3, provideNumber1AndRequireNumber2, provideString1, )(ValidFunctionalComponent); <ComposedComponent2 number1={1} number2={1} number3={1} />; <ComposedComponent2 number2={1} number3={1} />; // $FlowExpectError <ComposedComponent2 number1={1} number3={1} />; // $FlowExpectError <ComposedComponent2 number1={1} number2={1} />; })(); })(); type Props = { foo: number, bar: number, baz: number, }; class TestComponent extends React.Component<Props, void> { static defaultProps = { foo: 3, bar: 3, }; render = () => null; }; const injectFoo: HigherOrderComponent<{}, {foo: number}> = (C: any): any => { return (props: Props) => <C {...props} foo={3} />; }; const Injected = injectFoo(TestComponent); <Injected baz={10} />; // $FlowExpectError <Injected foo="asdf" bar={3} baz={10} />;
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 _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 _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; } import { Record, List, Map, fromJS } from 'immutable'; import { MODE_IDLE } from './constants'; import { SNAP_MASK } from './utils/snap'; var safeLoadMapList = function safeLoadMapList(mapList, Model, defaultMap) { return mapList ? new Map(mapList).map(function (m) { return new Model(m); }).toMap() : defaultMap || new Map(); }; export var Grid = function (_Record) { _inherits(Grid, _Record); function Grid() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Grid); return _possibleConstructorReturn(this, (Grid.__proto__ || Object.getPrototypeOf(Grid)).call(this, _extends({}, json, { properties: fromJS(json.properties || {}) }))); } return Grid; }(Record({ id: '', type: '', properties: Map() }, 'Grid')); export var DefaultGrids = new Map({ 'h1': new Grid({ id: 'h1', type: 'horizontal-streak', properties: { step: 20, colors: ['#808080', '#ddd', '#ddd', '#ddd', '#ddd'] } }), 'v1': new Grid({ id: 'v1', type: 'vertical-streak', properties: { step: 20, colors: ['#808080', '#ddd', '#ddd', '#ddd', '#ddd'] } }) }); export var ElementsSet = function (_Record2) { _inherits(ElementsSet, _Record2); function ElementsSet() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, ElementsSet); return _possibleConstructorReturn(this, (ElementsSet.__proto__ || Object.getPrototypeOf(ElementsSet)).call(this, { vertices: new List(json.vertices || []), lines: new List(json.lines || []), holes: new List(json.holes || []), areas: new List(json.areas || []), items: new List(json.items || []) })); } return ElementsSet; }(Record({ vertices: new List(), lines: new List(), holes: new List(), areas: new List(), items: new List() }, 'ElementsSet')); var sharedAttributes = { id: '', type: '', prototype: '', name: '', misc: new Map(), selected: false, properties: new Map(), visible: true }; export var Vertex = function (_Record3) { _inherits(Vertex, _Record3); function Vertex() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Vertex); return _possibleConstructorReturn(this, (Vertex.__proto__ || Object.getPrototypeOf(Vertex)).call(this, _extends({}, json, { lines: new List(json.lines || []), areas: new List(json.areas || []) }))); } return Vertex; }(Record(_extends({}, sharedAttributes, { x: -1, y: -1, prototype: 'vertices', lines: new List(), areas: new List() }), 'Vertex')); export var Line = function (_Record4) { _inherits(Line, _Record4); function Line() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Line); return _possibleConstructorReturn(this, (Line.__proto__ || Object.getPrototypeOf(Line)).call(this, _extends({}, json, { properties: fromJS(json.properties || {}), vertices: new List(json.vertices || []), holes: new List(json.holes || []) }))); } return Line; }(Record(_extends({}, sharedAttributes, { prototype: 'lines', vertices: new List(), holes: new List() }), 'Line')); export var Hole = function (_Record5) { _inherits(Hole, _Record5); function Hole() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Hole); return _possibleConstructorReturn(this, (Hole.__proto__ || Object.getPrototypeOf(Hole)).call(this, _extends({}, json, { properties: fromJS(json.properties || {}) }))); } return Hole; }(Record(_extends({}, sharedAttributes, { prototype: 'holes', offset: -1, line: '' }), 'Hole')); export var Area = function (_Record6) { _inherits(Area, _Record6); function Area() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Area); return _possibleConstructorReturn(this, (Area.__proto__ || Object.getPrototypeOf(Area)).call(this, _extends({}, json, { properties: fromJS(json.properties || {}), vertices: new List(json.vertices || []) }))); } return Area; }(Record(_extends({}, sharedAttributes, { prototype: 'areas', vertices: new List(), holes: new List() }), 'Area')); export var Item = function (_Record7) { _inherits(Item, _Record7); function Item() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Item); return _possibleConstructorReturn(this, (Item.__proto__ || Object.getPrototypeOf(Item)).call(this, _extends({}, json, { properties: fromJS(json.properties || {}) }))); } return Item; }(Record(_extends({}, sharedAttributes, { prototype: 'items', x: 0, y: 0, rotation: 0 }), 'Item')); export var Layer = function (_Record8) { _inherits(Layer, _Record8); function Layer() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Layer); return _possibleConstructorReturn(this, (Layer.__proto__ || Object.getPrototypeOf(Layer)).call(this, _extends({}, json, { vertices: safeLoadMapList(json.vertices, Vertex), lines: safeLoadMapList(json.lines, Line), holes: safeLoadMapList(json.holes, Hole), areas: safeLoadMapList(json.areas, Area), items: safeLoadMapList(json.items, Item), selected: new ElementsSet(json.selected) }))); } return Layer; }(Record({ id: '', altitude: 0, order: 0, opacity: 1, name: '', visible: true, vertices: new Map(), lines: new Map(), holes: new Map(), areas: new Map(), items: new Map(), selected: new ElementsSet() }, 'Layer')); export var Group = function (_Record9) { _inherits(Group, _Record9); function Group() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Group); return _possibleConstructorReturn(this, (Group.__proto__ || Object.getPrototypeOf(Group)).call(this, _extends({}, json, { properties: fromJS(json.properties || {}), elements: fromJS(json.elements || {}) }))); } return Group; }(Record(_extends({}, sharedAttributes, { prototype: 'groups', x: 0, y: 0, rotation: 0, elements: new Map() }), 'Group')); export var DefaultLayers = new Map({ 'layer-1': new Layer({ id: 'layer-1', name: 'default' }) }); export var Scene = function (_Record10) { _inherits(Scene, _Record10); function Scene() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Scene); var layers = safeLoadMapList(json.layers, Layer, DefaultLayers); return _possibleConstructorReturn(this, (Scene.__proto__ || Object.getPrototypeOf(Scene)).call(this, _extends({}, json, { grids: safeLoadMapList(json.grids, Grid, DefaultGrids), layers: layers, selectedLayer: layers.first().id, groups: safeLoadMapList(json.groups || {}, Group), meta: json.meta ? fromJS(json.meta) : new Map(), guides: json.guides ? fromJS(json.guides) : new Map({ horizontal: new Map(), vertical: new Map(), circular: new Map() }) }))); } return Scene; }(Record({ unit: 'cm', layers: new Map(), grids: new Map(), selectedLayer: null, groups: new Map(), width: 3000, height: 2000, meta: new Map(), //additional info guides: new Map() }, 'Scene')); export var CatalogElement = function (_Record11) { _inherits(CatalogElement, _Record11); function CatalogElement() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, CatalogElement); return _possibleConstructorReturn(this, (CatalogElement.__proto__ || Object.getPrototypeOf(CatalogElement)).call(this, _extends({}, json, { info: fromJS(json.info), properties: fromJS(json.properties) }))); } return CatalogElement; }(Record({ name: '', prototype: '', info: new Map(), properties: new Map() }, 'CatalogElement')); export var Catalog = function (_Record12) { _inherits(Catalog, _Record12); function Catalog() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Catalog); var elements = safeLoadMapList(json.elements, CatalogElement); return _possibleConstructorReturn(this, (Catalog.__proto__ || Object.getPrototypeOf(Catalog)).call(this, { elements: elements, ready: !elements.isEmpty() })); } _createClass(Catalog, [{ key: 'factoryElement', value: function factoryElement(type, options, initialProperties) { if (!this.elements.has(type)) { var catList = this.elements.map(function (element) { return element.name; }).toArray(); throw new Error('Element ' + type + ' does not exist in catalog ' + catList); } var element = this.elements.get(type); var properties = element.properties.map(function (value, key) { return initialProperties && initialProperties.has(key) ? initialProperties.get(key) : value.get('defaultValue'); }); switch (element.prototype) { case 'lines': return new Line(options).merge({ properties: properties }); case 'holes': return new Hole(options).merge({ properties: properties }); case 'areas': return new Area(options).merge({ properties: properties }); case 'items': return new Item(options).merge({ properties: properties }); default: throw new Error('prototype not valid'); } } }]); return Catalog; }(Record({ ready: false, page: 'root', path: new List(), elements: new Map() }, 'Catalog')); export var HistoryStructure = function (_Record13) { _inherits(HistoryStructure, _Record13); function HistoryStructure() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, HistoryStructure); return _possibleConstructorReturn(this, (HistoryStructure.__proto__ || Object.getPrototypeOf(HistoryStructure)).call(this, { list: fromJS(json.list || []), first: new Scene(json.scene), last: new Scene(json.last || json.scene) })); } return HistoryStructure; }(Record({ list: new List(), first: null, last: null }, 'HistoryStructure')); export var State = function (_Record14) { _inherits(State, _Record14); function State() { var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, State); return _possibleConstructorReturn(this, (State.__proto__ || Object.getPrototypeOf(State)).call(this, _extends({}, json, { scene: new Scene(json.scene), sceneHistory: new HistoryStructure(json), catalog: new Catalog(json.catalog || {}), viewer2D: new Map(json.viewer2D || {}), drawingSupport: new Map(json.drawingSupport || {}), draggingSupport: new Map(json.draggingSupport || {}), rotatingSupport: new Map(json.rotatingSupport || {}), misc: json.misc ? fromJS(json.misc) : new Map() }))); } return State; }(Record({ mode: MODE_IDLE, scene: new Scene(), sceneHistory: new HistoryStructure(), catalog: new Catalog(), viewer2D: new Map(), mouse: new Map({ x: 0, y: 0 }), zoom: 0, snapMask: SNAP_MASK, snapElements: new List(), activeSnapElement: null, drawingSupport: new Map(), draggingSupport: new Map(), rotatingSupport: new Map(), errors: new List(), warnings: new List(), clipboardProperties: new Map(), selectedElementsHistory: new List(), misc: new Map(), //additional info alterate: false }, 'State'));
// source: src/server/schemas/project.proto /** * @fileoverview * @enhanceable * @suppress {messageConventions} JS Compiler reports an error if a variable or * field starts with 'MSG_' and isn't a translatable message. * @public */ // GENERATED CODE -- DO NOT EDIT! /* eslint-disable */ // @ts-nocheck var jspb = require('google-protobuf'); var goog = jspb; var proto = {}; var google_protobuf_timestamp_pb = require('google-protobuf/google/protobuf/timestamp_pb.js'); goog.object.extend(proto, google_protobuf_timestamp_pb); goog.exportSymbol('Project', null, proto); /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.Project = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.Project.repeatedFields_, null); }; goog.inherits(proto.Project, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.Project.displayName = 'proto.Project'; } /** * List of repeated fields within this message type. * @private {!Array<number>} * @const */ proto.Project.repeatedFields_ = [5,6]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.Project.prototype.toObject = function(opt_includeInstance) { return proto.Project.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.Project} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.Project.toObject = function(includeInstance, msg) { var f, obj = { id: jspb.Message.getFieldWithDefault(msg, 1, ""), displayName: jspb.Message.getFieldWithDefault(msg, 11, ""), ownerId: jspb.Message.getFieldWithDefault(msg, 2, ""), isPublic: jspb.Message.getBooleanFieldWithDefault(msg, 3, false), description: jspb.Message.getFieldWithDefault(msg, 4, ""), tagsList: (f = jspb.Message.getRepeatedField(msg, 5)) == null ? undefined : f, collaboratorIdList: (f = jspb.Message.getRepeatedField(msg, 6)) == null ? undefined : f, version: jspb.Message.getFieldWithDefault(msg, 7, 0), fileId: jspb.Message.getFieldWithDefault(msg, 8, ""), created: (f = msg.getCreated()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f), updated: (f = msg.getUpdated()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.Project} */ proto.Project.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.Project; return proto.Project.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.Project} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.Project} */ proto.Project.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setId(value); break; case 11: var value = /** @type {string} */ (reader.readString()); msg.setDisplayName(value); break; case 2: var value = /** @type {string} */ (reader.readString()); msg.setOwnerId(value); break; case 3: var value = /** @type {boolean} */ (reader.readBool()); msg.setIsPublic(value); break; case 4: var value = /** @type {string} */ (reader.readString()); msg.setDescription(value); break; case 5: var value = /** @type {string} */ (reader.readString()); msg.addTags(value); break; case 6: var value = /** @type {string} */ (reader.readString()); msg.addCollaboratorId(value); break; case 7: var value = /** @type {number} */ (reader.readInt32()); msg.setVersion(value); break; case 8: var value = /** @type {string} */ (reader.readString()); msg.setFileId(value); break; case 9: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setCreated(value); break; case 10: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setUpdated(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.Project.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.Project.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.Project} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.Project.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getId(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getDisplayName(); if (f.length > 0) { writer.writeString( 11, f ); } f = message.getOwnerId(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getIsPublic(); if (f) { writer.writeBool( 3, f ); } f = message.getDescription(); if (f.length > 0) { writer.writeString( 4, f ); } f = message.getTagsList(); if (f.length > 0) { writer.writeRepeatedString( 5, f ); } f = message.getCollaboratorIdList(); if (f.length > 0) { writer.writeRepeatedString( 6, f ); } f = message.getVersion(); if (f !== 0) { writer.writeInt32( 7, f ); } f = message.getFileId(); if (f.length > 0) { writer.writeString( 8, f ); } f = message.getCreated(); if (f != null) { writer.writeMessage( 9, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } f = message.getUpdated(); if (f != null) { writer.writeMessage( 10, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } }; /** * optional string id = 1; * @return {string} */ proto.Project.prototype.getId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.Project} returns this */ proto.Project.prototype.setId = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string display_name = 11; * @return {string} */ proto.Project.prototype.getDisplayName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 11, "")); }; /** * @param {string} value * @return {!proto.Project} returns this */ proto.Project.prototype.setDisplayName = function(value) { return jspb.Message.setProto3StringField(this, 11, value); }; /** * optional string owner_id = 2; * @return {string} */ proto.Project.prototype.getOwnerId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.Project} returns this */ proto.Project.prototype.setOwnerId = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional bool is_public = 3; * @return {boolean} */ proto.Project.prototype.getIsPublic = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false)); }; /** * @param {boolean} value * @return {!proto.Project} returns this */ proto.Project.prototype.setIsPublic = function(value) { return jspb.Message.setProto3BooleanField(this, 3, value); }; /** * optional string description = 4; * @return {string} */ proto.Project.prototype.getDescription = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.Project} returns this */ proto.Project.prototype.setDescription = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; /** * repeated string tags = 5; * @return {!Array<string>} */ proto.Project.prototype.getTagsList = function() { return /** @type {!Array<string>} */ (jspb.Message.getRepeatedField(this, 5)); }; /** * @param {!Array<string>} value * @return {!proto.Project} returns this */ proto.Project.prototype.setTagsList = function(value) { return jspb.Message.setField(this, 5, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.Project} returns this */ proto.Project.prototype.addTags = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 5, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.Project} returns this */ proto.Project.prototype.clearTagsList = function() { return this.setTagsList([]); }; /** * repeated string collaborator_id = 6; * @return {!Array<string>} */ proto.Project.prototype.getCollaboratorIdList = function() { return /** @type {!Array<string>} */ (jspb.Message.getRepeatedField(this, 6)); }; /** * @param {!Array<string>} value * @return {!proto.Project} returns this */ proto.Project.prototype.setCollaboratorIdList = function(value) { return jspb.Message.setField(this, 6, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.Project} returns this */ proto.Project.prototype.addCollaboratorId = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 6, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.Project} returns this */ proto.Project.prototype.clearCollaboratorIdList = function() { return this.setCollaboratorIdList([]); }; /** * optional int32 version = 7; * @return {number} */ proto.Project.prototype.getVersion = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 7, 0)); }; /** * @param {number} value * @return {!proto.Project} returns this */ proto.Project.prototype.setVersion = function(value) { return jspb.Message.setProto3IntField(this, 7, value); }; /** * optional string file_id = 8; * @return {string} */ proto.Project.prototype.getFileId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 8, "")); }; /** * @param {string} value * @return {!proto.Project} returns this */ proto.Project.prototype.setFileId = function(value) { return jspb.Message.setProto3StringField(this, 8, value); }; /** * optional google.protobuf.Timestamp created = 9; * @return {?proto.google.protobuf.Timestamp} */ proto.Project.prototype.getCreated = function() { return /** @type{?proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 9)); }; /** * @param {?proto.google.protobuf.Timestamp|undefined} value * @return {!proto.Project} returns this */ proto.Project.prototype.setCreated = function(value) { return jspb.Message.setWrapperField(this, 9, value); }; /** * Clears the message field making it undefined. * @return {!proto.Project} returns this */ proto.Project.prototype.clearCreated = function() { return this.setCreated(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.Project.prototype.hasCreated = function() { return jspb.Message.getField(this, 9) != null; }; /** * optional google.protobuf.Timestamp updated = 10; * @return {?proto.google.protobuf.Timestamp} */ proto.Project.prototype.getUpdated = function() { return /** @type{?proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 10)); }; /** * @param {?proto.google.protobuf.Timestamp|undefined} value * @return {!proto.Project} returns this */ proto.Project.prototype.setUpdated = function(value) { return jspb.Message.setWrapperField(this, 10, value); }; /** * Clears the message field making it undefined. * @return {!proto.Project} returns this */ proto.Project.prototype.clearUpdated = function() { return this.setUpdated(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.Project.prototype.hasUpdated = function() { return jspb.Message.getField(this, 10) != null; }; goog.object.extend(exports, proto);
/** * Factory for creating the state-machine's <em>raise()</em> function. * * Creates implementation for the state-engine's * <pre> * { * name: STRING // engine name / description * doc: STRING // the URL to the SCXML document that holds the engine's definition * evalScript: BOOLEAN // true * onraise: FUNCTION // default impl. for onraise: print debug output (depending on logging-level for DialogEngine / InputEngine) * onload: FUNCTION // default impl. handling initialization of state-engine after SCXML definition was loaded * raise: FUNCTION // default impl. for raise-function: use execution-queue for allowing raise-invocations from within SCXML scripts * } * </pre> * * @class StateEngineFactory * * @requires cordova.plugins.queuePlugin [Cordova/android]: needed for Android before 4.4 -> Cordova plugin for non-WebWorker-based execution-queue * or * @requires Worker (WebWorker) on window or global object * or * @requires setTimeout (fallback/stub implementation) */ define(['mmirf/resources', 'mmirf/scionEngine', 'mmirf/util/extend', 'require'], function(resources, createScionEngine, extend, require) { /** * HELPER logging for state-changes * * @param {Engine} ctx * the context for the state-machine, i.e. the DialogEngine or InputEngine instance * * @memberOf StateEngineFactory# */ var printDebugStates = function(ctx){ if(!ctx._logger.isDebug()){ return; } ctx._logger.debug(ctx.name, 'current state: ' + JSON.stringify(ctx.getStates())); ctx._logger.debug(ctx.name, 'active states: ' + JSON.stringify(ctx.getActiveStates())); ctx._logger.debug(ctx.name, 'active events: ',+ JSON.stringify(ctx.getActiveEvents())); ctx._logger.debug(ctx.name, 'active transitions: '+ JSON.stringify(ctx.getStates()) + ":"+ JSON.stringify(ctx.getActiveTransitions())); }; /** * Factory for base / default implementation for state-engine, returns * <pre> * { * name: STRING // engine name / description * doc: STRING // the URL to the SCXML document that holds the engine's definition * evalScript: BOOLEAN // true * onraise: FUNCTION // default impl. for onraise: print debug output (depending on logging-level for DialogEngine / InputEngine) * onload: FUNCTION // default impl. handling initialization of state-engine after SCXML definition was loaded * raise: FUNCTION // raise-function created by envFactory(_instance) * } * </pre> * * @param {Engine} _engine * the instance of the SCION state-machine * * @param {ExecFactory} envFactory * the factory for creating the Worker/Thread and the raise() function * * @returns the implementation with raise-function * * @memberOf StateEngineFactory# */ var _baseFactory = function(_instance, envFactory){ /** @class StateEngineDefaultImpl */ return { /** @scope StateEngineDefaultImpl */ /** @memberOf StateEngineDefaultImpl */ name : envFactory.name? envFactory.name : 'base_engine', doc : null, onraise : function() { if (this._logger.isd()) { printDebugStates(_instance); }; }, evalScript : true, onload : function(scion, deferred) { //FIX (russa) for jQuery > 2.x: extend() uses isPlainObject(), which's impl. changed in 2.x // -> isPlainObject() now requires a constructor that is different from the native Object.constructor // in order to be able to detect, that an object is NOT a plain object // ... but scion does not provide such a non-native constructor for its _scion property // (which causes deep-copy in extend() to run into an infinite loop) // QUICK-FIX: just attach a dummy constructor function, so that isPlainObject will correctly detect property // _scion as not-a-plain-object (this should really be FIXed in the scion library itself...) // //TODO russa: check if we really need a deep copy here (maybe we should make a copy TO scion and replace _instance with the ext. scion obj. ...?) if(scion['_scion']) scion['_scion'].constructor = function dummy(){};//NOTE _scion only does exist on old SCION lib version! extend(_instance, scion); _instance.__proto__ = scion.constructor.prototype;//FIX: in newer SCION implementations we need the prototype too _instance.worker = envFactory.createWorker(_instance, _instance.gen);//_instance._genFuncFactory(_instance, _instance.gen); //FIXME @russa: is this a general functionality? should this be removed? if (!_instance.evalScript){ _instance.ignoreScript(); } // delete _instance.gen; delete _instance.evalScript; _instance.start(); deferred.resolve(_instance); },//END: onload raise: envFactory.createRaise(_instance) }; }; /** * Factory for WebWorker-based implementation of raise function. * * Provide creator-functions: * <code>createWorker(_engineInstance, genFunc) : WebWorker</code> * <code>createRaise(_engineInstance) : Function</code> * * @memberOf StateEngineFactory# */ var _browserFactory = { /** @scope StateEngineWebWorkerImpl */ /** @memberOf StateEngineWebWorkerImpl */ name: 'webworkerGen', workerConstructor: void(0), createWorker: function(_instance, gen) { var scionQueueWorker = new this.workerConstructor( typeof WEBPACK_BUILD !== 'undefined' && WEBPACK_BUILD? void(0) : resources.getWorkerPath()+ 'ScionQueueWorker.js' ); scionQueueWorker._engineInstance = _instance; scionQueueWorker._engineGen = gen; scionQueueWorker.onmessage = function(e) { if (e.data.command == "toDo") { var inst = this._engineInstance; inst._logger.debug('raising:' + e.data.toDo.event); this._engineGen.call(inst, e.data.toDo.event, e.data.toDo.eventData); // @chsc03: attention if something goes wrong along the transition, // the worker is not ready for any incoming jobs this.postMessage({ command : 'readyForJob' }); inst.onraise(); } }; // if worker implementation supports unref(), do "declare" that program // should exit even if the worker is still running: if(typeof scionQueueWorker.unref === 'function'){ scionQueueWorker.unref(); } return scionQueueWorker; }, createRaise: function(_instance){ return function(event, eventData) { if (eventData){ this._logger.debug('new Job:' + event); } _instance.worker.postMessage({ command : 'newJob', job : { event : event, eventData : eventData } }); }; } }; /** * Factory for CordovaPlugin-based implementation of raise function. * * Provide creator-functions: * <code>createWorker(_engineInstance, genFunc) : WebWorker</code> * <code>createRaise(_engineInstance) : Function</code> * * * @requires cordova.plugins.queuePlugin (Cordova plugin for execution-queue) * * @memberOf StateEngineFactory# */ var _queuePluginFactory = { /** @scope StateEngineQueuePluginImpl */ /** @memberOf StateEngineQueuePluginImpl */ name: 'queuepluginGen', createWorker: (function initWorkerFactory() { //"global" ID-list for all queues (i.e. ID-list for all engines) var callBackList = []; return function workerFactory(_instance, gen){ var id = callBackList.length; var execQueue = window.cordova.plugins.queuePlugin; function successCallBackHandler(args){ if (args.length===2){ // console.debug('QueuePlugin: success '+ JSON.stringify(args[0]) + ', '+JSON.stringify(args[1]));//DEBUG callBackList[args[0]](args[1]); } } function failureFallbackHandler(_err){ _instance._logger.error('failed to initialize SCION extension for ANDROID env'); _instance.worker = (function(gen){ return { raiseCordova: function fallback(event, eventData){ setTimeout(function(){ gen.call(_instance, event, eventData); }, 10); } }; })();//END: fallback } callBackList.push(function(data){ var inst = _instance; if(inst._logger.isv()) inst._logger.debug('raising:'+ data.event); var generatedState = gen.call(inst, data.event, data.eventData); if(inst._logger.isv()) inst._logger.debug('QueuePlugin: processed event '+id+' for '+ data.event+' -> new state: '+JSON.stringify(generatedState)+ ' at ' + inst.url); execQueue.readyForJob(id, successCallBackHandler, failureFallbackHandler); inst.onraise(); }); execQueue.newQueue(id, function(_args){ if(_instance._logger.isv()) _instance._logger.debug('QueuePlugin: entry '+id+' created.' + ' at ' + _instance.url); }, failureFallbackHandler ); return { _engineInstance: _instance, raiseCordova: function (event, eventData){ if(this._engineInstance._logger.isv()) this._engineInstance._logger.debug('QueuePlugin: new Job: '+ id + ' at ' + this._engineInstance.url); execQueue.newJob(id, {event: event, eventData: eventData}, successCallBackHandler,failureFallbackHandler); } }; };//END: workerFactory(_instance, gen) })(),//END: initWorkerFactory() createRaise: function(_instance){ return function(event, eventData) { if (eventData) _instance._logger.log('new Job:' + event); _instance.worker.raiseCordova(event, eventData); }; } }; /** * Factory for stub/dummy implementation of raise function. * * Provide creator-functions: * <code>createWorker(_engineInstance, genFunc) : WebWorker</code> * <code>createRaise(_engineInstance) : Function</code> * * * @requires cordova.plugins.queuePlugin (Cordova plugin for execution-queue) * * @memberOf StateEngineFactory# */ var _stubFactory = { /** @scope StateEngineStubImpl */ /** @memberOf StateEngineStubImpl */ name: 'stubGen', createWorker: function(_instance, gen) { return { _engineGen: gen, _engineInstance: _instance, raiseStubImpl: function fallback(event, eventData){ setTimeout(function(){ gen.call(_instance, event, eventData); }, 50); } }; }, createRaise: function(_instance){ return function(event, eventData) { if (eventData) _instance._logger.log('new Job:' + event); _instance.worker.raiseStubImpl(event, eventData); }; } }; /** * Get factory for raise-impl. depending on the runtime environment. * * Currently there are 3 impl. available * * WebWorker * * Android QueuePlugin * * STUB IMPLEMENTATION * * @memberOf StateEngineFactory# */ function getScionEnvFactory(){ var ctx = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : typeof global !== 'undefined' ? global : this; var hasWebWorkers = ctx && typeof ctx.Worker !== 'undefined'; //TODO make this configurable? through ConfigurationManager? if(hasWebWorkers){ if(!_browserFactory.workerConstructor){ _browserFactory.workerConstructor = typeof WEBPACK_BUILD !== 'undefined' && WEBPACK_BUILD? require('../../workers/ScionQueueWorker.js') : ctx.Worker; } return _browserFactory; //_browser; } else { var isCordovaEnv = resources.isCordovaEnv(); //if queue-plugin is available: if(isCordovaEnv && cordova.plugins && cordova.plugins.queuePlugin){ return _queuePluginFactory;//_cordova; } else { //otherwise use fallback: return _stubFactory;//_stub; } } } /** * no-op function for dummy logger * @memberOf StateEngineFactory# */ function noop(){}; /** * always-false function for dummy logger * @memberOf StateEngineFactory# */ function deny(){return false;}; // /** // * print-warning function for dummy logger // * @memberOf StateEngineFactory# // */ // function pw(){console.warn.apply(console,arguments);}; /** * print-error function for dummy logger * @memberOf StateEngineFactory# */ function pe(){console.error.apply(console,arguments);}; /** * dummy logger that does nothing: * the engine-creator should replace this with a "real" implementation * e.g. something like this (see also init() in dialogManager): * * engine = require('mmirf/engineConfig')('some-url', 'some-mode'); * engine._logger = require('mmirf/logger').create('my-module-id'); * * @memberOf StateEngineFactory# */ var nolog = { /** @scope StateEngineFactory.DummyLogger */ /** @memberOf DummyLogger */ d: noop, debug: noop, w: noop,//pw, warn: noop,//pw, e: pe, error: pe, log: noop, isVerbose: deny, isv: deny, isDebug: deny, isd: deny }; /** * Exported factory function for creating / adding impl. to SCION engine instance * * @memberOf StateEngineFactory# */ return function create(url, _mode) { var baseFactory = _baseFactory; var scionEnvConfig = getScionEnvFactory(); var _instance = {url: url,_logger: nolog}; // var scionConfig = scionEnvConfig(_instance); var scionConfig = baseFactory( _instance, scionEnvConfig); scionConfig.doc = url; _instance = createScionEngine(scionConfig, _instance); return _instance; }; });
import assert from 'assert'; import { xmlParse } from '../src/dom' import { xmlText } from '../src/util' describe('escape', () => { it('accepts already escaped ampersand', () => { const xmlString = '<root>Fish&amp;pie</root>'; const outXmlString = xmlText(xmlParse(xmlString)) assert.equal( outXmlString, xmlString ); }) it('escapes non-escaped ampersand', () => { const xmlString = '<root>Fish&pie</root>'; const outXmlString = xmlText(xmlParse(xmlString)) assert.equal( outXmlString, '<root>Fish&amp;pie</root>' ); }) it('accepts non-escaped ">" between elements', () => { const xmlString = '<root>Fish>pie</root>'; const outXmlString = xmlText(xmlParse(xmlString)) assert.equal( outXmlString, '<root>Fish&gt;pie</root>' ); }) it('accepts non-escaped "\'" between elements', () => { const xmlString = '<root>Fish\'pie</root>'; const outXmlString = xmlText(xmlParse(xmlString)) assert.equal( outXmlString, '<root>Fish\'pie</root>' ); }) it('accepts non-escaped \'"\' between elements', () => { const xmlString = '<root>Fish"pie</root>'; const outXmlString = xmlText(xmlParse(xmlString)) assert.equal( outXmlString, '<root>Fish"pie</root>' ); }) it('accepts non-escaped ">" in attributes', () => { const xmlString = '<root dish="eat>hunger">Fish</root>'; const outXmlString = xmlText(xmlParse(xmlString)) assert.equal( outXmlString, '<root dish="eat&gt;hunger">Fish</root>' ); }) it('accepts non-escaped "\'" in attributes', () => { const xmlString = '<root dish="eat\'hunger">Fish</root>'; const outXmlString = xmlText(xmlParse(xmlString)) assert.equal( outXmlString, '<root dish="eat\'hunger">Fish</root>' ); }) it('accepts non-escaped \'"\' in attributes', () => { const xmlString = "<root dish='eat\"hunger'>Fish</root>"; const outXmlString = xmlText(xmlParse(xmlString)) assert.equal( outXmlString, '<root dish="eat&quot;hunger">Fish</root>' ); }) })
const m = require("mithril"); module.exports = m( ".icon", m.trust( '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-tv"><rect x="2" y="7" width="20" height="15" rx="2" ry="2"></rect><polyline points="17 2 12 7 7 2"></polyline></svg>', ), );
const { chromium } = require("playwright"); (async () => { const browser = await chromium.launch({ headless: false }); const page = await browser.newPage(); await page.setViewport({ width: 1280, height: 800 }); await page.goto("https://login.live.com/"); await page.fill('[name="loginfmt"]', process.env.MSLIVE_USER); await page.click('[type="submit"]'); await page.fill('input[type="password"]', process.env.MSLIVE_PWD); await page.keyboard.press("Enter"); await browser.close(); })();
/* * Yet Another Sound-Novel * author: Noriaki Uchiyama */ // $script /*! * $script.js Async loader & dependency manager * https://github.com/ded/script.js * (c) Dustin Diaz 2013 * License: MIT */ (function(e,t,n){typeof module!="undefined"&&module.exports?module.exports=n():typeof define=="function"&&define.amd?define(n):t[e]=n()})("$script",this,function(){function v(e,t){for(var n=0,r=e.length;n<r;++n)if(!t(e[n]))return f;return 1}function m(e,t){v(e,function(e){return!t(e)})}function g(e,t,a){function d(e){return e.call?e():r[e]}function b(){if(!--p){r[h]=1,c&&c();for(var e in s)v(e.split("|"),d)&&!m(s[e],d)&&(s[e]=[])}}e=e[l]?e:[e];var f=t&&t.call,c=f?t:a,h=f?e.join(""):t,p=e.length;return setTimeout(function(){m(e,function(e){if(e===null)return b();if(u[e])return h&&(i[h]=1),u[e]==2&&b();u[e]=1,h&&(i[h]=1),y(!n.test(e)&&o?o+e+".js":e,b)})},0),g}function y(n,r){var i=e.createElement("script"),s=f;i.onload=i.onerror=i[d]=function(){if(i[h]&&!/^c|loade/.test(i[h])||s)return;i.onload=i[d]=null,s=1,u[n]=2,r()},i.async=1,i.src=n,t.insertBefore(i,t.firstChild)}var e=document,t=e.getElementsByTagName("head")[0],n=/^https?:\/\//,r={},i={},s={},o,u={},a="string",f=!1,l="push",c="DOMContentLoaded",h="readyState",p="addEventListener",d="onreadystatechange";return!e[h]&&e[p]&&(e[p](c,function b(){e.removeEventListener(c,b,f),e[h]="complete"},f),e[h]="loading"),g.get=y,g.order=function(e,t,n){(function r(i){i=e.shift(),e.length?g(i,r):g(i,t,n)})()},g.path=function(e){o=e},g.ready=function(e,t,n){e=e[l]?e:[e];var i=[];return!m(e,function(e){r[e]||i[l](e)})&&v(e,function(e){return r[e]})?t():!function(e){s[e]=s[e]||[],s[e][l](t),n&&n(i)}(e.join("|")),g},g.done=function(e){g([null],e)},g}); // main (function(w,d) { var VERSION = '0.0.2'; var isLoadedjQuery = false; if(w['jQuery'] !== undefined) { isLoadedjQuery = true; w['__jQuery'] = w['jQuery']; } $script([ 'https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js', 'https://raw.github.com/noriaki/ya-sound-novel/'+VERSION+'/extract-content-all.js' ], function() { if(isLoadedjQuery) { var __snjQuery = jQuery.noConflict(true); w['jQuery'] = w['__jQuery']; } (function($) { var ex = new ExtractContentJS.LayeredExtractor(); ex.addHandler(ex.factory.getHandler('Heuristics')); var res = ex.extract(d); if(res.isSuccess) { var c = res.content; var next_sentence = function() { var i = 0, texts = c.asTextFragment().split(/\u3002/); return function() { return texts[i++]; }; }(); // append background $('body').append($('<div id="__snbb">').attr('style', 'width:100%;height:100%;position:absolute;top:0;left:0;background:black;opacity:0.5;')); $('body').append($('<div id="__snbbt">').attr('style', 'width:94%;color:white;position:absolute;top:5%;left:3%;font-size:110%;font-family:serif;text-align:left;display:none;')); // set event and text $('#__snbbt').html('<p>'+res.title+'</p><p>'+res.url+'</p>').fadeIn(); $('#__snbb,#__snbbt').on('click', function(e, s) { if(s = next_sentence()) { $('#__snbbt') .fadeOut('fast', function() { $(this).html('<p>'+s+'\u3002</p>') }) .fadeIn(); } else { $('#__snbbt') .html('<p>End.</p>') .append($('<p><a href="javascript:void(0);">close [x]</a></p>').on('click',function() { $('#__snbb,#__snbbt').remove(); })); } }); } else {} })(__snjQuery); }); })(window, document);
"use strict"; exports.__esModule = true; exports.default = void 0; // encapsulates the subscription logic for connecting a component to the redux store, as // well as nesting subscriptions of descendant components, so that we can ensure the // ancestor components re-render before descendants var CLEARED = null; var nullListeners = { notify: function notify() {} }; function createListenerCollection() { // the current/next pattern is copied from redux's createStore code. // TODO: refactor+expose that code to be reusable here? var current = []; var next = []; return { clear: function clear() { next = CLEARED; current = CLEARED; }, notify: function notify() { var listeners = current = next; for (var i = 0; i < listeners.length; i++) { listeners[i](); } }, get: function get() { return next; }, subscribe: function subscribe(listener) { var isSubscribed = true; if (next === current) next = current.slice(); next.push(listener); return function unsubscribe() { if (!isSubscribed || current === CLEARED) return; isSubscribed = false; if (next === current) next = current.slice(); next.splice(next.indexOf(listener), 1); }; } }; } var Subscription = /*#__PURE__*/ function () { function Subscription(store, parentSub, onStateChange) { this.store = store; this.parentSub = parentSub; this.onStateChange = onStateChange; this.unsubscribe = null; this.listeners = nullListeners; } var _proto = Subscription.prototype; _proto.addNestedSub = function addNestedSub(listener) { this.trySubscribe(); return this.listeners.subscribe(listener); }; _proto.notifyNestedSubs = function notifyNestedSubs() { this.listeners.notify(); }; _proto.isSubscribed = function isSubscribed() { return Boolean(this.unsubscribe); }; _proto.trySubscribe = function trySubscribe() { if (!this.unsubscribe) { this.unsubscribe = this.parentSub ? this.parentSub.addNestedSub(this.onStateChange) : this.store.subscribe(this.onStateChange); this.listeners = createListenerCollection(); } }; _proto.tryUnsubscribe = function tryUnsubscribe() { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; this.listeners.clear(); this.listeners = nullListeners; } }; return Subscription; }(); exports.default = Subscription;
/* * Kendo UI v2015.2.624 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["ar-EG"] = { name: "ar-EG", numberFormat: { pattern: ["n-"], decimals: 3, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 3, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$n-","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "ج.م.‏" } }, calendars: { standard: { days: { names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"], namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"], namesShort: ["ح","ن","ث","ر","خ","ج","س"] }, months: { names: ["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليه","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر"], namesAbbr: ["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليه","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر"] }, AM: ["ص","ص","ص"], PM: ["م","م","م"], patterns: { d: "dd/MM/yyyy", D: "dd MMMM, yyyy", F: "dd MMMM, yyyy hh:mm:ss tt", g: "dd/MM/yyyy hh:mm tt", G: "dd/MM/yyyy hh:mm:ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "/", ":": ":", firstDay: 6 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
const pi = "3141592653589793238462643383279"; const numbers = [ "314159265358979323846", "26433", "8", "3279", "314159265", "35897932384626433832", "79", ]; const output = numbersInPi(pi, numbers); console.log(pi, "\n", numbers, "\nanswer:", output, "\n", output === 2); /* Minimum number of breaks/spaces to split up given pi digits into numbers that exist in numbers array. Key insight: prefixes+suffixes and memo. The prefixes + suffixes approach works with recursive checks, where the prefixes can start anywhere inside the (sub)string. Save all in the numbers array in memo as having 0 spaces = base cases. Then add the prefixes AND suffixes as (sub)-solutions to the memo, building up from those base cases. The memo saves us from re-computing a ton of options. Ot(n^3 + m) because you loop thru all prefix start positions (but just once each because of the memo), and process a suffix per prefix, (there are n^2 prefixes) and also slicing the string (Ot(n)), + set up pre-processing. Os(n + m) because of the memo storing answers for each prefix and each number in the given numbers array. ideas: (n = digits of pi given, m = numbers given) 1) brute force: add 1 to n spaces, and loop and verify Ot(n^n m), Os(n) 2) BCR = Ot(n m), Os(1) (somehow one pass, with just a count of spaces) 3) how? observations: - a number string can't be longer than the given section of pi - if one section is ok, then remaining gaps may include a number to return true - but not always: others may cover it differently & still return true - might have to check starting w/ each number: O(nm nm)= O(n^2 m^2) time - and might have to check each place that each number appears - faster lookup? pre-get all locations per numbers Ot(n m) - then overall becomes Ot(n m + m m), which is ≈ BCR! but Os(nm) 4) apparently we can do Ot(n^3 + m), Os(n + m) - what if we put each number into a hashtable Ot(m) + - and check every prefix (starting anywhere) of pi? Ot(n^2) * Ot(n) */ function numbersInPi(pi, numbers) { const memo = {}; for (let number of numbers) memo[number] = 0; const minSpaces = recursivelyCheckPrefixes(memo, pi, 0, memo); return minSpaces === Infinity ? -1 : minSpaces; } function recursivelyCheckPrefixes(memo, pi) { // the pi param here may simply be a suffix! if (pi in memo) return memo[pi]; // base case for (let p = 0; p < pi.length; p++) { for (let q = p + 1; q < pi.length; q++) { const prefix = pi.slice(p, q); const suffix = pi.slice(q, pi.length); if (prefix in memo) { const s = recursivelyCheckPrefixes(memo, suffix); const pPlusS = memo[prefix] + 1 + s; const ps = prefix + suffix; memo[ps] = ps in memo ? Math.min(memo[ps], pPlusS) : pPlusS; } } } return pi in memo ? memo[pi] : Infinity; }
const niceColors = [ "#eeff96", "#bdff96", "#96ffee", "#96bbff", "#be96ff", "#ef96ff", "#ff96d2", "#ff9696", "#ffd596", ]; export const mutations = { setInputSentences(state, payload) { if (!Array.isArray(payload)) { state.originalText = payload; payload = payload.split(state.separator); } state.inputSentences = payload.map((s, i) => ({ id: i, text: s })); }, addClass(state, payload) { let existing = state.classes.find((c) => c.name == payload); if (existing) { return; } let lastIndex = state.classes.reduce((p, c) => { return c.id > p ? c.id : p; }, 0); state.classes.push({ id: lastIndex + 1, name: payload, color: niceColors[lastIndex % niceColors.length], }); if (state.classes.length === 1) { state.currentClass = state.classes[0]; } }, removeClass(state, payload) { state.classes = state.classes.filter((c) => c.id != payload); if (state.currentClass.id === payload) { state.currentClass = state.classes[0]; } }, setCurrentClass(state, payload) { state.currentClass = state.classes.find((c) => c.id === payload); }, addAnnotation(state, payload) { state.annotations.push(payload); }, setSeparator(state, payload) { state.separator = payload; const sentences = state.originalText.split(state.separator); state.inputSentences = sentences.map((s, i) => ({ id: i, text: s })); }, setCurrentPage(state, payload) { state.currentPage = payload; }, }; export const getters = {}; export default { state() { return { currentPage: "", originalText: "", separator: "\n", classes: [], inputSentences: [], annotations: [], currentClass: {}, }; }, getters, mutations, actions: {}, };
/* **** Helper functions **** */ /** * Sort function for layer objects to sort by platform.<br> * HiSeq before MiSeq - then on Queue date * @param {Object} a Layer object * @param {Object} b Layer object * @returns {Number} A negative number if a should be sorted before b, a positive number if vice versa, otherwise 0 */ function sortByPlatform (a, b) { aPf = ""; bPf = ""; for (var i = 0; i < a.length; i++) { if(a[i]["y"] != 0) { aPf = a[i]["x"]; aQ = a[i]["queueDate"]; } if(b[i]["y"] != 0) { bPf = b[i]["x"]; bQ = b[i]["queueDate"]; } } if(aPf < bPf) return -1; if(aPf > bPf) return 1; if(aQ < bQ ) return -1; if(aQ > bQ ) return 1; return 0; } /** * Sort function for layer objects to sort by application.<br> * DNA/RNA/SeqCap/Other - then on Queue date * @param {Object} a Layer object * @param {Object} b Layer object * @returns {Number} A negative number if a should be sorted before b, a positive number if vice versa, otherwise 0 */ function sortByApplication (a, b) { var map = { "DNA": 0, "RNA": 1, "SeqCap": 2, "Other": 3 } var aAppl; var bAppl; for (var i = 0; i < a.length; i++) { if(a[i]["y"] != 0) { aAppl = map[a[i]["x"]]; aQ = a[i]["queueDate"]; aArr = a[i]["arrivalDate"]; aPid = a[i]["pid"];} if(b[i]["y"] != 0) { bAppl = map[b[i]["x"]]; bQ = b[i]["queueDate"]; bArr = b[i]["arrivalDate"]; bPid = b[i]["pid"];} } if(aAppl < bAppl) return -1; if(aAppl > bAppl) return 1; if(aQ < bQ ) return -1; if(aQ > bQ ) return 1; if(aArr < bArr ) return -1; if(aArr > bArr ) return 1; if(aPid < bPid ) return -1; if(aPid > bPid ) return 1; return 0; } function getFirstInQueue(data) { var qD = "9999-99-99"; var arrD = "9999-99-99"; var firstPid; for (var i = 0; i < data.length; i++) { if (data[i][0]["queueDate"] < qD) { qD = data[i][0]["queueDate"]; arrD = data[i][0]["arrivalDate"]; firstPid = data[i][0]["pid"]; } else if (data[i][0]["queueDate"] == qD) { if (data[i][0]["arrivalDate"] < arrD) { arrD = data[i][0]["arrivalDate"]; firstPid = data[i][0]["pid"]; } else if (data[i][0]["arrivalDate"] == arrD) { if (data[i][0]["pid"] < firstPid) { firstPid = data[i][0]["pid"]; } } } } return firstPid; } /** * Calculates number of projects per domain (x value) in a layer object data set * @param {Array} dataset Array of array of layer objects * @param {Array} domain Array of domain names (x values) * @returns {Object} An object with counts per domain */ function numProjects(dataset, domain) { var num_projects = {}; for (var i = 0; i < domain.length; i++) { num_projects[domain[i]] = 0; } //console.log(num_projects); for(var i = 0; i < dataset.length; i++) { for (var j = 0; j < dataset[i].length; j++) { var obj = dataset[i][j]; if(obj.y != 0) { num_projects[obj.x]++; } } } //console.log(num_projects); return num_projects; } /** * Calculates number of units (worksets or lanes) per domain (x value) in a layer object data set * @param {Array} dataset Array of array of layer objects * @param {Array} domain Array of domain names (x values) * @param {String} [unit="lanes"] Name of unit. Specify "samples" to get number of worksets, otherwise number of lanes * @returns {Object} An object with counts per domain. */ function numUnits(dataset, domain, unit) { var num_u = {}; for (var i = 0; i < domain.length; i++) { num_u[domain[i]] = 0; } //console.log(num_u); for(var i = 0; i < dataset.length; i++) { for (var j = 0; j < dataset[i].length; j++) { var obj = dataset[i][j]; if(obj.y != 0) { num_u[obj.x] += obj.y; } } } for (c in num_u) { if (unit == "samples") { // convert samples to worksets if (num_u[c] != 0) { num_u[c] = Math.ceil(num_u[c]/96); } } else { // round off lane counts to one digit num_u[c] = parseFloat(num_u[c]).toFixed(1); } } //console.log(num_u); return num_u; } /** * Calculates the total y value for all stacked bars per domain (x value) in a layer object data set * @param {Array} dataset Array of array of layer objects * @param {Array} domain Array of domain names (x values) * @returns {Object} An object with counts per domain */ function totalY(dataset, domain) { var tot = {}; for (var i = 0; i < domain.length; i++) { tot[domain[i]] = 0; } //console.log(num_projects); for(var i = 0; i < dataset.length; i++) { for (var j = 0; j < dataset[i].length; j++) { var obj = dataset[i][j]; tot[obj.x] += obj.y; } } //console.log(tot); return tot; } /* **** Data transformation functions **** */ /** * Generates a dataset for Rec Ctrl project load for stacked bar chart drawing * @param {Object} json A parsed json stream object at sample level * @param {Date} cmpDate A Date object to specify load date * @returns {Array} An array of arrays of "layer" objects */ function generateRecCtrlStackDataset(json, cmpDate) { var dateFormat = d3.time.format("%Y-%m-%d"); var cmpDateStr = dateFormat(cmpDate); // Turn cmp date into a string to compare to dates in data var dataArray = []; var rows = json["rows"]; var applBins = {}; var cat = ["DNA", "RNA", "SeqCap", "Other", "FinLib", "Application"]; for (i = 0; i < cat.length; i++) { //console.log("adding " + cat[i]); applBins[cat[i]] = { count: 0 };// initialize count for each category } //console.log(applBins); var projects = {}; // loop through each sample and add upp num of projects for (var i = 0; i < rows.length; i++) { var k = rows[i]["key"]; //console.log(k) var pid = k[0]; var type = k[1]; var appl = k[2]; var sampleID = k[4]; // skip projects that are labeled as neither Production or Application if (type == null ) { continue; } if(appl == null) { appl = "Other";} //console.log(sampleID); var applCat = ""; if(type == "Application") { applCat = "Application" } else if (appl.indexOf("capture") != -1) { applCat = "SeqCap"; } else if (appl == "Amplicon" || appl == "de novo" || appl == "Metagenome" || appl == "WG re-seq") { applCat = "DNA"; } else if (appl == "RNA-seq (total RNA)") { applCat = "RNA"; } else if (appl == "Finished library") { applCat = "FinLib"; } else { applCat = "Other"; } var v = rows[i]["value"]; // skip aborted projects var aborted_date = v["Aborted date"]; if (aborted_date != "0000-00-00") { //console.log("Skipping " + keys[0]); continue; } // Skip aborted or finished *samples* if (v["Status"] == "Aborted" || v["Status"] == "Finished" ) { continue; } // skip closed projects var closeDate = v["Close date"]; if(closeDate != "0000-00-00") { continue; } // skip projects that have passed later process steps var libQCDate = v["QC library finished"]; var seqDoneDate = v["All samples sequenced"]; if (appl != "Finished library" && libQCDate != "0000-00-00") { continue; } if (seqDoneDate != "0000-00-00") { continue; } var rawDataDelivered = v["All raw data delivered"]; if (rawDataDelivered != "0000-00-00") { continue; } var arrDate = v["Arrival date"]; var queueDate = v["Queue date"]; if (arrDate != "0000-00-00" && arrDate <= cmpDateStr && queueDate == "0000-00-00") { // initialize a value for the project if it doesn't exist in applBins if(applBins[applCat][pid] == undefined) { //this is only done once for each project applBins[applCat][pid] = 1; // just add a value for the project applBins[applCat]["count"]++; //console.log(pid + ", " + type + ", " + appl + ", " + applCat); } //if(projects[pid] == undefined) { // is this needed? // projects[pid] = { cat: applCat, arrivalDate: arrDate, queueDate: queueDate} //} } } //console.log(pfBins); // put into "layer structure", sort & then add up y0's //console.log(applBins); var projArr = []; for (i = 0; i < cat.length; i++) { var o = { x: "RecCtrl", y: applBins[cat[i]]["count"], cat: cat[i] }; var proj; for(var p in applBins[cat[i]]) { if(p.indexOf("P") == -1) { continue; } if (proj == undefined) { proj = p; } else { proj += ", " + p; } } o["projects"] = proj; proj = undefined; projArr.push(o); } tot = 0; for (var i = 0; i < projArr.length; i++) { projArr[i]["y0"] = tot; tot += projArr[i]["y"]; } return [projArr]; } /** * Generates a dataset for Libprep queue lane load for stacked bar chart drawing * @param {Object} json A parsed json stream object at sample level * @param {Date} cmpDate A Date object to specify load date * @returns {Array} An array of arrays of "layer" objects */ function generateQueueLaneLPStackDataset(json, cmpDate, ptype) { var dateFormat = d3.time.format("%Y-%m-%d"); var cmpDateStr = dateFormat(cmpDate); // Turn cmp date into a string to compare to dates in data var dataArray = []; var rows = json["rows"]; var pfBins = {}; var projects = {}; ptype = typeof ptype !== 'undefined' ? ptype : "Production"; //Default is production, unless something else is given // loop through each sample and add upp lane load per project for (var i = 0; i < rows.length; i++) { //console.log("looping through json array: 1"); var k = rows[i]["key"]; var pid = k[0]; var type = k[1]; var appl = k[2]; if (type != ptype) { continue; } // only matching ptype projectsprojects (Application or Production) will be returned. if (appl == "Finished library") { continue; } // need seq start date to be able to handle fin lib projects // Determine which platform var pf = k[3]; var otherPf = "MiSeq"; if (pf != "MiSeq") { pf = "HiSeq"; } else { otherPf = "HiSeq"; } var v = rows[i]["value"]; // skip aborted projects var aborted_date = v["Aborted date"]; if (aborted_date != "0000-00-00") { //console.log("Skipping " + keys[0]); continue; } // Skip aborted or finished *samples* if (v["Status"] == "Aborted" || v["Status"] == "Finished" ) { continue; } // skip closed projects var closeDate = v["Close date"]; if(closeDate != "0000-00-00") { continue; } // skip samples already done, but where dates are missing in lims var libQCDate = v["QC library finished"]; if (libQCDate != "0000-00-00") { continue; } var seqStartDate = v["Sequencing start"]; if (seqStartDate != "0000-00-00") { continue; } var seqFinishedDate = v["All samples sequenced"]; if (seqFinishedDate != "0000-00-00") { continue; } var rawDataDelivered = v["All raw data delivered"]; if (rawDataDelivered != "0000-00-00") { continue; } var queueDate = v["Queue date"]; var prepStartDate = v["Lib prep start"]; // this is for libprep projects if (queueDate != "0000-00-00" && queueDate <= cmpDateStr && prepStartDate == "0000-00-00") { //console.log(pf + ", " + pid + ", " + v["Lanes"]); // create bins for the platforms if they don't exist if(pfBins[pf] == undefined) { pfBins[pf] = {}; } if(pfBins[otherPf] == undefined) { pfBins[otherPf] = {}; } // initialize a value for the project if it doesn't exist in pfBins if(pfBins[pf][pid] == undefined) { pfBins[pf][pid] = 0; } if(pfBins[otherPf][pid] == undefined) { pfBins[otherPf][pid] = 0; } // add on lane load for this particular project pfBins[pf][pid] += v["Lanes"]; if(projects[pid] == undefined) { projects[pid] = { queueDate: queueDate } } } } //console.log(pfBins); // remove proj name?????? // put into "layer structure", sort & then add up y0's for (var projID in pfBins["HiSeq"]) { var hO = { x: "HiSeq", y: pfBins["HiSeq"][projID], pid: projID, queueDate: projects[projID]["queueDate"] }; var mO = { x: "MiSeq", y: pfBins["MiSeq"][projID], pid: projID, queueDate: projects[projID]["queueDate"] }; dataArray.push([hO, mO]); } dataArray.sort(sortByPlatform); var tot = { HiSeq: 0, MiSeq: 0}; for (var i = 0; i < dataArray.length; i++) { for (var j = 0; j < dataArray[i].length; j++) { var pf = dataArray[i][j]["x"]; dataArray[i][j]["y0"] = tot[pf]; tot[pf] += dataArray[i][j]["y"]; } } //console.log(dataArray); if (dataArray.length == 0 ) { dataArray = [ [ { x: "HiSeq", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "MiSeq", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"} ] ]; } return dataArray; } /** * Generates a dataset for Finished lib queue lane load for stacked bar chart drawing * @param {Object} json A parsed json stream object at sample level * @param {Date} cmpDate A Date object to specify load date * @returns {Array} An array of arrays of "layer" objects */ function generateQueueLaneFLStackDataset(json, cmpDate, ptype) { var dateFormat = d3.time.format("%Y-%m-%d"); var cmpDateStr = dateFormat(cmpDate); // Turn cmp date into a string to compare to dates in data // time limits in days to use for project bar colouring var timeLimit1 = 10; // to lable yellow var timeLimit2 = 20; // to lable red var dataArray = []; var rows = json["rows"]; var pfBins = {}; var projects = {}; ptype = typeof ptype !== 'undefined' ? ptype : "Production"; //Default is production, unless something else is given // loop through each sample and add upp lane load per project for (var i = 0; i < rows.length; i++) { //console.log("looping through json array: 1"); var k = rows[i]["key"]; var pid = k[0]; var type = k[1]; var appl = k[2]; if (type != ptype){ continue; } // only ptype are of interest - is this true?? if (appl != "Finished library") { continue; } // skip fin lib projects // Determine which platform var pf = k[3]; var otherPf = "MiSeq"; if (pf != "MiSeq") { pf = "HiSeq"; } else { otherPf = "HiSeq"; } var v = rows[i]["value"]; // skip aborted projects var aborted_date = v["Aborted date"]; if (aborted_date != "0000-00-00") { //console.log("Skipping " + k[0]); continue; } // Skip aborted or finished *samples* if (v["Status"] == "Aborted" || v["Status"] == "Finished" ) { continue; } // skip closed projects var closeDate = v["Close date"]; if(closeDate != "0000-00-00") { continue; } // skip samples already done, but where dates are missing in lims var seqStartDate = v["Sequencing start"]; if (seqStartDate != "0000-00-00") { continue; } var seqFinishedDate = v["All samples sequenced"]; if (seqFinishedDate != "0000-00-00") { continue; } var rawDataDelivered = v["All raw data delivered"]; if (rawDataDelivered != "0000-00-00") { continue; } var queueDate = v["Queue date"]; //var prepStartDate = v["Lib prep start"]; var seqStartDate = v["Sequencing start"]; // this is for libprep projects if (queueDate != "0000-00-00" && queueDate <= cmpDateStr && seqStartDate == "0000-00-00") { //console.log(pf + ", " + pid + ", " + v["Lanes"]); // create bins for the platforms if they don't exist if(pfBins[pf] == undefined) { pfBins[pf] = {}; } if(pfBins[otherPf] == undefined) { pfBins[otherPf] = {}; } // initialize a value for the project if it doesn't exist in pfBins if(pfBins[pf][pid] == undefined) { pfBins[pf][pid] = 0; } if(pfBins[otherPf][pid] == undefined) { pfBins[otherPf][pid] = 0; } // add on lane load for this particular project pfBins[pf][pid] += v["Lanes"]; if(projects[pid] == undefined) { // set a limit indicator based on how long the project has been going on // the limit variables are set at the beginning of this function // these limits can be used to set colouring of project bars var ongoingTime = daydiff(new Date(queueDate), cmpDate); var passedTimeLimit = 0; if (ongoingTime > timeLimit2) { passedTimeLimit = 2; } else if (ongoingTime > timeLimit1) { passedTimeLimit = 1; } //console.log(pid + " passedTimeLimit: " + passedTimeLimit) projects[pid] = { queueDate: queueDate, passedTimeLimit: passedTimeLimit } //projects[pid] = { queueDate: queueDate} } } } //console.log(pfBins); // put into "layer structure", sort & then add up y0's for (var projID in pfBins["HiSeq"]) { var hO = { x: "HiSeq", y: pfBins["HiSeq"][projID], pid: projID, queueDate: projects[projID]["queueDate"], passedTimeLimit: projects[projID]["passedTimeLimit"] }; var mO = { x: "MiSeq", y: pfBins["MiSeq"][projID], pid: projID, queueDate: projects[projID]["queueDate"], passedTimeLimit: projects[projID]["passedTimeLimit"] }; dataArray.push([hO, mO]); } dataArray.sort(sortByPlatform); var tot = { HiSeq: 0, MiSeq: 0}; for (var i = 0; i < dataArray.length; i++) { for (var j = 0; j < dataArray[i].length; j++) { var pf = dataArray[i][j]["x"]; dataArray[i][j]["y0"] = tot[pf]; tot[pf] += dataArray[i][j]["y"]; } } //console.log(dataArray); if (dataArray.length == 0 ) { dataArray = [ [ { x: "HiSeq", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "MiSeq", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"} ] ]; } return dataArray; } /** * Generates a dataset for Libprep queue sample load for stacked bar chart drawing * @param {Object} json A parsed json stream object at sample level * @param {Date} cmpDate A Date object to specify load date * @returns {Array} An array of arrays of "layer" objects */ function generateQueueSampleStackDataset(json, cmpDate, ptype) { var dateFormat = d3.time.format("%Y-%m-%d"); var cmpDateStr = dateFormat(cmpDate); // Turn cmp date into a string to compare to dates in data // time limits in days to use for project bar colouring var timeLimit1 = 10; // to lable yellow var timeLimit2 = 20; // to lable red var dataArray = []; var rows = json["rows"]; var applBins = {}; var cat = ["DNA", "RNA", "SeqCap", "Other"]; for (i = 0; i < cat.length; i++) { //console.log("adding " + cat[i]); applBins[cat[i]] = {}; } //console.log(applBins); ptype = typeof ptype !== 'undefined' ? ptype : "Production"; //Default is production, unless something else is given // array to capture libprep start dates var libPrepStartDates = []; var projects = {}; // loop through each sample and add upp lane load per project for (var i = 0; i < rows.length; i++) { var k = rows[i]["key"]; //console.log(k) var pid = k[0]; var type = k[1]; var appl = k[2]; var sampleID = k[4]; if (type != ptype){ continue; } // only ptype projects of interest if (appl == "Finished library") { continue; } // fin lib projects not of interest if(appl == null) { appl = "Other";} //console.log(sampleID); var applCat = ""; if (appl.indexOf("capture") != -1) { applCat = "SeqCap"; } else if (appl == "Amplicon" || appl == "de novo" || appl == "Metagenome" || appl == "WG re-seq" || appl == "WG re-seq (IGN)" ) { applCat = "DNA"; } else if (appl == "RNA-seq (total RNA)") { applCat = "RNA"; } else { applCat = "Other"; } var v = rows[i]["value"]; // skip aborted projects var aborted_date = v["Aborted date"]; if (aborted_date != "0000-00-00") { //console.log("Skipping " + keys[0]); continue; } // Skip aborted or finished *samples* if (v["Status"] == "Aborted" || v["Status"] == "Finished" ) { continue; } // skip closed projects var closeDate = v["Close date"]; if(closeDate != "0000-00-00") { continue; } // skip samples already done, but where dates are missing in lims var libQCDate = v["QC library finished"]; if (libQCDate != "0000-00-00") { continue; } var seqStartDate = v["Sequencing start"]; if (seqStartDate != "0000-00-00") { continue; } var seqFinishedDate = v["All samples sequenced"]; if (seqFinishedDate != "0000-00-00") { continue; } var rawDataDelivered = v["All raw data delivered"]; if (rawDataDelivered != "0000-00-00") { continue; } var arrivalDate = v["Arrival date"]; var queueDate = v["Queue date"]; var prepStartDate = v["Lib prep start"]; libPrepStartDates.push(prepStartDate); // this is for libprep projects if (queueDate != "0000-00-00" && queueDate <= cmpDateStr && prepStartDate == "0000-00-00") { //console.log("To add - app cat: " + applCat + ", pid: " + pid + ", sample: " + sampleID); // initialize a value for the project for all applications if it doesn't exist in applBins if(applBins[applCat][pid] == undefined) { //for (c in cat) { // applBins[c][pid] = 0; //} for (var j = 0; j < cat.length; j++) { applBins[cat[j]][pid] = 0; } } // add sample load for this particular project applBins[applCat][pid] += 1; if(projects[pid] == undefined) { // set a limit indicator based on how long the project has been going on // the limit variables are set at the beginning of this function // these limits can be used to set colouring of project bars var ongoingTime = daydiff(new Date(queueDate), cmpDate); var passedTimeLimit = 0; if (ongoingTime > timeLimit2) { passedTimeLimit = 2; } else if (ongoingTime > timeLimit1) { passedTimeLimit = 1; } //console.log(pid + " passedTimeLimit: " + passedTimeLimit) projects[pid] = { queueDate: queueDate, arrivalDate: arrivalDate, passedTimeLimit: passedTimeLimit } } } } //console.log(pfBins); // get the last prep start date // filter function to remove duplicates function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var libPrepStartDates = libPrepStartDates.filter( onlyUnique ); libPrepStartDates.sort(); var ps = libPrepStartDates.pop(); // last date while (ps > cmpDateStr ) { // continue pop'ing until last date is less than comparison date ps = libPrepStartDates.pop(); } var lastLibPrepStart = ps; var daysSincePrepStart = daydiff(new Date(lastLibPrepStart), cmpDate); // put into "layer structure", sort & then add up y0's for (var projID in applBins["DNA"]) { var projArr = []; //for (c in cat) { for (i = 0; i < cat.length; i++) { //var o = { x: cat[i], y: applBins[cat[i]][projID], pid: projID, queueDate: projects[projID]["queueDate"], arrivalDate: projects[projID]["arrivalDate"] }; var o = { x: cat[i], y: applBins[cat[i]][projID], pid: projID, queueDate: projects[projID]["queueDate"], arrivalDate: projects[projID]["arrivalDate"], passedTimeLimit: projects[projID]["passedTimeLimit"] }; projArr.push(o); } dataArray.push(projArr); } // change to sort by application dataArray.sort(sortByApplication); // by application & queue date - arrival date - project ID var firstInQueuePid = getFirstInQueue(dataArray); //console.log("first in queue pid: " + firstInQueuePid); var tot = { DNA: 0, RNA: 0, SeqCap: 0, Other: 0}; for (var i = 0; i < dataArray.length; i++) { for (var j = 0; j < dataArray[i].length; j++) { var a = dataArray[i][j]["x"]; dataArray[i][j]["y0"] = tot[a]; tot[a] += dataArray[i][j]["y"]; //if (i == 0) { // add info about time since last libprep start for the project first in queue if (dataArray[i][j]["pid"] == firstInQueuePid) { // add info about time since last libprep start for the project first in queue dataArray[i][j]["lastLibPrep"] = lastLibPrepStart; dataArray[i][j]["daysSincePrepStart"] = daysSincePrepStart; } } } //console.log(dataArray); //return pfBins; if (dataArray.length == 0 ) { dataArray = [ [ { x: "DNA", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "RNA", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "SeqCap", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "Other", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"} ] ]; } return dataArray; } /** * Generates a dataset for Libprep ongoing sample load for stacked bar chart drawing * @param {Object} json A parsed json stream object at sample level * @param {Date} cmpDate A Date object to specify load date * @returns {Array} An array of arrays of "layer" objects */ function generateLibprepSampleLoadDataset(json, cmpDate, ptype) { var dateFormat = d3.time.format("%Y-%m-%d"); var cmpDateStr = dateFormat(cmpDate); // Turn cmp date into a string to compare to dates in data // time limits in days to use for project bar colouring var timeLimit1 = 42; // to lable yellow var timeLimit2 = 63; // to lable red var dataArray = []; var rows = json["rows"]; var applBins = {}; var cat = ["DNA", "RNA", "SeqCap", "Other"]; for (i = 0; i < cat.length; i++) { //console.log("adding " + cat[i]); applBins[cat[i]] = {}; } //console.log(applBins); ptype = typeof ptype !== 'undefined' ? ptype : "Production"; //Default is production, unless something else is given var projects = {}; // loop through each sample and add upp lane load per project for (var i = 0; i < rows.length; i++) { var k = rows[i]["key"]; var pid = k[0]; var type = k[1]; var appl = k[2]; var sampleID = k[4]; if (appl == "Finished library") { continue; } // fin lib projects not of interest if (type != ptype) { continue; } // only projects of ptype are of interest if(appl == null) { appl = "Other";} //console.log(sampleID); var applCat = ""; if (appl.indexOf("capture") != -1) { applCat = "SeqCap"; } else if (appl == "Amplicon" || appl == "de novo" || appl == "Metagenome" || appl == "WG re-seq") { applCat = "DNA"; } else if (appl == "RNA-seq (total RNA)") { applCat = "RNA"; } else { applCat = "Other"; } var v = rows[i]["value"]; // skip aborted projects var aborted_date = v["Aborted date"]; if (aborted_date != "0000-00-00") { //console.log("Skipping " + keys[0]); continue; } // Skip aborted or finished *samples* if (v["Status"] == "Aborted" || v["Status"] == "Finished" ) { continue; } // skip closed projects var closeDate = v["Close date"]; if(closeDate != "0000-00-00") { continue; } // skip samples already done, but where dates are missing in lims var seqStartDate = v["Sequencing start"]; if (seqStartDate != "0000-00-00") { continue; } var seqFinishedDate = v["All samples sequenced"]; if (seqFinishedDate != "0000-00-00") { continue; } var rawDataDelivered = v["All raw data delivered"]; if (rawDataDelivered != "0000-00-00") { continue; } var queueDate = v["Queue date"]; var prepStartDate = v["Lib prep start"]; var libQCDate = v["QC library finished"]; //console.log("app cat: " + applCat + ", pid: " + pid + ", sample: " + sampleID + ", " + prepStartDate + "-" + libQCDate); // this is for libprep projects if (prepStartDate != "0000-00-00" && prepStartDate <= cmpDateStr && libQCDate == "0000-00-00") { //console.log("To add - app cat: " + applCat + ", pid: " + pid + ", sample: " + sampleID); // initialize a value for the project for all applications if it doesn't exist in applBins if(applBins[applCat][pid] == undefined) { for (var j = 0; j < cat.length; j++) { applBins[cat[j]][pid] = 0; } } // add sample load for this particular project applBins[applCat][pid] += 1; if(projects[pid] == undefined) { // set a limit indicator based on how long the project has been going on // the limit variables are set at the beginning of this function // these limits can be used to set colouring of project bars var ongoingTime = daydiff(new Date(queueDate), cmpDate); var passedTimeLimit = 0; if (ongoingTime > timeLimit2) { passedTimeLimit = 2; } else if (ongoingTime > timeLimit1) { passedTimeLimit = 1; } projects[pid] = { queueDate: queueDate, pid: pid, passedTimeLimit: passedTimeLimit } //projects[pid] = { queueDate: queueDate, pid: pid} } } } //console.log(pfBins); // put into "layer structure", sort & then add up y0's for (var projID in applBins["DNA"]) { var projArr = []; for (i = 0; i < cat.length; i++) { //var o = { x: cat[i], y: applBins[cat[i]][projID], pid: projID, projName: projects[projID]["projName"], queueDate: projects[projID]["queueDate"] }; var o = { x: cat[i], y: applBins[cat[i]][projID], pid: projID, projName: projects[projID]["projName"], queueDate: projects[projID]["queueDate"], passedTimeLimit: projects[projID]["passedTimeLimit"] }; projArr.push(o); } dataArray.push(projArr); } // change to sort by application dataArray.sort(sortByApplication); var tot = { DNA: 0, RNA: 0, SeqCap: 0, Other: 0}; for (var i = 0; i < dataArray.length; i++) { for (var j = 0; j < dataArray[i].length; j++) { var a = dataArray[i][j]["x"]; dataArray[i][j]["y0"] = tot[a]; tot[a] += dataArray[i][j]["y"]; } } if (dataArray.length == 0 ) { dataArray = [ [ { x: "DNA", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "RNA", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "SeqCap", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "Other", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"} ] ]; } return dataArray; } /** * Generates a dataset for Libprep ongoing lane load for stacked bar chart drawing * @param {Object} json A parsed json stream object at sample level * @param {Date} cmpDate A Date object to specify load date * @returns {Array} An array of arrays of "layer" objects */ function generateLibprepLaneLoadDataset(json, cmpDate, ptype) { var dateFormat = d3.time.format("%Y-%m-%d"); var cmpDateStr = dateFormat(cmpDate); // Turn cmp date into a string to compare to dates in data var dataArray = []; var rows = json["rows"]; var pfBins = {}; var projects = {}; ptype = typeof ptype !== 'undefined' ? ptype : "Production"; //Default is production, unless something else is given for (var i = 0; i < rows.length; i++) { var k = rows[i]["key"]; var pid = k[0]; var type = k[1]; var appl = k[2]; if (appl == "Finished library") { continue; } // skip fin lib projects if (type != ptype) { continue; } // only ptype projects are of interest // Determine which platform var pf = k[3]; var otherPf = "MiSeq"; if (pf != "MiSeq") { pf = "HiSeq"; } else { otherPf = "HiSeq"; } var v = rows[i]["value"]; // skip aborted projects var aborted_date = v["Aborted date"]; if (aborted_date != "0000-00-00") { //console.log("Skipping " + keys[0]); continue; } // Skip aborted or finished *samples* if (v["Status"] == "Aborted" || v["Status"] == "Finished" ) { continue; } // skip closed projects var closeDate = v["Close date"]; if(closeDate != "0000-00-00") { continue; } // skip samples already done, but where dates are missing in lims var seqStartDate = v["Sequencing start"]; if (seqStartDate != "0000-00-00") { continue; } var seqFinishedDate = v["All samples sequenced"]; if (seqFinishedDate != "0000-00-00") { continue; } var rawDataDelivered = v["All raw data delivered"]; if (rawDataDelivered != "0000-00-00") { continue; } var queueDate = v["Queue date"]; var prepStartDate = v["Lib prep start"]; //console.log(prepStartDate); var libQCDate = v["QC library finished"]; // this is for libprep projects if (prepStartDate != "0000-00-00" && prepStartDate <= cmpDateStr && libQCDate == "0000-00-00") { //console.log(pf + ", " + pid + ", " + v["Lanes"]); // create bins for the platforms if they don't exist if(pfBins[pf] == undefined) { pfBins[pf] = {}; } if(pfBins[otherPf] == undefined) { pfBins[otherPf] = {}; } // initialize a value for the project if it doesn't exist in pfBins if(pfBins[pf][pid] == undefined) { pfBins[pf][pid] = 0; } if(pfBins[otherPf][pid] == undefined) { pfBins[otherPf][pid] = 0; } // add on lane load for this particular project pfBins[pf][pid] += v["Lanes"]; if(projects[pid] == undefined) { projects[pid] = { queueDate: queueDate, pid: pid} } } } //console.log(pfBins); // put into "layer structure", sort & then add up y0's for (var projID in pfBins["HiSeq"]) { var hO = { x: "HiSeq", y: pfBins["HiSeq"][projID], pid: projID, projName: projects[projID]["projName"], queueDate: projects[projID]["queueDate"] }; var mO = { x: "MiSeq", y: pfBins["MiSeq"][projID], pid: projID, projName: projects[projID]["projName"], queueDate: projects[projID]["queueDate"] }; dataArray.push([hO, mO]); } dataArray.sort(sortByPlatform); var tot = { HiSeq: 0, MiSeq: 0}; for (var i = 0; i < dataArray.length; i++) { for (var j = 0; j < dataArray[i].length; j++) { var pf = dataArray[i][j]["x"]; dataArray[i][j]["y0"] = tot[pf]; tot[pf] += dataArray[i][j]["y"]; } } //console.log(dataArray); if (dataArray.length == 0 ) { dataArray = [ [ { x: "HiSeq", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "MiSeq", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"} ] ]; } return dataArray; } /** * Generates a dataset for Seq lane load for stacked bar chart drawing * @param {Object} json A parsed json stream object at sample level * @param {Date} cmpDate A Date object to specify load date * @returns {Array} An array of arrays of "layer" objects */ function generateSeqLoadDataset(json, cmpDate, ptype) { var dateFormat = d3.time.format("%Y-%m-%d"); var cmpDateStr = dateFormat(cmpDate); // Turn cmp date into a string to compare to dates in data // time limits in days to use for project bar colouring var timeLimit1 = 42; // to lable yellow var timeLimit2 = 63; // to lable red ptype = typeof ptype !== 'undefined' ? ptype : "Production"; //Default is production, unless something else is given var dataArray = []; var rows = json["rows"]; var pfBins = {}; var projects = {}; // loop through each sample and add upp lane load per project for (var i = 0; i < rows.length; i++) { //console.log("looping through json array: 1"); var k = rows[i]["key"]; var pid = k[0]; var type = k[1]; var appl = k[2]; var sid = k[4]; if (type != ptype) { continue; } // only ptype pptype projects aree of interest // Determine which platform var pf = k[3]; var otherPf = "MiSeq"; if (pf != "MiSeq") { pf = "HiSeq"; } else { otherPf = "HiSeq"; } var v = rows[i]["value"]; // skip aborted projects var aborted_date = v["Aborted date"]; if (aborted_date != "0000-00-00") { //console.log("Skipping " + keys[0]); continue; } // Skip aborted or finished *samples* if (v["Status"] == "Aborted" || v["Status"] == "Finished" ) { continue; } // skip closed projects var closeDate = v["Close date"]; if(closeDate != "0000-00-00") { continue; } var queueDate = v["Queue date"]; var libQCDate = v["QC library finished"]; var seqStartDate = v["Sequencing start"]; var seqDoneDate = v["All samples sequenced"]; //skip samples were there are missing dates in the LIMS var rawDataDelivered = v["All raw data delivered"]; if (rawDataDelivered != "0000-00-00") { continue; } // The start date of the process step depends on if project is libprep or fin lib var stepStartDate = libQCDate; if(appl == "Finished library") { stepStartDate = seqStartDate; } if (stepStartDate != "0000-00-00" && libQCDate <= cmpDateStr && seqDoneDate == "0000-00-00") { //console.log(pf + ", " + pid + ": " + sid + ", " + v["Lanes"]); // create bins for the platforms if they don't exist if(pfBins[pf] == undefined) { pfBins[pf] = {}; } if(pfBins[otherPf] == undefined) { pfBins[otherPf] = {}; } // initialize a value for the project if it doesn't exist in pfBins if(pfBins[pf][pid] == undefined) { pfBins[pf][pid] = 0; } if(pfBins[otherPf][pid] == undefined) { pfBins[otherPf][pid] = 0; } // add on lane load for this particular project pfBins[pf][pid] += v["Lanes"]; if(projects[pid] == undefined) { // set a limit indicator based on how long the project has been going on // the limit variables are set at the beginning of this function // these limits can be used to set colouring of project bars var ongoingTime = daydiff(new Date(queueDate), cmpDate); var passedTimeLimit = 0; if (ongoingTime > timeLimit2) { passedTimeLimit = 2; } else if (ongoingTime > timeLimit1) { passedTimeLimit = 1; } projects[pid] = { queueDate: queueDate, pid: pid, passedTimeLimit: passedTimeLimit } //projects[pid] = { queueDate: queueDate, pid: pid} } } } //console.log(pfBins); // put into "layer structure", sort & then add up y0's for (var projID in pfBins["HiSeq"]) { var hO = { x: "HiSeq", y: pfBins["HiSeq"][projID], pid: projID, projName: projects[projID]["projName"], queueDate: projects[projID]["queueDate"], passedTimeLimit: projects[projID]["passedTimeLimit"] }; var mO = { x: "MiSeq", y: pfBins["MiSeq"][projID], pid: projID, projName: projects[projID]["projName"], queueDate: projects[projID]["queueDate"], passedTimeLimit: projects[projID]["passedTimeLimit"] }; dataArray.push([hO, mO]); } dataArray.sort(sortByPlatform); var tot = { HiSeq: 0, MiSeq: 0}; for (var i = 0; i < dataArray.length; i++) { for (var j = 0; j < dataArray[i].length; j++) { var pf = dataArray[i][j]["x"]; dataArray[i][j]["y0"] = tot[pf]; tot[pf] += dataArray[i][j]["y"]; } } //console.log(dataArray); if (dataArray.length == 0 ) { dataArray = [ [ { x: "HiSeq", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"}, { x: "MiSeq", y: 0, y0: 0, pid: "Px", projName: "empty", queueDate: "0000-00-00"} ] ]; } return dataArray; } /* **** Drawing functions **** */ /** * Code to draw a stacked barchart plot * @param {Array} dataset Array of array of layer objects * @param {String} divID Id of DOM div to where plot should reside * @param {Number} width plot width * @param {Number} height plot height * @param {String} [unit="lanes"] Unit of values. Used for bar legend * @param {Boolean} showFirstInQueue=false If first in queue project should be indicated visually * @param {Number} maxY "Normal" max value for y-axis * @param {Boolean} showNumWS If number of worksets should be shown */ function drawStackedBars (dataset, divID, width, height, unit, showFirstInQueue, maxY, showNumWS) { //console.log(dataset) var w = width, h = height, p = [30, 0, 30, 20], // t, r, b, l x = d3.scale.ordinal().rangeRoundBands([0, w - p[1] - p[3]]), y = d3.scale.linear().range([0, h - p[0] - p[2]]), parse = d3.time.format("%m/%Y").parse, format = d3.time.format("%b"); // Time limit colours var limitCol1 = "#FFC447"; var limitCol2 = "#FD464B"; if (unit == undefined) { unit = "lanes"} var fixedDigits = 1; if (unit == "samples") { fixedDigits = 0; } // Get a handle to the tooltip div var tooltipDiv = d3.select(".tooltip"); // Resize slightly for lane and sample information (done in mouseover code below) // width var tooltipWidth = tooltipDiv.style("width"); // remove last two letters: "px" & turn into an integer tooltipWidth = parseInt(tooltipWidth.substring(0, tooltipWidth.length - 2)); var tooltipNewWidth = tooltipWidth + 5; // height var tooltipHeight = tooltipDiv.style("height"); // remove last two letters: "px" & turn into an integer tooltipHeight = parseInt(tooltipHeight.substring(0, tooltipHeight.length - 2)); var tooltipRowHeight = "13"; // 13px per row var tooltipNewHeight = tooltipHeight - tooltipRowHeight; /* * Not really using these colour schemes at the moment * Will leave the code in for my bad old memory, if they are to be * used later on */ // color scales // use colorbrewer color schemes // number of colors to use. NB! not all schemes have the same number of colors, see colorbrewer.js // Also, see colorbrewer2.org //var num_colors = 11; // also used in svg color code functions below //var color_scheme = colorbrewer.RdYlGn[num_colors]; // array of colors defined in colorbrewer.js var num_colors = 3; // also used in svg color code functions below var color_scheme = colorbrewer.Blues[num_colors]; // array of colors defined in colorbrewer.js //var num_colors = 20; // also used in svg color code functions below //var color_scheme = d3.scale.category20c(); // array of colors defined in d3.js //z = d3.scale.ordinal().range(["lightpink", "darkgray", "lightblue"]); //var z = d3.scale.ordinal().range(colorbrewer.PuBu[3]); var z = d3.scale.ordinal().range(color_scheme); // this takes an array of colors as argument var svg = d3.select("#" + divID).append("svg:svg") .attr("width", w) .attr("height", h) .append("svg:g") .attr("transform", "translate(" + p[3] + "," + (h - p[2]) + ")"); // Compute the x-domain (by platform) and y-domain. x.domain(dataset[0].map(function(d) { return d.x; })); var yMultiples = 1; // multiples of the set maxY needed to fit the data. Used to set colours to indicate that scales differ from "normal" var dataYMax = d3.max(dataset[dataset.length - 1], function(d) { return d.y0 + d.y; }); // get the max of the data set // check if the max of the data set will fit the 'normal' maxY passed to the function var newMaxY = maxY; while (newMaxY < dataYMax ) { //if not, increase drawing maxY newMaxY += maxY; yMultiples++; } y.domain([0, newMaxY]); // compute the y-domain using the maxY that will fit the data set //set colours for scales depending on how many multiples of maxY had to be used to fit the data set var loadCol = "#fff"; if (yMultiples == 2) { loadCol = "yellow"; } else if (yMultiples > 2) { loadCol = "red"; } //var stackMax; //if (maxY) { // stackMax = maxY; //} else { // stackMax = d3.max(dataset[dataset.length - 1], function(d) { return d.y0 + d.y; }); //} //console.log("stackMax: ", stackMax); //y.domain([0, stackMax]); // Add a group for each project. var project = svg.selectAll("g.project") //.data(projLayers) .data(dataset) .enter().append("svg:g") .attr("class", "project") .style("fill", function(d, i) { var col = d3.rgb("#5B87FF"); if(i%2 == 0) { col = col.brighter(); } // #82c0ff - spell out instead? // set color dep on wait time since queue date if (d[0].passedTimeLimit != undefined && d[0].passedTimeLimit > 0) { if (d[0].passedTimeLimit == 1) { col = limitCol1; } else { col = limitCol2; } } // Handle vis que regarding time since last prep start for first in queue project var dayLimit = 7; if (showFirstInQueue) { if (d[0].daysSincePrepStart != undefined) { //if (d[0].daysSincePrepStart > dayLimit ) { // col = timeseriesColors[1]; //} else { // col = timeseriesColors[2]; //} //col = "green"; col = timeseriesColors[2]; } } return col; }) .style("stroke", function(d, i) { return "white"; }) ; // Add a rect for each date. var rect = project.selectAll("rect") .data(Object) .enter().append("svg:rect") .attr("x", function(d) { return x(d.x); }) .attr("y", function(d) { return -y(d.y0) - y(d.y); }) .attr("height", function(d) { return y(d.y); }) .attr("width", x.rangeBand()) .style("stroke-width", function(d, i) { if(d.y == 0) { return "0"; } return "1px"; }) .on("mouseover", function(d) { // Make tooltip div visible and fill with appropriate text tooltipDiv.transition() .duration(200) .style("opacity", .9); tooltipDiv.html(d.pid + "<br/>" + parseFloat(d.y).toFixed(fixedDigits) + " " + unit ) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 28) + "px") .style("height", (tooltipNewHeight + "px")) .style("width", (tooltipNewWidth + "px")) ; }) .on("mouseout", function(d) { //Remove the tooltip // Make tooltip div invisible tooltipDiv.transition() .duration(200) .style("opacity", 0) .style("height", (tooltipHeight + "px")) .style("width", (tooltipWidth + "px")) ; }) .on("click", function(d) { var projID = d.pid; var url = "https://genomics-status.scilifelab.se/project/" + projID; window.open(url, "genomics-status"); }) ; // Add a label per category. var label = svg.selectAll("text") .data(x.domain()) .enter().append("svg:text") .attr("x", function(d) { return x(d) + x.rangeBand() / 2; }) .attr("y", 6) .attr("text-anchor", "middle") .attr("dy", ".71em") .text(function(d) { return d; }) ; var tmp = x.domain(); var num_projects = numProjects(dataset, tmp); var num_units = numUnits(dataset, tmp, unit); var totals = totalY(dataset, tmp); var loadText = svg.selectAll("g.load_label") .data(x.domain()) .enter().append("svg:text") .attr("class", ".load_label") .attr("x", function(d) { return x(d) + x.rangeBand() / 2; }) .attr("y", function(d) { return -y(totals[d]) - 5; }) .attr("text-anchor", "middle") //.attr("dy", ".71em") .text(function(d) { var t = num_projects[d] + " proj"; return t; }) ; if (unit == "samples" && showNumWS){ var loadText2 = svg.selectAll("g.load_label") .data(x.domain()) .enter().append("svg:text") .attr("class", ".load_label") .attr("x", function(d) { return x(d) + x.rangeBand() / 2; }) //.attr("y", function(d) { return -y(d.y0) - 10; }) //.attr("y", function(d) { return -100; }) .attr("y", function(d) { return -y(totals[d]) - 15; }) .attr("text-anchor", "middle") //.attr("dy", ".71em") //.text(function(d) { return d; }) .text(function(d) { var t = num_units[d] + " WS"; return t; }) ; } // Add y-axis rules. var rule = svg.selectAll("g.rule") .data(y.ticks(5)) .enter().append("svg:g") .attr("class", "rule") .attr("transform", function(d) { return "translate(0," + -y(d) + ")"; }); // horizontal lines. Add? rule.append("svg:line") .attr("x2", w - p[1] - p[3] + 10) .style("stroke", function(d) { return d ? "#fff" : "#000"; }) .style("stroke-opacity", function(d) { return d ? .1 : null; }); rule.append("svg:text") //.attr("x", w - p[1] - p[3] + 6) .attr("text-anchor", "end") .attr("x", -p[3] + 18) .attr("dy", ".35em") .text(d3.format(",d")) .style("fill", loadCol) ; } /** * Code to draw a stacked barchart plot for RecCtrl load * @param {Array} dataset Array of array of layer objects * @param {String} divID Id of DOM div to where plot should reside * @param {Number} width plot width * @param {Number} height plot height */ function drawRCStackedBars (dataset, divID, width, height, maxY) { var w = width, h = height, p = [30, 10, 30, 20], // t, r, b, l x = d3.scale.ordinal().rangeRoundBands([0, w - p[1] - p[3]]), y = d3.scale.linear().range([0, h - p[0] - p[2]]), parse = d3.time.format("%m/%Y").parse, format = d3.time.format("%b"); // Get a handle to the tooltip div var tooltipDiv = d3.select(".tooltip"); // Resize slightly for lane and sample information (done in mouseover code below) // height var tooltipHeight = tooltipDiv.style("height"); // original height // remove last two letters: "px" & turn into an integer tooltipHeight = parseInt(tooltipHeight.substring(0, tooltipHeight.length - 2)); var tooltipRowHeight = "13"; // 13px per row // width var tooltipWidth = tooltipDiv.style("width"); // original width // remove last two letters: "px" & turn into an integer tooltipWidth = parseInt(tooltipWidth.substring(0, tooltipWidth.length - 2)); var tooltipNewWidth = tooltipWidth + 20; // make room for two four-digit id's per row // color scales // use colorbrewer color schemes // number of colors to use. NB! not all schemes have the same number of colors, see colorbrewer.js // Also, see colorbrewer2.org var num_colors = 9; var color_scheme = colorbrewer.Blues[num_colors]; // array of colors defined in colorbrewer.js //var color_scheme = d3.scale.category20c(); // array of colors defined in d3.js var svg = d3.select("#" + divID).append("svg:svg") .attr("width", w) .attr("height", h) .append("svg:g") .attr("transform", "translate(" + p[3] + "," + (h - p[2]) + ")"); // Compute the x-domain (by platform) and y-domain (by top). x.domain(dataset[0].map(function(d) { return d.x; })); var yMultiples = 1; // multiples of the set maxY needed to fit the data. Used to set colours to indicate that scales differ from "normal" var dataYMax = d3.max(dataset[dataset.length - 1], function(d) { return d.y0 + d.y; }); // get the max of the data set // check if the max of the data set will fit the 'normal' maxY passed to the function var newMaxY = maxY; while (newMaxY < dataYMax ) { //if not, increase drawing maxY newMaxY += maxY; yMultiples++; } y.domain([0, newMaxY]); // compute the y-domain using the maxY that will fit the data set //set colours for scales depending on how many multiples of maxY had to be used to fit the data set var loadCol = "#fff"; if (yMultiples == 2) { loadCol = "yellow"; } else if (yMultiples > 2) { loadCol = "red"; } //var stackMax; //if (maxY) { // stackMax = maxY; //} else { // stackMax = d3.max(dataset[dataset.length - 1], function(d) { return d.y0 + d.y; }); //} // //console.log("stackMax: ", stackMax); //y.domain([0, stackMax]); // Add a group for each project. var project = svg.selectAll("g.project") .data(dataset) .enter().append("svg:g") .attr("class", "project") .style("stroke", function(d, i) { return "white"; }) ; // Add a rect for each . var rect = project.selectAll("rect") .data(Object) .enter().append("svg:rect") .attr("x", function(d) { return x(d.x); }) .attr("y", function(d) { return -y(d.y0) - y(d.y); }) .attr("height", function(d) { return y(d.y); }) .attr("width", x.rangeBand()) .style("stroke-width", function(d, i) { if(d.y == 0) { return "0"; } return "1px"; }) .style("fill", function(d, i) { return color_scheme[i + 2]; // make sure the chosen colorbrewer color space has num_colors defined }) .on("mouseover", function(d) { // calculate how many rows are needed var ids = d.projects; //list of proj IDs var numIDs = (ids.split("P").length - 1); //count proj IDs var rows = Math.ceil(numIDs/2); var tooltipNewHeight = rows * tooltipRowHeight; // Make tooltip div visible and fill with appropriate text tooltipDiv.transition() .duration(200) .style("opacity", .9); tooltipDiv.html(d.projects) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 28) + "px") .style("height", (tooltipNewHeight + "px")) .style("width", (tooltipNewWidth + "px")) ; }) .on("mouseout", function(d) { //Remove the tooltip // Make tooltip div invisible & reset size to default tooltipDiv.transition() .duration(100) .style("opacity", 0) .style("height", (tooltipHeight + "px")) .style("width", (tooltipWidth + "px")) ; //d3.select("#tooltipA").remove(); }) .on("click", function(d) { alert("These " + d.y + " " + d.cat + " projects are currently in Reception control\n"+ d.projects) //var projID = d.pid; //var url = "http://genomics-status.scilifelab.se/projects/" + projID; //window.open(url, "genomics-status"); }) ; svg.selectAll("text") .data(dataset[0]) // all elements for the only bar .enter().append("svg:text") .attr("x", function (d, i) { return x(d.x) + (w - p[1] - p[3])/2; }) .attr("y", function (d, i) { var yPos = -y(d.y0) - y(d.y)/2 + 3;// position for offset value (y0) + half hight of layer return yPos; }) .attr("text-anchor", "middle") .text(function (d, i) { if(d.y > 0) { return d.cat + " (" + d.y + ")"; } else { return ""; } }) ; //console.log(x.domain()); // Add a label per category. var label = svg.selectAll("text") .data(x.domain()) .enter().append("svg:text") .attr("x", function(d) { return x(d) + x.rangeBand() / 2; }) .attr("y", 6) .attr("text-anchor", "middle") .attr("dy", ".71em") .text(function(d) { return d; }) ; // Add y-axis rules. var rule = svg.selectAll("g.rule") .data(y.ticks(5)) .enter().append("svg:g") .attr("class", "rule") .attr("transform", function(d) { return "translate(0," + -y(d) + ")"; }); // horizontal lines. Add? rule.append("svg:line") .attr("x2", w - p[1] - p[3] + 5) .style("stroke", function(d) { return d ? "#fff" : "#000"; }) .style("stroke-opacity", function(d) { return d ? .1 : null; }); rule.append("svg:text") //.attr("x", w - p[1] - p[3] + 6) .attr("text-anchor", "end") .attr("x", -p[3] + 18) .attr("dy", ".35em") .text(d3.format(",d")) .style("fill", loadCol) ; }
var APIAdmin = (function($, _, undefined){ var _inop = false; var self = { is_valid_url: function (url) { return /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url); }, is_valid_name: function (name) { return /^[a-zA-Z0-9_\-\.]+$/.test(name); }, create_api: function (api_name, cmd, description, oncreate) { if(self._inop) { return; } api_name = $.trim(api_name); cmd = $.trim(cmd); description = $.trim(description); if(!self.is_valid_url(description)) { JuliaBox.popup_alert("Invalid URL specified for the description link."); return; } if(!self.is_valid_name(api_name)) { JuliaBox.popup_alert("Invalid API name specified."); return; } if(cmd.length == 0) { JuliaBox.popup_alert("Command not specified."); return; } s = function(res) { if (res.code == 0) { if(oncreate) { oncreate(); } } else { if (res.data) { JuliaBox.popup_alert("Error creating API. " + res.data); } else { JuliaBox.popup_alert("Unknown error creating API."); } } }; f = function() { JuliaBox.popup_alert("Communication error while creating API."); }; self._inop = true; params = { 'mode': 'create', 'api_name': api_name, 'cmd': cmd, 'description': description }; JuliaBox.comm('/jboxplugin/api_admin/', 'GET', params, s, f); self._inop = false }, delete_api: function (api_name, ondelete) { if(self._inop) { return; } s = function(res) { if (res.code == 0) { if(ondelete) { ondelete(); } } else { if (res.data) { JuliaBox.popup_alert("Error deleting API. " + res.data); } else { JuliaBox.popup_alert("Unknown error deleting API."); } } }; f = function() { JuliaBox.popup_alert("Communication error while deleting API."); }; self._inop = true; JuliaBox.popup_confirm('Delete API specification for ' + api_name + '?', function(res) { self._inop = false; if(res) { params = { 'mode' : 'delete', 'api_name': api_name }; JuliaBox.comm('/jboxplugin/api_admin/', 'GET', params, s, f); } }); }, get_apis: function (cb_success, cb_failure) { if(self._inop) { return; } s = function(res) { if (res.code == 0) { cb_success(res.data) } else { cb_failure(res.data) } }; f = function() { cb_failure(null) }; JuliaBox.comm('/jboxplugin/api_admin/', 'GET', { 'mode' : 'info' }, s, f, dolock=false); }, enable_apis: function () { if(self._inop) { return; } s = function(res) { if (res.code == 0) { JuliaBox.popup_alert("API publishing is now enabled for your account. Logout and login again to be able to publish APIs."); } else { JuliaBox.popup_alert("Could not enable APIs for your account. " + res.data); } }; f = function() { JuliaBox.popup_alert("Could not enable APIs for your account. Please contact JuliaBox administrator."); }; JuliaBox.comm('/jboxplugin/api_admin/', 'GET', { 'mode' : 'enable' }, s, f); } }; return self; })(jQuery, _);
const bodyParser = require('body-parser'); const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); const {qraphqlHTTP, graphqlHTTP} = require('express-graphql'); const config = require("./config/config.json"); const app = express(); app.use(bodyParser.json()); app.use(cors()); const userSchema = require('./graphql/users/usersSchema'); const usersResolver = require('./graphql/users/usersResolver'); //graphql app.use( '/graphql', graphqlHTTP({ schema:userSchema , rootValue:usersResolver, graphiql:true, }) ) app.listen(process.env.PORT || 3000,console.log("Server Running")) app.get('/',(req,res)=>res.send('Backend')); mongoose.connect( `mongodb+srv://${config.username}:${config.password}@cluster0.hs3ud.mongodb.net/${config.dbname}?retryWrites=true&w=majority`, { useUnifiedTopology:true, useNewUrlParser:true, } ).then(()=>{ console.log("Connected to mongo") }).catch((err)=>console.log(err));
// eslint-disable-next-line @typescript-eslint/no-var-requires const faunadb = require("faunadb"); const client = new faunadb.Client({ secret: process.env.FAUNADB_SECRET }); const { Get, Match, Index } = faunadb.query; export default async (req, res) => { try { const doc = await client.query( Get(Match(Index("parcel_by_id"), req.query.id)) ); res.setHeader("Access-Control-Allow-Origin", "http://localhost:8080"); res.json(doc.data); } catch (error) { res.status(500).json({ error }); } };
/** * This widget is an outer DOM container for a KBase Narrative control element. * It instantiates a panel that the widget lives in, with some flexibility for * the title of the panel, adds a list of buttons on the panel, and gives the * option to minimize or restore the panel. * * This is a base class widget for any sidebar widgets that want its behavior. * Those sidebars should just include a title option. * Usage: new kbaseNarrativeControlPanel(* $('#my-element'), { * title : 'My Controls', * collapsible : true, * buttons: [], * }); * * @author Bill Riehl <wjriehl@lbl.gov> * @public */ define(['kbwidget', 'bootstrap', 'jquery', 'kbaseAuthenticatedWidget'], ( KBWidget, bootstrap, $, kbaseAuthenticatedWidget ) => { 'use strict'; return KBWidget({ name: 'kbaseNarrativeControlPanel', parent: kbaseAuthenticatedWidget, version: '0.0.1', options: { title: 'Control', showTitle: true, collapsible: true, maxHeight: '400px', collapseCallback: null, // called when this panel is minimized/maximized slideTime: 400, // set minimize/maximize animation time }, /** * @method * Initializes the widget. This sets up internal variables, renders * the DOM structure, and creates an internal spot for the widget it * should hold. * Runs automatically on instantiation. * @param {object} options - set of inserted options from the instantiation * statement. * @returns {object} the initialized widget * @private */ init: function (options) { this._super(options); this.slideTime = this.options.slideTime; this.render(); return this; }, userCollapse: false, toggleCollapse: function (override) { const $toggleIcon = this.$elem.find('.kb-narr-panel-toggle'); let collapse; if (override) { switch (override) { case 'collapse': collapse = true; break; case 'expand': collapse = false; break; case 'restore': collapse = this.userCollapse; break; case 'user': collapse = !this.isMinimized(); this.userCollapse = collapse; } } else { collapse = this.Min ? false : true; } // nothing to do if the new collapse state is the same as the old. if ((collapse && this.isMinimized()) || (!collapse && !this.isMinimized())) { return; } if (collapse) { $toggleIcon.removeClass('fa-chevron-down').addClass('fa-chevron-right'); this.$bodyDiv.parent().slideUp(this.slideTime); this.isMin = true; } else { $toggleIcon.removeClass('fa-chevron-right').addClass('fa-chevron-down'); this.$bodyDiv.parent().slideDown(this.slideTime); this.isMin = false; } if (this.options.collapseCallback) { this.options.collapseCallback(this.isMin); } }, /** * @method * Renders the new containing panel widget * @private */ render: function () { // DOM structure setup here. // After this, just need to update the function list /* There's a few bits here. * 1. It's all in a Bootstrap Panel scaffold. * 2. The panel-body section contains the core of the widget: * a. loading panel (just a blank thing with a spinning gif) * b. error panel * c. actual function widget setup. * * So, initialize the scaffold, bind the three core pieces in the * panel-body, make sure the right one is being shown at the start, * and off we go. */ // Make a main body panel for everything to sit inside. this.$bodyDiv = $('<div>'); this.$headerDiv = $('<div>'); this.$buttonPanel = $('<span>') .addClass('btn-toolbar pull-right') .attr('role', 'toolbar') .css({ 'margin-top': '-2px' }); const $titleSpan = $('<span>'); if (this.options.showTitle) { $titleSpan.append( $('<span>') .css({ cursor: 'pointer' }) .click( $.proxy(function (event) { event.preventDefault(); this.toggleCollapse('user'); }, this) ) .append($('<span>').addClass('fa fa-chevron-down kb-narr-panel-toggle')) .append(this.options.title) ); } $titleSpan.append(this.$buttonPanel); this.isMin = false; this.$elem.append( $('<div>') .css({ height: '100%' }) .addClass('kb-narr-side-panel') .append($('<div>').addClass('kb-title').append($titleSpan)) .append($('<div>').addClass('kb-narr-panel-body-wrapper').append(this.$bodyDiv)) ); }, // remember the minimization state isMin: null, /** * Returns minimization state of the Panel, true if minimized, false otherwise * @public */ isMinimized: function () { return this.isMin; }, // allows the height of the entire panel to be dynamically set setHeight: function (height) { this.$elem.css({ height: height }); }, /** * Adds a button to the button panel that sits on the right side of the header. * @param {object} btn - the button element to add. Expected to be a jquery node. * @public */ addButton: function (btn) { this.$buttonPanel.append(btn); }, /** * Sets the button panel to have the given list of buttons. This replaces any * existing buttons that might be there. * @param {Array} btnList - the list of button elements. Each one is expected to * be a jquery node representing a button * @public */ addButtonList: function (btnList) { this.$buttonPanel.empty(); for (let i = 0; i < btnList.length; i++) { this.addButton(btnList[i]); } }, /** * Returns the main body element of the widget as a jquery node. This is effective * for binding a functional widget into it. * @returns {object} a jquery node for the main widget panel * @public */ body: function () { return this.$bodyDiv; }, /** * Gets invoked whenever the user clicks over to the side panel tab where this control * panel lives. For example, the current (5/29/2019) narrative starts on the Analyze tab. * When a user clicks on the Narratives tab, each widget there (just the one, really) has * this function called. */ activate: function () { // no op - meant to be extended by some functional widget. }, }); });
/** * Table 信息栏渲染器 * @author Brian Li * @email lbxxlht@163.com * @version 0.0.2.1 */ define(function (require) { var React = require('react'); return React.createClass({ /** * @properties * @param {String} message 信息栏显示的内容 * @param {String} buttonLabel 信息栏按钮的文本,如果为空将不显示此按钮 * @param {Number} colSpan 信息栏横跨单元格个数 * @param {Function} onClick 按钮点击回调,即table.props.onAction */ getDefaultProps: function getDefaultProps() { return { content: '', buttonLabel: '', colSpan: 1, onClick: function onClick() {} }; }, onButtonClick: function onButtonClick(e) { /** * @fire table onAction * @param {String} type TableMessageBarClick: 表头下部信息栏被点击 */ this.props.onAction('TableMessageBarClick', {}); }, render: function render() { return React.createElement( 'tr', { className: 'tr-message' }, React.createElement( 'td', { colSpan: this.props.colSpan }, React.createElement( 'span', null, this.props.content ), React.createElement( 'span', { onClick: this.onButtonClick, className: 'link' }, this.props.buttonLabel ) ) ); } }); });
let LANGUAGE = {} export const setLanguage = (data) => (LANGUAGE = data) export const getLanguage = () => LANGUAGE let objktBlockList = [] export const setObjktBlockList = (data) => (objktBlockList = data) export const getObjktBlockList = () => objktBlockList let walletBlockList = [] export const setWalletBlockList = (data) => (walletBlockList = data) export const getWalletBlockList = () => walletBlockList let banBlockList = [] export const setBanBlockList = (data) => (banBlockList = data) export const getBanBlockList = () => banBlockList export const PATH = { FEED: '/', ISSUER: '/tz', ABOUT: '/about', FAQ: '/faq', SYNC: '/sync', MINT: '/mint', OBJKT: '/objkt', GALLERY: '/gallery', TAGS: '/tags', } export const MINT_MIN_LIMIT = 1 export const MINT_MAX_LIMIT = 10000 export const MINT_FILESIZE = 40 export const MIMETYPE = { BMP: 'image/bmp', GIF: 'image/gif', JPEG: 'image/jpeg', PNG: 'image/png', SVG: 'image/svg+xml', TIFF: 'image/tiff', WEBP: 'image/webp', MP4: 'video/mp4', OGV: 'video/ogg', QUICKTIME: 'video/quicktime', WEBM: 'video/webm', GLB: 'model/gltf-binary', GLTF: 'model/gltf+json', MP3: 'audio/mpeg', OGA: 'audio/ogg', WAV: 'audio/wav', FLAC: 'audio/flac', PDF: 'application/pdf', ZIP: 'application/zip', ZIP1: 'application/x-zip-compressed', ZIP2: 'multipart/x-zip', } export const IPFS_DIRECTORY_MIMETYPE = 'application/x-directory' export const ALLOWED_MIMETYPES = Object.keys(MIMETYPE) .map((k) => MIMETYPE[k]) .filter((e) => e !== MIMETYPE.GLTF) // disabling GLTF from new updates export const ALLOWED_FILETYPES_LABEL = Object.entries(MIMETYPE) .filter((e) => ALLOWED_MIMETYPES.includes(e[1])) .filter((e) => !['ZIP1', 'ZIP2'].includes(e[0])) .map((e) => (e[0] === 'ZIP' ? 'HTML (ZIP ARCHIVE)' : e[0])) .join(', ') export const ALLOWED_COVER_MIMETYPES = [ MIMETYPE.JPEG, MIMETYPE.PNG, MIMETYPE.GIF, ] export const ALLOWED_COVER_FILETYPES_LABEL = ['jpeg, png, gif'] export const IPFS_DISPLAY_URI_BLACKCIRCLE = 'ipfs://QmNrhZHUaEqxhyLfqoq1mtHSipkWHeT31LNHb1QEbDHgnc'
module.exports = { final: 'F', inProgress: 'I', preGame: 'P', // Incomplete... }
//Used to reset users cookies var cookie_version = 1; //Check if cookie version is/is not the same as the current version var versionMatch = false; //Set positions and visibility of configurable ui elements $(function() { //Check each cookie and test for 'undefined'. If any cookie is undefined $.each(document.cookie.split(/; */), function(){ var cookie = this.split("=") if(!cookie[1] || cookie[1] == 'undefined'){ deleteCookies(); } else if(cookie[0] === "cookie_version"){ if(cookie[1] == cookie_version){ versionMatch = true; } } }); if(!versionMatch) { //If cookie version is not the same as the current version then toggle the visibility of each //rubric panel then update the cookies deleteCookies(); setAutogradingVisible(true); setRubricVisible(true); setSubmissionsVisible(true); setInfoVisible(true); setRegradeVisible(true); resetModules(); updateCookies(); } else{ readCookies(); updateCookies(); } $('body').css({'position':'fixed', 'width':'100%'}); var progressbar = $(".progressbar"), value = progressbar.val(); $(".progress-value").html("<b>" + value + '%</b>'); $( ".draggable" ).draggable({snap:false, grid:[2, 2], stack:".draggable"}).resizable(); $("#bar_wrapper").resizable("destroy"); //We don't want the toolbar to be resizable // $('#pdf_annotation_bar').length != 0 && $('#pdf_annotation_bar').resizable("destroy"); //Same with PDF annotation. $(".draggable").on("dragstop", function(){ $('#bar_wrapper').css({'z-index':'40'}); //Reset z-index after jquery drag // $('#pdf_annotation_bar').length != 0 && $('#pdf_annotation_bar').css({'z-index':'40'}); updateCookies(); }); $(".draggable").on("resizestop", function(){ updateCookies(); }); eraseCookie("reset"); }); function createCookie(name,value,seconds) { if(seconds) { var date = new Date(); date.setTime(date.getTime()+(seconds*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function eraseCookie(name) { createCookie(name,"",-3600); } function deleteCookies(){ $.each(document.cookie.split(/; */), function(){ var cookie = this.split("=") if(!cookie[1] || cookie[1] == 'undefined'){ document.cookie = cookie[0] + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; document.cookie = "cookie_version=-1; path=/;"; } }); } function onAjaxInit() {} function readCookies(){ var output_top = document.cookie.replace(/(?:(?:^|.*;\s*)output_top\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var output_left = document.cookie.replace(/(?:(?:^|.*;\s*)output_left\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var output_width = document.cookie.replace(/(?:(?:^|.*;\s*)output_width\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var output_height = document.cookie.replace(/(?:(?:^|.*;\s*)output_height\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var output_visible = document.cookie.replace(/(?:(?:^|.*;\s*)output_visible\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var files_top = document.cookie.replace(/(?:(?:^|.*;\s*)files_top\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var files_left = document.cookie.replace(/(?:(?:^|.*;\s*)files_left\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var files_width = document.cookie.replace(/(?:(?:^|.*;\s*)files_width\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var files_height = document.cookie.replace(/(?:(?:^|.*;\s*)files_height\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var files_visible = document.cookie.replace(/(?:(?:^|.*;\s*)files_visible\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var rubric_top = document.cookie.replace(/(?:(?:^|.*;\s*)rubric_top\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var rubric_left = document.cookie.replace(/(?:(?:^|.*;\s*)rubric_left\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var rubric_width = document.cookie.replace(/(?:(?:^|.*;\s*)rubric_width\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var rubric_height = document.cookie.replace(/(?:(?:^|.*;\s*)rubric_height\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var rubric_visible = document.cookie.replace(/(?:(?:^|.*;\s*)rubric_visible\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var status_top = document.cookie.replace(/(?:(?:^|.*;\s*)status_top\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var status_left = document.cookie.replace(/(?:(?:^|.*;\s*)status_left\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var status_width = document.cookie.replace(/(?:(?:^|.*;\s*)status_width\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var status_height = document.cookie.replace(/(?:(?:^|.*;\s*)status_height\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var status_visible = document.cookie.replace(/(?:(?:^|.*;\s*)status_visible\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var regrade_top = document.cookie.replace(/(?:(?:^|.*;\s*)regrade_top\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var regrade_left = document.cookie.replace(/(?:(?:^|.*;\s*)regrade_left\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var regrade_width = document.cookie.replace(/(?:(?:^|.*;\s*)regrade_width\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var regrade_height = document.cookie.replace(/(?:(?:^|.*;\s*)regrade_height\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var regrade_visible = document.cookie.replace(/(?:(?:^|.*;\s*)regrade_visible\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var bar_wrapper_top = document.cookie.replace(/(?:(?:^|.*;\s*)bar_wrapper_top\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var bar_wrapper_left = document.cookie.replace(/(?:(?:^|.*;\s*)bar_wrapper_left\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var bar_wrapper_visible = document.cookie.replace(/(?:(?:^|.*;\s*)bar_wrapper_visible\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var silent_edit_enabled = document.cookie.replace(/(?:(?:^|.*;\s*)silent_edit_enabled\s*\=\s*([^;]*).*$)|^.*$/, "$1") === 'true'; // var pdf_annotation_bar_top = document.cookie.replace(/(?:(?:^|.*;\s*)pdf_annotation_bar_top\s*\=\s*([^;]*).*$)|^.*$/, "$1"); // var pdf_annotation_bar_left = document.cookie.replace(/(?:(?:^|.*;\s*)pdf_annotation_bar_left\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var autoscroll = document.cookie.replace(/(?:(?:^|.*;\s*)autoscroll\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var opened_mark = document.cookie.replace(/(?:(?:^|.*;\s*)opened_mark\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var scroll_pixel = document.cookie.replace(/(?:(?:^|.*;\s*)scroll_pixel\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var testcases = document.cookie.replace(/(?:(?:^|.*;\s*)testcases\s*\=\s*([^;]*).*$)|^.*$/, "$1"); var files = document.cookie.replace(/(?:(?:^|.*;\s*)files\s*\=\s*([^;]*).*$)|^.*$/, "$1"); (output_top) ? $("#autograding_results").css("top", output_top):{}; (output_left) ? $("#autograding_results").css("left", output_left):{}; (output_width) ? $("#autograding_results").css("width", output_width):{}; (output_height) ? $("#autograding_results").css("height", output_height):{}; (output_visible) ? $("#autograding_results").css("display", output_visible):{}; (rubric_top) ? $("#grading_rubric").css("top", rubric_top):{}; (rubric_left) ? $("#grading_rubric").css("left", rubric_left):{}; (rubric_width) ? $("#grading_rubric").css("width", rubric_width):{}; (rubric_height) ? $("#grading_rubric").css("height", rubric_height):{}; (rubric_visible) ? $("#grading_rubric").css("display", rubric_visible):{}; (files_top) ? $("#submission_browser").css("top", files_top):{}; (files_left) ? $("#submission_browser").css("left", files_left):{}; (files_width) ? $("#submission_browser").css("width", files_width):{}; (files_height) ? $("#submission_browser").css("height", files_height):{}; (files_visible) ? $("#submission_browser").css("display", files_visible):{}; (status_top) ? $("#student_info").css("top", status_top):{}; (status_left) ? $("#student_info").css("left", status_left):{}; (status_width) ? $("#student_info").css("width", status_width):{}; (status_height) ? $("#student_info").css("height", status_height):{}; (status_visible) ? $("#student_info").css("display", status_visible):{}; (regrade_top) ? $("#regrade_info").css("top", regrade_top):{}; (regrade_left) ? $("#regrade_info").css("left", regrade_left):{}; (regrade_width) ? $("#regrade_info").css("width", regrade_width):{}; (regrade_height) ? $("#regrade_info").css("height", regrade_height):{}; (regrade_visible) ? $("#regrade_info").css("display", regrade_visible):{}; (bar_wrapper_top) ? $("#bar_wrapper").css("top", bar_wrapper_top):{}; (bar_wrapper_left) ? $("#bar_wrapper").css("left", bar_wrapper_left):{}; (bar_wrapper_visible) ? $("#bar_wrapper").css("display", bar_wrapper_visible):{}; $('#silent-edit-id').prop('checked', silent_edit_enabled); // (pdf_annotation_bar_top) ? $("#pdf_annotation_bar").css("top", pdf_annotation_bar_top):{}; // (pdf_annotation_bar_left) ? $("#pdf_annotation_bar").css("left", pdf_annotation_bar_left):{}; (output_visible) ? ((output_visible) == "none" ? $(".fa-list-alt").removeClass("icon-selected") : $(".fa-list-alt").addClass("icon-selected")) : {}; (files_visible) ? ((files_visible) == "none" ? $(".fa-folder-open").removeClass("icon-selected") : $(".fa-folder-open").addClass("icon-selected")) : {}; (rubric_visible) ? ((rubric_visible) == "none" ? $(".fa-pencil-square-o").removeClass("icon-selected") : $(".fa-pencil-square-o").addClass("icon-selected")) : {}; (status_visible) ? ((status_visible) == "none" ? $(".fa-user").removeClass("icon-selected") : $(".fa-user").addClass("icon-selected")) : {}; (regrade_visible) ? ((regrade_visible) == "none" ? $(".fa-hand-paper-o").removeClass("icon-selected") : $(".fa-hand-paper-o").addClass("icon-selected")) : {}; (autoscroll) ? ((autoscroll) == "on" ? $('#autoscroll_id').prop('checked', true) : $('#autoscroll_id').prop('checked', false)) : {}; onAjaxInit = function() { $('#title-'+opened_mark).click(); if (scroll_pixel > 0) { document.getElementById('grading_rubric').scrollTop = scroll_pixel; } } if (autoscroll == "on") { var files_array = JSON.parse(files); files_array.forEach(function(element) { var file_path = element.split('#$SPLIT#$'); var current = $('#file-container'); for (var x = 0; x < file_path.length; x++) { current.children().each(function() { if (x == file_path.length - 1) { $(this).children('div[id^=file_viewer_]').each(function() { if ($(this)[0].dataset.file_name == file_path[x] && !$($(this)[0]).hasClass('open')) { openFrame($(this)[0].dataset.file_name, $(this)[0].dataset.file_url, $(this).attr('id').split('_')[2]); } }); $(this).children('div[id^=div_viewer_]').each(function() { if ($(this)[0].dataset.file_name == file_path[x] && !$($(this)[0]).hasClass('open')) { openDiv($(this).attr('id').split('_')[2]); } }); } else { $(this).children('div[id^=div_viewer_]').each(function() { if ($(this)[0].dataset.file_name == file_path[x]) { current = $(this); return false; } }); } }); } }); } for(var x=0; x<testcases.length; x++){ if(testcases[x]!='[' && testcases[x]!=']') openAutoGrading(testcases[x]); } } function updateCookies(){ document.cookie = "output_top=" + $("#autograding_results").css("top") + "; path=/;"; document.cookie = "output_left=" + $("#autograding_results").css("left") + "; path=/;"; document.cookie = "output_width=" + $("#autograding_results").css("width") + "; path=/;"; document.cookie = "output_height=" + $("#autograding_results").css("height") + "; path=/;"; document.cookie = "output_visible=" + $("#autograding_results").css("display") + "; path=/;"; document.cookie = "rubric_top=" + $("#grading_rubric").css("top") + "; path=/;"; document.cookie = "rubric_left=" + $("#grading_rubric").css("left") + "; path=/;"; document.cookie = "rubric_width=" + $("#grading_rubric").css("width") + "; path=/;"; document.cookie = "rubric_height=" + $("#grading_rubric").css("height") + "; path=/;"; document.cookie = "rubric_visible=" + $("#grading_rubric").css("display") + "; path=/;"; document.cookie = "files_top=" + $("#submission_browser").css("top") + "; path=/;"; document.cookie = "files_left=" + $("#submission_browser").css("left") + "; path=/;"; document.cookie = "files_width=" + $("#submission_browser").css("width") + "; path=/;"; document.cookie = "files_height=" + $("#submission_browser").css("height") + "; path=/;"; document.cookie = "files_visible=" + $("#submission_browser").css("display") + "; path=/;"; document.cookie = "status_top=" + $("#student_info").css("top") + "; path=/;"; document.cookie = "status_left=" + $("#student_info").css("left") + "; path=/;"; document.cookie = "status_width=" + $("#student_info").css("width") + "; path=/;"; document.cookie = "status_height=" + $("#student_info").css("height") + "; path=/;"; document.cookie = "status_visible=" + $("#student_info").css("display") + "; path=/;"; document.cookie = "regrade_top=" + $("#regrade_info").css("top") + "; path=/;"; document.cookie = "regrade_left=" + $("#regrade_info").css("left") + "; path=/;"; document.cookie = "regrade_width=" + $("#regrade_info").css("width") + "; path=/;"; document.cookie = "regrade_height=" + $("#regrade_info").css("height") + "; path=/;"; document.cookie = "regrade_visible=" + $("#regrade_info").css("display") + "; path=/;"; document.cookie = "bar_wrapper_top=" + $("#bar_wrapper").css("top") + "; path=/;"; document.cookie = "bar_wrapper_left=" + $("#bar_wrapper").css("left") + "; path=/;"; document.cookie = "bar_wrapper_visible=" + $("#bar_wrapper").css("display") + "; path=/;"; document.cookie = "silent_edit_enabled=" + isSilentEditModeEnabled() + "; path=/;"; // document.cookie = "pdf_annotation_bar_top=" + $("#pdf_annotation_bar").css("top") + "; path=/;"; // document.cookie = "pdf_annotation_bar_left=" + $("#pdf_annotation_bar").css("left") + "; path=/;"; var autoscroll = "on"; if ($('#autoscroll_id').is(":checked")) { autoscroll = "on"; } else { autoscroll = "off"; } document.cookie = "autoscroll=" + autoscroll + "; path=/;"; var files = []; $('#file-container').children().each(function() { $(this).children('div[id^=div_viewer_]').each(function() { files = files.concat(findAllOpenedFiles($(this), "", $(this)[0].dataset.file_name, [], true)); }); }); files = JSON.stringify(files); document.cookie = "files=" + files + "; path=/;" document.cookie = "cookie_version=" + cookie_version + "; path=/;"; } function changeEditorStyle(newStyle){ if(newStyle === 'style_light'){ localStorage.setItem("codeDisplayStyle", "light"); } else { localStorage.setItem("codeDisplayStyle", "dark"); } window.location.reload(); } //----------------------------------------------------------------------------- // Student navigation function gotoPrevStudent() { if (getGradeableId() !== '') { closeAllComponents(true).then(function () { window.location = $("#prev-student")[0].dataset.href; }).catch(function () { if (confirm("Could not save open component, change student anyway?")) { window.location = $("#prev-student")[0].dataset.href; } }); } else { window.location = $("#prev-student")[0].dataset.href; } } function gotoNextStudent() { if (getGradeableId() !== '') { closeAllComponents(true).then(function () { window.location = $("#next-student")[0].dataset.href; }).catch(function () { if (confirm("Could not save open component, change student anyway?")) { window.location = $("#next-student")[0].dataset.href; } }); } else { window.location = $("#next-student")[0].dataset.href; } } //Navigate to the prev / next student buttons registerKeyHandler({name: "Previous Student", code: "ArrowLeft"}, function() { gotoPrevStudent(); }); registerKeyHandler({name: "Next Student", code: "ArrowRight"}, function() { gotoNextStudent(); }); //----------------------------------------------------------------------------- // Panel show/hide function isAutogradingVisible() { return $("#autograding_results").is(":visible"); } function isRubricVisible() { return $("#grading_rubric").is(":visible"); } function isSubmissionsVisible() { return $("#submission_browser").is(":visible"); } function isInfoVisible() { return $("#student_info").is(":visible"); } function isRegradeVisible(){ return $("#regrade_info").is(":visible"); } function setAutogradingVisible(visible) { $('.fa-list-alt').toggleClass('icon-selected', visible); $("#autograding_results").toggle(visible); hideIfEmpty("#autograding_results"); } function setRubricVisible(visible) { $('.fa-pencil-square-o').toggleClass('icon-selected', visible); $("#grading_rubric").toggle(visible); } function setSubmissionsVisible(visible) { $('.fa-folder-open.icon-header').toggleClass('icon-selected', visible); $("#submission_browser").toggle(visible); hideIfEmpty("#submission_browser"); } function setInfoVisible(visible) { $('.fa-user').toggleClass('icon-selected', visible); $("#student_info").toggle(visible); hideIfEmpty("#student_info"); } function setRegradeVisible(visible) { $('.fa-hand-paper-o').toggleClass('icon-selected', visible); $("#regrade_info").toggle(visible); hideIfEmpty("#regrade_info"); } function toggleAutograding() { setAutogradingVisible(!isAutogradingVisible()); } function toggleRubric() { setRubricVisible(!isRubricVisible()); } function toggleSubmissions() { setSubmissionsVisible(!isSubmissionsVisible()); } function toggleInfo() { setInfoVisible(!isInfoVisible()); } function toggleRegrade() { setRegradeVisible(!isRegradeVisible()); } function resetModules() { var width = $("#nav-positioner").width(); var height = $("#nav-positioner").height(); $('.fa-list-alt').addClass('icon-selected'); $("#autograding_results").attr("style", "z-index:30; left:0; top:60%; width:48%; height:40%; display:block;"); $('.fa-pencil-square-o').addClass('icon-selected'); $("#grading_rubric").attr("style", "left: 50%; z-index:30; top:10%; width:48%; height:68%; display:block;"); $('.fa-folder-open').addClass('icon-selected'); $("#submission_browser").attr("style", "left:0; z-index:30; top:10%; width:48%; height:48%; display:block;"); $('.fa-user').addClass('icon-selected'); $('#bar_wrapper').attr("style", "top: 0; left: " + ((width - $('#bar_wrapper').width()) / 2) + "; z-index:40;"); $("#student_info").attr("style", "left: 50%; top: 80%; z-index:30; width:48%; height:20%; display:block;"); $('.fa-hand-paper-o').addClass('icon-selected'); $("#regrade_info").attr("style", "bottom:30px; z-index:30; right:15px; width:48%; height:37%; display:block;"); // $("#pdf_annotation_bar").attr("style", "left: 58%, z-index:40; top:307px"); deleteCookies(); updateCookies(); } registerKeyHandler({name: "Reset Panel Positions", code: "KeyR"}, function() { resetModules(); updateCookies(); }); registerKeyHandler({name: "Toggle Autograding Panel", code: "KeyA"}, function() { toggleAutograding(); updateCookies(); }); registerKeyHandler({name: "Toggle Rubric Panel", code: "KeyG"}, function() { toggleRubric(); updateCookies(); }); registerKeyHandler({name: "Toggle Submissions Panel", code: "KeyO"}, function() { toggleSubmissions(); updateCookies(); }); registerKeyHandler({name: "Toggle Student Information Panel", code: "KeyS"}, function() { toggleInfo(); updateCookies(); }); registerKeyHandler({name: "Toggle Regrade Requests Panel", code: "KeyX"}, function() { toggleRegrade(); updateCookies(); }); //----------------------------------------------------------------------------- // Show/hide components registerKeyHandler({name: "Open Next Component", code: 'ArrowDown'}, function(e) { let openComponentId = getFirstOpenComponentId(); let numComponents = getComponentCount(); // Note: we use the 'toggle' functions instead of the 'open' functions // Since the 'open' functions don't close any components if (isOverallCommentOpen()) { // Overall comment is open, so just close it closeOverallComment(true); } else if (openComponentId === NO_COMPONENT_ID) { // No component is open, so open the first one let componentId = getComponentIdByOrder(0); toggleComponent(componentId, true).then(function () { getComponentJQuery(componentId)[0].scrollIntoView(); }); } else if (openComponentId === getComponentIdByOrder(numComponents - 1)) { // Last component is open, so open the general comment toggleOverallComment(true).then(function () { getOverallCommentJQuery()[0].scrollIntoView(); }); } else { // Any other case, open the next one let nextComponentId = getNextComponentId(openComponentId); toggleComponent(nextComponentId, true).then(function () { getComponentJQuery(nextComponentId)[0].scrollIntoView(); }); } e.preventDefault(); }); registerKeyHandler({name: "Open Previous Component", code: 'ArrowUp'}, function(e) { let openComponentId = getFirstOpenComponentId(); let numComponents = getComponentCount(); // Note: we use the 'toggle' functions instead of the 'open' functions // Since the 'open' functions don't close any components if (isOverallCommentOpen()) { // Overall comment open, so open the last component let componentId = getComponentIdByOrder(numComponents - 1); toggleComponent(componentId, true).then(function () { getComponentJQuery(componentId)[0].scrollIntoView(); }); } else if (openComponentId === NO_COMPONENT_ID) { // No Component is open, so open the overall comment toggleOverallComment(true).then(function () { getOverallCommentJQuery()[0].scrollIntoView(); }); } else if (openComponentId === getComponentIdByOrder(0)) { // First component is open, so close it closeAllComponents(true); } else { // Any other case, open the previous one let prevComponentId = getPrevComponentId(openComponentId); toggleComponent(prevComponentId, true).then(function () { getComponentJQuery(prevComponentId)[0].scrollIntoView(); }); } e.preventDefault(); }); //----------------------------------------------------------------------------- // Selecting marks registerKeyHandler({name: "Select Mark 1", code: 'Digit1', locked: true}, function() { checkOpenComponentMark(0); }); registerKeyHandler({name: "Select Mark 2", code: 'Digit2', locked: true}, function() { checkOpenComponentMark(1); }); registerKeyHandler({name: "Select Mark 3", code: 'Digit3', locked: true}, function() { checkOpenComponentMark(2); }); registerKeyHandler({name: "Select Mark 4", code: 'Digit4', locked: true}, function() { checkOpenComponentMark(3); }); registerKeyHandler({name: "Select Mark 5", code: 'Digit5', locked: true}, function() { checkOpenComponentMark(4); }); registerKeyHandler({name: "Select Mark 6", code: 'Digit6', locked: true}, function() { checkOpenComponentMark(5); }); registerKeyHandler({name: "Select Mark 7", code: 'Digit7', locked: true}, function() { checkOpenComponentMark(6); }); registerKeyHandler({name: "Select Mark 8", code: 'Digit8', locked: true}, function() { checkOpenComponentMark(7); }); registerKeyHandler({name: "Select Mark 9", code: 'Digit9', locked: true}, function() { checkOpenComponentMark(8); }); function checkOpenComponentMark(index) { let component_id = getFirstOpenComponentId(); if (component_id !== NO_COMPONENT_ID) { let mark_id = getMarkIdFromOrder(component_id, index); toggleCommonMark(component_id, mark_id) .catch(function (err) { console.error(err); alert('Error toggling mark! ' + err.message); }); } } // expand all files in Submissions and Results section function openAll(click_class, class_modifier) { $("."+click_class + class_modifier).each(function(){ $(this).click(); }); } function updateValue(obj, option1, option2) { // Switches the value of an element between option 1 and two console.log('hi'); obj.text(function(i, oldText){ if(oldText.indexOf(option1) >= 0){ newText = oldText.replace(option1, option2); } else{ newText = oldText.replace(option2, option1); } return newText; }); } function openAutoGrading(num){ $('#tc_' + num).click(); if($('#testcase_' + num)[0]!=null){ $('#testcase_' + num)[0].style.display="block"; } } // expand all outputs in Auto-Grading Testcases section function openAllAutoGrading() { // show all divs whose id starts with testcase_ $("[id^='tc_']").click(); $("[id^='testcase_']")[0].style.display="block"; } // close all outputs in Auto-Grading Testcases section function closeAllAutoGrading() { // hide all divs whose id starts with testcase_ $("[id^='testcase_']").hide(); } function openDiv(num) { var elem = $('#div_viewer_' + num); if (elem.hasClass('open')) { elem.hide(); elem.removeClass('open'); $($($(elem.parent().children()[0]).children()[0]).children()[0]).removeClass('fa-folder-open').addClass('fa-folder'); } else { elem.show(); elem.addClass('open'); $($($(elem.parent().children()[0]).children()[0]).children()[0]).removeClass('fa-folder').addClass('fa-folder-open'); } return false; } function resizeFrame(id) { var height = parseInt($("iframe#" + id).contents().find("body").css('height').slice(0,-2)); if (height > 500) { document.getElementById(id).height= "500px"; } else { document.getElementById(id).height = (height+18) + "px"; } } // delta in this function is the incremental step of points, currently hardcoded to 0.5pts function validateInput(id, question_total, delta){ var ele = $('#' + id); if(isNaN(parseFloat(ele.val())) || ele.val() == ""){ ele.val(""); return; } if(ele.val() < 0 && parseFloat(question_total) > 0) { ele.val( 0 ); } if(ele.val() > 0 && parseFloat(question_total) < 0) { ele.val( 0 ); } if(ele.val() < parseFloat(question_total) && parseFloat(question_total) < 0) { ele.val(question_total); } if(ele.val() > parseFloat(question_total) && parseFloat(question_total) > 0) { ele.val(question_total); } if(ele.val() % delta != 0) { ele.val( Math.round(ele.val() / delta) * delta ); } } // autoresize the comment box function autoResizeComment(e){ e.target.style.height =""; e.target.style.height = e.target.scrollHeight + "px"; } function downloadFile(html_file, url_file) { var directory = ""; if (url_file.includes("submissions")) { directory = "submissions"; } else if (url_file.includes("results")) { directory = "results"; } window.location = buildUrl({'component': 'misc', 'page': 'download_file', 'dir': directory, 'file': html_file, 'path': url_file}); return false; } function hideIfEmpty(element) { $(element).each(function() { if ($(this).hasClass("empty")) { $(this).hide(); } }); } function findOpenTestcases() { var testcase_num = []; var current_testcase; $(".box").each(function() { current_testcase = $(this).find('div[id^=testcase_]'); if (typeof current_testcase[0] !== 'undefined'){ if (current_testcase[0].style.display != 'none' ) { testcase_num.push(parseInt(current_testcase.attr('id').split('_')[1])); } } }); return testcase_num; } //finds all the open files and folder and stores them in stored_paths function findAllOpenedFiles(elem, current_path, path, stored_paths, first) { if (first === true) { current_path += path; if ($(elem)[0].classList.contains('open')) { stored_paths.push(path); } else { return []; } } else { current_path += "#$SPLIT#$" + path; } $(elem).children().each(function() { $(this).children('div[id^=file_viewer_]').each(function() { if ($(this)[0].classList.contains('shown')) { stored_paths.push((current_path + "#$SPLIT#$" + $(this)[0].dataset.file_name)); } }); }); $(elem).children().each(function() { $(this).children('div[id^=div_viewer_]').each(function() { if ($(this)[0].classList.contains('open')) { stored_paths.push((current_path + "#$SPLIT#$" + $(this)[0].dataset.file_name)); stored_paths = findAllOpenedFiles($(this), current_path, $(this)[0].dataset.file_name, stored_paths, false); } }); }); return stored_paths; } function adjustSize(name) { var textarea = document.getElementById(name); textarea.style.height = ""; textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px"; }
let instance = null; /** * Asset(资产表) */ class Asset { /** * * @param address (账户地址/publicKey) * @param code (资产类型||资产编码) * @param name () * @param issuer 发布者 * @param profile (资产描述的url,资产描述后台配置) */ constructor(address, code, name, issuer, profile) { this.address = address; this.code = code; this.name = name; this.issuer = issuer; this.profile = profile; } /** * 保存资产信息到资产表 * @param address * @param code * @param name * @param profile * @returns {Asset} */ static insertAsset( { address = '', code = '', name = '', issuer ='', profile = '' } = {} ) { let asset = new Asset(address, code, name, issuer, profile); instance.insert(asset); return this; } /** * 根据地址查询 * @returns {Array|*} 返回 */ static findByAddress (address) { let result = instance.find({address: address}); return result; } /** * 根据地址和code删除 * @param address */ static removAssetByAddressAndName (option) { return instance.findAndRemove(option); } /** * 创建asset表并返回 * @param db * @returns {asset} */ static newInstance (db) { instance = db.getCollection('asset') || db.addCollection('asset'); return this; } /** * 返回asset表信息 * @param db * @returns {*} */ static getInstance () { return instance; } } export default Asset;
import apiResult from '../../../utils/api-result' import { adminEditUser, adminEditPassword } from '../../../services/api/admin/user' import { adminGetStatistics } from '../../../services/api/admin/statistic' import { adminAddAttachment } from '../../../services/api/admin/attachment' import { ApiBaseUrl } from '../../../config/api.js' const app = getApp() Page({ data: { url: ApiBaseUrl, logo: '', CustomBar: app.globalData.CustomBar, statistics: {}, username: '', nickname: '', email: '', description: '', oldPassword: '', newPassword: '', confirmPassword: '', isOldPassword: true, isNewPassword: true, isConfirmPassword: true, selectAttachment: null, uploadModal: false }, onLoad: function () { const that = this that.setData({ logo: app.globalData.logo }) }, async onShow() { const that = this const selectAttachment = that.data.selectAttachment if (selectAttachment) { that.setData({ uploadModal: true }) await that.editAvatar(selectAttachment.path) that.setData({ selectAttachment: null, uploadModal: false }) } that.setData({ loadModal: true }) const statistics = await this.adminGetStatistics() that.setData({ statistics: statistics, loadModal: false }) }, /** * 复制 * @param {*} e */ CopyLink(e) { wx.setClipboardData({ data: e.currentTarget.dataset.link, success: res => { wx.showToast({ title: '已复制', duration: 1000 }) } }) }, /** * 获取站点及博主信息 */ async adminGetStatistics() { try { const result = await adminGetStatistics() return result } catch (error) { return error.message } }, showModal(e) { const that = this const type = e.currentTarget.dataset.type const user = that.data.statistics.user if (type === 'editUser') { that.setData({ username: user.username, nickname: user.nickname, email: user.email, description: user.description }) } this.setData({ modalName: e.currentTarget.dataset.target }) }, hideModal(e) { this.setData({ modalName: null, username: '', nickname: '', email: '', description: '', oldPassword: '', newPassword: '', confirmPassword: '' }) }, usernameInput(e) { this.setData({ username: e.detail.value }) }, nicknameInput(e) { this.setData({ nickname: e.detail.value }) }, emailInput(e) { this.setData({ email: e.detail.value }) }, descriptionInput(e) { this.setData({ description: e.detail.value }) }, oldPasswordInput(e) { this.setData({ oldPassword: e.detail.value }) }, newPasswordInput(e) { this.setData({ newPassword: e.detail.value }) }, confirmPasswordInput(e) { this.setData({ confirmPassword: e.detail.value }) }, /** * 修改信息 */ async editUser() { const that = this if (!that.data.username) { apiResult.warn('用户名为空') return } if (!that.data.nickname) { apiResult.warn('昵称为空') return } if (!that.data.email) { apiResult.warn('邮箱为空') return } const param = { username: that.data.username, nickname: that.data.nickname, email: that.data.email, description: that.data.description } try { const result = await adminEditUser(param) // //视图修改,而非重新调用接口刷新 that.data.statistics.user = result that.setData({ statistics: that.data.statistics }) apiResult.success('修改成功') that.hideModal() } catch (error) { return error.message } }, /** * 修改密码 */ async editPassword() { const that = this if (!that.data.oldPassword) { apiResult.warn('旧密码为空') return } if (!that.data.newPassword) { apiResult.warn('新密码为空') return } if (!that.data.confirmPassword) { apiResult.warn('请确认密码') return } if (that.data.confirmPassword !== that.data.newPassword) { apiResult.warn('输入不一致') return } const param = { oldPassword: that.data.oldPassword, newPassword: that.data.newPassword } try { await adminEditPassword(param) apiResult.success('修改成功') that.hideModal() } catch (error) { return error.message } }, /** * 密码框是否可见 * @param {*} e */ viewPassword(e) { const that = this const passwordType = e.currentTarget.dataset.type if (passwordType === 'isOldPassword') { let flag = true if (that.data.isOldPassword) { flag = false } this.setData({ isOldPassword: flag }) } if (passwordType === 'isNewPassword') { let flag = true if (that.data.isNewPassword) { flag = false } this.setData({ isNewPassword: flag }) } if (passwordType === 'isConfirmPassword') { let flag = true if (that.data.isConfirmPassword) { flag = false } this.setData({ isConfirmPassword: flag }) } }, /** * 选择图片 */ async chooseImage(event) { const that = this const type = event.currentTarget.dataset.type const sourceType = [type] that.setData({ uploadModal: true, modalName: null }) wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: sourceType, // 从相册选择 success: async res => { const imgInfo = await that.adminAddAttachment(res.tempFilePaths[0]) await that.editAvatar(imgInfo.path) that.setData({ uploadModal: false }) }, fail: () => { that.setData({ uploadModal: false }) apiResult.warn('取消上传') } }) }, async adminAddAttachment(imgPath) { try { const param = { path: imgPath } const result = await adminAddAttachment(param) return result } catch (error) { this.setData({ modalName: null }) return await Promise.reject(error) } }, /** * 修改头像 */ async editAvatar(url) { const that = this const user = that.data.statistics.user const param = { avatar: url, username: user.username, nickname: user.nickname, email: user.email, description: user.description } try { const result = await adminEditUser(param) // 视图修改,而非重新调用接口刷新 that.data.statistics.user = result that.setData({ statistics: that.data.statistics }) apiResult.success('修改成功') that.hideModal() } catch (error) { return error.message } }, toChooseAttachment: function () { wx.navigateTo({ url: '/pages/admin/attachment/select/index?type=2' }) } })
import React from 'react'; import withIconEnhancer from '../HOCs/withIconEnhancer'; export default withIconEnhancer('Helicopter', 'helicopter', (props) => ( <svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path stroke="none" d="M0 0h24v24H0z" fill="none"/> <path d="M3 10l1 2h6" /> <path d="M12 9a2 2 0 0 0 -2 2v3c0 1.1 .9 2 2 2h7a2 2 0 0 0 2 -2c0 -3.31 -3.13 -5 -7 -5h-2z" /> <line x1="13" y1="9" x2="13" y2="6" /> <line x1="5" y1="6" x2="20" y2="6" /> <path d="M15 9.1v3.9h5.5" /> <line x1="15" y1="19" x2="15" y2="16" /> <line x1="19" y1="19" x2="11" y2="19" /> </svg> ));
import Axios from 'axios'; import { store } from '../../index'; const env = { url: 'https://us-central1-chatcorp-34e5b.cloudfunctions.net/app' // 'http://localhost:3001'// 'https://us-central1-get-servicos.cloudfunctions.net/app' } export const setUser = (userId, username, user) => { const {dispatch} = store; dispatch({ type: 'UPDATE_USER', user: {userId, username, ...user} }); } export const setLoading = (load) => { const {dispatch} = store; let type = load ? 'LOADING_START' : 'LOADING_STOP' dispatch({ type }); } export const refreshHome = (value) => { const {dispatch} = store; //console.log("dispatch({ type: 'UPDATE_LIST', home: true })"); dispatch({ type: 'UPDATE_LIST', home: value }) } export const refreshMessage = (value) => { const {dispatch} = store; //console.log("dispatch({ type: 'UPDATE_LIST', home: true })"); dispatch({ type: 'UPDATE_LIST', answer: value }) } export const redirect = (value) => { const {dispatch} = store; //console.log("dispatch({ type: 'REDIRECT' })"); dispatch({ type: 'REDIRECT', page: value }) } export const redirectSearch = (search, page) => { const {dispatch} = store; //console.log("dispatch({ type: 'REDIRECT' })"); dispatch({ type: 'REDIRECT', page: `/?data=${search}&page=${page}` }); } export function clearSearch() { const {dispatch} = store; dispatch({ type: 'CLEAR_SEARCH', data: {} }); } export const voteQuestion = async (data) => { const url = `${env.url}/voteQuestion`; return await Axios.post(url, {data}) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const likeAnswer = async (data) => { const url = `${env.url}/likeAnswer`; return await Axios.post(url, {data}) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const verifyToken = async (data) => { const url = `${env.url}/verifyToken`; return await Axios.post(url, {data}) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const registerUser = async (data) => { const url = `${env.url}/register`; return await Axios.post(url, {data}) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const authenticateUser = async (data) => { const url = `${env.url}/authenticate`; return await Axios.post(url, {data}) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const getKeywordsQuestion = async (data) => { const url = `${env.url}/getKeywordsQuestion`; return await Axios.post(url, {data}) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const getQuestions = async (data) => { let url = `${env.url}/getQuestions`; if(data) url = `${env.url}/getKeywordsQuestion`; return await Axios.post(url, {data}) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const getAnswers = async (data) => { const url = `${env.url}/getAnswers`; return await Axios.post(url, {data}) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const setQuestion = async (value) => { const url = `${env.url}/saveQuestion`; return await Axios.post(url, {value}) .then((res) => { //console.log('export const setQuestion', res.data); return res.data; }).catch((e) => { return null; }); } export const setAnswer = async (value) => { const url = `${env.url}/saveAnswer`; return await Axios.post(url, {value}) .then((res) => { //console.log('export const setQuestion', res.data); return res.data; }).catch((e) => { return null; }); } export const getTabs = async (value) => { const url = `${env.url}/getTabs`; return await Axios.get(url) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const getProdutos = async (value) => { const url = `${env.url}/getProdutos`; const produto = { search: value }; return await Axios.post(url, produto) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const getTagProdutos = async (value) => { const url = `${env.url}/getTagProdutos`; const produto = { search: null, tagId: value }; return await Axios.post(url, produto) .then((res) => { return res.data; }).catch((e) => { return null; }); } export const getParam = (data) => { let search = window.location.search; let params = new URLSearchParams(search); return params.get(data); } export const updateUrlPage= (page) => { let search = getParam('data'); return `/search?data=${search}&page=${page}`; } export const updateUrlSearch = (search, page) => { return `/?data=${search}&page=${page}`; }
if(!_.pyramid_funnel){_.pyramid_funnel=1;(function($){var sR=function(a,b,c){$.hw.call(this,null,[],[],b,c);this.ya=a},uR=function(a,b,c){$.hw.call(this,null,[],[],b,c);this.ya=a;this.F=!tR(this.ya);this.J=this.ya.N("connectorStroke")},vR=function(a,b){$.Pu.call(this);$.T(this);this.P=null;this.Ob=[];this.ca=null;this.Oc=1;this.Sa=this.o=null;this.state=new $.uu(this);this.data(a||null,b);var c={};$.vp(c,[["fill",528,1],["stroke",528,1],["hatchFill",528,1],["labels",0,0],["markers",0,0]]);this.Ua=new $.pw(this,c,$.cm);$.iq(this.Ua,"labelsAfterInitCallback", function(a){$.S(a,this.sd,this);a.mb(this);this.D(4096,1)});this.Ua.ua.markersAfterInitCallback=$.rw;c={};$.vp(c,[["fill",16,1],["stroke",16,1],["hatchFill",0,0],["labels",0,0],["markers",0,0]]);this.Xb=new $.pw(this,c,1);this.dc=new $.pw(this,c,2);$.vp(this.J,[["baseWidth",16,1],["neckHeight",16,1],["neckWidth",16,1],["pointsPadding",16,1],["reversed",16,1],["overlapMode",4096,1],["connectorLength",4100,9],["connectorStroke",16,1]]);this.ka(!1)},wR=function(a,b){var c=a.la().G("point");if($.n(c)){var d= $.am("fill",1,!0)(a,b,!1,!0);c.fill(d);d=$.am("stroke",2,!0)(a,b,!1,!0);c.stroke(d)}},xR=function(a,b,c){if($.J(a.o,b))c&&a.o.X(c);else{var d=!!a.o;$.K(a.o);a.o=new b;c&&a.o.X(c);$.S(a.o,a.k3,a);$.L(a,a.o);d&&a.D(528,1)}},yR=function(a,b){var c=a.la().G("hatchPoint");if(c){var d=$.am("hatchFill",3,!0)(a,b,!1);c.stroke(null).fill(d)}},zR=function(a,b){var c=a.vc,d=a.ub.height,e=a.Ie,f=a.Rc;return b>d-f||d==f?e:e+(d-f-b)/(d-f)*(c-e)},AR=function(a){a=$.O(a);return 0>=a||!(0,window.isFinite)(a)},BR= function(a){var b=a.la(),c=b.sa(),d=a.ub,e,f,h,k,l,m;e=b.G("height")/2;k=b.G("startY");l=b.G("height")+k;m=null;if(f=a.Jd)c?c==b.Ib()-1?(k+=f/2,k>l&&(k=l-a.Oc)):(k+=f/2,l-=f/2,k>l&&(k=b.G("startY")+e,l=k+a.Oc)):(l-=f/2,l<k&&(l=a.Oc));h=zR(a,k);c=a.b-h/2;e=c+h;h=zR(a,l);f=a.b-h/2;h=f+h;k+=d.top;l+=d.top;c=d.left+c;e=d.left+e;0<a.Rc&&k<a.md&&l>a.md&&(m=l,l=a.md,h=zR(a,l),f=a.b-h/2,h=f+h);f=d.left+f;h=d.left+h;a.N("reversed")||(k=d.height-(k-d.top)+d.top,l=d.height-(l-d.top)+d.top,m=m?d.height-(m-d.top)+ d.top:null,k=[l,l=k][0],c=[f,f=c][0],e=[h,h=e][0]);b.G("x1",c);b.G("x2",e);b.G("x3",f);b.G("x4",h);b.G("y1",k);b.G("y2",l);b.G("y3",m)},CR=function(a,b,c,d){var e=a.labels();$.T(e);e.fontOpacity(b);e.ea();e.ka(!1);if(d&&a.g)for(var f in a.g)a.g.hasOwnProperty(f)&&a.g[f].stroke($.Tl(a.N("connectorStroke"),c))},oea=function(a){var b=a.la(),c=b.sa(),d=$.Ty(a.ha),e=$.Ty(a.Ba);b.G("point",d);b.G("hatchPoint",e);BR(a);var f=b.G("x1"),h=b.G("x2"),k=b.G("x3"),l=b.G("x4"),m=b.G("y1"),p=b.G("y2"),q=b.G("y3"); d.moveTo(f,m).lineTo(h,m);q?d.lineTo(l,p).lineTo(l,q).lineTo(k,q).lineTo(k,p):d.lineTo(l,p).lineTo(k,p);d.close();b.G("point",d);d.tag={index:c,ia:a};b=$.zu(a.state,b.sa());wR(a,b);e&&(e.jd(d.O()),e.tag={index:c,ia:a},yR(a,b))},GR=function(a,b){var c=a.la(),d=!!(b&2),e=!d&&!!(b&1),f=c.get("normal"),f=$.n(f)?f.label:void 0,h=c.get("hovered"),h=$.n(h)?h.label:void 0,k=c.get("selected"),k=$.n(k)?k.label:void 0,f=$.so(f,c.get("label")),h=e?$.so(h,c.get("hoverLabel")):null,k=d?$.so(k,c.get("selectLabel")): null,l=c.sa(),m,p=null,q=a.Kb().labels(),r=a.selected().labels();d?p=m=r:e?p=m=q:m=a.labels();var t=a.labels().Yd(l),u=f&&$.n(f.enabled)?f.enabled:null,v=h&&$.n(h.enabled)?h.enabled:null,w=k&&$.n(k.enabled)?k.enabled:null,q=e||d?e?null===v?null===q.enabled()?null===u?a.labels().enabled():u:q.enabled():v:null===w?null===r.enabled()?null===u?a.labels().enabled():u:r.enabled():w:null===u?a.labels().enabled():u,u=DR(a,null,b),v=ER(a),r=tR(a),w=!0;if(!e&&!d&&r&&"no-overlap"==a.N("overlapMode")){m=m.ki(v, u,f,l);var w=a.la(),x=[w.G("x1"),w.G("y1"),w.G("x2"),w.G("y1"),w.G("x4"),w.G("y2"),w.G("x3"),w.G("y2")],z=!0,E,N,R,P,aa,X,ba,Y,ja,Ja;E=0;for(N=x.length;E<N-1;E+=2)R=E==N-2?0:E+2,P=E==N-2?1:E+3,aa=x[E],X=x[E+1],ba=x[R],Y=x[P],ja=m[E],Ja=m[E+1],R=m[R],P=m[P],w.G("y3")&&4==E&&(X=$.O(w.G("y3")),Y=$.O(w.G("y3"))),aa==ba&&(ba+=.01),z=(z=z&&1==$.Xm(aa,X,ba,Y,ja,Ja))&&1==$.Xm(aa,X,ba,Y,R,P);w=z}q&&w?(t?(t.ig(),t.Fe(v),t.rc(u)):t=a.labels().add(v,u,l),$.dv(t,p),t.wc(f,e?h:k),c.G("labelWidthForced")&&(t.width($.O(c.G("labelWidthForced"))), c=h&&h.anchor?h.anchor:null,k=k&&k.anchor?k.anchor:null,f&&f.anchor&&f.anchor||c||k||(u=DR(a,t,b),t.rc(u))),t.ea(),(e||d)&&!t.$()&&a.labels().$e()&&(t.$(a.labels().$e()),t.$().parent()||t.$().parent(a.labels().$()),t.ea())):t&&t.clear();q&&!r&&FR(a,t,b)},DR=function(a,b,c){var d=HR(a),e=a.la(),f=a.ub,h=$.n(c)?!!(c&2):null,k=$.n(c)?!h&&!!(c&1):null,l=e.get("normal"),l=$.n(l)?l.label:void 0,m=e.get("hovered"),m=$.n(m)?m.label:void 0,p=e.get("selected"),p=$.n(p)?p.label:void 0,l=$.so(l,e.get("label")), m=k?$.so(m,e.get("hoverLabel")):null,h=(p=h?$.so(p,e.get("selectLabel")):null)||m||l||{},l=$.O(e.G("x1")),p=$.O(e.G("x2")),m=$.O(e.G("y1")),k=$.O(e.G("y2")),q=$.O(e.G("y3")),e=p-l,k=q?q-m:k-m,m=m+k/2,p=$.O(h.offsetY)||0;b?c=IR(a,b,c):(c=a.labels().ki(ER(a),null,h),c=$.$m(c));h=b&&b.N("anchor")||a.labels().N("anchor");b&&(m=b.rc().value.y);b=m+p;c.height>k&&("left-center"==h||"center"==h||"right-center"==h)&&(m+c.height/2>f.top+f.height&&(m=f.top+f.height-c.height/2),m-c.height/2<f.top&&(m=f.top+c.height/ 2));b=JR(a,b);switch(d){case "inside":l+=e/2;break;case "outside-left":l=a.b-b/2;l=f.left+l-a.K-c.width/2;break;case "outside-left-in-column":l=f.left+c.width/2;break;case "outside-right":l=a.b+b/2;l=f.left+l+a.K+c.width/2;break;case "outside-right-in-column":l=f.left+f.width-c.width/2}if("left-top"==h||"center-top"==h||"right-top"==h)m-=.5;else if("left-bottom"==h||"center-bottom"==h||"right-bottom"==h)m+=.5;return{value:{x:l,y:m}}},IR=function(a,b,c){var d=!!(c&2),e=!d&&!!(c&1);c=a.data().get(b.sa(), "label");e=e?a.data().get(b.sa(),"hoverLabel"):null;d=(d?a.data().get(b.sa(),"selectLabel"):null)||e||c||{};a.data().G(b.sa(),"labelWidthForced")&&(d=$.Rc(d),d.width=b.width());a.la().select(b.sa());b.Fe(ER(a));a=a.labels().ki(b.Fe(),b.rc(),d);return $.$m(a)},MR=function(a,b){if("no-overlap"==a.N("overlapMode")&&!tR(a)&&a.labels().enabled()){KR(a);a.de=0;var c=a.state.Kg()|(b?$.zu(a.state,b.sa()):0);LR(a,c,b)}},LR=function(a,b,c){if(10!=a.de){for(var d=a.la().Ib(),e=!1,f,h,k,l,m=a.N("reversed"),p= 0;p<d-1;p++)if(f=m?p:d-1-p,(f=a.labels().Yd(f))&&0!=f.enabled()&&(h=IR(a,f,b),k=m?pea(a,f):qea(a,f))){l=IR(a,k,b);var q=NR(a,f),r=NR(a,k);q&&r&&q==r||!(l.top<=h.top+h.height)||(e=!0,q&&r?rea(a,q,r):!q&&r?OR(a,k,f):OR(a,f,k))}e&&((0,$.Za)(a.Ob,function(a){if(2>a.labels.length){var b=a.ya;b.Ob.length&&(a.clear(),$.jb(b.Ob,a))}else{for(var d,e,f=0,h=0,k=b=0,l=a.labels.length;k<l;k++)d=a.labels[k],e=a.ya.state.Kg()|$.zu(a.ya.state,d.sa()),e=PR(a,d,e),d=a.ya.data().G(d.sa(),"point"),d=d.sb(),k||(f=d.top), b+=e.height,h+=d.height;h+=a.ya.Jd*(l-1);f=f+h/2-b/2;h=a.ya.ub;f+b>h.top+h.height&&(f=h.top+h.height-b);f<h.top&&(f=h.top);a.y=f;sea(a,c)}}),a.de++,LR(a,b,c))}},pea=function(a,b){if(!b)return null;var c=a.la().Ib();if(b.sa()==c-1)return null;for(var d,e=b.sa()+1;e<=c-1;e++)if((d=a.labels().Yd(e))&&!1!==d.enabled())return d;return null},qea=function(a,b){if(!b||!b.sa())return null;for(var c,d=b.sa()-1;0<=d;d--)if((c=a.labels().Yd(d))&&!1!==c.enabled())return c;return null},OR=function(a,b,c){var d= NR(a,b);d?QR(d,c):(d=new RR(a),QR(d,b),QR(d,c),a.Ob.push(d))},NR=function(a,b){return a.Ob.length?$.bb(a.Ob,function(a){return-1!==(0,$.cb)(a.labels,b)}):null},rea=function(a,b,c){var d=b.labels[0].sa(),e=c.labels[0].sa();b.labels=a.N("reversed")==d<e?$.lb(b.labels,c.labels):$.lb(c.labels,b.labels);$.jb(a.Ob,c)},KR=function(a){a.Ob.length&&((0,$.Za)(a.Ob,function(a){a.clear()}),a.Ob.length=0)},tR=function(a){return"inside"==HR(a)},SR=function(a){a=HR(a);return"outside-right-in-column"==a||"outside-left-in-column"== a},TR=function(a){a=HR(a);return"outside-left"==a||"outside-left-in-column"==a},UR=function(a){a=HR(a);return"outside-right"==a||"outside-right-in-column"==a},tea=function(a){if(a.labels().enabled()&&!tR(a)){BR(a);var b=a.la();b.G("labelWidthForced",void 0);var c=a.ub,d,e=b.get("label"),f=DR(a),h=ER(a),h=a.labels().ki(h,f,e),h=$.$m(h),e=h.left,f=h.left+h.width,k,h=a.N("reversed")?zR(a,h.top-c.top):zR(a,c.height-(h.top+h.height)+c.top);if(TR(a))d=a.b-h/2,d=c.left+d,k=a.vc/2,k=c.width-a.b-k,SR(a)?f+ 5>d&&(d=f+5-d,d>k?(a.b+=k,d=a.b-h/2,d=c.left+d,b.G("labelWidthForced",d-5-e)):a.b+=d):e<c.left&&(d=Math.abs(c.left-e),d>k?(a.b+=k,d=a.b-h/2,a=d-a.K,10>a&&(a=10),b.G("labelWidthForced",a)):a.b+=d);else if(UR(a))if(d=a.b+h/2,d+=c.left,k=a.vc/2,k=c.width-(c.width-a.b)-k,SR(a)){if(0>e||e-5<d)d=Math.abs(d-e+5),0>e||d>k?(a.b=a.b-k,d=a.b+h/2,d+=c.left,b.G("labelWidthForced",f-5-d)):a.b=a.b-d}else f>c.left+c.width&&(d=f-(c.left+c.width),d>k?(a.b=a.b-k,a=c.left+c.width-e+k,10>a&&(a=10),b.G("labelWidthForced", a)):a.b=a.b-d)}},HR=function(a){a=a.labels().N("position");return $.wk(uea,"outside"==a?"outside-left":a,"outside-left-in-column")},VR=function(a,b,c,d){var e=a.ub,f=b.sa(),f=a.data().G(f,"point").sb();b=IR(a,b,d);d=b.left;var h=b.top+b.height/2,k,f=f.top+f.height/2,l=JR(a,f);TR(a)?(d+=b.width,k=a.b-l/2,k+=e.left,d>k&&5>Math.abs(f-h)&&(d=k-5)):UR(a)&&(k=a.b+l/2,k+=e.left,d<k&&5>Math.abs(f-h)&&(d=k+5));c.clear().moveTo(d,h).lineTo(k,f+.001)},FR=function(a,b,c){var d=b.sa();if(a.g[d])VR(a,b,a.g[d], c);else{var e=$.Ty(a.Ja);a.g[d]=e;e.stroke(a.N("connectorStroke"));VR(a,b,e,c)}},WR=function(a){a=$.am("fill",1,!1)(a,$.cm,!0,!0);return $.Tl(a,1,!0)},vea=function(a,b){b=$.Ck(b);var c=a.ub,d=a.la(),e=d.G("point").sb(),f=d.G("x1"),h=d.G("y1");switch(b){case "left-top":h=d.G("y1");f=d.G("x1");break;case "left-center":h+=e.height/2;d=JR(a,h);f=a.b-d/2;f+=c.left;break;case "left-bottom":h+=e.height;f=d.G("x3");break;case "center-top":f=a.b;f+=c.left;break;case "center":h+=e.height/2;JR(a,h);f=a.b;f+= c.left;break;case "center-bottom":h+=e.height;JR(a,h);f=a.b;f+=c.left;break;case "right-top":d=JR(a,h);f+=d;break;case "right-center":h+=e.height/2;d=JR(a,h);f=a.b+d/2;f+=c.left;break;case "right-bottom":f=d.G("x4"),h+=e.height}return{value:{x:f,y:h}}},JR=function(a,b){var c=a.ub;return a.N("reversed")?zR(a,b-c.top):zR(a,c.height-b+c.top)},XR=function(a){var b=a.Db();a.tc("mousemove",a.UB);b.cd()},ER=function(a){var b=a.la();a.ba||(a.ba=new $.Nt);a.ba.Eh(b).vh([a.$d(b.sa()),a]);b={x:{value:b.get("x"), type:"string"},value:{value:b.get("value"),type:"number"},name:{value:b.get("name"),type:"string"},index:{value:b.sa(),type:"number"},chart:{value:a,type:""}};$.Ct(a.ba,b);return a.ba},RR=function(a){this.ya=a;this.labels=[]},QR=function(a,b){a.labels.push(b);a.ya.N("reversed")?$.wb(a.labels,function(a,b){return a.sa()-b.sa()}):$.wb(a.labels,function(a,b){return b.sa()-a.sa()})},sea=function(a,b){var c=0,d=0,e=null,f=null,h=null,k=a.ya.state.Kg()|(b?$.zu(a.ya.state,b.sa()):0);(0,$.Za)(a.labels,function(b){var l= b.rc().value,p=PR(a,b,k),q=a.y+c+d+p.height/2;if(e&&f&&h){var r=h.y+f.height/2+(e.N("offsetY")||0),t=q-p.height/2+(b.N("offsetY")||0);t<r&&(q+=r-t)}b.rc({value:{x:l.x,y:q}});b.ea();FR(a.ya,b,k);c+=p.height;d+=b.N("offsetY")||0;e=b;f=p;h={x:l.x,y:q}})},PR=function(a,b,c){var d=!!(c&2),e=!d&&!!(c&1);c=a.ya.data().get(b.sa(),"label");e=e?a.ya.data().get(b.sa(),"hoverLabel"):null;d=(d?a.ya.data().get(b.sa(),"selectLabel"):null)||e||c||{};a.ya.data().G(b.sa(),"labelWidthForced")&&(d=$.Rc(d),d.width=b.width()); a.ya.la().select(b.sa());b.Fe(ER(a.ya));a=a.ya.labels().ki(b.Fe(),b.rc(),d);return $.$m(a)},YR=function(a,b){var c=new vR(a,b);c.R="funnel";c.va(!0,$.jm("funnel"));return c},ZR=function(a,b){var c=new vR(a,b);c.R="pyramid";c.va(!0,$.jm("pyramid"));return c},uea={IG:"inside",zga:"outside-left",Aga:"outside-left-in-column",Bga:"outside-right",Cga:"outside-right-in-column"};$.G(sR,$.hw);$.g=sR.prototype; $.g.update=function(){this.g.length=this.j.length=0;for(var a=this.ya.qf();a.advance();)if(!a.G("missing")){var b=a.G("x1"),c=a.G("x2"),d=a.G("x3"),e=a.G("x4"),f=a.G("y1"),h=a.G("y2"),k=a.G("y3");a.G("neck",!!k);this.g.push(b,c,d,e,0,0,0);this.j.push(b,c,d,e,f,h,k?k:0)}};$.g.sl=function(){CR(this.ya,1E-5,1E-5,!tR(this.ya))}; $.g.li=function(){for(var a=this.ya.qf(),b=0;a.advance();)if(!a.G("missing")){a.G("x1",this.b[b++]);a.G("x2",this.b[b++]);a.G("x3",this.b[b++]);a.G("x4",this.b[b++]);a.G("y1",this.b[b++]);a.G("y2",this.b[b++]);a.G("y3",this.b[b++]);var c=this.ya,d=a,e=d.G("point");e.clear();var f=d.G("x1"),h=d.G("x2"),k=d.G("x3"),l=d.G("x4"),m=d.G("y1"),p=d.G("y2"),q=d.G("y3");e.moveTo(f,m).lineTo(h,m);d.G("neck")?e.lineTo(l,p).lineTo(l,q).lineTo(k,q).lineTo(k,p):e.lineTo(l,p).lineTo(k,p);e.close();if(f=d.G("hatchPoint"))c.la().select(d.sa()), f.clear(),f.jd(e.O()),d=$.zu(c.state,d.sa()),e=$.am("hatchFill",3,!0),f.stroke(null).fill(e(c,d,!1))}};$.g.Ng=function(){this.li()};$.g.da=function(){sR.I.da.call(this);this.ya=null};$.G(uR,$.hw);uR.prototype.update=function(){this.g.length=this.j.length=0;this.g.push(1E-5,1E-5);this.j.push(1,this.J.opacity||1)};uR.prototype.li=function(){CR(this.ya,this.b[0],this.b[1],this.F)};uR.prototype.Ng=function(){this.li()};uR.prototype.da=function(){uR.I.da.call(this);this.J=this.ya=null;delete this.F};$.G(vR,$.Pu);$.Hp(vR,["fill","stroke","hatchFill"]);$.g=vR.prototype;$.g.Za=function(a){return $.n(a)?(this.Ua.X(a),this):this.Ua};$.g.Kb=function(a){return $.n(a)?(this.Xb.X(a),this):this.Xb};$.g.selected=function(a){return $.n(a)?(this.dc.X(a),this):this.dc};$.g.Aa=$.Pu.prototype.Aa|16;$.g.xa=$.Pu.prototype.xa|28688;$.g.we=function(){return[this]};$.g.vf=function(){return!0};$.g.Yg=function(){return!1};$.g.xg=function(){return!0}; $.g.data=function(a,b){if($.n(a)){if(a){var c=a.title||a.caption;c&&this.title(c);a.rows&&(a=a.rows)}if(this.Ia!==a){this.Ia=a;if(this.Sa!=a||null===a){$.K(this.Y);delete this.Ha;var d;$.J(a,$.rq)?(d=a,this.Y=null):($.J(a,$.Cq)?d=(this.Y=a).qe():d=$.y(a)||$.B(a)?(this.Y=new $.Cq(a,b)).qe():(this.Y=new $.Cq(null)).qe(),$.L(this,this.Y));this.Sa=d.xk()}$.K(this.Na);this.Na=this.Sa;$.S(this.Na,this.g3,this);$.L(this,this.Na);this.D(29456,17)}return this}return this.Na}; $.g.g3=function(a){$.U(a,16)&&this.D(29456,17)};$.g.la=function(){return this.Ha||(this.Ha=this.Na.la())};$.g.hc=function(){return this.Ha=this.Na.la()};$.g.qf=function(){return this.Na.la()};$.g.TB=function(a){if($.J(a,$.xr))return xR(this,$.xr,a),this;if($.J(a,$.tr))return xR(this,$.tr,a),this;$.A(a)&&"range"==a.type?xR(this,$.xr):!$.A(a)&&this.o||xR(this,$.tr);return $.n(a)?(this.o.X(a),this):this.o}; $.g.SB=function(a){this.ca||(this.ca=new $.vr,$.S(this.ca,this.i3,this),$.L(this,this.ca));return $.n(a)?(this.ca.X(a),this):this.ca};$.g.RB=function(a){this.P||(this.P=new $.ur,$.S(this.P,this.h3,this),$.L(this,this.P));return $.n(a)?(this.P.X(a),this):this.P};$.g.k3=function(a){$.U(a,2)&&this.D(528,1)};$.g.i3=function(a){$.U(a,2)&&this.D(528,1)};$.g.h3=function(a){$.U(a,2)&&this.D(528,1)};$.g.remove=function(){this.pb().$(null);this.labels().$(null);KR(this);this.ha&&this.ha.parent(null);vR.I.remove.call(this)}; $.g.$h=function(a){if(!$.kq(this)){this.yc();var b=this.la();this.W(4)&&this.D(4112);if(this.W(16)){this.ha?this.ha.clear():(this.ha=new $.Sy(function(){return $.kk()},function(a){a.clear()}),$.L(this,this.ha),this.ha.zIndex(30),this.ha.parent(this.Ta));this.Ba?this.Ba.clear():(this.Ba=new $.Sy(function(){return $.kk()},function(a){a.clear()}),$.L(this,this.Ba),this.Ba.parent(this.Ta),this.Ba.zIndex(31).Xc(!0));this.o&&$.J(this.o,$.xr)&&this.o.count(b.Ib());this.Jd=Math.abs($.Om($.M(this.N("pointsPadding"), a.height),2));this.vc=Math.abs($.Om($.M(this.N("baseWidth"),a.width),2));this.Ie=Math.abs($.Om($.M(this.N("neckWidth"),a.width),2));this.Rc=Math.abs($.Om($.M(this.N("neckHeight"),a.height),2));this.md=a.top+a.height-this.Rc;this.b=a.width/2;this.K=$.M(this.N("connectorLength"),(a.width-this.vc)/2);0>this.K&&(this.K=5);this.ub=a;var c=0,d,e,f=b.Ib()-$.O(this.Da("count")),h=$.Om(this.Jd/a.height*100,2);for(b.reset();b.advance();){d=b.get("value");e=AR(d);d=AR(d)?0:$.O(d);var k=$.Om(d/$.O(this.Da("sum"))* 100,2);e&&(k=h);k=$.Om(a.height/(100+f*h)*k,2);k||(k=this.Oc);b.G("value",d);b.G("height",k);b.G("startY",c);b.G("missing",e);c+=k;tea(this)}for(b.reset();b.advance();)c=b.sa(),"selected"==String(b.get("state")).toLowerCase()&&this.state.o(2,c),oea(this);if(this.g)for(var l in this.g)this.g.hasOwnProperty(l)&&this.g[l].stroke(this.N("connectorStroke"));this.D(4096);this.D(8192);this.U(16)}if(this.W(8192)){this.pb().$()||this.pb().$(this.Ta);this.pb().clear();for(b.reset();b.advance();)this.Wo(this.state.j| $.zu(this.state,b.sa()));this.pb().ea();this.U(8192)}if(this.W(4096)){this.labels().$()||this.labels().$(this.Ta);this.labels().clear();this.Ja&&this.Ja.clear();l=tR(this)?$.jm("pie.insideLabels"):$.jm("pie.outsideLabels");this.labels().yl(l.autoColor);this.labels().disablePointerEvents(l.disablePointerEvents);tR(this)||(this.K=$.M(this.N("connectorLength"),(a.width-this.vc)/2),0>this.K&&(this.K=5),this.Ja?this.Ja.clear():(this.Ja=new $.Sy(function(){return $.kk()},function(a){a.clear()}),$.L(this, this.Ja),this.Ja.parent(this.Ta),this.Ja.zIndex(32)),this.Ja.clip(a),this.g=[]);for(b.reset();b.advance();)tR(this)&&b.G("labelWidthForced",void 0),GR(this,this.state.j|$.zu(this.state,b.sa()));MR(this);this.labels().ea();this.labels().$e().clip(a);this.U(4096)}}}; $.g.pD=function(){if(this.Jl().enabled()&&0<this.Jl().duration())if(this.fa&&1==this.fa.Ud)this.fa.update();else if(this.W(2048)){$.K(this.fa);this.fa=new $.Ry;var a=this.Jl().duration(),b=a*(1-.85),a=new sR(this,.85*a),b=new uR(this,b);this.fa.add(a);this.fa.add(b);this.fa.pa("begin",function(){$.Iu(this,!0);$.lq(this,{type:"animationstart",chart:this})},!1,this);this.fa.pa("end",function(){$.Iu(this,!1);$.lq(this,{type:"animationend",chart:this})},!1,this);this.fa.Jh(!1)}}; $.g.If=function(a){a={type:a.type,target:this,relatedTarget:$.js(a.relatedTarget)||a.relatedTarget,domTarget:a.target,relatedDomTarget:a.relatedTarget,offsetX:a.offsetX,offsetY:a.offsetY,clientX:a.clientX,clientY:a.clientY,screenX:a.screenX,screenY:a.screenY,button:a.button,keyCode:a.keyCode,charCode:a.charCode,ctrlKey:a.ctrlKey,altKey:a.altKey,shiftKey:a.shiftKey,metaKey:a.metaKey,platformModifierKey:a.platformModifierKey,state:a.state};var b=$.Tn(a.domTarget);a.pointIndex=$.O(b.index);return a}; $.g.dg=function(a){(a=this.lf(a))&&this.dispatchEvent(a)}; $.g.lf=function(a){var b;"pointIndex"in a?b=a.pointIndex:"labelIndex"in a?b=a.labelIndex:"markerIndex"in a&&(b=a.markerIndex);b=$.O(b);a.pointIndex=b;var c=a.type;switch(c){case "mouseout":c="pointmouseout";break;case "mouseover":c="pointmouseover";break;case "mousemove":c="pointmousemove";break;case "mousedown":c="pointmousedown";break;case "mouseup":c="pointmouseup";break;case "click":c="pointclick";break;case "dblclick":c="pointdblclick";break;default:return null}var d=this.data().la();d.select(b)|| d.reset();return{type:c,actualTarget:a.target,iterator:d,sliceIndex:b,pointIndex:b,target:this,originalEvent:a,point:this.$d(b)}};$.g.$d=function(a){var b=new $.Ax(this,a),c;this.la().select(a)&&b.$s()&&!AR(c=b.get("value"))&&(a=c/this.af("sum")*100,b.Da("percentValue",a),b.Da("yPercentOfTotal",a));return b};$.g.Um=function(){return[]};$.g.Xg=function(a){$.n(a)?this.eg(a):this.hi();return this}; $.g.Qc=function(a){if(($.yu(this.state,1)||$.Fu(this.state.Kg(),1))&&this.enabled()){var b;$.n(a)?b=a:b=this.state.j==$.cm?window.NaN:void 0;this.state.g(1,b);a=this.la();for(a.reset();a.advance();)GR(this,$.zu(this.state,a.sa()));MR(this);XR(this)}}; $.g.eg=function(a,b){if(!this.enabled())return this;var c;if($.y(a)){c=$.Du(this.state,1);for(var d=0;d<c.length;d++)$.eb(a,c[d])||this.state.g(1,c[d]);$.Bu(this.state,1,a);$.n(b)&&this.UB(b);for(c=this.hc();c.advance();)GR(this,$.zu(this.state,c.sa()));MR(this)}else if($.C(a)&&(this.Qc(),$.Bu(this.state,1,a),$.n(b)&&this.UB(b),this.ub)){for(c=this.hc();c.advance();)GR(this,$.zu(this.state,c.sa()));MR(this,this.labels().Yd(a))}this.la().select(a[0]||a);return this}; $.g.hi=function(){if(!this.enabled())return this;this.state.o(1);MR(this,null);return this};$.g.select=function(a){if(!this.enabled())return this;$.n(a)?this.jg(a):this.enabled()&&(XR(this),this.state.o(2),MR(this,null));return this}; $.g.jg=function(a,b){if(!this.enabled())return this;var c=!(b&&b.shiftKey);$.y(a)?(b||this.vd(),this.state.o(2,a,c?1:void 0)):$.C(a)&&this.state.o(2,a,c?1:void 0);if(this.ub){for(c=this.hc();c.advance();)GR(this,$.zu(this.state,c.sa()));var d;$.C(a)&&(d=this.labels().Yd(a));MR(this,d)}this.la().select(a[0]||a);return this}; $.g.vd=function(a){if(this.enabled()){var b;$.n(a)?b=a:b=this.state.j==$.cm?window.NaN:void 0;this.state.g(2,b);a=this.la();for(a.reset();a.advance();)GR(this,$.zu(this.state,a.sa()));MR(this)}};$.g.jh=function(a){wR(this,a);yR(this,a);this.Wo(a)};$.g.Hi=$.ia;$.g.kh=function(a){GR(this,a);wR(this,a);yR(this,a);this.Wo(a)};var $R={};$.Q($R,0,"baseWidth",$.Bp);$.Q($R,0,"neckHeight",$.Bp);$.Q($R,0,"neckWidth",$.Bp);$.Q($R,0,"pointsPadding",$.Bp);$.Q($R,0,"reversed",$.Bp);$.Q($R,0,"overlapMode",$.Sk); $.Q($R,0,"connectorLength",$.Bp);$.Q($R,1,"connectorStroke",$.Np);$.Gp(vR,$R);$.g=vR.prototype;$.g.Si=function(a,b,c,d,e,f,h){e=b?1==b?this.Xb:this.dc:this.Ua;h?a=e.N(a):(h=c.get(b?1==b?"hovered":"selected":"normal"),a=$.so($.n(h)?h[a]:void 0,c.get($.dm(b,a)),e.N(a)));$.n(a)&&(a=d(a));return a};$.g.Ci=function(){return $.zc(this.RB().pd(this.la().sa())||"diagonal-brick")};$.g.Tk=function(){var a=this.la();return{index:a.sa(),sourceHatchFill:this.Ci(),iterator:a}}; $.g.Yi=function(a){var b=this.la();return{index:b.sa(),sourceColor:a||this.TB().pd(b.sa())||"blue",iterator:b}};$.g.labels=function(a){return $.n(a)?(this.Ua.labels(a),this):this.Ua.labels()};$.g.sd=function(a){var b=0,c=0;$.U(a,1)&&(b|=4096,c|=1);$.U(a,8)&&(b|=4100,c|=9);this.D(b,c)};$.g.pb=function(a){return $.n(a)?(this.Ua.pb(a),this):this.Ua.pb()};$.g.Ik=function(a){$.U(a,1)&&this.D(8192,1)}; $.g.Wo=function(a){var b=this.la(),c=!!(a&2);a=!c&&!!(a&1);var d=b.get("normal"),d=$.n(d)?d.marker:void 0,e=b.get("hovered"),e=$.n(e)?e.marker:void 0,f=b.get("selected"),f=$.n(f)?f.marker:void 0,d=$.so(d,b.get("marker")),e=$.so(e,b.get("hoverMarker")),f=$.so(f,b.get("selectMarker")),h=this.la().sa(),k=this.Kb().pb(),l=this.selected().pb(),b=c?l:a?k:this.pb(),m=$.rv(this.pb(),h),p=d&&$.n(d.enabled)?d.enabled:null,q=e&&$.n(e.enabled)?e.enabled:null,r=f&&$.n(f.enabled)?f.enabled:null;if(a||c?a?null=== q?null===k.enabled()?null===p?this.pb().enabled():p:k.enabled():q:null===r?null===l.enabled()?null===p?this.pb().enabled():p:l.enabled():r:null===p?this.pb().enabled():p){p=d&&d.position?d.position:null;q=e&&e.position?e.position:null;r=f&&f.position?f.position:null;p=a&&(q||k.position())||c&&(r||l.position())||p||this.pb().position();p=vea(this,p);m?m.rc(p):m=this.pb().add(p,h);var t={},p="position anchor offsetX offsetY type size fill stroke enabled".split(" ");d&&(0,$.Za)(p,function(a){a in d&& (t[a]=d[a])});p=d&&d.type;h=$.n(p)?p:this.pb().Va()||this.SB().pd(h);p=e&&e.type;p=$.n(p)?p:k.Va();q=f&&f.type;q=$.n(q)?q:l.Va();t.type=c&&$.n(q)?q:a&&$.n(p)?p:h;h=d&&d.fill;h=$.n(h)?h:this.pb().F||WR(this);p=e&&e.fill;p=$.n(p)?p:k.F;q=f&&f.fill;q=$.n(q)?q:l.F;t.fill=c&&$.n(q)?q:a&&$.n(p)?p:h;h=d&&d.stroke;h=$.n(h)?h:this.pb().B||$.Ql(WR(this));p=e&&e.stroke;k=$.n(p)?p:k.B||$.Ql(WR(this));p=f&&f.stroke;l=$.n(p)?p:l.B||$.Ql(WR(this));t.stroke=c&&$.n(l)?l:a&&$.n(k)?k:h;m.ig();$.uv(m,b);m.wc(t,a?e:f); m.ea()}else m&&m.clear()};$.g.XC=function(){var a=new $.Ht(0);$.L(this,a);a.ya(this);$.S(a,this.j3,this);return a};$.g.j3=function(){this.Db().ea()};$.g.UB=function(a){if(!a||a.target!=this.be()){var b=this.Db(),c=ER(this);a&&($.Wt(b,a.clientX,a.clientY,c),this.pa("mousemove",this.UB))}}; $.g.yc=function(){if(this.W(16384)){this.jk={};for(var a=this.data().la(),b,c=0,d=Number.MAX_VALUE,e=-Number.MAX_VALUE,f=0;a.advance();)b=a.get("value"),AR(b)?c++:(b=AR(b)?0:$.O(b),d=Math.min(b,d),e=Math.max(b,e),f+=b);var a=a.Ib()-c,h;a?h=f/a:d=e=f=h=void 0;this.Da("count",a);this.Da("min",d);this.Da("max",e);this.Da("sum",f);this.Da("average",h);this.U(16384)}};$.g.Dh=function(){return ER(this)}; $.g.bj=function(a,b){for(var c=[],d=this.la().reset(),e;d.advance();){e=d.sa();var f=d.get("legendItem")||{},h=null;$.D(b)&&(h=ER(this),h.vV=this.$d(e),h=b.call(h,h));$.B(h)||(h=String($.n(d.get("name"))?d.get("name"):d.get("x")));var k=$.am("fill",1,!1),l=$.am("stroke",2,!1),m=$.am("hatchFill",3,!1),h={enabled:!0,meta:{pointIndex:e,pointValue:d.get("value"),ia:this},iconType:"square",text:h,iconStroke:l(this,$.cm,!1),iconFill:k(this,$.cm,!1),iconHatchFill:m(this,$.cm,!1)};$.Tc(h,f);h.sourceUid=$.ra(this); h.sourceKey=e;c.push(h)}return c};$.g.Zm=function(){return!0};$.g.em=function(a,b){var c=a.Jf();if(!a||null!=c||(0,window.isNaN)(c))if(c=$.Tn(b.domTarget))c.ia=this};$.g.il=function(a,b){var c=a.Jf();if(!a||null!=c||(0,window.isNaN)(c))if(c=$.Tn(b.domTarget))c.ia=this};$.g.hl=function(a,b){var c=a.Jf();if(!a||null!=c||(0,window.isNaN)(c))if(c=$.Tn(b.domTarget))c.ia=this};$.g.De=function(){return null};$.g.Mc=function(a){return $.n(a)?(a=$.yk(a),a!=this.qa&&(this.qa=a),this):this.qa};$.g.uj=function(){return!this.la().Ib()}; $.g.O=function(){var a=vR.I.O.call(this);a.type=this.Va();a.data=this.data().O();a.palette=this.TB().O();a.hatchFillPalette=this.RB().O();a.markerPalette=this.SB().O();a.tooltip=this.Db().O();$.Rp(this,$R,a);a.normal=this.Ua.O();a.hovered=this.Xb.O();a.selected=this.dc.O();return{chart:a}}; $.g.ga=function(a,b){vR.I.ga.call(this,a,b);$.Ip(this,$R,a);this.Ua.va(!!b,a);this.Ua.va(!!b,a.normal);this.Xb.va(!!b,a.hovered);this.dc.va(!!b,a.selected);this.data(a.data);this.RB(a.hatchFillPalette);this.SB(a.markerPalette);this.TB(a.palette);"tooltip"in a&&this.Db().va(!!b,a.tooltip)};$.g.da=function(){$.od(this.fa,this.Ua,this.Xb,this.dc);vR.I.da.call(this)};RR.prototype.clear=function(){this.labels.length=0};var aS=vR.prototype;aS.data=aS.data;aS.getType=aS.Va;aS.palette=aS.TB;aS.tooltip=aS.Db; aS.hatchFillPalette=aS.RB;aS.markerPalette=aS.SB;aS.labels=aS.labels;aS.markers=aS.pb;aS.hover=aS.Xg;aS.unhover=aS.Qc;aS.select=aS.select;aS.unselect=aS.vd;aS.getPoint=aS.$d;aS.normal=aS.Za;aS.hovered=aS.Kb;aS.selected=aS.selected;$.Yo.funnel=YR;$.Yo.pyramid=ZR;$.F("anychart.funnel",YR);$.F("anychart.pyramid",ZR);}).call(this,$)}
var stage = "main"; var currentObject; var currentSelectedPie = undefined; $("#main_page").show(); $("#user_data_page").hide(); $("#terms_and_conditions").hide(); // var adjective_ratings_overall = [ // {'name': 'Worst', 'from': -3, 'to': -0.736}, // {'name': 'Poor', 'from': -0.736, 'to': -0.485}, // {'name': 'Bad', 'from': -0.485, 'to': -0.105}, // {'name': 'Fair', 'from': -0.105, 'to': 0.393}, // {'name': 'Good', 'from': 0.393, 'to': 0.724}, // {'name': 'Excellent', 'from': 0.724, 'to': 1.363}, // {'name': 'Best', 'from': 1.363, 'to': 3}, // ]; var adjective_ratings_overall = [ {'name': 'Class VI', 'from': -3, 'to': 0.230}, {'name': 'Class V', 'from': 0.230, 'to': 0.667}, {'name': 'Class IV', 'from': 0.667, 'to': 1.104}, {'name': 'Class III', 'from': 1.104, 'to': 1.465}, {'name': 'Class II', 'from': 1.465, 'to': 1.883}, {'name': 'Class I', 'from': 1.883, 'to': 3}, ]; var adjective_ratings_SP = [ {'name': 'Class VI', 'from': -3, 'to': 0.638}, {'name': 'Class V', 'from': 0.638, 'to': 1.310}, {'name': 'Class IV', 'from': 1.310, 'to': 1.790}, {'name': 'Class III', 'from': 1.790, 'to': 2.000}, {'name': 'Class II', 'from': 2.000, 'to': 2.340}, {'name': 'Class I', 'from': 2.340, 'to': 3}, ]; var adjective_ratings_INV = [ {'name': 'Class VI', 'from': -3, 'to': 0.250}, {'name': 'Class V', 'from': 0.250, 'to': 0.700}, {'name': 'Class IV', 'from': 0.700, 'to': 1.158}, {'name': 'Class III', 'from': 1.158, 'to': 1.385}, {'name': 'Class II', 'from': 1.385, 'to': 1.810}, {'name': 'Class I', 'from': 1.810, 'to': 3}, ]; var adjective_ratings_REAL = [ {'name': 'Class VI', 'from': -3, 'to': -0.317}, {'name': 'Class V', 'from': -0.317, 'to': -0.014}, {'name': 'Class IV', 'from': -0.014, 'to': 0.590}, {'name': 'Class III', 'from': 0.590, 'to': 1.100}, {'name': 'Class II', 'from': 1.100, 'to': 1.846}, {'name': 'Class I', 'from': 1.846, 'to': 3}, ]; var adjective_ratings_GP = [ {'name': 'Class VI', 'from': -3, 'to': 0.875}, {'name': 'Class V', 'from': 0.875, 'to': 1.390}, {'name': 'Class IV', 'from': 1.390, 'to': 1.800}, {'name': 'Class III', 'from': 1.800, 'to': 2.000}, {'name': 'Class II', 'from': 2.000, 'to': 2.500}, {'name': 'Class I', 'from': 2.500, 'to': 3}, ]; var adjective_ratings_hmd = [ {'name': 'Class VI', 'from': -3, 'to': 0.471}, {'name': 'Class V', 'from': 0.471, 'to': 0.900}, {'name': 'Class IV', 'from': 0.900, 'to': 1.301}, {'name': 'Class III', 'from': 1.301, 'to': 1.629}, {'name': 'Class II', 'from': 1.629, 'to': 2.041}, {'name': 'Class I', 'from': 2.041, 'to': 3}, ]; var adjective_ratings_monoscopic = [ {'name': 'Class VI', 'from': -3, 'to': 0.049}, {'name': 'Class V', 'from': 0.049, 'to': 0.581}, {'name': 'Class IV', 'from': 0.581, 'to': 1.398}, {'name': 'Class III', 'from': 1.398, 'to': 1.520}, {'name': 'Class II', 'from': 1.520, 'to': 1.898}, {'name': 'Class I', 'from': 1.898, 'to': 3}, ]; var adjective_ratings_projection_display = [ {'name': 'Class VI', 'from': -3, 'to': 0.105}, {'name': 'Class V', 'from': 0.105, 'to': 0.600}, {'name': 'Class IV', 'from': 0.600, 'to': 0.725}, {'name': 'Class III', 'from': 0.725, 'to': 0.740}, {'name': 'Class II', 'from': 0.740, 'to': 1.105}, {'name': 'Class I', 'from': 1.105, 'to': 3}, ]; var adjective_ratings = [ {'name': 'Overall', 'ranges': adjective_ratings_overall}, {'name': 'GP', 'ranges': adjective_ratings_GP}, {'name': 'SP', 'ranges': adjective_ratings_SP}, {'name': 'INV', 'ranges': adjective_ratings_INV}, {'name': 'REAL', 'ranges': adjective_ratings_REAL}, {'name': '3D - HMD VR', 'ranges': adjective_ratings_hmd}, {'name': '3D - Monoscopic', 'ranges': adjective_ratings_monoscopic}, {'name': 'Projection Display', 'ranges': adjective_ratings_projection_display}]; var rootPapers = []; var overallObject = {'name': 'Overall', 'attr': 'Ranking_class', 'value': []}; var subscalesObject = {'name': 'Subscales', 'value': []}; var spObject = {'name': 'SP', 'attr': 'Sp_ranking_class', 'value': []}; var gpObject = {'name': 'GP', 'attr': 'Gp_ranking_class', 'value': []}; var invObject = {'name': 'INV', 'attr': 'Inv_ranking_class', 'value': []}; var realObject = {'name': 'REAL', 'attr': 'Real_ranking_class', 'value': []}; subscalesObject.value.push(spObject); subscalesObject.value.push(gpObject); subscalesObject.value.push(invObject); subscalesObject.value.push(realObject); var visualDisplaysObject = {'name': 'Visual_Displays', 'value': []}; var hmdObject = {'name': '3D - HMD VR', 'attr': 'Ranking_class', 'value': []}; var monoscopicObject = {'name': '3D - Monoscopic', 'attr': 'Ranking_class', 'value': []}; var projectionObject = {'name': 'Projection Display', 'attr': 'Ranking_class', 'value': []}; visualDisplaysObject.value.push(hmdObject); visualDisplaysObject.value.push(monoscopicObject); visualDisplaysObject.value.push(projectionObject); var maxNumberofStudiesForYear = 0, fromYear = 2019, toYear = 2019; var numberofBins = 30; var rangeforEachBin = Math.round(7 / numberofBins * 10) / 10; var maxNumberofBins = 0; var numberofParticipants = 0; // var colors = [ // {"name": "Worst", "color":"#EBF5FB"}, // {"name": "Poor", "color":"#D6EAF8"}, // {"name": "Bad", "color":"#AED6F1"}, // {"name": "Fair", "color":"#85C1E9"}, // {"name": "Good", "color":"#5DADE2"}, // {"name": "Excellent", "color":"#3498DB"}, // {"name": "Best", "color":"#3092C7"} // ]; // var colors = [ // {"name": "Worst", "color":"#ebf5fb"}, // {"name": "Poor", "color":"#a9d4ef"}, // {"name": "Bad", "color":"#69b3e4"}, // {"name": "Fair", "color":"#3498db"}, // {"name": "Good", "color":"#2c82bb"}, // {"name": "Excellent", "color":"#2670a1"}, // {"name": "Best", "color":"#21618c"} // ]; // var colors = [ // {"name": "Worst", "color":"#fbf0ff"}, // {"name": "Poor", "color":"#cce2fd"}, // {"name": "Bad", "color":"#a9d7fc"}, // {"name": "Fair", "color":"#80cafb"}, // {"name": "Good", "color":"#51bbfa"}, // {"name": "Excellent", "color":"#31b1f9"}, // {"name": "Best", "color":"#3092c7"} // ]; var colors = [ {"name": 'Class VI', "color":"#cce2fd"}, {"name": 'Class V', "color":"#a9d7fc"}, {"name": 'Class IV', "color":"#80cafb"}, {"name": 'Class III', "color":"#51bbfa"}, {"name": 'Class II', "color":"#31b1f9"}, {"name": 'Class I', "color":"#3092c7"} ]; var user_data_color = "#F39C12"; var layout_colors = ["#F8F9F9", "#E5E7E9", "#CACFD2", "#F2F3F4", "#D7DBDD"]; var code_layout_color = "#EBDEF0"; var standard_total_each_item = []; var standard_sp_each_item = []; var standard_inv_each_item = []; var standard_real_each_item = []; var standard_gp_each_item = []; var standard_total_each_item_hmd = []; var standard_total_each_item_mono = []; var standard_total_each_item_proj = []; jQuery(window).ready(function () { d3.csv("data/August2020_Revision2021/IPQReport_EachCondition_August2020_Revision2021_Reformatted_EachSubscale_UTF8.csv", function (error, data) { for(var i = 0; i < subscalesObject.value.length; i++) { var div = "#main_hmd_pie_chart"; var col = "Standard_sp_each_item"; if(subscalesObject.value[i].name === "SP") { div = "#main_sp_pie_chart"; col = "Standard_sp_each_item"; } else if(subscalesObject.value[i].name === "GP") { div = "#main_gp_pie_chart"; col = "Standard_gp_each_item"; } else if(subscalesObject.value[i].name === "INV") { div = "#main_inv_pie_chart"; col = "Standard_inv_each_item"; } else if(subscalesObject.value[i].name === "REAL") { div = "#main_real_pie_chart"; col = "Standard_real_each_item"; } var e = ParseData(data, subscalesObject.value[i].name, subscalesObject.value[i].attr, col); var adjectiveRatingsObject = e.value.find(function(element) { return element.name === "AdjectiveRatings"; }); var width = 0.85 * $(div).width(); DrawPie(adjectiveRatingsObject.value, width, width,"", div, false, ""); subscalesObject.value[i] = e; } }); d3.csv("data/August2020_Revision2021/IPQReport_EachCondition_August2020_Revision2021_Reformatted_VisualDisplays_UTF8.csv", function (error, data) { for(var i = 0; i < visualDisplaysObject.value.length; i++) { var e = ParseData(data, visualDisplaysObject.value[i].name, visualDisplaysObject.value[i].attr, "Standard_total_each_item", "display"); var adjectiveRatingsObject = e.value.find(function(element) { return element.name === "AdjectiveRatings"; }); var div = "#main_hmd_pie_chart"; if(e.name === "3D - Monoscopic") { div = "#main_monoscopic_pie_chart"; } else if(e.name === "Projection Display") { div = "#main_projectiondisplay_pie_chart"; } var width = 0.85 * $(div).width(); DrawPie(adjectiveRatingsObject.value, width, width,"", div, false, ""); visualDisplaysObject.value[i] = e; } }); d3.csv("data/August2020_Revision2021/IPQReport_EachCondition_August2020_Revision2021_Reformatted_EachStudy_UTF8.csv", function (error, data) { overallObject = ParseData(data, "Overall", "Ranking_class", "Standard_total_each_item"); var adjectiveRatingsObject = overallObject.value.find(function(element) { return element.name === "AdjectiveRatings"; }); var overallObject1 = overallObject.value.find(function(e){ return e.name === "Overall"; }); var summaryObject = overallObject1.value.find(function(e){ return e.name === "Summary"; }); $("info_main_category").html("Overall"); $("#info_main_participants").html(summaryObject.participants); $("#info_main_percent").html("100%"); $("#info_main_adjective_rating").html("All Classes"); $("#info_main_years").html(summaryObject.years.length); $("#info_main_user_studies").html(summaryObject.user_studies.length); $("#info_main_publications").html(summaryObject.publications.length); // var byYearObject = summaryObject.value.find(function(e){ // return e.name === "ByYear"; // }); // var byScoreObject = summaryObject.value.find(function(e){ // return e.name === "ByScore"; // }); // var studiesObject = summaryObject.value.find(function(e){ // return e.name === "Studies"; // }); AddScoreBarChart(summaryObject, "#main_bar_chart_for_score"); AddYearBarChart(summaryObject, "#main_bar_chart_for_year"); WriteTable(summaryObject, "#main_list_publications"); SortBy(true, false, true); SortBy(false, true, true); _currentObject = overallObject; _currentClassObject = summaryObject; // _currentObject = summaryObject; // _currentObject = _currentObject.value.find(function(e) // { // return e.name === "Overall"; // }); // _currentObject = _currentObject.value[0]; var width = 0.85 * $("#main_pie_chart").width(); DrawPie(adjectiveRatingsObject.value, width, width,"", "#main_pie_chart", false, ""); }); AddAppendix(); }); function ParseData(data, name, attr, col = "", type = "ipq") { var mainObject = {'name': name, 'attr': attr, 'value': []}; // Data Summary var overallObject = {'name': 'Overall', 'value': [{"name":'Summary',"number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}]}; var adjectiveRatingsObject = {'name': 'AdjectiveRatings', 'value': []}; var display = ""; var subscale = ""; if(type === "display") { display = name; subscale = ""; } else { display = ""; subscale = name; } // adjectiveRatingsObject.value.push({"name": "Worst", "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); // adjectiveRatingsObject.value.push({"name": "Poor", "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); // adjectiveRatingsObject.value.push({"name": "Bad", "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); // adjectiveRatingsObject.value.push({"name": "Fair", "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); // adjectiveRatingsObject.value.push({"name": "Good", "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); // adjectiveRatingsObject.value.push({"name": "Excellent", "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); // adjectiveRatingsObject.value.push({"name": "Best", "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); adjectiveRatingsObject.value.push({"name": 'Class VI', "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); adjectiveRatingsObject.value.push({"name": 'Class V', "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); adjectiveRatingsObject.value.push({"name": 'Class IV', "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); adjectiveRatingsObject.value.push({"name": 'Class III', "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); adjectiveRatingsObject.value.push({"name": 'Class II', "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); adjectiveRatingsObject.value.push({"name": 'Class I', "condition": "Previous Studies", "subscale": subscale, "display": display, "number": "0", "percent": "", "color":"", "participants": "0", "publications": [], "years": [], "user_studies": [], "value": [{"name": "Studies", "value": []}, {"name": "ByYear", "value": []}, {"name": "ByScore", "value": []}]}); mainObject.value.push(overallObject); mainObject.value.push(adjectiveRatingsObject); numberofParticipants = 0; data.forEach(function(d){ numberofParticipants += parseInt(d.Number_of_study_participants); mainObject.value.forEach(function(object) { object.value.forEach(function(e) { if(((e.name === "Summary" && object.name === "Overall") || (e.name === d[attr] && object.name === "AdjectiveRatings")) && (type === "ipq" || (type === "display" && name === d["Visual_display"]))) { e.number++; var selectedColor = colors.find(function(element) { return element.name === d[attr]; }); e.color = selectedColor.color; e.participants = parseInt(e.participants) + parseInt(d.Number_of_study_participants); if(!e.years.includes(d.Year)) { e.years.push(d.Year); } if(!e.publications.includes(d.Paperid)) { e.publications.push(d.Paperid); } if(!e.user_studies.includes(d.Studyid)) { e.user_studies.push(d.Studyid); } e.value.forEach(function(e2) { if(e2.name === "Studies") { e2.value.push(d); } if(e2.name == "ByYear") { var flag = false; e2.value.forEach(function(e3){ if(e3.year === d.Year) { e3.number++; e3.value.push(d); flag = true; if(e3.number > maxNumberofStudiesForYear) maxNumberofStudiesForYear = e3.number; } }); if(!flag) { var element = {"year": d.Year, "number": 1, "value": []}; element.value.push(d); e2.value.push(element); } if(d.Year < fromYear) { fromYear = d.Year; } else if(d.Year > toYear) { toYear = d.Year; } } if(e2.name == "ByScore") { var flag = false; var bin = Math.round(parseFloat(d[col]) / rangeforEachBin) * rangeforEachBin; bin = parseFloat(bin.toFixed(1)); e2.value.forEach(function(e3){ if(e3.bin === bin) { e3.number ++; e3.value.push(d); e3.type = type; e3.name = name; flag = true; if(e3.number > maxNumberofBins) { maxNumberofBins = e3.number; } } }); if(!flag) { var element = {"bin": bin, "number": 1, "percent": 0, "value": []}; element.value.push(d); e2.value.push(element); } } }); } }); }); //For computing percentiles if(type === "ipq") { if(name === "Overall") { standard_total_each_item.push(d[col]); } else if(name === "SP") { standard_sp_each_item.push(d[col]); } else if(name === "INV") { standard_inv_each_item.push(d[col]); } else if(name === "REAL") { standard_real_each_item.push(d[col]); } else if(name === "GP") { standard_gp_each_item.push(d[col]); } } else if(type === "display") { if(d.Visual_display === name) { if(name === "3D - HMD VR") { standard_total_each_item_hmd.push(d[col]); } else if(name === "3D - Monoscopic") { standard_total_each_item_mono.push(d[col]); } else if(name === "Projection Display") { standard_total_each_item_proj.push(d[col]); } } } }); var summaryObject = overallObject.value.find(function(element) { return element.name === "Summary"; }); adjectiveRatingsObject.value.forEach(function(e){ e.percent = Math.round(e.number / summaryObject.number * 100000) / 1000; // e.value.forEach(function(e2){ // if(e2.name === "Summary") // { // e2.percent = Math.round(e2.number / data.length * 10000) / 100; // if(e.name != "All") // { // overallObject.value.push({"name": e.name, "percent": e2.percent, "color": e2.color, "number": e2.number}); // } // } // }); }); return mainObject; } function AddYearBarChart(object, div){ $(div).html(""); var data = object.value.find(function(element) { return element.name === "ByYear"; }); var margin = {top: 20, right: 10, bottom: 70, left: 50}, width = $(div).width() - margin.left - margin.right, height = 275 - margin.top - margin.bottom; d3.select(div).html(""); var barChartSVG = d3.select(div).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var yearDomain = []; for(var i = fromYear; i <= toYear; i++) { yearDomain.push(i); } var x = d3.scale.ordinal().domain(yearDomain).rangeRoundBands([0, width], .05); var y = d3.scale.linear().domain([0,maxNumberofStudiesForYear]).range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .ticks(2); var yAxis = d3.svg.axis() .scale(y) .orient("left") .ticks(5); barChartSVG.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .selectAll("text") .style("text-anchor", "end") .style("font-size", "12px") .attr("dx", "-0.5em") .attr("dy", "0.5em") .attr("transform", "rotate(-45)"); barChartSVG.append("text") .attr("transform", "translate(" + (width/2) + " ," + (height + margin.top + 25) + ")") .style("text-anchor", "middle") .style("font-size", "14px") .text("year"); barChartSVG.append("g") .attr("class", "y axis") .style("font-size", "12px") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", "-3em") .attr("x", 0 - (height / 2)) .attr("dy", "0.71em") .style("text-anchor", "middle") .style("font-size", "14px") .text("number of user studies"); barChartSVG.selectAll("bar") .data(data.value) .enter().append("rect") .style("fill", function(d, i){ return object.color }) .attr("x", function(d) { return x(d.year); }) .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.number); }) .attr("height", function(d) { return height - y(d.number); }); barChartSVG.append("text") .attr("transform", "translate(" + (width/2) + " ," + (height + margin.top + 40) + ")") .attr("text-anchor", "middle") .style("font-size", "14px") .style("font-weight", "bold") .text("Number of user studies per year"); } function AddScoreBarChart(object, div){ $(div).html(""); var data = object.value.find(function(element) { return element.name === "ByScore"; }); var margin = {top: 20, right: 20, bottom: 70, left: 50}, width = $(div).width() - margin.left - margin.right, height = 270 - margin.top - margin.bottom; d3.select(div).html(""); var barChartSVG = d3.select(div).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var binDomain = []; for(var i = -3; i <= 3; ) { binDomain.push(i); i += rangeforEachBin; i = parseFloat(i.toFixed(1)); } var x = d3.scale.ordinal().domain(binDomain).rangeBands([0, width]); var y = d3.scale.linear().domain([0,maxNumberofBins]).range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .ticks(1); var yAxis = d3.svg.axis() .scale(y) .orient("left") .ticks(5); barChartSVG.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .selectAll("text") .style("text-anchor", "end") .style("font-size", "12px") .attr("dx", "-0.5em") .attr("dy", "0.5em") .attr("transform", "rotate(-45)"); barChartSVG.append("g") .attr("class", "y axis") .style("font-size", "12px") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", "-3em") .attr("x", 0 - (height / 2)) .attr("dy", "0.71em") .style("text-anchor", "middle") .style("font-size", "14px") .text("number of user studies"); barChartSVG.append("text") .attr("transform", "translate(" + (width/2) + " ," + (height + margin.top + 25) + ")") .style("text-anchor", "middle") .style("font-size", "14px") .text("rating scale"); barChartSVG.selectAll("bar") .data(data.value) .enter().append("rect") .style("fill", function(d, i) { return object.color; }) //.style("fill", object.color) .attr("x", function(d) { return x(d.bin); }) .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.number); }) .attr("height", function(d) { return height - y(d.number); }); var text1 = " "; var text2 = " "; if(object.name == "Summary") { text1 += "for all classes" } else { text1 = "for " + object.name; } if(typeof object.subscale !== "undefined") { if(object.subscale == "Overall" || object.subscale == "") { text2 += " overall average"; } else if(object.subscale == "REAL") { text2 += " Experienced Realism sub-scale average"; } else if(object.subscale == "INV") { text2 += " Involvement sub-scale average"; } else if(object.subscale == "SP") { text2 += " Spatial Presence sub-scale average"; } else if(object.subscale == "GP") { text2 += " General Presence sub-scale average"; } } else { if(typeof _category !== "undefined") { if(_category == "SP") { text2 += " Spatial Presence sub-scale average"; } else if(_category == "INV") { text2 += " Involvement sub-scale average"; } else if(_category == "REAL") { text2 += " Experienced Realism sub-scale average"; } else if(_category == "GP") { text2 += " General Presence sub-scale average"; } else { text2 += " overall average"; } } } if(object.display != "" && typeof object.display !== "undefined") { text1 += " with " + object.display; } barChartSVG.append("text") .attr("transform", "translate(" + (width/2) + " ," + (height + margin.top + 40) + ")") .attr("text-anchor", "middle") .style("font-size", "14px") .style("font-weight", "bold") .text("Distribution of" + text2 + " rating scores from previous user studies " + text1); } function UpdateInfo(stage, object, option = "") { if(stage === "main") { AddScoreBarChart(object, "#main_bar_chart_for_score"); AddYearBarChart(object, "#main_bar_chart_for_year"); WriteTable(object, "#main_list_publications"); var overallObject = currentObject.value.find(function(element) { return element.name === "Overall"; }); var summaryObject = overallObject.value.find(function(element) { return element.name === "Summary"; }); var category = ""; if(object.subscale === "") category = object.display; else category = object.subscale; $("#info_main_category").html(category); $("#info_main_participants").html(object.participants); $("#info_main_percent").html(object.percent); $("#info_main_adjective_rating").html(object.name); $("#info_main_years").html(object.years.length); $("#info_main_user_studies").html(object.user_studies.length); $("#info_main_publications").html(object.publications.length); } else if(stage === "user_data") { AddScoreBarChart(object, "#user_data_bar_chart_for_score_" + object.condition); } } function WriteTable(data, div) { var html = ""; var detailObject = data.value.find(function(element) { return element.name === "Studies"; }); html += '<div class="table-container">' + '<table class="table" id="reported_papers_table">' + '<thead>' + '<tr style="background-color: gainsboro;">' + '<th><abbr title="Title">Title</abbr></th>' + '<th><abbr title="Author">Author</abbr></th>' + '<th><abbr title="AdjectiveRating">Adjective Rating</abbr></th>' + '<th><abbr title="Score">Score</abbr></th>' + '<th><abbr title="Participants">Number of Participants</abbr></th>' + '<th><abbr title="Year">Year</abbr></th>' + '<th><abbr title="Published in">Published in</abbr></th>' + '<th><abbr title="Link">Link</abbr></th>' + '</tr>' + '</thead>' + '<tfoot>' + '<tr style="background-color: gainsboro;">' + '<th><abbr title="Title">Title</abbr></th>' + '<th><abbr title="Author">Author</abbr></th>' + '<th><abbr title="AdjectiveRating">Adjective Rating</abbr></th>' + '<th><abbr title="Score">Score</abbr></th>' + '<th><abbr title="Participants">Number of Participants</abbr></th>' + '<th><abbr title="Year">Year</abbr></th>' + '<th><abbr title="Published in">Published in</abbr></th>' + '<th><abbr title="Link">Link</abbr></th>' + '</tr>' + '</tfoot>' + '<tbody height="200px">'; var rating_scale = "Ranking_class"; if(data.subscale === "Overall") { rating_scale = 'Ranking_class'; } else if(data.subscale === "SP") { rating_scale = 'Sp_ranking_class'; } else if(data.subscale === "GP") { rating_scale = 'Gp_ranking_class'; } else if(data.subscale === "INV") { rating_scale = 'Inv_ranking_class'; } else if(data.subscale === "REAL") { rating_scale = 'Real_ranking_class'; } detailObject.value.forEach(function(e){ html = html + '<tr style="background-color:' + data.color + '">' + '<td>' + e.Title + '</td>' + '<td>' + e.Authors + '</td>' + '<td>' + e[rating_scale] + '</td>' + '<td>' + Math.round(e.Standard_total_each_item * 1000) / 1000 + '</td>' + '<td>' + e.Number_of_total_participants + '</td>' + '<td>' + e.Year + '</td>' + '<td>' + e.Source + '</td>' + '<td><a href="' + e.ArticleURL + '">Link</a></td>' + '</tr>'; }); html += '</tbody>' + '</table>' + '</div>'; $(div).html(html); } //User input var uploadedFileData = ""; var loadFile = function(event) { var input = event.target; var reader = new FileReader(); reader.onload = function(){ var dataURL = reader.result; $("#user_data_file_name").html(input.files[0].name); $("#main_page").hide(); $("#user_data_page").show(); $("#header").css('background-color', '#E9F7EF'); $("#navbar").css('background-color', '#E9F7EF'); uploadedFileData = reader.result; HandleUploadedData(); stage="user_data"; }; reader.readAsText(input.files[0]); }; function HandleUploadedData() { var uploadedDataLines = uploadedFileData.split("\n"); var research_id = "", number_of_participants = "", experiment_design = "", number_of_experimental_conditions ="", number_of_entries =""; var tmp = uploadedDataLines[0].split(","); research_id = tmp[1]; tmp = uploadedDataLines[1].split(","); experiment_design = tmp[1]; tmp = uploadedDataLines[2].split(","); number_of_experimental_conditions = tmp[1]; tmp = uploadedDataLines[3].split(","); number_of_participants = tmp[1]; tmp = uploadedDataLines[4].split(","); number_of_entries = tmp[1]; var rootUploadedData = [{'name': 'Summary', 'research_id': research_id, 'number_of_participants': number_of_participants, 'number_of_experimental_conditions': number_of_experimental_conditions, 'number_of_entries': number_of_entries}]; var rawData = {'name': 'Raw', 'value': []}; var averageData = {'name': 'Average', 'value': [ { 'name': 'Overall---AAA', 'value': [ {'name':'Overall', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]}, {'name':'GP', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]}, {'name':'SP', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]}, {'name':'INV', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]}, {'name':'REAL', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]} ] } ]}; var arrayData = {'name': 'Array', 'value': []}; var overallSPScore = 0, overallGPScore = 0, overallINVScore = 0, overallREALScore = 0; var overallSPCount = 0, overallGPCount = 0, overallINVCount = 0, overallREALCount = 0; for(var i = 7; i < parseInt(number_of_entries) + 7; i++) { var eachSPScore = 0, eachGPScore = 0, eachINVScore = 0, eachREALScore = 0; var averageSPScore = 0, averageGPScore = 0, averageINVScore = 0, averageREALScore = 0, averageEach = 0; var subStrings = uploadedDataLines[i].split(","); var participant_id = subStrings[0], visual_display = subStrings[1], experimental_condition = subStrings[2]; var item_1 = parseInt(subStrings[3]), item_2 = parseInt(subStrings[4]), item_3 = parseInt(subStrings[5]), item_4 = parseInt(subStrings[6]), item_5 = parseInt(subStrings[7]), item_6 = parseInt(subStrings[8]), item_7 = parseInt(subStrings[9]), item_8 = parseInt(subStrings[10]), item_9 = parseInt(subStrings[11]), item_10 = parseInt(subStrings[12]), item_11 = parseInt(subStrings[13]), item_12 = parseInt(subStrings[14]), item_13 = parseInt(subStrings[15]), item_14 = parseInt(subStrings[16]); var isLineValid = true; for(var j = 3; j < 17; j++) { if(subStrings[j] === "") { alert("Line " + (i + 1) + ". Score for item " + (j - 2) + " is missing! This entry will be discarded!"); isLineValid = false; } } if(isLineValid) { rawData.value.push({'participant_id': participant_id, 'visual_display': visual_display, 'experimental_condition': experimental_condition, 'item_1': item_1, 'item_2': item_2, 'item_3': item_3, 'item_4': item_4, 'item_5': item_5, 'item_6': item_6, 'item_7': item_7, 'item_8': item_8, 'item_9': item_9, 'item_10': item_10, 'item_11': item_11, 'item_12': item_12, 'item_13': item_13, 'item_14': item_14}); eachSPScore += item_3 - item_6 + item_9 + item_10 - item_13; eachGPScore += item_8; eachINVScore += item_1 + item_7 - item_11 + item_14; eachREALScore += item_2 + item_4 + item_5 + item_12; averageSPScore = eachSPScore / 5; averageGPScore = eachGPScore / 1; averageINVScore = eachINVScore / 4; averageREALScore = eachREALScore / 4; averageEach = (eachSPScore + eachGPScore + eachINVScore + eachREALScore) / 14; overallSPScore += eachSPScore; overallGPScore += eachGPScore; overallINVScore += eachINVScore; overallREALScore += eachREALScore; overallSPCount += 5; overallGPCount += 1; overallINVCount += 4; overallREALCount += 4; var consideredObject = ['Overall---AAA']; if(number_of_experimental_conditions > 1) { consideredObject.push(experimental_condition); } consideredObject.forEach(function(obj){ var conditionObject = averageData.value.find(function(e){ return e.name.replace(/\s/g,'') === obj.replace(/\s/g,''); }); if(conditionObject === undefined) { conditionObject = { 'name': experimental_condition, 'value': [ {'name':'Overall', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]}, {'name':'GP', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]}, {'name':'SP', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]}, {'name':'INV', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]}, {'name':'REAL', 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]} ] }; averageData.value.push(conditionObject); } var displayObject = conditionObject.value.find(function(e){ return e.name === visual_display; }); if(displayObject === undefined) { conditionObject.value.push({'name': visual_display, 'adjective_rating': '---', 'count': 0, 'total': 0, 'average': 0, 'value':[]}); } conditionObject.value.forEach(function(e){ var eachObject = e.value.find(function(e1) { return e1.name === experimental_condition; }); if(eachObject === undefined) { eachObject = {"name": experimental_condition, "value":[], "participants": []}; e.value.push(eachObject); } eachObject.participants.push(participant_id); if(e.name === "Overall" || e.name === visual_display) { eachObject.value.push(averageEach); e.count += 14; e.total += eachSPScore + eachGPScore + eachINVScore + eachREALScore; } else if(e.name === "GP") { eachObject.value.push(averageGPScore); e.count += 1; e.total += eachGPScore; } else if(e.name === "SP") { eachObject.value.push(averageSPScore); e.count += 5; e.total += eachSPScore; } else if(e.name === "INV") { eachObject.value.push(averageINVScore); e.count += 4; e.total += eachINVScore; } else if(e.name === "REAL") { eachObject.value.push(averageREALScore); e.count += 4; e.total += eachREALScore; } }); }); var retObject = arrayData.value.find(function(e) { return e.name === experimental_condition; }); if(retObject === undefined) { retObject = {"name": experimental_condition, "value":[], "participants": []}; arrayData.value.push(retObject); } for(var j = 0; j < 14; j++) { retObject.participants.push(participant_id); } retObject.value.push(item_1,item_2); retObject.value.push(item_3); retObject.value.push(item_4); retObject.value.push(item_5); retObject.value.push((-1) * item_6); retObject.value.push(item_7); retObject.value.push(item_8); retObject.value.push(item_9); retObject.value.push(item_10); retObject.value.push((-1) * item_11); retObject.value.push(item_12); retObject.value.push((-1) * item_13); retObject.value.push(item_14); } } averageData.value.forEach(function(c) { c.value.forEach(function(e){ e.average = Math.round (e.total / e.count * 1000) / 1000; var adjectiveRating = "---"; var average_score = e.average; var retObject = adjective_ratings.find(function(ea){ return ea.name.replace(/\s/g,'') === e.name.replace(/\s/g,'') }); if(retObject !== undefined) { retObject.ranges.forEach(function(r) { if(r.name === 'Class VI' && average_score >= r.from && average_score < r.to) { adjectiveRating = 'Class VI'; } else if(r.name === 'Class V' && average_score >= r.from && average_score < r.to) { adjectiveRating = 'Class V'; } else if(r.name === 'Class IV' && average_score >= r.from && average_score < r.to) { adjectiveRating = 'Class IV'; } else if(r.name === 'Class III' && average_score >= r.from && average_score <= r.to) { adjectiveRating = 'Class III'; } else if(r.name === 'Class II' && average_score > r.from && average_score <= r.to) { adjectiveRating = 'Class II'; } else if(r.name === 'Class I' && average_score > r.from && average_score <= r.to) { adjectiveRating = 'Class I'; } // else if(r.name === "Best" && average_score > r.from && average_score <= r.to) // { // adjectiveRating = "Best"; // } }); } e.adjective_rating = adjectiveRating; }); }); rootUploadedData.push(rawData); rootUploadedData.push(averageData); //Generate HTML var html = ""; $("#user_data_summary").empty(); for(var i = 0; i < averageData.value.length; i++) { html = ""; html += `<div class="row" style="margin-bottom: 10px; background-color: ` + layout_colors[i] + `;"> <section class="section"> <div class="container"> <div class="columns">`; if(averageData.value[i].name === "Overall---AAA") { html += ` <div class="column is-4 has-text-centered"> <div class="box"> <h2 class="subtitle"> <h1 class="title">Whole Experiment</h1> </h2> </div> </div>`; } else { html += ` <div class="column is-4 has-text-centered"> <div class="box"> <h2 class="subtitle"> Condition <h1 class="title">` + averageData.value[i].name + `</h1> </h2> </div> </div>`; } html += ` <div class="column"></div> <div class="column is-8"> <div class="container"> <nav class="level is-mobile"> <div class="level-item has-text-centered is-small"> <div> <p class="heading">OVERALL</p> <p class="title" id="info_user_data_overall_` + averageData.value[i].name + `">...</p> </div> </div> <div class="level-item has-text-centered"> <div> <p class="heading">GENERAL PRESENCE</p> <p class="title" id="info_user_data_gp_` + averageData.value[i].name + `">...</p> </div> </div> <div class="level-item has-text-centered"> <div> <p class="heading">SPATIAL PRESENCE</p> <p class="title" id="info_user_data_sp_` + averageData.value[i].name + `">...</p> </div> </div> <div class="level-item has-text-centered"> <div> <p class="heading">INVOLVEMENT</p> <p class="title" id="info_user_data_inv_` + averageData.value[i].name + `">...</p> </div> </div> <div class="level-item has-text-centered_` + averageData.value[i].name + `"> <div> <p class="heading">EXPERIENCE REALISM</p> <p class="title" id="info_user_data_real_` + averageData.value[i].name + `">...</p> </div> </div> </nav> </div> </div> </div> </div> </section> <div class='row'> <div class="columns"> <div class="column"></div> <div class="column is-11"> <div class="box"> <div class="columns"> <div class="column has-text-centered is-4" > <div class="row" id="user_data_pie_chart_` + averageData.value[i].name + `"> </div> </div> <div class="column has-text-centered is-8"> <div class="row"> <div class="columns"> <div class="column has-text-centered is-3" id="user_data_gp_pie_chart_` + averageData.value[i].name + `"> </div> <div class="column has-text-centered is-3" id="user_data_sp_pie_chart_` + averageData.value[i].name + `"> </div> <div class="column has-text-centered is-3" id="user_data_inv_pie_chart_` + averageData.value[i].name + `"> </div> <div class="column has-text-centered is-3" id="user_data_real_pie_chart_` + averageData.value[i].name + `"> </div> </div> </div> <div class="row"> <div class="columns"> <div class="column has-text-centered is-3" id="user_data_hmd_pie_chart_` + averageData.value[i].name + `"> </div> <div class="column has-text-centered is-3" id="user_data_monoscopic_pie_chart_` + averageData.value[i].name + `"> </div> <div class="column has-text-centered is-3" id="user_data_projectiondisplay_pie_chart_` + averageData.value[i].name + `"> </div> <div class="column has-text-centered is-3" id="user_data_appendix_` + averageData.value[i].name + `"> </div> </div> </div> </div> </div> </div> </div> <div class="column"></div> </div> </div> <div class="row"> <div class="columns"> <div class="column"> </div> <div class="column is-11 is-centered"> <div class="columns"> <div class="column is-5 is-vcentered"> <div class="box summary-text" class="" id="user_data_text_report_` + averageData.value[i].name + `"> </div> </div> <div class="column is-7"> <div class="box" class="" id="user_data_bar_chart_for_score_` + averageData.value[i].name + `"> </div> </div> </div> </div> <div class="column"> </div> </div> </div> </div>`; $("#user_data_summary").append(html); $("#info_user_data_overall_" + averageData.value[i].name).html(averageData.value[i].value[0].adjective_rating); $("#info_user_data_gp_" + averageData.value[i].name).html(averageData.value[i].value[1].adjective_rating); $("#info_user_data_sp_" + averageData.value[i].name).html(averageData.value[i].value[2].adjective_rating); $("#info_user_data_inv_" + averageData.value[i].name).html(averageData.value[i].value[3].adjective_rating); $("#info_user_data_real_" + averageData.value[i].name).html(averageData.value[i].value[4].adjective_rating); var user_data_report_text = ""; if(i === 0) { var user_data_report_text = '<p>In general, the analysis on IPQ scores showed that this experiment provided users with level "' + averageData.value[i].value[0].adjective_rating + '" of presence in comparison with previous user studies. For more details, the level presence for sub-scales of IPQ including general presence, spatial presence, involvement, and experience realism are "' + averageData.value[0].value[1].adjective_rating + '", "' + averageData.value[0].value[2].adjective_rating + '", "' + averageData.value[0].value[3].adjective_rating + '", and "' + averageData.value[0].value[4].adjective_rating + '", ' + ' respectively. '; if(averageData.value[0].value.length > 5) { user_data_report_text += 'The ' + averageData.value[0].value[5].name + ' visual display used in this study provided a "' + averageData.value[0].value[5].adjective_rating + '" level of presence. '; } if(averageData.value[0].value.length > 6) { user_data_report_text += 'In addition, users perceived presence at level "' + averageData.value[0].value[6].adjective_rating + '" when they experienced with the ' + averageData.value[0].value[6].name + ' display. '; } if(averageData.value[0].value.length > 7) { user_data_report_text += 'For the ' + averageData.value[0].value[7].name + ' visual display, the level of presence was eventually at "' + averageData.value[0].value[7].adjective_rating + '" in comparison with previous studies using the same technology. '; } user_data_report_text += '</p>'; } else if(i === 1) { var user_data_report_text = '<p>Condition ' + averageData.value[i].name + ' generally present users with "' + averageData.value[i].value[0].adjective_rating + '" level of presence. In addition, the classes for general presence and spatial presence are "' + averageData.value[0].value[1].adjective_rating + '" and "' + averageData.value[0].value[2].adjective_rating + '", respectively. "' + averageData.value[0].value[3].adjective_rating + '" and "' + averageData.value[0].value[4].adjective_rating + '" are, furthermore, categories for involvement and experience realism.</p>'; } else if(i === 2) { var user_data_report_text = '<p>Users reported that they perceived the "' + averageData.value[i].value[0].adjective_rating + '" level of presence in condition ' + averageData.value[i].name + '. In this condition, the level of presence for general presence was "' + averageData.value[0].value[1].adjective_rating + '" and "' + averageData.value[0].value[2].adjective_rating + '" was the level of presence of spatial presence. While involvement sub-scale had level "' + averageData.value[0].value[3].adjective_rating + '" of presence, "' + averageData.value[0].value[4].adjective_rating + '" is the class for experience realism.</p>'; } $("#user_data_text_report_" + averageData.value[i].name).html(user_data_report_text); var width = 0.85 * $("#user_data_pie_chart_" + averageData.value[i].name).width(); IllustrateUserData(Object.assign({}, overallObject), width, width, "#user_data_pie_chart_" + averageData.value[i].name, averageData.value[i].value[0], averageData.value[i].name); subscalesObject.value.forEach(function(e) { var div = "#user_data_sp_pie_chart_" + averageData.value[i].name; if(e.name === "SP") { div = "#user_data_sp_pie_chart_" + averageData.value[i].name; } else if(e.name === "GP") { div = "#user_data_gp_pie_chart_" + averageData.value[i].name; } else if(e.name === "INV") { div = "#user_data_inv_pie_chart_" + averageData.value[i].name; } else if(e.name === "REAL") { div = "#user_data_real_pie_chart_" + averageData.value[i].name; } width = 0.85 * $(div).width(); averageData.value[i].value.forEach(function(f){ if(e.name === f.name) { IllustrateUserData(Object.assign({}, e), width, width, div, f, averageData.value[i].name); } }); }); visualDisplaysObject.value.forEach(function(e) { var div = ""; if(e.name.replace(/\s/g,'') === ("3D - HMD VR").replace(/\s/g,'')) { div = "#user_data_hmd_pie_chart_" + averageData.value[i].name; } else if(e.name.replace(/\s/g,'') === ("3D - Monoscopic").replace(/\s/g,'')) { div = "#user_data_monoscopic_pie_chart_" + averageData.value[i].name; } else if(e.name === "Projection Display_" + averageData.value[i].name) { div = "#user_data_projectiondisplay_pie_chart"; } if(div != "") { width = 0.85 * $(div).width(); averageData.value[i].value.forEach(function(f){ if(e.name.replace(/\s/g,'') === f.name.replace(/\s/g,'')) { IllustrateUserData(Object.assign({}, e), width, width, div, f, averageData.value[i].name); } }); } }); AddAppendix(true, "#user_data_appendix_" + averageData.value[i].name); } //ANALYSIS document.getElementById("analysis_code").innerHTML = '<p class="code">Initializing...</p><br><p class="code" style="font-size: 10px;">(might be up to 2 minutes)</p><br><button class="button is-info is-loading is-large">Initializing...</button>'; //Statistics var code = ` ## import libraries #import io #import base64 #import numpy as np #from scipy import stats #import pandas as pd #import statsmodels.stats.api as sm #from statsmodels.stats.anova import AnovaRM #from statsmodels.regression.mixed_linear_model import MixedLM #from statsmodels.formula.api import ols #import matplotlib.pyplot as plt #from js import window, eval as jseval data = ` + JSON.stringify(arrayData.value) + ` alpha = 0.05 is_normal_distribution = True number_conditions = ` + number_of_experimental_conditions + ` standard_total_each_item = [` + standard_total_each_item + `] standard_sp_each_item = [` + standard_sp_each_item+ `] standard_inv_each_item = [` + standard_inv_each_item+ `] standard_real_each_item = [` + standard_real_each_item+ `] standard_gp_each_item = [` + standard_gp_each_item+ `] standard_total_each_item_hmd = [` + standard_total_each_item_hmd+ `] standard_total_each_item_mono = [` + standard_total_each_item_mono+ `] standard_total_each_item_proj = [` + standard_total_each_item_proj+ `] standard_total_each_item.sort() standard_sp_each_item.sort() standard_inv_each_item.sort() standard_real_each_item.sort() standard_gp_each_item.sort() standard_total_each_item_hmd.sort() standard_total_each_item_mono.sort() standard_total_each_item_proj.sort() ## compute quantiles print("Quantiles for overall scores") print(stats.mstats.mquantiles(standard_total_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) print("Quantiles for SP scores") print(stats.mstats.mquantiles(standard_sp_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) print("Quantiles for INV scores") print(stats.mstats.mquantiles(standard_inv_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) print("Quantiles for REAL scores") print(stats.mstats.mquantiles(standard_real_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) print("Quantiles for GP scores") print(stats.mstats.mquantiles(standard_gp_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) print("Quantiles for 3D - HMD scores") print(stats.mstats.mquantiles(standard_total_each_item_hmd, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) print("Quantiles for 3D - Monoscopic scores") print(stats.mstats.mquantiles(standard_total_each_item_mono, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) print("Quantiles for Projection Display scores") print(stats.mstats.mquantiles(standard_total_each_item_proj, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) ## logging document = window.document`; if(number_of_experimental_conditions == 2) { code += ` document.getElementById("header_analysis_statistics").innerHTML = '<div class="container"> <div class="columns"> <div class="column"></div> <div class="column is-6 has-text-centered"> <div class="box"> <h1 class="title">ANALYSIS STATISTICS</h1> </div> </div> <div class="column"></div> <div class="column is-6"> <div class="box has-text-centered" style="background-color: #F8F9F9;" id="analysis_methods"> <table class="table"> <thead> <tr> <th rowspan="2">Experiment Design</th> <th colspan="2">Data Distribution</th> </tr> <tr> <th>Normal</th> <th>Non-normal</th> </tr> </thead> <tbody> <tr> <th>Between-subject</th> <td id="between_subject_anova">Between-subjects ANOVA</td> <td id="mann_whitneyu">Mann-Whitney U</td> </tr> <tr> <th>Within-subject</th> <td id="within_subject_anova">Repeated-measures ANOVA</td> <td id="wilcoxon_signed_rank">Wilcoxon Signed-Rank</td> </tr> </tbody> </table> </div> </div> <div class="column"></div> </div></div>'`; } code += ` analysis_code = document.getElementById("analysis_code") analysis_code.style.textAlign = "left" analysis_code.innerHTML = '<p class="code comment"> ## import libraries<p>' analysis_code.innerHTML += '<p class="code"> import numpy as np<p>' analysis_code.innerHTML += '<p class="code"> from scipy import stats<p>' analysis_code.innerHTML += '<p class="code"> import pandas as pd<p>' analysis_code.innerHTML += '<p class="code"> import statsmodels.stats.api as sm<p>' analysis_code.innerHTML += '<p class="code"> from statsmodels.stats.anova import AnovaRM<p>' analysis_code.innerHTML += '<p class="code"> from statsmodels.formula.api import ols<p>' analysis_code.innerHTML += '<p class="code"> import matplotlib.pyplot as mlplot<p>' analysis_code.innerHTML += '<p class="code"> data = ' + str(data) + '<p>' analysis_code.innerHTML += '<p class="code"> alpha = 0.05<p>' analysis_code.innerHTML += '<p class="code"> is_normal_distribution = True<p></br>' analysis_code.innerHTML += '<p class="code"> standard_total_each_item = ' + str(standard_total_each_item) + '<p>' analysis_code.innerHTML += '<p class="code"> standard_sp_each_item = ' + str(standard_sp_each_item) + '<p>' analysis_code.innerHTML += '<p class="code"> standard_inv_each_item = ' + str(standard_inv_each_item) + '<p>' analysis_code.innerHTML += '<p class="code"> standard_real_each_item = ' + str(standard_real_each_item) + '<p>' analysis_code.innerHTML += '<p class="code"> standard_gp_each_item = ' + str(standard_gp_each_item) + '<p>' analysis_code.innerHTML += '<p class="code"> standard_total_each_item_hmd = ' + str(standard_total_each_item_hmd) + '<p>' analysis_code.innerHTML += '<p class="code"> standard_total_each_item_mono = ' + str(standard_total_each_item_mono) + '<p>' analysis_code.innerHTML += '<p class="code"> standard_total_each_item_proj = ' + str(standard_total_each_item_proj) + '<p>' ## compute quantiles analysis_code.innerHTML += '<p class="comment code"> # percentiles at 50th, 75th, 90th, 95th, and 99th for overall scores <p>' analysis_code.innerHTML += '<p class="code"> print(stats.mstats.mquantiles(standard_total_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0))<p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(stats.mstats.mquantiles(standard_total_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) + '<p>' analysis_code.innerHTML += '<p class="comment code"> # percentiles at 50th, 75th, 90th, 95th, and 99th for SP scores <p>' analysis_code.innerHTML += '<p class="code"> print(stats.mstats.mquantiles(standard_sp_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0))<p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(stats.mstats.mquantiles(standard_sp_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) + '<p>' analysis_code.innerHTML += '<p class="comment code"> # percentiles at 50th, 75th, 90th, 95th, and 99th for INV scores <p>' analysis_code.innerHTML += '<p class="code"> print(stats.mstats.mquantiles(standard_inv_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0))<p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(stats.mstats.mquantiles(standard_inv_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) + '<p>' analysis_code.innerHTML += '<p class="comment code"> # percentiles at 50th, 75th, 90th, 95th, and 99th for REAL scores <p>' analysis_code.innerHTML += '<p class="code"> print(stats.mstats.mquantiles(standard_real_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0))<p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(stats.mstats.mquantiles(standard_real_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) + '<p>' analysis_code.innerHTML += '<p class="comment code"> # percentiles at 50th, 75th, 90th, 95th, and 99th for GP scores <p>' analysis_code.innerHTML += '<p class="code"> print(stats.mstats.mquantiles(standard_gp_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0))<p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(stats.mstats.mquantiles(standard_gp_each_item, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) + '<p>' analysis_code.innerHTML += '<p class="comment code"> # percentiles at 50th, 75th, 90th, 95th, and 99th for 3D - HMD scores <p>' analysis_code.innerHTML += '<p class="code"> print(stats.mstats.mquantiles(standard_total_each_item_hmd, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0))<p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(stats.mstats.mquantiles(standard_total_each_item_hmd, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) + '<p>' analysis_code.innerHTML += '<p class="comment code"> # percentiles at 50th, 75th, 90th, 95th, and 99th for 3D - Monoscopic scores <p>' analysis_code.innerHTML += '<p class="code"> print(stats.mstats.mquantiles(standard_total_each_item_mono, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0))<p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(stats.mstats.mquantiles(standard_total_each_item_mono, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) + '<p>' analysis_code.innerHTML += '<p class="comment code"> # percentiles at 50th, 75th, 90th, 95th, and 99th for Projection Display scores <p>' analysis_code.innerHTML += '<p class="code"> print(stats.mstats.mquantiles(standard_total_each_item_proj, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0))<p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(stats.mstats.mquantiles(standard_total_each_item_proj, prob=[0.5, 0.75, 0.90, 0.95, 0.99], alphap = 0, betap = 0)) + '<p>' `; if(number_of_experimental_conditions < 3) { var overallScoreObject = averageData.value[0].value.find(function(e){ return e.name === "Overall"; }); var spScoreObject = averageData.value[0].value.find(function(e){ return e.name === "SP"; }); var gpScoreObject = averageData.value[0].value.find(function(e){ return e.name === "GP"; }); var realScoreObject = averageData.value[0].value.find(function(e){ return e.name === "REAL"; }); var invScoreObject = averageData.value[0].value.find(function(e){ return e.name === "INV"; }); code += ` ## assign data to variable analysis_code.innerHTML += '<p class="code comment"> ## assign data to variable<p>' whole_experiment_overall = [] whole_experiment_gp = [] whole_experiment_sp = [] whole_experiment_inv = [] whole_experiment_real = [] analysis_code.innerHTML += '<p class="code"> whole_experiment_overall = []<p>' analysis_code.innerHTML += '<p class="code"> whole_experiment_gp = []<p>' analysis_code.innerHTML += '<p class="code"> whole_experiment_sp = []<p>' analysis_code.innerHTML += '<p class="code"> whole_experiment_inv = []<p>' analysis_code.innerHTML += '<p class="code"> whole_experiment_real = []<p>' `; var fullAverageArray = []; for(var i = 1; i <= number_of_experimental_conditions; i++) { code += ` ## init variable ` + i + ` variable_` + i + `_name = "` + overallScoreObject.value[i-1].name + `" variable_` + i + `_value_overall = ` + JSON.stringify(overallScoreObject.value[i-1].value) + ` variable_` + i + `_participantsid_overall = ` + JSON.stringify(overallScoreObject.value[i-1].participants) + ` variable_` + i + `_mean_overall = round(np.mean(variable_` + i + `_value_overall), 3) variable_` + i + `_std_overall = round(np.std(variable_` + i + `_value_overall), 3) whole_experiment_overall += variable_` + i + `_value_overall variable_` + i + `_value_gp = ` + JSON.stringify(gpScoreObject.value[i-1].value) + ` variable_` + i + `_participantsid_gp = ` + JSON.stringify(gpScoreObject.value[i-1].participants) + ` variable_` + i + `_mean_gp = round(np.mean(variable_` + i + `_value_gp), 3) variable_` + i + `_std_gp = round(np.std(variable_` + i + `_value_gp), 3) whole_experiment_gp += variable_` + i + `_value_gp variable_` + i + `_value_sp = ` + JSON.stringify(spScoreObject.value[i-1].value) + ` variable_` + i + `_participantsid_sp = ` + JSON.stringify(spScoreObject.value[i-1].participants) + ` variable_` + i + `_mean_sp = round(np.mean(variable_` + i + `_value_sp), 3) variable_` + i + `_std_sp = round(np.std(variable_` + i + `_value_sp), 3) whole_experiment_sp += variable_` + i + `_value_sp variable_` + i + `_value_inv = ` + JSON.stringify(invScoreObject.value[i-1].value) + ` variable_` + i + `_participantsid_inv = ` + JSON.stringify(invScoreObject.value[i-1].participants) + ` variable_` + i + `_mean_inv = round(np.mean(variable_` + i + `_value_inv), 3) variable_` + i + `_std_inv = round(np.std(variable_` + i + `_value_inv), 3) whole_experiment_inv += variable_` + i + `_value_inv variable_` + i + `_value_real = ` + JSON.stringify(realScoreObject.value[i-1].value) + ` variable_` + i + `_participantsid_real = ` + JSON.stringify(realScoreObject.value[i-1].participants) + ` variable_` + i + `_mean_real = round(np.mean(variable_` + i + `_value_real), 3) variable_` + i + `_std_real = round(np.std(variable_` + i + `_value_real), 3) whole_experiment_real += variable_` + i + `_value_real print(variable_` + i + `_name + " ( M = " + str(variable_` + i + `_mean_overall) + ", SD = " + str(variable_` + i + `_std_overall) + ")") ## calculate percentiles percentile_variable_` + i + `_overall = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_overall)) percentile_variable_` + i + `_sp = stats.percentileofscore(standard_sp_each_item, np.average(variable_` + i + `_value_sp)) percentile_variable_` + i + `_inv = stats.percentileofscore(standard_inv_each_item, np.average(variable_` + i + `_value_inv)) percentile_variable_` + i + `_real = stats.percentileofscore(standard_real_each_item, np.average(variable_` + i + `_value_real)) percentile_variable_` + i + `_gp = stats.percentileofscore(standard_gp_each_item, np.average(variable_` + i + `_value_gp)) print("Percentiles for condition: " + variable_` + i + `_name) print("Overall score percentile: " + str(percentile_variable_` + i + `_overall)) print("SP score percentile: " + str(percentile_variable_` + i + `_sp)) print("INV score percentile: " + str(percentile_variable_` + i + `_inv)) print("REAL score percentile: " + str(percentile_variable_` + i + `_real)) print("GP score percentile: " + str(percentile_variable_` + i + `_gp)) analysis_code.innerHTML += '<p class="comment code"> # calculate percentiles for ' + variable_` + i + `_name + '</p>' analysis_code.innerHTML += '<p class="code"> percentile_variable_` + i + `_overall = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_overall))</p>' analysis_code.innerHTML += '<p class="code"> print("Overall score percentile: " + str(percentile_variable_` + i + `_overall))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_variable_` + i + `_overall) + '</p><br>' analysis_code.innerHTML += '<p class="code"> percentile_variable_` + i + `_sp = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_sp))</p>' analysis_code.innerHTML += '<p class="code"> print("SP score percentile: " + str(percentile_variable_` + i + `_sp))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_variable_` + i + `_sp) + '</p><br>' analysis_code.innerHTML += '<p class="code"> percentile_variable_` + i + `_inv = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_inv))</p>' analysis_code.innerHTML += '<p class="code"> print("INV score percentile: " + str(percentile_variable_` + i + `_inv))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_variable_` + i + `_inv) + '</p><br>' analysis_code.innerHTML += '<p class="code"> percentile_variable_` + i + `_real = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_real))</p>' analysis_code.innerHTML += '<p class="code"> print("REAL score percentile: " + str(percentile_variable_` + i + `_real))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_variable_` + i + `_real) + '</p><br>' analysis_code.innerHTML += '<p class="code"> percentile_variable_` + i + `_gp = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_gp))</p>' analysis_code.innerHTML += '<p class="code"> print("GP score percentile: " + str(percentile_variable_` + i + `_gp))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_variable_` + i + `_gp) + '</p><br>' analysis_code.innerHTML += '<p class="code comment"> ## init variable ` + i + `<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_name = "' + variable_` + i + `_name + '"<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value_overall = ' + str(variable_` + i + `_value_overall) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid_overall = ' + str(variable_` + i + `_participantsid_overall) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean_overall = ' + str(round(np.mean(variable_` + i + `_value_overall), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std_overall = ' + str(round(np.std(variable_` + i + `_value_overall), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> whole_experiment_overall += variable_` + i + `_value_overall<p><br/>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value_gp = ' + str(variable_` + i + `_value_gp) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid_gp = ' + str(variable_` + i + `_participantsid_gp) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean_gp = ' + str(round(np.mean(variable_` + i + `_value_gp), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std_gp = ' + str(round(np.std(variable_` + i + `_value_gp), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> whole_experiment_gp += variable_` + i + `_value_gp<p><br/>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value_sp = ' + str(variable_` + i + `_value_sp) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid_sp = ' + str(variable_` + i + `_participantsid_sp) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean_sp = ' + str(round(np.mean(variable_` + i + `_value_sp), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std_sp = ' + str(round(np.std(variable_` + i + `_value_sp), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> whole_experiment_sp += variable_` + i + `_value_sp<p><br/>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value_inv = ' + str(variable_` + i + `_value_inv) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid_inv = ' + str(variable_` + i + `_participantsid_inv) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean_inv = ' + str(round(np.mean(variable_` + i + `_value_inv), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std_inv = ' + str(round(np.std(variable_` + i + `_value_inv), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> whole_experiment_inv += variable_` + i + `_value_inv<p><br/>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value_real = ' + str(variable_` + i + `_value_real) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid_real = ' + str(variable_` + i + `_participantsid_real) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean_real = ' + str(round(np.mean(variable_` + i + `_value_real), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std_real = ' + str(round(np.std(variable_` + i + `_value_real), 3)) + '<p>' analysis_code.innerHTML += '<p class="code"> whole_experiment_real += variable_` + i + `_value_real<p><br/>' `; } code += ` ## whole experiment: calculate percentiles percentile_whole_experiment_overall = stats.percentileofscore(standard_total_each_item, np.average(whole_experiment_overall)) percentile_whole_experiment_sp = stats.percentileofscore(standard_sp_each_item, np.average(whole_experiment_sp)) percentile_whole_experiment_inv = stats.percentileofscore(standard_inv_each_item, np.average(whole_experiment_inv)) percentile_whole_experiment_real = stats.percentileofscore(standard_real_each_item, np.average(whole_experiment_real)) percentile_whole_experiment_gp = stats.percentileofscore(standard_gp_each_item, np.average(whole_experiment_gp)) print("Percentiles for the whole experiment:") print("Overall score percentile: " + str(percentile_whole_experiment_overall)) print(str("SP score percentile: " + str(percentile_whole_experiment_sp))) print("INV score percentile: " + str(percentile_whole_experiment_inv)) print("REAL score percentile: " + str(percentile_whole_experiment_real)) print("GP score percentile: " + str(percentile_whole_experiment_gp)) analysis_code.innerHTML += '<p class="comment code"> # calculate percentiles for the whole experiment</p>' analysis_code.innerHTML += '<p class="code"> percentile_whole_experiment_overall = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_overall))</p>' analysis_code.innerHTML += '<p class="code"> print("Overall score percentile: " + str(percentile_whole_experiment_overall))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_whole_experiment_overall) + '</p><br>' analysis_code.innerHTML += '<p class="code"> percentile_whole_experiment_sp = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_sp))</p>' analysis_code.innerHTML += '<p class="code"> print("SP score percentile: " + str(percentile_whole_experiment_sp))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_whole_experiment_sp) + '</p><br>' analysis_code.innerHTML += '<p class="code"> percentile_whole_experiment_inv = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_inv))</p>' analysis_code.innerHTML += '<p class="code"> print("INV score percentile: " + str(percentile_whole_experiment_inv))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_whole_experiment_inv) + '</p><br>' analysis_code.innerHTML += '<p class="code"> percentile_whole_experiment_real = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_real))</p>' analysis_code.innerHTML += '<p class="code"> print("REAL score percentile: " + str(percentile_whole_experiment_real))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_whole_experiment_real) + '</p><br>' analysis_code.innerHTML += '<p class="code"> percentile_whole_experiment_gp = stats.percentileofscore(standard_total_each_item, np.average(variable_` + i + `_value_gp))</p>' analysis_code.innerHTML += '<p class="code"> print("GP score percentile: " + str(percentile_whole_experiment_gp))</p>' analysis_code.innerHTML += '<p class="code" style="background-color: white;"> &nbsp;' + str(percentile_whole_experiment_gp) + '</p><br>' `; code += ` ## draw boxplot function def draw_boxplot(data, edge_color, fill_color, position = [0]): bp = ax.boxplot(data, widths = 0.35, patch_artist=True, showmeans=True, positions=position) for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']: plt.setp(bp[element], color=edge_color) for patch in bp['boxes']: patch.set(facecolor=fill_color) return bp ## prepare data to plot conditions_values = [] conditions_values.append([whole_experiment_overall, whole_experiment_gp, whole_experiment_sp, whole_experiment_inv, whole_experiment_real]) ## init boxplot x-axis groups bp_xgroups = ["Whole Experiment"] `; if(number_of_experimental_conditions > 1) { for(var i = 1; i <= number_of_experimental_conditions; i++) { code += ` bp_xgroups.append(variable_` + i + `_name) conditions_values.append([variable_` + i + `_value_overall, variable_` + i + `_value_gp, variable_` + i + `_value_sp, variable_` + i + `_value_inv, variable_` + i + `_value_real]) `; } } code += ` print(conditions_values) bp_colors = ["#D2B4DE", "#A9CCE3", "#A3E4D7", "#F9E79F", "#F5CBA7"] bp_xlabels = ["Overall", "General Presence", "Spatial Presence", "Involvement", "Experience Realism"] left = 0.25 bottom = 0.25 right = 0.75 top = 0.75 width = 11.811 height = 3.93701 print("left: ", left) print("right: ", right) print("top: ", top) print("bottom: ", bottom) fig, ax = plt.subplots(figsize=(width, height)) plt.subplots_adjust(left=left, bottom=bottom, right=right, top=top, wspace=0.5) ax.set_xlabel('Igroup Presence Questionnaire', fontsize=12) ax.set_ylabel('score rating scale', fontsize=12) def generate_positions(init_pos, ngroups): bp_positions = [] for i in range(0, len(bp_xlabels)): bp_positions.append(i * (ngroups + 1) + init_pos) return bp_positions boxplots = [] legends = [] for i in range(0, len(bp_xgroups)): print(conditions_values[i]) positions = generate_positions(i+1, len(bp_xgroups)) print("positions: ", positions) bp = draw_boxplot(conditions_values[i], "black", bp_colors[i], positions) boxplots.append(bp) legends.append(bp["boxes"][0]) print("legends: ", legends) ax.legend(legends, bp_xgroups, loc='upper right') x_ticks = [0] for i in range(0, len(bp_xlabels)): x = 0 for j in range(0, len(bp_xgroups)): x = x + (len(bp_xgroups) + 1) * i + 1 + j x = x / len(bp_xgroups) x_ticks.append(x) print(x_ticks) bp_xlabels = [""] + bp_xlabels ax.set_xticks(x_ticks) ax.set_xticklabels(bp_xlabels) ax.set_ylim(-3, 3) plt.tight_layout() plt.show() def export_figure_to_base64(fig): png = io.BytesIO() fig.savefig(png, format='png', bbox_inches='tight') png.seek(0) return base64.b64encode(png.getvalue()) exported_fig = export_figure_to_base64(fig) html = '<img src="data:image/png;base64, {}">'.format(exported_fig.decode('utf-8')) html = '<br>' + html + '<br>' analysis_code.innerHTML += html whole_analysis_report_text = "" `; for(var j = 0; j < 5; j++) { if(j === 0) { code += ` current_scale = "overall" ## analyse overall score data analysis_code.innerHTML += '<p class="code comment"> ## analyse overall score data<p>' `; } else if(j === 1) { code += ` current_scale = "general_presence" ## analyse general presence score data analysis_code.innerHTML += '<p class="code comment"> ## analyse general presence score data<p>' `; } else if(j === 2) { code += ` current_scale = "spatial_presence" ## analyse spatial presence score data analysis_code.innerHTML += '<p class="code comment"> ## analyse spatial presence score data<p>' `; } else if(j === 3) { code += ` current_scale = "involvement" ## analyse involvement score data analysis_code.innerHTML += '<p class="code comment"> ## analyse involvement score data<p>' `; } else { code += ` current_scale = "experience_realism" ## analyse experience realism score data analysis_code.innerHTML += '<p class="code comment"> ## analyse experience realism score data<p>' `; } for(var i = 1; i <= number_of_experimental_conditions; i++) { if(j === 0) { code += ` variable_` + i + `_value = variable_` + i + `_value_overall variable_` + i + `_participantsid = variable_` + i + `_participantsid_overall variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_overall), 3) variable_` + i + `_std = round(np.std(variable_` + i + `_value_overall), 3) analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value = variable_` + i + `_value_overall<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid = variable_` + i + `_participantsid_overall<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_overall), 3)<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std = round(np.std(variable_` + i + `_value_overall), 3)<p>' `; } else if(j === 1) { code += ` variable_` + i + `_value = variable_` + i + `_value_gp variable_` + i + `_participantsid = variable_` + i + `_participantsid_gp variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_gp), 3) variable_` + i + `_std = round(np.std(variable_` + i + `_value_gp), 3) analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value = variable_` + i + `_value_gp<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid = variable_` + i + `_participantsid_gp<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_gp), 3)<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std = round(np.std(variable_` + i + `_value_gp), 3)<p>' `; } else if(j === 2) { code += ` variable_` + i + `_value = variable_` + i + `_value_sp variable_` + i + `_participantsid = variable_` + i + `_participantsid_sp variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_sp), 3) variable_` + i + `_std = round(np.std(variable_` + i + `_value_sp), 3) analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value = variable_` + i + `_value_sp<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid = variable_` + i + `_participantsid_sp<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_sp), 3)<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std = round(np.std(variable_` + i + `_value_sp), 3)<p>' `; } else if(j === 3) { code += ` variable_` + i + `_value = variable_` + i + `_value_inv variable_` + i + `_participantsid = variable_` + i + `_participantsid_inv variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_inv), 3) variable_` + i + `_std = round(np.std(variable_` + i + `_value_inv), 3) analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value = variable_` + i + `_value_inv<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid = variable_` + i + `_participantsid_inv<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_inv), 3)<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std = round(np.std(variable_` + i + `_value_inv), 3)<p>' `; } else { code += ` variable_` + i + `_value = variable_` + i + `_value_real variable_` + i + `_participantsid = variable_` + i + `_participantsid_real variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_real), 3) variable_` + i + `_std = round(np.std(variable_` + i + `_value_real), 3) analysis_code.innerHTML += '<p class="code"> variable_` + i + `_value = variable_` + i + `_value_real<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_participantsid = variable_` + i + `_participantsid_real<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_mean = round(np.mean(variable_` + i + `_value_real), 3)<p>' analysis_code.innerHTML += '<p class="code"> variable_` + i + `_std = round(np.std(variable_` + i + `_value_real), 3)<p>' `; } } if(number_of_experimental_conditions == 1) { code += ` all_value = variable_1_value all_value_mean = round(np.mean(all_value), 3) all_value_std = round(np.std(all_value), 3) print("all_value_mean = ", all_value_mean) print("all_value_std = ", all_value_std) analysis_code.innerHTML += '<p class="code"> all_value = variable_1_value<p>' analysis_code.innerHTML += '<p class="code"> all_value_mean = np.mean(all_value)<p>' analysis_code.innerHTML += '<p class="code"> all_value_std = np.std(all_value)<p>' html = "" html = '<br>' + html + '<br>' html += '<div class="box analysis-report">' if current_scale == "general_presence": string = "The average score for general presence sub-scale was " + str(all_value_mean) + " (SD = " + str(all_value_std) + "), while " print(string) whole_analysis_report_text += string html += string elif current_scale == "spatial_presence": string = " that score for spatial presence sub-scale was " + str(all_value_mean) + " (SD = " + str(all_value_std) + "). " print(string) whole_analysis_report_text += string html += string elif current_scale == "involvement": string = "For the involvement sub-scale, the mean score rated by users was " + str(all_value_mean) + " (SD = " + str(all_value_std) + "). " print(string) whole_analysis_report_text += string html += string elif current_scale == "experience_realism": string = "Finally, " + str(all_value_mean) + " and " + str(all_value_std) + " were mean and standard deviation rating score for experience realism sub-scale. " print(string) whole_analysis_report_text += string html += string else: string = "In this experiment, users overally rated their score on the level of presence they felt in the environment around " + str(all_value_mean) + " (SD = " + str(all_value_std) + "). " print(string) whole_analysis_report_text += string html += string html += "</div>" analysis_code.innerHTML += html `; } else if(number_of_experimental_conditions == 2) { code += ` all_value = variable_1_value + variable_2_value analysis_code.innerHTML += '<p class="code"> all_value = variable_1_value + variable_2_value<p>' ## normal distribution test analysis_code.innerHTML += '<p class="code comment"> ## normal distribution test<p>' conditions_values = [] conditions_values.append(variable_1_value) conditions_values.append(variable_2_value) analysis_code.innerHTML += '<p class="code"> conditions_values = []<p>' analysis_code.innerHTML += '<p class="code"> conditions_values.append(variable_1_value)<p>' analysis_code.innerHTML += '<p class="code"> conditions_values.append(variable_2_value)<p>' for x in conditions_values: k2, p = stats.normaltest(x) if p < alpha: is_normal_distribution = False break analysis_code.innerHTML += '<br><p class="code">for x in conditions_values:<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;k2, p = stats.normaltest(all_value)<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;if p < alpha:<p>' analysis_code.innerHTML += '<p class="code"> &nbsp; &nbsp;is_normal_distribution = False<p>' analysis_code.innerHTML += '<p class="code"> &nbsp; &nbsp;break<p>' if is_normal_distribution == True: ## if data has normal distribution analysis_code.innerHTML += '<br><p class="code comment">## if data has normal distribution<p>' analysis_code.innerHTML += '<p class="code"> if is_normal_distribution == True:<p>' df = pd.DataFrame({'condition': variable_1_name, 'value': variable_1_value, 'participantid': variable_1_participantsid}) d2 = pd.DataFrame({'condition': variable_2_name, 'value': variable_2_value, 'participantid': variable_2_participantsid}) df = df.append(d2, ignore_index=True) analysis_code.innerHTML += '<p class="code"> &nbsp;df = pd.DataFrame({"condition": variable_1_name, "value": variable_1_value, "participantid": variable_1_participantsid})<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;d2 = pd.DataFrame({"condition": variable_2_name, "value": variable_2_value, "participantid": variable_2_participantsid})<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;df = df.append(d2, ignore_index=True)<p>'` if(experiment_design === "between-subject") { code += ` document.getElementById("between_subject_anova").setAttribute("style", "background-color: #F5B041;") ## conduct one-way anova anova_model = ols('value ~ condition', data=df).fit() anova_ret = sm.anova_lm(anova_model, typ=2) analysis_code.innerHTML += '<br><p class="code comment">> &nbsp;## conduct one-way anova<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;anova_model = ols("value ~ condition", data=df).fit()<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;anova_ret = sm.anova_lm(anova_model, typ=2)<p>' ## calculate Eta-Squared from Sum Squared eta_squared = anova_ret['sum_sq'][0] / (anova_ret['sum_sq'][0] + anova_ret['sum_sq'][1]) anova_ret['Eta-Squared'] = [eta_squared, 'NaN'] print(anova_ret) analysis_code.innerHTML += '<br><p class="code comment">> &nbsp;## calculate Eta-Squared from Sum Squared<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;eta_squared = anova_ret["sum_sq"][0] / (anova_ret["sum_sq"][0] + anova_ret["sum_sq"][1])<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;anova_ret["Eta-Squared"] = [eta_squared, "NaN"]<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;print(anova_ret)<p>' html = str(anova_ret.to_html()).replace('class="dataframe"', 'class="table is-hoverable" style="font-size: 12px;"') html = '<br>' + html + '<br>' html += '<div class="box analysis-report">' # if current_scale = "general_presence": # elif current_scale = "spatial_presence": # elif current_scale = "involvement": # elif current_scale = "experience_realism": # else: if current_scale == "general_presence": if anova_ret['PR(>F)'][0] < alpha: string = "The scores for general presence sub-scale analysed with one-way ANOVA showed that the difference in the level of presence between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + ") was significant. " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "For this subscale, condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "For this subscale, condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The scores for general presence sub-scale analysed with one-way ANOVA showed that the difference in the level of presence between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + ") was not significant. " string += "For this subscale, the average scores for condition " + variable_1_name + " and condition " + variable_2_name + " are " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "), respectively. " print(string) whole_analysis_report_text += string html += string elif current_scale == "spatial_presence": if anova_ret['PR(>F)'][0] < alpha: string = "According to an test with one-way ANOVA, the scores of spatial presence was significant difference between" + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "The result of this analysis showed that the rating scores for condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") was significantly higher than condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The result of this analysis showed that the rating scores for condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") was significantly higher than condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "According to an test with one-way ANOVA, the scores of spatial presence was not significant difference between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + ") " string += "The average score of spatial presence for condition " + variable_1_name + " was at " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + " and for condition " + variable_2_name + " was " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string elif current_scale == "involvement": if anova_ret['PR(>F)'][0] < alpha: string = "The analysis for involvement sub-scale scores with one-way ANOVA procedure showed that the scores between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + ") was significantly different. " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "It is observed that users had rated higher scores for involvement sub-scale for condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") than for " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "It is observed that users had rated higher scores for involvement sub-scale for condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") than for " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The analysis for involvement sub-scale scores with one-way ANOVA procedure showed no significant difference between conditions " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + "). " string += "The average scores for this sub-scale for condition " + variable_1_name + " and condition " + variable_2_name + " are " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "), respectively. " print(string) whole_analysis_report_text += string html += string elif current_scale == "experience_realism": if anova_ret['PR(>F)'][0] < alpha: string = "Finally, the rating scores for experienced realism was analysed with an one-way ANOVA procedure. The results showed that there was a significant difference in rating scores for this sub-scale between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "Condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Finally, the rating scores for experienced realism was analysed with an one-way ANOVA procedure. The results showed that there was no significant difference in rating scores for this sub-scale between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + "). " string += "The mean rating score of this sub-scale for condition " + variable_1_name + " is " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + variable_2_name + " had the average score at " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: if anova_ret['PR(>F)'][0] < alpha: string = "One-way ANOVA analysis for the overall scores could not show significant differences in the level of presence provided by " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "Condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "One-way ANOVA analysis for the overall scores could not show significant differences in the level of presence provided by " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(round(anova_ret['df'][0])) + ", " + str(round(anova_ret['df'][1])) + "</sub> = " + str(round(anova_ret['F'][0], 3)) + ", p = " + str(round(p, 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_ret['Eta-Squared'][0], 3)) + "). " string += "The average overall presence scores for condition " + variable_1_name + " was " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and for condition " + variable_2_name + " was " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string html += "</div>"; analysis_code.innerHTML += html if is_normal_distribution == False: ## if data has non normal distribution analysis_code.innerHTML += '<br><p class="code comment">## if data has non normal distribution<p>' analysis_code.innerHTML += '<p class="code"> if is_normal_distribution == False:<p>' document.getElementById("mann_whitneyu").setAttribute("style", "background-color: #F5B041;") ## Mann-Whitney U rank test is conducted for between-subject experiment ## with non-normal distribution data u, p = stats.mannwhitneyu(variable_1_value, variable_2_value) analysis_code.innerHTML += '<p class="code"> &nbsp;## Mann-Whitney U rank test was conducted for between-subject experiment<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;## with non-normal distribution data<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;u, p = stats.mannwhitneyu(variable_1_value, variable_2_value)<p><br/>' ## calculate z and r values m_u = len(variable_1_value) * len(variable_2_value) / 2 sigma_u = np.sqrt(len(variable_1_value) * len(variable_2_value) * (len(variable_1_value) + len(variable_2_value) + 1) / 12) z = (u - m_u) / sigma_u r = z / np.sqrt(len(variable_1_value) + len(variable_2_value)) analysis_code.innerHTML += '<p class="code comment"> &nbsp;## calculate z and r values<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;m_u = len(variable_1_value) * len(variable_2_value) / 2<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;sigma_u = np.sqrt(len(variable_1_value) * len(variable_2_value) * (len(variable_1_value) + len(variable_2_value) + 1) / 12)<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;z = (u - m_u) / sigma_u<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;r = z / np.sqrt(len(variable_1_value) + len(variable_2_value))<p><br/>' print("u: ", u) print("p: ", p) print("z: ", z) print("r: ", r) u = round(u, 3) z = round(z, 3) p = round(p, 3) r = round(r, 3) html = '<br><br>' html += '<div class="box analysis-report">' if current_scale == "general_presence": if p < alpha: string = "The scores for general presence sub-scale analysed with a Mann-Whitney U test showed that the difference in the level of presence between " + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + ") was significant. " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "For this subscale, condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "For this subscale, condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The scores for general presence sub-scale analysed with a Mann-Whitney U test showed that the difference in the level of presence between " + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + ") was not significant. " string += "For this subscale, the average scores for condition " + variable_1_name + " and condition " + variable_2_name + " are " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "), respectively. " print(string) whole_analysis_report_text += string html += string elif current_scale == "spatial_presence": if p < alpha: string = "According to a Mann-Whitney U test, the scores for spatial presence reveal significant differences between" + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "The result of this analysis showed that the rating scores for condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") was significantly higher than condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The result of this analysis showed that the rating scores for condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") was significantly higher than condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "According to a Mann-Whitney U test, the scores for spatial presence did not reveal significant differences between " + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " string += "The average score of spatial presence for condition " + variable_1_name + " was at " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and for condition " + variable_2_name + " was " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string elif current_scale == "involvement": if p < alpha: string = "The analysis for involvement sub-scale scores with a Mann-Whitney U test showed that the scores between " + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + ") was significantly different. " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "It was observed that users had rated higher scores for involvement sub-scale for condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") than for " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "It was observed that users had rated higher scores for involvement sub-scale for condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") than for " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The analysis for involvement sub-scale scores with a Mann-Whitney U test showed no significant difference between conditions " + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " string += "The average of these scores for condition " + variable_1_name + " and condition " + variable_2_name + " are " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "), respectively. " print(string) whole_analysis_report_text += string html += string elif current_scale == "experience_realism": if p < alpha: string = "Finally, the rating scores for experienced realism was analysed with a Mann-Whitney U test. The results showed that there was a significant difference in rating scores for this sub-scale between " + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "Condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Finally, the rating scores for experienced realism was analysed with a Mann-Whitney U test. The results showed that there was no significant difference in rating scores for this sub-scale between " + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " string += "The mean rating score of this sub-scale for condition " + variable_1_name + " was " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + variable_2_name + " had the average score at " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: if p < alpha: string = "Mann-Whitney U test showed that there was significant difference in the level of presence provided by " + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "Condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Mann-Whitney U test showed that there was no significant difference in the level of presence provided by " + variable_1_name + " and " + variable_2_name + " (U = " + str(u) + ", Z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " string += "The average overall presence scores for condition " + variable_1_name + " was " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and for condition " + variable_2_name + " was " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string html += "</div>"; analysis_code.innerHTML += html`; } else if(experiment_design === "within-subject") { code += ` document.getElementById("within_subject_anova").setAttribute("style", "background-color: #F5B041;") ## calculate eta-squared n = len(all_value) grand_mean = 0; for x in all_value: grand_mean += x grand_mean = grand_mean / n print("grand_mean = ", grand_mean) s2_grand = 0 for x in all_value: s2_grand += (x - grand_mean)**2 s2_grand = s2_grand / (n - 1) print("s2_grand = ", s2_grand) SSt = s2_grand * (n - 1) print("SSt = " + str(SSt)) SSw = 0 for x in range(1, 3): value = []; if x == 1: value = variable_1_value else: value = variable_2_value tmp_n = len(value) tmp_grand_mean = 0 for i in value: tmp_grand_mean += i tmp_grand_mean = tmp_grand_mean / tmp_n tmp_s2_grand = 0 for i in value: tmp_s2_grand += (i - tmp_grand_mean)**2 tmp_s2_grand = tmp_s2_grand / (tmp_n - 1) SSw += tmp_s2_grand * (tmp_n - 1) print("SSw = " + str(SSw)) data_by_participants = pd.DataFrame(columns=['count', 'total', 'participantid', 'grand_mean']) print("length ", len(df['participantid'])) print(df) for i in range(0, len(df['participantid'])): isExisted = False if len(data_by_participants['participantid']) > 0: for j in range(0, len(data_by_participants['participantid'])): if df.iloc[i, :]['participantid'] == data_by_participants.iloc[j, :]['participantid']: isExisted = True data_by_participants.at[j, 'count']= data_by_participants.at[j, 'count'] + 1 data_by_participants.at[j, 'total'] = data_by_participants.at[j, 'total'] + df.at[i, 'value'] break if isExisted == False: value = df.iloc[i, :]['value'] id = df.iloc[i, :]['participantid'] count = 1 tmp_df = pd.DataFrame({'count': [count], 'total': [value], 'participantid': [id], 'grand_mean': [0]}) data_by_participants = data_by_participants.append(tmp_df,ignore_index=True) isBalanced = True for i in range(0, len(data_by_participants['participantid']) - 1): if data_by_participants.at[i, 'count'] != data_by_participants.at[i + 1, 'count']: isBalanced = False data_by_participants.at[i, 'grand_mean'] = data_by_participants.at[i, 'total'] / data_by_participants.at[i, 'count'] break if isBalanced == True: print("Data for each participant is balanced!") SSsubjects = 0; for i in range(0, len(data_by_participants['participantid']) ): data_by_participants.at[i, 'grand_mean'] = data_by_participants.at[i, 'total'] / data_by_participants.at[i, 'count'] SSsubjects = SSsubjects + data_by_participants.at[i, 'count'] * (data_by_participants.at[i, 'grand_mean'] - grand_mean)**2 print("Data by participants: ", data_by_participants) print("SSsubjects: ", SSsubjects) SSerror = SSw - SSsubjects print("SSerror: ", SSerror) SStime = SSt - SSw print("SStime: ", SStime) MStime = SStime / (2 - 1) print("MStime: ", MStime) MSerror = SSerror / ((n - 1) * (2 - 1)) print("MSerror: ", MSerror) F = MStime / MSerror print("F: ", F) ## conduct one-way anova repeated measure anova_rep = AnovaRM(df, 'value', 'participantid', within=['condition'], aggregate_func='mean').fit() print(anova_rep) eta_squared_partial = SStime / (SStime + SSerror) print("eta_squared_partial: ", eta_squared_partial) eta_squared = SStime / SSt print("eta_squared: ", eta_squared) anova_table = anova_rep.anova_table anova_table['Eta-Squared'] = [eta_squared] analysis_code.innerHTML += '<p class="code comment"> &nbsp;## conduct one-way anova repeated measure<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;anova_rep = AnovaRM(df, "value", "participantid", within=["condition"], aggregate_func="mean").fit()<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;print(anova_rep.anova_table)<p>' html = str(anova_table.to_html()).replace('class="dataframe"', 'class="table is-hoverable" style="font-size: 12px;"') html = '<br>' + html + '<br>' html += '<div class="box analysis-report">' if current_scale == "general_presence": if anova_table['Pr > F'][0] < alpha: string = "The scores for general presence sub-scale analysed with one-way repeated-measures ANOVA showed that the difference in the level of presence between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + ") was significant. " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "For this subscale, condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "For this subscale, condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The scores for general presence sub-scale analysed with one-way repeated-measures ANOVA showed that the difference in the level of presence between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + ") was not significant. " string += "For this subscale, the average scores for condition " + variable_1_name + " and condition " + variable_2_name + " are " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "), respectively. " print(string) whole_analysis_report_text += string html += string elif current_scale == "spatial_presence": if anova_table['Pr > F'][0] < alpha: string = "According to an test with one-way repeated-measures ANOVA, the scores of spatial presence was significant difference between" + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "The result of this analysis showed that the rating scores for condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") was significantly higher than condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The result of this analysis showed that the rating scores for condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") was significantly higher than condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "According to an test with one-way repeated-measures ANOVA, the scores of spatial presence was not significant difference between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + ") " string += "The average score of spatial presence for condition " + variable_1_name + " was at " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + " and for condition " + variable_2_name + " was " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string elif current_scale == "involvement": if anova_table['Pr > F'][0] < alpha: string = "The analysis for involvement sub-scale scores with one-way repeated-measures ANOVA procedure showed that the scores between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + ") was significantly different. " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "It is observed that users had rated higher scores for involvement sub-scale for condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") than for " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "It is observed that users had rated higher scores for involvement sub-scale for condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") than for " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The analysis for involvement sub-scale scores with one-way repeated-measures ANOVA procedure showed no significant difference between conditions " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + "). " string += "The average of these scores for condition " + variable_1_name + " and condition " + variable_2_name + " are " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "), respectively. " print(string) whole_analysis_report_text += string html += string elif current_scale == "experience_realism": if anova_table['Pr > F'][0] < alpha: string = "Finally, the rating scores for experienced realism was analysed with an one-way repeated-measures ANOVA procedure. The results showed that there was a significant difference in rating scores for this sub-scale between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "Condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Finally, the rating scores for experience realism was analysed with an one-way repeated-measures ANOVA procedure. The results showed that there was no significant difference in rating scores for this sub-scale between " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + "). " string += "The mean rating score of this sub-scale for condition " + variable_1_name + " is " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + variable_2_name + " had the average score at " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: if anova_table['Pr > F'][0] < alpha: string = "One-way repeated-measures ANOVA analysis for the overall scores could not show significant differences in the level of presence provided by " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "Condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "One-way repeated-measures ANOVA analysis showed that there was no significant difference in the level of presence provided by " + variable_1_name + " and " + variable_2_name + " (F<sub>" + str(anova_table['Num DF'][0]) + ", " + str(anova_table['Den DF'][00]) + "</sub> = " + str(round(anova_table['F Value'][0], 3)) + ", p = " + str(round(anova_table['Pr > F'][0], 3)) + ", &eta;<sup>2</sup> = " + str(round(anova_table['Eta-Squared'][0], 3)) + "). " string += "The average overall presence scores for condition " + variable_1_name + " was " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and for condition " + variable_2_name + " was " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string html += "</div>"; analysis_code.innerHTML += html else: print("The number of entries are different between participants!") alert("The number of entries are different between participants. The analysis is interrupted!") ## if data has non normal distribution if is_normal_distribution == False: analysis_code.innerHTML += '<br><p class="code comment">## if data has non normal distribution<p>' analysis_code.innerHTML += '<p class="code"> if is_normal_distribution == False:<p>' document.getElementById("wilcoxon_signed_rank").setAttribute("style", "background-color: #F5B041;") ## Wilcoxon Signed-Rank test is conducted for within-subject experiment ## with non-normal distribution data z, p = stats.wilcoxon(variable_1_value, variable_2_value) r = z / np.sqrt(len(variable_1_value) + len(variable_2_value)) z = round(z, 3) p = round(p, 3) r = round(r, 3) analysis_code.innerHTML += '<p class="code"> &nbsp;## Wilcoxon Signed-Rank test is conducted for within-subject experiment<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;## with non-normal distribution data<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;z, p = stats.wilcoxon(variable_1_value, variable_2_value)<p>' analysis_code.innerHTML += '<p class="code"> &nbsp;r = z / np.sqrt(len(variable_1_value) + len(variable_2_value))<p>' html = '<br><br>' html += '<div class="box analysis-report">' if current_scale == "general_presence": if p < alpha: string = "The scores for general presence sub-scale analysed with a Wilcoxon Signed-Rank test showed that the difference in the level of presence between " + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + ") was significant. " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "For this subscale, condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "For this subscale, condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The scores for general presence sub-scale analysed with a Wilcoxon Signed-Rank test showed that the difference in the level of presence between " + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + ") was not significant. " string += "For this subscale, the average scores for condition " + variable_1_name + " and condition " + variable_2_name + " are " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "), respectively. " print(string) whole_analysis_report_text += string html += string elif current_scale == "spatial_presence": if p < alpha: string = "According to a Wilcoxon Signed-Rank test, the scores of spatial presence was significant difference between" + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "The result of this analysis showed that the rating scores for condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") was significantly higher than condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The result of this analysis showed that the rating scores for condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") was significantly higher than condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "According to a Wilcoxon Signed-Rank test, the scores of spatial presence was not significant difference between " + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " string += "The average score of spatial presence for condition " + variable_1_name + " was at " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + " and for condition " + variable_2_name + " was " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string elif current_scale == "involvement": if p < alpha: string = "The analysis for involvement sub-scale scores with a Wilcoxon Signed-Rank test showed that the scores between " + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + ") was significantly different. " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "It was observed that users had rated higher scores for involvement sub-scale for condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") than for " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "It was observed that users had rated higher scores for involvement sub-scale for condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") than for " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "The analysis for involvement sub-scale scores with a Wilcoxon Signed-Rank test showed no significant difference between conditions " + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " string += "The average scores for this sub-scales for condition " + variable_1_name + " and condition " + variable_2_name + " are " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "), respectively. " print(string) whole_analysis_report_text += string html += string elif current_scale == "experience_realism": if p < alpha: string = "Finally, the rating scores for experienced realism was analysed with a Wilcoxon Signed-Rank test. The results showed that there was a significant difference in rating scores for this sub-scale between " + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "Condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Finally, the rating scores for experienced realism was analysed with a Wilcoxon Signed-Rank test. The results showed that there was no significant difference in rating scores for this sub-scale between " + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " string += "The mean rating score of this sub-scale for condition " + variable_1_name + " was " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and " + variable_2_name + " had the average score at " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: if p < alpha: string = "Wilcoxon Signed-Rank test showed that there was significant difference in the level of presence provided by " + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " print(string) whole_analysis_report_text += string html += string if variable_1_mean > variable_2_mean: string = "Condition " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + ") had higher ratings of presence than " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Condition " + variable_2_name + " (M = " + str(variable_2_mean) + ", SD = " + str(variable_2_std) + ") had higher ratings of presence than " + variable_1_name + " (M = " + str(variable_1_mean) + ", SD = " + str(variable_1_std) + "). " print(string) whole_analysis_report_text += string html += string else: string = "Wilcoxon Signed-Rank test showed that there was no significant difference in the level of presence provided by " + variable_1_name + " and " + variable_2_name + " (z = " + str(z) + ", p = " + str(p) + ", r = " + str(r) + "). " string += "The average overall presence scores for condition " + variable_1_name + " was " + str(variable_1_mean) + " (SD = " + str(variable_1_std) + ") and for condition " + variable_2_name + " was " + str(variable_2_mean) + " (SD = " + str(variable_2_std) + "). " print(string) whole_analysis_report_text += string html += string html += "</div>"; analysis_code.innerHTML += html `; } } code += ` user_data_sample_report_text = document.getElementById("user_data_sample_report_text") html = '<div class="columns"><div class="column"> </div><div class="column is-11"><div class="box" style="background: #ECF0F1;"><div class="box report-text" style="margin: 20px 20px 20px 20px; text-align:justify; margin-bottom: 20px;" id="analysis_report_text"><p>' html += whole_analysis_report_text html += '</p></div></div> </div> <div class="column"> </div> </div>' user_data_sample_report_text.innerHTML = html `; } } else if(number_of_experimental_conditions > 2) { alert("Current version of this tool only supports upto two experimental conditions!"); } console.log(code); languagePluginLoader.then(() => { pyodide.loadPackage(['numpy', 'scipy', 'pandas', 'statsmodels', 'matplotlib']).then(() => { pyodide.runPython(code); }); }) } function IllustrateUserData(data, width, height, div, user_data, condition) { var json = JSON.stringify(data); var tmpObject = JSON.parse(json); var generalObject = tmpObject.value.find(function(element) { return element.name === "Overall"; }); var summaryObject = generalObject.value.find(function(element) { return element.name === "Summary"; }); summaryObject.number++; var adjectiveRatingsObject = tmpObject.value.find(function(element) { return element.name === "AdjectiveRatings"; }); adjectiveRatingsObject.value.forEach(function(e){ if(e.name === user_data.adjective_rating) { e.number++; e.color = user_data_color; } e.condition = condition; e.percent = Math.round(e.number * 10000 / summaryObject.number) / 100; }); DrawPie(adjectiveRatingsObject.value, width, height, "", div, false, user_data.average, user_data.name); } function DrawPie(data, width, height, margin, div_id, is_reference, data_score = "", adjective_rating = "") { $(div_id).html(""); var radius = Math.min(width, height) / 2, innerRadius = 0.3 * radius; var circlePie = d3.layout.pie() .sort(null) .value(function(element){ return element.percent; }); var outerCircleArc = d3.svg.arc() .innerRadius(innerRadius) .outerRadius(function(element){ return (radius - innerRadius) + innerRadius; }); var outlineCircleArc = d3.svg.arc() .innerRadius(innerRadius) .outerRadius(radius); var mainPieSVG = d3.select(div_id).append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); var path = mainPieSVG.selectAll(".solidArc") .data(circlePie(data)) .enter().append("path") .attr("fill", function(element) { return element.data.color; }) .attr("class", "solidArc") .attr("stroke", "gray") .attr('d', outerCircleArc) .on("click", function(element){ if(element.data === currentSelectedPie) currentSelectedPie = undefined; else { currentSelectedPie = element.data; } UpdateInfo("main", element.data); // if(!is_reference) // { // if(element.data.name !== selectedItem) // { // selectedItem = element.data.name; // isClicked = true; // } // else // { // isClicked = false; // selectedItem = ""; // //AddYearBarChart("All", "#2E86C1"); // //AddScoreBarChart("All", "#2E86C1"); // //UpdateInfo("All"); // //WriteTable("All"); // } // } }) .on("mouseover", function(element) { SetCurrentObject(element.data); UpdateInfo(stage, element.data); // if(!is_reference) // { // // AddYearBarChart(element.data); // // AddScoreBarChart(element.data); // // //UpdateInfo(element.data.name); // // WriteTable(element.data); // } }) .on("mouseout", function(element) { // if(!is_reference && !isClicked) // { // //AddYearBarChart("All", "#2E86C1"); // //AddScoreBarChart("All", "#2E86C1"); // //UpdateInfo("All"); // //WriteTable("All"); // } }); var outerPath = mainPieSVG.selectAll(".outlineArc") .data(circlePie(data)) .enter().append("path") .attr("fill", "none") .attr("stroke", "gray") .attr("class", "outlineArc") .attr('d', outlineCircleArc); if(data_score !== "") { mainPieSVG.append("svg:text") .attr("class", "ipq-eachstudyscore") .attr("dy", "-0.05em") .attr("text-anchor", "middle") .style("font-size", (width/2) + "%") .text(data_score); mainPieSVG.append("svg:text") .attr("class", "ipq-eachstudyscore") .attr("dy", "1.5em") .attr("text-anchor", "middle") .style("font-size", (width/4) + "%") .text(adjective_rating); } else if(stage === "main") { var category = ""; if(data[0].subscale === "") category = data[0].display; else category = data[0].subscale; mainPieSVG.append("svg:text") .attr("class", "ipq-eachstudyscore") .attr("dy", "0.5em") .attr("text-anchor", "middle") .style("font-size", (width/4) + "%") .text(category); } if(!is_reference) { //AddYearBarChart("All", "#2E86C1"); //AddScoreBarChart("All", "#2E86C1"); //UpdateInfo("All"); //WriteTable("All"); } } function AddAppendix(is_user_data = false, div = "#main_appendix") { var width = 0.85 * $(div).width(); var height = width; var appendixSVG = d3.select(div) .append("svg") .attr("width", width) .attr("height", height); appendixSVG.append("text").attr("x", width/2 - 30).attr("y", height - 5 * (height / 8)).text("APPENDIX").attr("alignment-baseline","middle").style("font-size", (width/2.5) + "%"); // appendixSVG.append("circle").attr("cx", width/5).attr("cy", height - height / 8).attr("r", 6).style("fill", "#3092C7"); // appendixSVG.append("circle").attr("cx", width/5 + width/3).attr("cy", height - 2 * (height / 8)).attr("r", 6).style("fill", "#3498DB"); // appendixSVG.append("circle").attr("cx", width/5).attr("cy", height - 2 * (height / 8)).attr("r", 6).style("fill", "#5DADE2"); // appendixSVG.append("circle").attr("cx", width/5 + width/3).attr("cy", height - 3 * (height / 8)).attr("r", 6).style("fill", "#85C1E9"); // appendixSVG.append("circle").attr("cx", width/5).attr("cy", height - 3 * (height / 8)).attr("r", 6).style("fill", "#AED6F1"); // appendixSVG.append("circle").attr("cx", width/5 + width/3).attr("cy", height - 4 * (height / 8)).attr("r", 6).style("fill", "#D6EAF8"); // appendixSVG.append("circle").attr("cx", width/5).attr("cy", height - 4 * (height / 8)).attr("r", 6).style("fill", "#EBF5FB"); appendixSVG.append("circle").attr("cx", width/5 + width/3).attr("cy", height - 2 * (height / 8)).attr("r", 6).style("fill", "#cce2fd"); appendixSVG.append("circle").attr("cx", width/5).attr("cy", height - 2 * (height / 8)).attr("r", 6).style("fill", "#a9d7fc"); appendixSVG.append("circle").attr("cx", width/5 + width/3).attr("cy", height - 3 * (height / 8)).attr("r", 6).style("fill", "#80cafb"); appendixSVG.append("circle").attr("cx", width/5).attr("cy", height - 3 * (height / 8)).attr("r", 6).style("fill", "#51bbfa"); appendixSVG.append("circle").attr("cx", width/5 + width/3).attr("cy", height - 4 * (height / 8)).attr("r", 6).style("fill", "#31b1f9"); appendixSVG.append("circle").attr("cx", width/5).attr("cy", height - 4 * (height / 8)).attr("r", 6).style("fill", "#3092c7"); // appendixSVG.append("text").attr("x", width/5 + 15).attr("y", height - 1 * (height / 8)).text("Best").attr("alignment-baseline","middle").style("font-size", (width/3) + "%"); appendixSVG.append("text").attr("x", width/5 + width/3 + 15).attr("y", height - 2 * (height / 8)).text('Class VI').attr("alignment-baseline","middle").style("font-size", (width/3) + "%"); appendixSVG.append("text").attr("x", width/5 + 15).attr("y", height - 2 * (height / 8)).text('Class V').attr("alignment-baseline","middle").style("font-size", (width/3) + "%"); appendixSVG.append("text").attr("x", width/5 + width/3 + 15).attr("y", height - 3 * (height / 8)).text('Class IV').attr("alignment-baseline","middle").style("font-size", (width/3) + "%"); appendixSVG.append("text").attr("x", width/5 + 15).attr("y", height - 3 * (height / 8)).text('Class III').attr("alignment-baseline","middle").style("font-size", (width/3) + "%"); appendixSVG.append("text").attr("x", width/5 + width/3 + 15).attr("y", height - 4 * (height / 8)).text('Class II').attr("alignment-baseline","middle").style("font-size", (width/3) + "%"); appendixSVG.append("text").attr("x", width/5 + 15).attr("y", height - 4 * (height / 8)).text('Class I').attr("alignment-baseline","middle").style("font-size", (width/3) + "%"); if(is_user_data) { appendixSVG.append("circle").attr("cx", width/5 + width/3).attr("cy", height - height / 8).attr("r", 6).style("fill", "#F39C12"); appendixSVG.append("text").attr("x", width/5 + width/3 + 15).attr("y", height - 1 * (height / 8)).text("Your Data").attr("alignment-baseline","middle").style("font-size", (width/3) + "%"); } } function SetCurrentObject(object) { if(object.subscale !== "") { if(object.subscale === "Overall") { currentObject = overallObject; } else{ currentObject = subscalesObject.value.find(function(e) { return e.name === object.subscale; }); } } else{ currentObject = visualDisplaysObject.value.find(function(e) { return e.name === object.display; }); } } $( document ).ready(function() { var copyrightText = $("#copyright").text(); var years = "2020"; var date = new Date(); var year = date.getFullYear(); if(year !== 2020) { years += " - " + year; } copyrightText = years + " " + copyrightText; $("#copyright").text(copyrightText); }); languagePluginLoader.then(() => { pyodide.loadPackage(['numpy', 'scipy', 'pandas', 'statsmodels', 'matplotlib']).then(() => { pyodide.runPython(` import io import base64 import numpy as np from scipy import stats import pandas as pd import statsmodels.stats.api as sm from statsmodels.stats.anova import AnovaRM from statsmodels.regression.mixed_linear_model import MixedLM from statsmodels.formula.api import ols import matplotlib.pyplot as plt from js import window, eval as jseval print("Preload libraries are finished!") `); }); }) function HideTermsandCondition(){ $("#terms_and_conditions").hide(); $("#btn_terms_and_conditions").addClass("is-outlined") } function ShowTermsandCondition(){ $("#terms_and_conditions").show(); $("#btn_terms_and_conditions").removeClass("is-outlined") } function ShowWhatIsIPQ(){ $("#what_is_ipq").show(); $("#btn_what_is_ipq").removeClass("is-outlined"); } function HideWhatIsIPQ(){ $("#what_is_ipq").hide(); $("#btn_what_is_ipq").addClass("is-outlined"); } function ShowUsageGuidelines(){ $("#usage_guidelines").show(); $("#btn_usage_guidelines").removeClass("is-outlined"); } function HideUsageGuidelines(){ $("#usage_guidelines").hide(); $("#btn_usage_guidelines").addClass("is-outlined"); } function ShowContribute() { $("#contribute").show(); $("#btn_contribute").removeClass("is-outlined"); } function HideContribute() { $("#contribute").hide(); $("#btn_contribute").addClass("is-outlined"); } $("#what_is_ipq").hide(); $("#usage_guidelines").hide(); $("#contribute").hide(); // When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() { Scroll() }; function Scroll() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { $("#goTopBtn").css("display","block"); } else { $("#goTopBtn").css("display","none"); } } // When the user clicks on the button, scroll to the top of the document function GoTop() { document.body.scrollTop = 0; // For Safari document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera } function NumberOfContributedStudies(){ var number_of_studies = parseInt($("#in_numberofstudies").val()); html = ""; for(var i = 1; i <= number_of_studies; i++) { html += `<div class="file has-name"> <label class="file-label"> <input class="file-input" type="file" name="user_uploaded_file" id="contributed_file_` + i + `" onchange="GetUserContributedFile(event)"> <span class="file-cta"> <span class="file-label">Choose the data file for user study ` + i + `</span> </span> <span class="file-name" id="name_of_contributed_file_` + i + `">...</span> </label> </div>`; } $("#user_contributed_files").html(html); user_contribute_files = []; } var user_contribute_files = []; function GetUserContributedFile(event) { var id = event.currentTarget.id; sub_id = id.split("_"); id = sub_id[sub_id.length - 1]; var input = event.target; var div = "#name_of_contributed_file_" + id; var filename = input.files[0].name; $(div).text(filename); for(var i = 0; i < user_contribute_files.length; i++) { if(user_contribute_files[i]["id"] === id) { user_contribute_files.splice(i, 1); } } user_contribute_files.push({"id": id, "file": input.files[0]}); } function SubmitUserData() { var author = $("#in_author").val(); var title = $("#in_title").val(); var booktitle = $("#in_booktitle").val(); var series = $("#in_series").val(); var year = $("#in_year").val(); var isbn = $("#in_isbn").val(); var url = $("#in_url").val(); var publisher = $("#in_publisher").val(); var location = $("#in_location").val(); var pages = $("#in_pages").val(); var number_of_pages = $("#in_numberofpages").val(); var article_number = $("#in_articlenumber").val(); var doi = $("#in_doi").val(); var address = $("#in_address").val(); var keywords = $("#in_keywords").val(); var number_of_user_studies = $("#in_numberofstudies").val(); if(author != "" && title != "" && booktitle != "" && series != "" && year != "" && isbn != "" && url != "" && publisher != "") { var is_duplicated = false; for(var i = 0; i < user_contribute_files.length - 1; i++) { for(var j = i+1; j < user_contribute_files.length; j++) { if(user_contribute_files[i]["file"].name === user_contribute_files[j]["file"].name) { is_duplicated = true; break; } } } if(is_duplicated) { alert("Please make sure that there is no same data file for two different studies!"); } else{ var fs = require('fs'); // Without checking if dir already exists fs.mkdir('PATH/TO/DIR'); // With checking if dir already exists if (!fs.existsSync('PATH/TO/DIR')) fs.mkdir('PATH/TO/DIR'); } } else { alert("Please fill in all of the required entries!"); return; } } var _currentRankingClass = "All Classes"; var _currentCategory = "btn_overall"; var _category = "Overall"; var _currentObject; function ChangeRankingClass(btn) { $("#all_classes").removeClass("is-info"); $("#class_a").removeClass("is-info"); $("#class_b").removeClass("is-info"); $("#class_c").removeClass("is-info"); $("#class_d").removeClass("is-info"); $("#class_e").removeClass("is-info"); $("#class_f").removeClass("is-info"); $("#" + btn.id).addClass("is-info"); if(btn.id === "all_classes") { _currentRankingClass = "All Classes"; } else if(btn.id === "class_a") { _currentRankingClass = "Class I"; } else if(btn.id === "class_b") { _currentRankingClass = "Class II"; } else if(btn.id === "class_c") { _currentRankingClass = "Class III"; } else if(btn.id === "class_d") { _currentRankingClass = "Class IV"; } else if(btn.id === "class_e") { _currentRankingClass = "Class V"; } else if(btn.id === "class_f") { _currentRankingClass = "Class VI"; } UpdateCategoryAndClassSelection(); } function ChangeCategory(btn) { $("#btn_overall").removeClass("is-info"); $("#btn_sp").removeClass("is-info"); $("#btn_inv").removeClass("is-info"); $("#btn_real").removeClass("is-info"); $("#btn_gp").removeClass("is-info"); $("#btn_hmd").removeClass("is-info"); $("#btn_mono").removeClass("is-info"); $("#btn_proj").removeClass("is-info"); $("#" + btn.id).addClass("is-info"); _currentCategory = btn.id; if(_currentCategory === "btn_overall") { _currentObject = overallObject; _category = "Overall"; } else if(_currentCategory === "btn_sp") { _category = "SP"; _currentObject = subscalesObject.value.find(function(e) { return e.name === "SP"; }); } else if(_currentCategory === "btn_inv") { _category = "INV"; _currentObject = subscalesObject.value.find(function(e) { return e.name === "INV"; }); } else if(_currentCategory === "btn_real") { _category = "REAL"; _currentObject = subscalesObject.value.find(function(e) { return e.name === "REAL"; }); } else if(_currentCategory === "btn_gp") { _category = "GP"; _currentObject = subscalesObject.value.find(function(e) { return e.name === "GP"; }); } else if(_currentCategory === "btn_hmd") { _category = "3D - HMD"; _currentObject = visualDisplaysObject.value.find(function(e) { return e.name === "3D - HMD VR"; }); } else if(_currentCategory === "btn_mono") { _category = "3D - Monoscopic"; _currentObject = visualDisplaysObject.value.find(function(e) { return e.name === "3D - Monoscopic"; }); } else if(_currentCategory === "btn_proj") { _category = "3D - Projection Display"; _currentObject = visualDisplaysObject.value.find(function(e) { return e.name === "Projection Display"; }); } UpdateCategoryAndClassSelection(); } function UpdateCategoryAndClassSelection() { var _currentClassObject = _currentObject; if(_currentRankingClass === "All Classes") { _currentClassObject = _currentObject.value.find(function(e) { return e.name === "Overall"; }); _currentClassObject = _currentClassObject.value.find(function(e) { return e.name === "Summary"; }); } else { _currentClassObject = _currentObject.value.find(function(e) { return e.name === "AdjectiveRatings"; }); _currentClassObject = _currentClassObject.value.find(function(e) { return e.name === _currentRankingClass; }); } AddScoreBarChart(_currentClassObject, "#main_bar_chart_for_score"); AddYearBarChart(_currentClassObject, "#main_bar_chart_for_year"); WriteTable(_currentClassObject, "#main_list_publications"); $("#info_main_category").html(_category); $("#info_main_participants").html(_currentClassObject.participants); $("#info_main_percent").html(_currentClassObject.percent); $("#info_main_adjective_rating").html(_currentRankingClass); $("#info_main_years").html(_currentClassObject.years.length); $("#info_main_user_studies").html(_currentClassObject.user_studies.length); $("#info_main_publications").html(_currentClassObject.publications.length); SortBy(); } function SortBy(isYear = true, isNPar = false, isAscending = true) { var table, needSwapping = false; var table = document.getElementById("reported_papers_table"); var rows = table.rows; var islooped = true; var row1, row2; var id = 0; if(isYear) { id = 5; } if(isNPar) { id = 4; } for (var i = 1; i < (rows.length - 2); i++) { for(var j = i + 1; j < (rows.length - 1); j++) { row1 = parseInt(rows[i].getElementsByTagName("td")[id].innerHTML); row2 = parseInt(rows[j].getElementsByTagName("td")[id].innerHTML); if((isAscending && row1 > row2) || (!isAscending && row1 < row2)) { rows[i].parentNode.insertBefore(rows[j], rows[i]); switching = true; } } } } function YearSortBy(btn, isYear = true, isNPar = false, isAscending = true) { $("#btn_year_ascending").removeClass("is-info"); $("#btn_year_descending").removeClass("is-info"); $("#" + btn.id).addClass("is-info"); SortBy(isYear, isNPar, isAscending); } function NParSortBy(btn, isYear = false, isNPar = true, isAscending = true) { $("#btn_npar_ascending").removeClass("is-info"); $("#btn_npar_descending").removeClass("is-info"); $("#" + btn.id).addClass("is-info"); SortBy(isYear, isNPar, isAscending); }
module.exports = { newNote: async (parent, args, { models }) => { return await models.Note.create({ content: args.content, author: 'Jack Middlebot' }); }, deleteNote: async (parent, { id }, { models }) => { try { await models.Note.findOneAndRemove({ _id: id}); return true; } catch ( err ) { return false } }, updateNote: async (parent, { content, id }, { models }) => { return await models.Note.findOneAndUpdate( { _id: id }, { $set: { content } }, { new: true } ) } }
(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(require,module,exports){ (function (global){ 'use strict'; var stub = require('./stub'); var tracking = require('./tracking'); var ls = 'localStorage' in global && global.localStorage ? global.localStorage : stub; function accessor (key, value) { if (arguments.length === 1) { return get(key); } return set(key, value); } function get (key) { return JSON.parse(ls.getItem(key)); } function set (key, value) { try { ls.setItem(key, JSON.stringify(value)); return true; } catch (e) { return false; } } function remove (key) { return ls.removeItem(key); } function clear () { return ls.clear(); } accessor.set = set; accessor.get = get; accessor.remove = remove; accessor.clear = clear; accessor.on = tracking.on; accessor.off = tracking.off; module.exports = accessor; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./stub":2,"./tracking":3}],2:[function(require,module,exports){ 'use strict'; var ms = {}; function getItem (key) { return key in ms ? ms[key] : null; } function setItem (key, value) { ms[key] = value; return true; } function removeItem (key) { var found = key in ms; if (found) { return delete ms[key]; } return false; } function clear () { ms = {}; return true; } module.exports = { getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear }; },{}],3:[function(require,module,exports){ (function (global){ 'use strict'; var listeners = {}; var listening = false; function listen () { if (global.addEventListener) { global.addEventListener('storage', change, false); } else if (global.attachEvent) { global.attachEvent('onstorage', change); } else { global.onstorage = change; } } function change (e) { if (!e) { e = global.event; } var all = listeners[e.key]; if (all) { all.forEach(fire); } function fire (listener) { listener(JSON.parse(e.newValue), JSON.parse(e.oldValue), e.url || e.uri); } } function on (key, fn) { if (listeners[key]) { listeners[key].push(fn); } else { listeners[key] = [fn]; } if (listening === false) { listen(); } } function off (key, fn) { var ns = listeners[key]; if (ns.length > 1) { ns.splice(ns.indexOf(fn), 1); } else { listeners[key] = []; } } module.exports = { on: on, off: off }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],4:[function(require,module,exports){ window.ls = require('local-storage'); },{"local-storage":1}]},{},[4]);
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var react_1 = require("react"); var react_2 = require("react"); var map_1 = require("./map"); var assert_1 = require("../utils/assert"); var deep_equal_1 = require("../utils/deep-equal"); var sourceCounter = 0; function createSource(map, id, props) { // @ts-ignore if (map.style && map.style._loaded) { var options = __assign({}, props); delete options.id; delete options.children; // @ts-ignore map.addSource(id, options); return map.getSource(id); } return null; } /* eslint-disable complexity */ function updateSource(source, props, prevProps) { (0, assert_1.default)(props.id === prevProps.id, 'source id changed'); (0, assert_1.default)(props.type === prevProps.type, 'source type changed'); var changedKey = ''; var changedKeyCount = 0; for (var key in props) { if (key !== 'children' && key !== 'id' && !(0, deep_equal_1.deepEqual)(prevProps[key], props[key])) { changedKey = key; changedKeyCount++; } } if (!changedKeyCount) { return; } var type = props.type; if (type === 'geojson') { source.setData(props.data); } else if (type === 'image') { source.updateImage({ url: props.url, coordinates: props.coordinates }); } else if ((type === 'canvas' || type === 'video') && changedKeyCount === 1 && changedKey === 'coordinates') { source.setCoordinates(props.coordinates); } else if (type === 'vector' && 'setUrl' in source) { // Added in 1.12.0: // vectorTileSource.setTiles // vectorTileSource.setUrl switch (changedKey) { case 'url': source.setUrl(props.url); break; case 'tiles': source.setTiles(props.tiles); break; default: } } else { // eslint-disable-next-line console.warn("Unable to update <Source> prop: ".concat(changedKey)); } } /* eslint-enable complexity */ function Source(props) { var map = (0, react_1.useContext)(map_1.MapContext).map.getMap(); var propsRef = (0, react_1.useRef)(props); var _a = __read((0, react_1.useState)(0), 2), setStyleLoaded = _a[1]; var id = (0, react_1.useMemo)(function () { return props.id || "jsx-source-".concat(sourceCounter++); }, []); (0, react_1.useEffect)(function () { if (map) { var forceUpdate_1 = function () { return setStyleLoaded(function (version) { return version + 1; }); }; map.on('styledata', forceUpdate_1); forceUpdate_1(); return function () { map.off('styledata', forceUpdate_1); // Parent effects are destroyed before child ones, see // https://github.com/facebook/react/issues/16728 // Source can only be removed after all child layers are removed /* global setTimeout */ setTimeout(function () { // @ts-ignore if (map.style && map.style._loaded && map.getSource(id)) { map.removeSource(id); } }, 0); }; } return undefined; }, [map]); // @ts-ignore var source = map && map.style && map.getSource(id); if (source) { updateSource(source, props, propsRef.current); } else { source = createSource(map, id, props); } propsRef.current = props; return ((source && React.Children.map(props.children, function (child) { return child && (0, react_2.cloneElement)(child, { source: id }); })) || null); } exports.default = Source; //# sourceMappingURL=source.js.map
import { TaskManager, Constants, Logger } from 'rnv'; import { updateProfile } from '../sdks/sdk-xcode/fastlane'; const { executeTask, shouldSkipTask } = TaskManager; const { logTask } = Logger; const { TASK_CRYPTO_UPDATE_PROFILE, TASK_PROJECT_CONFIGURE, TVOS, PARAMS } = Constants; export const taskRnvCryptoUpdateProfile = async (c, parentTask, originTask) => { logTask('taskRnvCryptoUpdateProfile'); await executeTask(c, TASK_PROJECT_CONFIGURE, TASK_CRYPTO_UPDATE_PROFILE, originTask); if (shouldSkipTask(c, TASK_CRYPTO_UPDATE_PROFILE, originTask)) return true; await updateProfile(c); }; export default { description: 'Update provisioning profile', fn: taskRnvCryptoUpdateProfile, task: TASK_CRYPTO_UPDATE_PROFILE, params: PARAMS.withBase(), platforms: [TVOS], skipPlatforms: true, };
const winston = require("winston") require("winston-daily-rotate-file") module.exports = winston.createLogger({ format: winston.format.combine( winston.format.colorize(), winston.format.timestamp(), winston.format.printf(({ level, timestamp, message }) => { return `[${level}][${timestamp}] ${message}` }) ), transports: [ new winston.transports.Console(), new winston.transports.DailyRotateFile({ dirname: "logs", filename: "%DATE%.log", datePattern: "YYYY-MM-DD" }) ] })
// ----------------------------------------------------------------------------------- // // Lightbox v2.04 // by Lokesh Dhakar - http://www.lokeshdhakar.com // Last Modification: 2/9/08 // // For more information, visit: // http://lokeshdhakar.com/projects/lightbox2/ // // Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ // - Free for use in both personal and commercial projects // - Attribution requires leaving author name, author link, and the license info intact. // // Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets. // Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous. // // ----------------------------------------------------------------------------------- /* Table of Contents ----------------- Configuration Lightbox Class Declaration - initialize() - updateImageList() - start() - changeImage() - resizeImageContainer() - showImage() - updateDetails() - updateNav() - enableKeyboardNav() - disableKeyboardNav() - keyboardAction() - preloadNeighborImages() - end() Function Calls - document.observe() */ // ----------------------------------------------------------------------------------- // // Configurationl // LightboxOptions = Object.extend({ fileLoadingImage: '/js/lightbox/loading.gif', fileBottomNavCloseImage: '/js/lightbox/closelabel.gif', overlayOpacity: 0.8, // controls transparency of shadow overlay animate: true, // toggles resizing animations resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest) borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable // When grouping images this is used to write: Image # of #. // Change it for non-english localization labelImage: "Image", labelOf: "of" }, window.LightboxOptions || {}); // ----------------------------------------------------------------------------------- var Lightbox = Class.create(); Lightbox.prototype = { imageArray: [], activeImage: undefined, // initialize() // Constructor runs on completion of the DOM loading. Calls updateImageList and then // the function inserts html at the bottom of the page which is used to display the shadow // overlay and the image container. // initialize: function() { this.updateImageList(); this.keyboardAction = this.keyboardAction.bindAsEventListener(this); if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10; if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1; this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0; this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension. // If animations are turned off, it will be hidden as to prevent a flicker of a // white 250 by 250 box. var size = (LightboxOptions.animate ? 250 : 1) + 'px'; // Code inserts html at the bottom of the page that looks similar to this: // // <div id="overlay"></div> // <div id="lightbox"> // <div id="outerImageContainer"> // <div id="imageContainer"> // <img id="lightboxImage"> // <div style="" id="hoverNav"> // <a href="#" id="prevLink"></a> // <a href="#" id="nextLink"></a> // </div> // <div id="loading"> // <a href="#" id="loadingLink"> // <img src="images/loading.gif"> // </a> // </div> // </div> // </div> // <div id="imageDataContainer"> // <div id="imageData"> // <div id="imageDetails"> // <span id="caption"></span> // <span id="numberDisplay"></span> // </div> // <div id="bottomNav"> // <a href="#" id="bottomNavClose"> // <img src="images/close.gif"> // </a> // </div> // </div> // </div> // </div> var objBody = $$('body')[0]; objBody.appendChild(Builder.node('div',{id:'overlay'})); objBody.appendChild(Builder.node('div',{id:'lightbox'}, [ Builder.node('div',{id:'outerImageContainer'}, Builder.node('div',{id:'imageContainer'}, [ Builder.node('img',{id:'lightboxImage'}), Builder.node('div',{id:'hoverNav'}, [ Builder.node('a',{id:'prevLink', href: '#' }), Builder.node('a',{id:'nextLink', href: '#' }) ]), Builder.node('div',{id:'loading'}, Builder.node('a',{id:'loadingLink', href: '#' }, Builder.node('img', {src: LightboxOptions.fileLoadingImage}) ) ) ]) ), Builder.node('div', {id:'imageDataContainer'}, Builder.node('div',{id:'imageData'}, [ Builder.node('div',{id:'imageDetails'}, [ Builder.node('span',{id:'caption'}), Builder.node('span',{id:'numberDisplay'}) ]), Builder.node('div',{id:'bottomNav'}, Builder.node('a',{id:'bottomNavClose', href: '#' }, Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage }) ) ) ]) ) ])); $('overlay').hide().observe('click', (function() { this.end(); }).bind(this)); $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this)); $('outerImageContainer').setStyle({ width: size, height: size }); $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this)); $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this)); $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); var th = this; (function(){ var ids = 'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose'; $w(ids).each(function(id){ th[id] = $(id); }); }).defer(); }, // // updateImageList() // Loops through anchor tags looking for 'lightbox' references and applies onclick // events to appropriate links. You can rerun after dynamically adding images w/ajax. // updateImageList: function() { this.updateImageList = Prototype.emptyFunction; document.observe('click', (function(event){ var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]'); if (target) { event.stop(); this.start(target); } }).bind(this)); }, // // start() // Display overlay and lightbox. If image is part of a set, add siblings to imageArray. // start: function(imageLink) { $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' }); // stretch overlay to fill page and fade in var arrayPageSize = this.getPageSize(); $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity }); this.imageArray = []; var imageNum = 0; if ((imageLink.rel == 'lightbox')){ // if image is NOT part of a set, add single image to imageArray this.imageArray.push([imageLink.href, imageLink.title]); } else { // if image is part of a set.. this.imageArray = $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]'). collect(function(anchor){ return [anchor.href, anchor.title]; }). uniq(); while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; } } // calculate top and left offset for the lightbox var arrayPageScroll = document.viewport.getScrollOffsets(); var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10); var lightboxLeft = arrayPageScroll[0]; this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show(); this.changeImage(imageNum); }, // // changeImage() // Hide most elements and preload image in preparation for resizing image container. // changeImage: function(imageNum) { this.activeImage = imageNum; // update global var // hide elements during transition if (LightboxOptions.animate) this.loading.show(); this.lightboxImage.hide(); this.hoverNav.hide(); this.prevLink.hide(); this.nextLink.hide(); // HACK: Opera9 does not currently support scriptaculous opacity and appear fx this.imageDataContainer.setStyle({opacity: .0001}); this.numberDisplay.hide(); var imgPreloader = new Image(); // once image is preloaded, resize image container imgPreloader.onload = (function(){ this.lightboxImage.src = this.imageArray[this.activeImage][0]; this.resizeImageContainer(imgPreloader.width, imgPreloader.height); }).bind(this); imgPreloader.src = this.imageArray[this.activeImage][0]; }, // // resizeImageContainer() // resizeImageContainer: function(imgWidth, imgHeight) { // get current width and height var widthCurrent = this.outerImageContainer.getWidth(); var heightCurrent = this.outerImageContainer.getHeight(); // get new width and height var widthNew = (imgWidth + LightboxOptions.borderSize * 2); var heightNew = (imgHeight + LightboxOptions.borderSize * 2); // scalars based on change from old to new var xScale = (widthNew / widthCurrent) * 100; var yScale = (heightNew / heightCurrent) * 100; // calculate size difference between new and old image, and resize if necessary var wDiff = widthCurrent - widthNew; var hDiff = heightCurrent - heightNew; if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); // if new and old image are same size and no scaling transition is necessary, // do a quick pause to prevent image flicker. var timeout = 0; if ((hDiff == 0) && (wDiff == 0)){ timeout = 100; if (Prototype.Browser.IE) timeout = 250; } (function(){ this.prevLink.setStyle({ height: imgHeight + 'px' }); this.nextLink.setStyle({ height: imgHeight + 'px' }); this.imageDataContainer.setStyle({ width: widthNew + 'px' }); this.showImage(); }).bind(this).delay(timeout / 1000); }, // // showImage() // Display image and begin preloading neighbors. // showImage: function(){ this.loading.hide(); new Effect.Appear(this.lightboxImage, { duration: this.resizeDuration, queue: 'end', afterFinish: (function(){ this.updateDetails(); }).bind(this) }); this.preloadNeighborImages(); }, // // updateDetails() // Display caption, image number, and bottom nav. // updateDetails: function() { // if caption is not null if (this.imageArray[this.activeImage][1] != ""){ this.caption.update(this.imageArray[this.activeImage][1]).show(); } // if image is part of set display 'Image x of x' if (this.imageArray.length > 1){ this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show(); } new Effect.Parallel( [ new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) ], { duration: this.resizeDuration, afterFinish: (function() { // update overlay size and update nav var arrayPageSize = this.getPageSize(); this.overlay.setStyle({ height: arrayPageSize[1] + 'px' }); this.updateNav(); }).bind(this) } ); }, // // updateNav() // Display appropriate previous and next hover navigation. // updateNav: function() { this.hoverNav.show(); // if not first image in set, display prev image button if (this.activeImage > 0) this.prevLink.show(); // if not last image in set, display next image button if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show(); this.enableKeyboardNav(); }, // // enableKeyboardNav() // enableKeyboardNav: function() { document.observe('keydown', this.keyboardAction); }, // // disableKeyboardNav() // disableKeyboardNav: function() { document.stopObserving('keydown', this.keyboardAction); }, // // keyboardAction() // keyboardAction: function(event) { var keycode = event.keyCode; var escapeKey; if (event.DOM_VK_ESCAPE) { // mozilla escapeKey = event.DOM_VK_ESCAPE; } else { // ie escapeKey = 27; } var key = String.fromCharCode(keycode).toLowerCase(); if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox this.end(); } else if ((key == 'p') || (keycode == 37)){ // display previous image if (this.activeImage != 0){ this.disableKeyboardNav(); this.changeImage(this.activeImage - 1); } } else if ((key == 'n') || (keycode == 39)){ // display next image if (this.activeImage != (this.imageArray.length - 1)){ this.disableKeyboardNav(); this.changeImage(this.activeImage + 1); } } }, // // preloadNeighborImages() // Preload previous and next images. // preloadNeighborImages: function(){ var preloadNextImage, preloadPrevImage; if (this.imageArray.length > this.activeImage + 1){ preloadNextImage = new Image(); preloadNextImage.src = this.imageArray[this.activeImage + 1][0]; } if (this.activeImage > 0){ preloadPrevImage = new Image(); preloadPrevImage.src = this.imageArray[this.activeImage - 1][0]; } }, // // end() // end: function() { this.disableKeyboardNav(); this.lightbox.hide(); new Effect.Fade(this.overlay, { duration: this.overlayDuration }); $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' }); }, // // getPageSize() // getPageSize: function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } return [pageWidth,pageHeight]; } } document.observe('dom:loaded', function () { new Lightbox(); });
fetch('/admin') .then(res => res.text()) .then(data => { const element = document.createElement('div'); const { body } = document; element.innerHTML = data; body.insertBefore(element, body.firstChild); const input = document.querySelector('input[name="csrf_token"]'); const token = input.value; const reqBody = `csrf_token=${token}`; return fetch('/admin/delete', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: reqBody, }); }) .then(() => console.log('Deleted the account!')) .catch(err => console.error(err));
{"frequencies":[261.6255653006,272.52663052146,294.32876096318,313.95067836072,327.03195662575,348.83408706747,367.91095120397,392.4383479509,408.78994578219,436.04260883433,475.68284600109,490.54793493862,523.2511306012],"description":"Choquel/Barbour/Marpurg?"}
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.readRangeOfDates = exports.readSingleDate = exports.generateKeyStorageDirectoryIfNotExists = exports.createKeyStorageDirectory = exports.keyStorageExists = exports.generateKeyStorageDirectoryPath = exports.createCollectionIfNotExists = exports.createDatabaseIfNotExists = exports.createCollection = exports.createDatabase = exports.collectionExists = exports.databaseExists = exports.getCollectionPath = exports.getDatabasePath = 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; }; var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _local = require('../../config/local'); var _local2 = _interopRequireDefault(_local); var _logger = require('../utils/logger'); var _logger2 = _interopRequireDefault(_logger); var _fs3 = require('./fs'); var _metaData = require('./metaData'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } var caches = { databases: {}, collections: {}, files: {} }; var getDatabasePath = exports.getDatabasePath = function getDatabasePath(database) { return _path2.default.join(_local2.default.path, database); }; var getCollectionPath = exports.getCollectionPath = function getCollectionPath(database, collection) { _logger2.default.debug('getCollectionPath : ', { path: _local2.default.path, database: database, collection: collection }); return _path2.default.join(_local2.default.path, database, 'collections', collection); }; var registerDatabaseInCache = function registerDatabaseInCache(database) { _logger2.default.debug('[utils/fileSystem] cache registration : database ' + database); caches.databases[database] = { collections: {} }; return true; }; var registerCollectionInCache = function registerCollectionInCache(database, collection) { _logger2.default.debug('[utils/fileSystem] cache registration : collection ' + collection); caches.collections[database + '.' + collection] = true; caches.databases[database]['collections'][collection] = true; return true; }; var databaseExists = exports.databaseExists = function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(database) { return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!caches.databases[database]) { _context.next = 2; break; } return _context.abrupt('return', true); case 2: // in case we are not in sync with the file system (bad server reboot ...) _logger2.default.debug('[utils/fileSystem] check path : ' + getDatabasePath(database)); if (!_fs2.default.existsSync(getDatabasePath(database))) { _context.next = 5; break; } return _context.abrupt('return', registerDatabaseInCache(database)); case 5: _logger2.default.debug('[utils/fileSystem] database not found in the file sytem'); return _context.abrupt('return', false); case 7: case 'end': return _context.stop(); } } }, _callee, undefined); })); return function databaseExists(_x) { return _ref.apply(this, arguments); }; }(); var collectionExists = exports.collectionExists = function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(database, collection) { return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return databaseExists(database); case 2: if (_context2.sent) { _context2.next = 4; break; } throw new Error('You cannot create a collection for an unknown database'); case 4: if (!caches.collections[database + '.' + collection]) { _context2.next = 6; break; } return _context2.abrupt('return', true); case 6: // in case we are not in sync with the file system (bad server reboot ...) _logger2.default.debug('[utils/fileSystem] check path : ' + getDatabasePath(database)); if (!_fs2.default.existsSync(getCollectionPath(database, collection))) { _context2.next = 9; break; } return _context2.abrupt('return', registerCollectionInCache(database, collection)); case 9: _logger2.default.debug('[utils/fileSystem] collection not found in the file sytem'); return _context2.abrupt('return', false); case 11: case 'end': return _context2.stop(); } } }, _callee2, undefined); })); return function collectionExists(_x2, _x3) { return _ref2.apply(this, arguments); }; }(); var createDatabase = exports.createDatabase = function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(database) { return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _logger2.default.debug('[utils/fileSystem] create dir : ' + getDatabasePath(database)); _context3.next = 3; return (0, _fs3.mkdir)(getDatabasePath(database) + '/collections'); case 3: if (!_context3.sent) { _context3.next = 5; break; } return _context3.abrupt('return', registerDatabaseInCache(database)); case 5: _logger2.default.debug('[utils/fileSystem] Cannot create the database ' + database + ' - ' + getDatabasePath(database)); throw new Error('Cannot create the database ' + database + ' in ' + getDatabasePath(database)); case 7: case 'end': return _context3.stop(); } } }, _callee3, undefined); })); return function createDatabase(_x4) { return _ref3.apply(this, arguments); }; }(); var createCollection = exports.createCollection = function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(database, collection) { return regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _logger2.default.debug('[utils/fileSystem] create dir : ' + getCollectionPath(database, collection)); _context4.next = 3; return (0, _fs3.mkdir)('' + getCollectionPath(database, collection)); case 3: if (!_context4.sent) { _context4.next = 5; break; } return _context4.abrupt('return', registerCollectionInCache(database, collection)); case 5: _logger2.default.debug('[utils/fileSystem] Cannot create the collection ' + collection + ' - ' + getCollectionPath(database, collection)); throw new Error('Cannot create the database ' + database + ' in ' + getCollectionPath(database, collection)); case 7: case 'end': return _context4.stop(); } } }, _callee4, undefined); })); return function createCollection(_x5, _x6) { return _ref4.apply(this, arguments); }; }(); var createDatabaseIfNotExists = exports.createDatabaseIfNotExists = function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(database) { return regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _logger2.default.debug('[utils/fileSystem] check if database exists: ' + database); _context5.next = 3; return databaseExists(database); case 3: if (_context5.sent) { _context5.next = 10; break; } _logger2.default.debug('[utils/fileSystem] database doesn\'t exists : ' + database); _context5.next = 7; return createDatabase(database); case 7: _context5.next = 9; return (0, _metaData.createDatabase)(database); case 9: return _context5.abrupt('return', getDatabasePath(database)); case 10: _logger2.default.debug('[utils/fileSystem] no database : ' + database); return _context5.abrupt('return', getDatabasePath(database)); case 12: case 'end': return _context5.stop(); } } }, _callee5, undefined); })); return function createDatabaseIfNotExists(_x7) { return _ref5.apply(this, arguments); }; }(); var createCollectionIfNotExists = exports.createCollectionIfNotExists = function () { var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(database, collection) { return regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _logger2.default.debug('[utils/fileSystem] check if collection exists: ' + database + '.' + collection); _context6.next = 3; return collectionExists(database, collection); case 3: if (_context6.sent) { _context6.next = 10; break; } _logger2.default.debug('[utils/fileSystem] collection doesn\'t exists : ' + database + '.' + collection); _context6.next = 7; return createCollection(database, collection); case 7: _context6.next = 9; return (0, _metaData.createCollection)(database, collection); case 9: return _context6.abrupt('return', getCollectionPath(database, collection)); case 10: _logger2.default.debug('[utils/fileSystem] no collection : ' + database + '.' + collection); return _context6.abrupt('return', getCollectionPath(database, collection)); case 12: case 'end': return _context6.stop(); } } }, _callee6, undefined); })); return function createCollectionIfNotExists(_x8, _x9) { return _ref6.apply(this, arguments); }; }(); var formatDate = function formatDate(date) { var d = new Date(date); var month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) { month = '0' + month; } if (day.length < 2) { day = '0' + day; } return [year, month, day].join(''); }; var generateKeyStorageDirectoryPath = exports.generateKeyStorageDirectoryPath = function generateKeyStorageDirectoryPath(database, collection, date) { return _path2.default.join(getCollectionPath(database, collection), formatDate(date)); }; var keyStorageExists = exports.keyStorageExists = function keyStorageExists(path) { if (caches.files[path]) { return true; } if (_fs2.default.existsSync(path)) { caches.files[path] = true; return true; } return false; }; var createKeyStorageDirectory = exports.createKeyStorageDirectory = function createKeyStorageDirectory(path) { return (0, _fs3.mkdir)(path); }; var generateKeyStorageDirectoryIfNotExists = exports.generateKeyStorageDirectoryIfNotExists = function () { var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(database, collection, date) { var path; return regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: path = generateKeyStorageDirectoryPath(database, collection, date); if (!keyStorageExists(path)) { _context7.next = 3; break; } return _context7.abrupt('return', path); case 3: _context7.next = 5; return createKeyStorageDirectory(path); case 5: return _context7.abrupt('return', path); case 6: case 'end': return _context7.stop(); } } }, _callee7, undefined); })); return function generateKeyStorageDirectoryIfNotExists(_x10, _x11, _x12) { return _ref7.apply(this, arguments); }; }(); var escapeOutput = function escapeOutput(content) { if (!content || (typeof content === 'undefined' ? 'undefined' : _typeof(content)) !== _typeof(" ")) { return false; } return content.substring(0, content.length - 2); }; var readSingleDate = exports.readSingleDate = function () { var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(database, collection, key, date) { var objectMode = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; var dirPath, error, content, escapedContent; return regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: dirPath = generateKeyStorageDirectoryPath(database, collection, date); error = {}; content = {}; _context8.prev = 3; _context8.next = 6; return (0, _fs3.readFile)(dirPath + '/' + key + '.json', false); case 6: content = _context8.sent; _context8.next = 12; break; case 9: _context8.prev = 9; _context8.t0 = _context8['catch'](3); error = _context8.t0; case 12: if (!(objectMode === true)) { _context8.next = 19; break; } escapedContent = escapeOutput(content); if (!escapedContent) { _context8.next = 18; break; } return _context8.abrupt('return', { data: JSON.parse('[' + escapedContent + ']'), error: error }); case 18: return _context8.abrupt('return', { data: null, error: 'content is undefined - cannot escape sentence' }); case 19: return _context8.abrupt('return', { data: content, error: error }); case 20: case 'end': return _context8.stop(); } } }, _callee8, undefined, [[3, 9]]); })); return function readSingleDate(_x13, _x14, _x15, _x16) { return _ref8.apply(this, arguments); }; }(); var readRangeOfDates = exports.readRangeOfDates = function () { var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(database, collection, key, dateFrom, dateTo) { var data, errors, d, response, content; return regeneratorRuntime.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: data = []; errors = []; d = dateFrom; case 3: if (!(d <= dateTo)) { _context9.next = 12; break; } _context9.next = 6; return readSingleDate(database, collection, key, d); case 6: response = _context9.sent; if (response.data && response.data.length > 0) { data.push(response.data); } if (response.error && response.error.length > 0) { errors.push(response.error); } case 9: d.setDate(d.getDate() + 1); _context9.next = 3; break; case 12: content = data.join(''); return _context9.abrupt('return', { response: JSON.parse('[' + content.substring(0, content.length - 2) + ']'), errors: errors }); case 14: case 'end': return _context9.stop(); } } }, _callee9, undefined); })); return function readRangeOfDates(_x18, _x19, _x20, _x21, _x22) { return _ref9.apply(this, arguments); }; }();
#!/usr/bin/env node //LED top light controller. code similar to Glowline /* * Copyright (c) 2018, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var fs = require('fs'); var _valid_color = { "min": 0, "max": 30 }; function _openFD(path, fd) { return new Promise(function(resolve, reject) { fs.open(path, "w", 0666, function(err, fd) { if (err) reject(err); else resolve(fd); }); }); } // function _testArrayintwos(array) { // if (array.length % 2 === 0) return true; // else return false; // } // function _wrappedWrite(FD, stat) { // FD = parseInt(FD); // return new dev$Promise(null).when(function(token) { // fs.write(FD, stat, null, null, function(err, written, string) { // if (err) token.reject("error"); // else token.resolve("success"); // }); // }); // } // function _writeColor(FR, FG, FB, r, g, b) { // return new dev$Promise(null).join(_wrappedWrite(FR, r), _wrappedWrite(FB, b), _wrappedWrite(FG, g)); // } /** * [LED class for managing the led] */ var LED = function LED() { this.colorProfile = "RGB"; this.currentred = 0; this.currentgreen = 0; this.currentblue = 0; this.currentalert = false; this.intervalobject = null; this.SDATA = { "gpio": "/sys/class/gpio/gpio37/value", "FD": "", "des": "IO pin on the LPD6803" }; this.SCLK = { "gpio": "/sys/class/gpio/gpio38/value", "FD": "", "des": "Clock pin on the LPD6803" }; if (LED.caller != LED.getInstance) { throw new Error("This object cannot be instanciated"); } }; /** * [init initializes the GPIO pins and the LED] * @return {[ES6-Promise]} [an ES6 style promise for determining if the gpio is ready] */ LED.prototype.init = function(LEDProfile) { //console.log("LPD6803 got inited with " + LEDProfile); if (LEDProfile === null || LEDProfile === undefined) { log.error("LPD6803.js says make sure to specify a LED colorProfile. Defaulting to RGB."); } else { this.colorProfile = LEDProfile; } var self = this; this.SDATA.high = function() { fs.writeSync(self.SDATA.FD, 1); }; this.SDATA.low = function() { fs.writeSync(self.SDATA.FD, 0); }; this.SCLK.high = function() { fs.writeSync(self.SCLK.FD, 1); }; this.SCLK.low = function() { fs.writeSync(self.SCLK.FD, 0); }; var Promise_FD_IO = _openFD(self.SDATA.gpio, self.FD_IO); var Promise_FD_CLK = _openFD(self.SCLK.gpio, self.FD_CLK); return Promise.all([ Promise_FD_IO, Promise_FD_CLK ]).then(function(results) { self.SDATA.FD = results[0]; self.SDATA.low(); self.SCLK.FD = results[1]; self.SCLK.low(); }); /*return new Promise(function(resolve, reject) { Promise_FD_IO.then(function(result) { self.SDATA.FD = result; self.SDATA.low(); }, function(err) {}); Promise_FD_CLK.then(function(result) { self.SCLK.FD = result; self.SCLK.low(); resolve("good man"); }, function(err) {}); });*/ }; /** * [setColorProfile function set the color profile of the LED used on the hardware .] * @param {[string]} LEDProfile ['RGB', 'RBG'] */ LED.prototype.setColorProfile = function(LEDProfile) { if (typeof LEDProfile === 'undefined' || LEDProfile === null || LEDProfile === undefined) { log.error("LPD6803.js says make sure to specify a LED colorProfile. Defaulting to RGB."); } else { this.colorProfile = LEDProfile; log.debug('LPD6803.js says changing color profile to- ', this.colorProfile); } }; /** * [_setcolor internal function that does the work for actually setting the led.] * @param {[integer]} red [Red brightness 0 (off) through 30 (max bright)] * @param {[integer]} green [Green brightness 0 (off) through 30 (max bright)] * @param {[integer]} blue [Blue brightness 0 (off) through 30 (max bright)] */ LED.prototype._setcolor = function(red, green, blue) { self = this; var i, j, k; var nDots = 1; time = 0; var t1; var t2; if(red < 0) { red = 0; } if(green < 0) { green = 0; } if(blue < 0) { blue = 0; } if (self.colorProfile != "RGB") { if (self.colorProfile == "RBG") { t1 = green; green = blue; blue = t1; } if (self.colorProfile == "GRB") { t1 = red; red = green; green = t1; } if (self.colorProfile == "GBR") { t1 = red; red = green; green = blue; blue = t1; } if (self.colorProfile == "BGR") { t1 = red; red = blue; blue = t1; } if (self.colorProfile == "BRG") { t1 = red; t2 = green; red = blue; green = t1; blue = t2; } } self.SCLK.low(); self.SDATA.low(); for (i = 0; i < 32; i++) { self.SCLK.high(); self.SCLK.low(); } for (i = 0; i < nDots; i++) { self.SDATA.high(); self.SCLK.high(); self.SCLK.low(); //output 5 bits red data Mask = 0x10; for (j = 0; j < 5; j++) { maskfilter = (Mask & red); if (Mask & red) { self.SDATA.high(); } else { self.SDATA.low(); } self.SCLK.high(); self.SCLK.low(); Mask >>= 1; } // output 5 bits green data Mask = 0x10; for (j = 0; j < 5; j++) { if (Mask & blue) { self.SDATA.high(); } else { self.SDATA.low(); } self.SCLK.high(); self.SCLK.low(); Mask >>= 1; } // output 5 bits blue data Mask = 0x10; for (j = 0; j < 5; j++) { if (Mask & green) { self.SDATA.high(); } else { self.SDATA.low(); } self.SCLK.high(); self.SCLK.low(); Mask >>= 1; } } self.SDATA.low(); for (i = 0; i < nDots; i++) { self.SCLK.high(); self.SCLK.low(); } }; LED.prototype.heartbeat = function(red, green, blue, bdiff) { self = this; var i = 0; if(this.haveHeartbeat && this.heartbeatColor && (red == this.heartbeatColor.r && green == this.heartbeatColor.g && blue == this.heartbeatColor.b)) { //Heartbeat already running with same color return; } else { this.haveHeartbeat = false; clearInterval(this.heartbeatTimer); } function goLow() { setTimeout(function() { self.setcolor(red - bdiff, green - bdiff, blue - bdiff); goHigh(); }, 2000); } function goHigh() { setTimeout(function() { self.setcolor(red, green, blue); goLow(); }, 500); } this.haveHeartbeat = true; this.heartbeatColor = {r: red, g: green, b: blue}; this.setcolor(red, green, blue); goLow(); }; /** * [alertOn Enables the alert which will interrupt the locked color (last color set by setcolor(R,G,B)) every 2 seconds for 500ms] * @param {[integer]} red [Red brightness 0 (off) through 30 (max bright)] * @param {[integer]} green [Green brightness 0 (off) through 30 (max bright)] * @param {[integer]} blue [Blue brightness 0 (off) through 30 (max bright)] */ LED.prototype.alertOn = function(red, green, blue) { self = this; status = 1; if (self.currentalert === true) { self.alertOff(); } self.currentalert = true; self.intervalobject = setInterval(function() { if (status == 1) { status++; self._setcolor(red, green, blue); } else { if (status == 2) { self._setcolor(self.currentred, self.currentgreen, self.currentblue); } if (status == 5) { status = 0; } status++; } }, 500, status); }; /** * [alertOff diables the current alert led (if there is one)] */ LED.prototype.alertOff = function() { self = this; if(self.currentalert) { self.currentalert = false; clearInterval(self.intervalobject); } }; /** * [alertOneTime immediately blinks the led for 500ms] * @param {[integer]} red [Red brightness 0 (off) through 30 (max bright)] * @param {[integer]} green [Green brightness 0 (off) through 30 (max bright)] * @param {[integer]} blue [Blue brightness 0 (off) through 30 (max bright)] */ LED.prototype.alertOneTime = function(red, green, blue) { var self = this; self._setcolor(red, green, blue); setTimeout(function() { self._setcolor(self.currentred, self.currentgreen, self.currentblue); }, 400); }; /** * [setcolor locks the led to this color] * @param {[integer]} red [Red brightness 0 (off) through 30 (max bright)] * @param {[integer]} green [Green brightness 0 (off) through 30 (max bright)] * @param {[integer]} blue [Blue brightness 0 (off) through 30 (max bright)] * @param {[boolean]} checkPrevious [Only apply if different from previous value] */ LED.prototype.setcolor = function(red, green, blue, checkPrevious) { self = this; if (self.currentred == red && self.currentblue == blue && self.currentgreen == green && !!checkPrevious) { return; } else { self.currentred = red; self.currentgreen = green; self.currentblue = blue; self._setcolor(self.currentred, self.currentgreen, self.currentblue); } }; LED.instance = null; /** * LED getInstance definition * @return LED class */ LED.getInstance = function() { if (this.instance === null) { this.instance = new LED(); } return this.instance; }; //a Singleton. There is only 1 led, so the state should be treated universally throughout the entire system. module.exports = LED.getInstance();
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=world-population-density.json&callback=?', function (data) { // Initiate the chart var chart = Highcharts.mapChart('container', { title: { text: 'Destroy chart from button' }, mapNavigation: { enabled: true, buttonOptions: { verticalAlign: 'bottom' } }, colorAxis: { min: 1, max: 1000, type: 'logarithmic' }, series: [{ data: data, mapData: Highcharts.maps['custom/world'], joinBy: ['iso-a2', 'code'], name: 'Population density', states: { hover: { color: '#a4edba' } }, tooltip: { valueSuffix: '/km²' } }] }); // Activate the button $('#destroy') .attr('disabled', false) .click(function () { chart.destroy(); $(this).attr('disabled', true); }); });
import {} from 'rxjs'; import {} from 'rxjs/operators'; const btnStart = document.getElementById('btnStart'); const result = document.getElementById('result'); btnStart.addEventListener('click', () => { result.textContent = new Date().toLocaleTimeString(); }); /* */ if (module.hot) { module.hot.dispose(function() { location.reload(); }); }
// Do this as the first thing so that any code reading it knows the right env. process.env.BABEL_ENV = 'test' process.env.NODE_ENV = 'test' process.env.PUBLIC_URL = '' // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. process.on('unhandledRejection', (err) => { throw err }) // Ensure environment variables are read. require('../config/env') const jest = require('jest') const execSync = require('child_process').execSync let argv = process.argv.slice(2) function isInGitRepository() { try { execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' }) return true } catch (e) { return false } } function isInMercurialRepository() { try { execSync('hg --cwd . root', { stdio: 'ignore' }) return true } catch (e) { return false } } // Watch unless on CI or explicitly running all tests if ( !process.env.CI && argv.indexOf('--watchAll') === -1 && argv.indexOf('--watchAll=false') === -1 ) { // https://github.com/facebook/create-react-app/issues/5210 const hasSourceControl = isInGitRepository() || isInMercurialRepository() argv.push(hasSourceControl ? '--watch' : '--watchAll') } jest.run(argv)
/*! * LetsBlog * Header - v1.0.0 (2018-09-26T09:18:17Z) * Released under MIT license */ const base = require('lib/base@1.1'); const $ = require('lib/dom@1.1'); const ajax = require('lib/ajax@1.3'); const currentUser = window.currentUser; const header = $('#header'); // 菜单开关类 const Toggle = base.createClass(function(wrapper, toggleClass, layerClass) { const t = this; t._toggle = wrapper.find('.' + toggleClass).click(function() { if (t._on) { t.hide(); } else { t.show(); } }); t._layer = wrapper.find('.' + layerClass); t._toggleOnClass = toggleClass + '--on'; t._layerOnClass = layerClass + '--on'; let isClickInWrapper; wrapper.click(function() { isClickInWrapper = true; }); $('body').click(function() { if (!isClickInWrapper) { t.hide(); } isClickInWrapper = false; }); }, { show: function() { const t = this; t._toggle.addClass(t._toggleOnClass); t._layer.addClass(t._layerOnClass); t._on = true; }, hide: function() { const t = this; t._toggle.removeClass(t._toggleOnClass); t._layer.removeClass(t._layerOnClass); t._on = false; } }); new Toggle( header.find('.header__nav'), 'header__nav__toggle', 'header__nav__list' ); new Toggle( header.find('.header__user'), 'header__user__toggle', 'header__user__menu' ); if (currentUser && currentUser.group.perm_manage_comment) { const getTotalPendingViews = function() { ajax.send({ url: '/admin/comment/totalpendingreviews', dataType: 'json' }).spread(function(res) { const element = header.find('.header__user__menu__item__admin__pending-reviews'); if (res.status === 1 && res.data.total > 0) { element.find('em').text(res.data.total); element.show(); } else { element.hide(); } setTimeout(getTotalPendingViews, 60000); }); }; getTotalPendingViews(); }
mycallback( {"CONTRIBUTOR OCCUPATION": "Consultant", "CONTRIBUTION AMOUNT (F3L Bundled)": "200.00", "ELECTION CODE": "G2010", "MEMO CODE": "", "CONTRIBUTOR EMPLOYER": "TekForm Management Inc", "DONOR CANDIDATE STATE": "", "CONTRIBUTOR STREET 1": "P.O. Box 1780", "CONTRIBUTOR MIDDLE NAME": "", "DONOR CANDIDATE FEC ID": "", "DONOR CANDIDATE MIDDLE NAME": "", "CONTRIBUTOR STATE": "CA", "DONOR CANDIDATE FIRST NAME": "", "CONTRIBUTOR FIRST NAME": "Stanley", "BACK REFERENCE SCHED NAME": "", "DONOR CANDIDATE DISTRICT": "", "CONTRIBUTION DATE": "20101026", "DONOR COMMITTEE NAME": "", "MEMO TEXT/DESCRIPTION": "", "Reference to SI or SL system code that identifies the Account": "", "FILER COMMITTEE ID NUMBER": "C00441410", "DONOR CANDIDATE LAST NAME": "", "CONTRIBUTOR LAST NAME": "Zalkind", "_record_type": "fec.version.v7_0.SA", "CONDUIT STREET2": "", "CONDUIT STREET1": "", "DONOR COMMITTEE FEC ID": "", "CONTRIBUTION PURPOSE DESCRIP": "", "CONTRIBUTOR ZIP": "92038", "CONTRIBUTOR STREET 2": "", "CONDUIT CITY": "", "ENTITY TYPE": "IND", "CONTRIBUTOR CITY": "LA JOLLA", "CONTRIBUTOR SUFFIX": "", "TRANSACTION ID": "INCA781", "DONOR CANDIDATE SUFFIX": "", "DONOR CANDIDATE OFFICE": "", "CONTRIBUTION PURPOSE CODE": "15", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727399.fec_1.yml", "CONDUIT STATE": "", "CONTRIBUTOR ORGANIZATION NAME": "", "BACK REFERENCE TRAN ID NUMBER": "", "DONOR CANDIDATE PREFIX": "", "CONTRIBUTOR PREFIX": "Mr.", "CONDUIT ZIP": "", "CONDUIT NAME": "", "CONTRIBUTION AGGREGATE F3L Semi-annual Bundled": "200.00", "FORM TYPE": "SA11AI"});
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; function main(name) { // [START datacatalog_v1_generated_PolicyTagManager_GetPolicyTag_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. Resource name of the policy tag. */ // const name = 'abc123' // Imports the Datacatalog library const {PolicyTagManagerClient} = require('@google-cloud/datacatalog').v1; // Instantiates a client const datacatalogClient = new PolicyTagManagerClient(); async function callGetPolicyTag() { // Construct request const request = { name, }; // Run request const response = await datacatalogClient.getPolicyTag(request); console.log(response); } callGetPolicyTag(); // [END datacatalog_v1_generated_PolicyTagManager_GetPolicyTag_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
let commands = {}, helpers = {}, extensions = {}; function assertIsSimulator (driver) { if (!driver.isSimulator()) { throw new Error('Permissions setting can only be performed on Simulator'); } } function assertPermissionOptions (opts = {}) { if (!opts.service) { throw new Error('Service name is mandatory to set'); } if (!opts.bundleId) { throw new Error('Bundle identifier name is mandatory to set'); } return opts; } /** * @typedef {Object} GetPermissionOptions * * @property {string} service - One of available service names. The following services are supported: * calendar, * camera, * contacts, * homekit, * microphone, * photos, * reminders, * medialibrary, * motion, * health:, * siri, * speech. * @property {string} bundleId - The bundle identifier of the destination app. */ /** * Gets application permission state on Simulator. * * @param {GetPermissionOptions} opts - Permission options. * @returns {string} Either 'yes', 'no' or 'unset' * @throws {Error} If permission getting fails or the device is not a Simulator. */ commands.mobileGetPermission = async function mobileGetPermission (opts = {}) { const { service, bundleId, } = assertPermissionOptions(opts); assertIsSimulator(this); return await this.opts.device.getPermission(bundleId, service); }; Object.assign(extensions, commands, helpers); export { commands, helpers }; export default extensions;
/* * Copyright 2018 Comcast Cable Communications Management, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ angular.module('controller.zones', []) .controller('ZonesController', function ($scope, $http, $location, $log, recordsService, zonesService, profileService, groupsService, utilityService, $timeout, pagingService) { $scope.alerts = []; $scope.zonesLoaded = false; $scope.allZonesLoaded = false; $scope.hasZones = false; // Re-assigned each time zones are fetched without a query $scope.query = ""; // Paging status for zone sets var zonesPaging = pagingService.getNewPagingParams(100); var allZonesPaging = pagingService.getNewPagingParams(100); profileService.getAuthenticatedUserData().then(function (results) { if (results.data) { $scope.profile = results.data; $scope.profile.active = 'zones'; } }, function () { $scope.profile = $scope.profile || {}; $scope.profile.active = 'zones'; }); $scope.resetCurrentZone = function () { $scope.currentZone = {}; if($scope.myGroups && $scope.myGroups.length) { $scope.currentZone.adminGroupId = $scope.myGroups[0].id; } $scope.currentZone.connection = {}; $scope.currentZone.transferConnection = {}; }; groupsService.getGroups().then(function (results) { if (results.data) { $scope.myGroups = results.data.groups; $scope.myGroupIds = results.data.groups.map(function(grp) {return grp['id']}); } $scope.resetCurrentZone(); }); zonesService.getBackendIds().then(function (results) { if (results.data) { $scope.backendIds = results.data; } }); $scope.canAccessGroup = function(groupId) { return $scope.myGroupIds.indexOf(groupId) > -1; }; $scope.canAccessZone = function(accessLevel) { if (accessLevel == 'Read' || accessLevel == 'Delete') { return true; } else { return false; } }; /* Refreshes zone data set and then re-displays */ $scope.refreshZones = function () { zonesPaging = pagingService.resetPaging(zonesPaging); allZonesPaging = pagingService.resetPaging(allZonesPaging); zonesService .getZones(zonesPaging.maxItems, undefined, $scope.query) .then(function (response) { $log.log('zonesService::getZones-success (' + response.data.zones.length + ' zones)'); zonesPaging.next = response.data.nextId; updateZoneDisplay(response.data.zones); if (!$scope.query.length) { $scope.hasZones = response.data.zones.length > 0; } }) .catch(function (error) { handleError(error, 'zonesService::getZones-failure'); }); zonesService .getZones(zonesPaging.maxItems, undefined, $scope.query, true) .then(function (response) { $log.log('zonesService::getZones-success (' + response.data.zones.length + ' zones)'); allZonesPaging.next = response.data.nextId; updateAllZonesDisplay(response.data.zones); }) .catch(function (error) { handleError(error, 'zonesService::getZones-failure'); }); }; function updateZoneDisplay (zones) { $scope.zones = zones; $scope.myZoneIds = zones.map(function(zone) {return zone['id']}); $scope.zonesLoaded = true; $log.log("Displaying my zones: ", $scope.zones); if($scope.zones.length > 0) { $("td.dataTables_empty").hide(); } else { $("td.dataTables_empty").show(); } } function updateAllZonesDisplay (zones) { $scope.allZones = zones; $scope.allZonesLoaded = true; $log.log("Displaying all zones: ", $scope.allZones); if($scope.allZones.length > 0) { $("td.dataTables_empty").hide(); } else { $("td.dataTables_empty").show(); } } /* Set total number of zones */ $scope.addZoneConnection = function () { if ($scope.processing) { $log.log('zoneConnection::processing is true; exiting'); return; } //flag to prevent multiple clicks until previous promise has resolved. $scope.processing = true; $scope.currentZone = zonesService.checkBackendId($scope.currentZone); zonesService.sendZone($scope.currentZone) .then(function () { $timeout($scope.refreshZones(), 1000); $("#zone_connection_modal").modal("hide"); $scope.processing = false; }) .catch(function (error){ $("#zone_connection_modal").modal("hide"); $scope.zoneError = true; handleError(error, 'zonesService::sendZone-failure'); $scope.processing = false; }); }; function handleError(error, type) { $scope.zoneError = true; var alert = utilityService.failure(error, type); $scope.alerts.push(alert); if(error.data !== undefined && error.data.errors !== undefined) { var errors = error.data.errors; for(i in errors) { $scope.alerts.push({type: "danger", content:errors[i]}); } } } /* * Zone set paging */ $scope.getZonesPageNumber = function(tab) { switch(tab) { case 'myZones': return pagingService.getPanelTitle(zonesPaging); case 'allZones': return pagingService.getPanelTitle(allZonesPaging); } }; $scope.prevPageEnabled = function(tab) { switch(tab) { case 'myZones': return pagingService.prevPageEnabled(zonesPaging); case 'allZones': return pagingService.prevPageEnabled(allZonesPaging); } }; $scope.nextPageEnabled = function(tab) { switch(tab) { case 'myZones': return pagingService.nextPageEnabled(zonesPaging); case 'allZones': return pagingService.nextPageEnabled(allZonesPaging); } }; $scope.prevPageMyZones = function() { var startFrom = pagingService.getPrevStartFrom(zonesPaging); return zonesService .getZones(zonesPaging.maxItems, startFrom, $scope.query, false) .then(function(response) { zonesPaging = pagingService.prevPageUpdate(response.data.nextId, zonesPaging); updateZoneDisplay(response.data.zones); }) .catch(function (error) { handleError(error,'zonesService::prevPage-failure'); }); } $scope.prevPageAllZones = function() { var startFrom = pagingService.getPrevStartFrom(allZonesPaging); return zonesService .getZones(allZonesPaging.maxItems, startFrom, $scope.query, true) .then(function(response) { allZonesPaging = pagingService.prevPageUpdate(response.data.nextId, allZonesPaging); updateAllZonesDisplay(response.data.zones); }) .catch(function (error) { handleError(error,'zonesService::prevPage-failure'); }); } $scope.nextPageMyZones = function () { return zonesService .getZones(zonesPaging.maxItems, zonesPaging.next, $scope.query, false) .then(function(response) { var zoneSets = response.data.zones; zonesPaging = pagingService.nextPageUpdate(zoneSets, response.data.nextId, zonesPaging); if (zoneSets.length > 0) { updateZoneDisplay(response.data.zones); } }) .catch(function (error) { handleError(error,'zonesService::nextPage-failure') }); }; $scope.nextPageAllZones = function () { return zonesService .getZones(allZonesPaging.maxItems, allZonesPaging.next, $scope.query, true) .then(function(response) { var zoneSets = response.data.zones; allZonesPaging = pagingService.nextPageUpdate(zoneSets, response.data.nextId, allZonesPaging); if (zoneSets.length > 0) { updateAllZonesDisplay(response.data.zones); } }) .catch(function (error) { handleError(error,'zonesService::nextPage-failure') }); }; $timeout($scope.refreshZones, 0); });
function button_states() { var win = Ti.UI.createWindow(); var button1 = Titanium.UI.createButton({ left:10, top:10, height:50, width:50, enabled:true, focusable:true, title:'B1', backgroundColor: 'white', backgroundImage:'/images/slightlylargerimage.png' }); var button2 = Titanium.UI.createButton({ left:70, top:10, height:50, width:50, focusable:true, enabled:true, title:'B2', backgroundColor: 'white', backgroundDisabledImage:'/images/slightlylargerimage.png' }); var button3 = Titanium.UI.createButton({ left:130, top:10, height:50, width:50, enabled:true, focusable:true, title:'B3', backgroundColor: 'white', backgroundFocusedImage:'/images/slightlylargerimage.png' }); var button4 = Titanium.UI.createButton({ left:190, top:10, height:50, width:50, focusable:true, enabled:true, title:'B4', backgroundColor: 'white', backgroundSelectedImage:'/images/slightlylargerimage.png' }); var button5 = Titanium.UI.createButton({ left:10, top:200, height:60, width:100, focusable:true, enabled:true, title:'click me' }); var state=1; button5.addEventListener('click',function() { switch(state) { case 0: button2.focusable=true; button2.enabled=true; state=1; break; case 1: button2.focusable=false; button2.enabled=false; state=0; break; } }) win.add(button1); win.add(button2); win.add(button3); win.add(button4); win.add(button5); return win; } module.exports = button_states;
!function(t){"use strict";t.fn.activateRangeOutput=function(){return this.each(function(){var n=t(this),a=t('output[for="'+n.attr("id")+'"]').first();a.length&&(a.html(n.val()),n.on("change",function(a){t('output[for="'+n.attr("id")+'"]').first().html(t(this).val())})),(a=t('input[for="'+n.attr("id")+'"]').first()).length&&(a.val(n.val()),n.on("change",function(a){t('input[for="'+n.attr("id")+'"]').first().val(t(this).val())}),a.on("change",function(n){t("#"+a.attr("for")).val(t(this).val())}),a.on("keyup",function(n){t("#"+a.attr("for")).val(t(this).val())}))})},t.fn.activateMaxlengthOutput=function(){function n(n){var a=parseInt(n.attr("maxlength")),i=n.val().length;t('output[for="'+n.attr("id")+'"]').first().html(i+" / "+a)}return this.each(function(){var a=t(this);parseInt(a.attr("maxlength"))&&t('output[for="'+a.attr("id")+'"]').first().length&&(n(a),a.on("keyup",function(){n(t(this))}))})},t.fn.activateAutosizeTextarea=function(){function n(t){for(var n=t.val().split(/[\n\r]/g),a=0,i=parseInt(t.attr("cols")),r=0;r<n.length;++r)a+=Math.max(Math.ceil(n[r].length/i),1);t.attr("rows",Math.max(a,2)+1)}return this.each(function(){var a=t(this);a.attr("cols")||a.attr("cols",Math.ceil(a.width()/16)),n(a),a.on("keyup",function(){n(t(this))})})},t.fn.getScriptWithCache=function(t,n){return this.length&&jQuery.ajax({url:t,dataType:"script",cache:!0}).done(this.each(n)),this}}(jQuery);
import React from 'react'; import Button from '@material-ui/core/Button' import Typography from '@material-ui/core/Typography' import StyledDate from './StyledDate' import TweetText from './TweetText' import Paper from '@material-ui/core/Paper' import Avatar from '@material-ui/core/Avatar' import Grid from '@material-ui/core/Grid' import PropTypes from 'prop-types' import { withStyles } from '@material-ui/core/styles' const styles = { tweet:{ maxWidth: 400 }, avatar:{ width: 48, height: 48, marginLeft: 8, marginTop: 8, marginRight: 8, marginBottom: 0 }, username: { padding: 5, paddingTop:10 }, content:{ padding: 5, paddingBottom: 8 } }; const Tweet = (props) => { const { classes } = props; return( <Paper className={classes.tweet}> <Grid container alignItems={"center"}> <Grid item> {/*if no profile image is found, provide a default*/} {(props.tweet.user.profile_image_url ? <Avatar className={classes.avatar} src={props.tweet.user.profile_image_url} /> : <Avatar className={classes.avatar} src={"/people.ico"}/>)} </Grid> <Grid item className={classes.username}> <Typography variant={"title"}> {props.tweet.user.name} <br/> <Typography component={"p"}> @{props.tweet.user.screen_name} </Typography> </Typography> </Grid> <Grid item> <Grid container direction={"column"} className={classes.content}> <Grid item > <TweetText tweet={props.tweet}/> </Grid> <Grid container direction={"row"} justify={"space-around"} alignItems={"flex-end"}> <Grid item > <Typography variant={'body1'} gutterBottom> <StyledDate date={props.tweet.created_at}/> </Typography> </Grid> <Grid item> <a href={`https://www.twitter.com/statuses/${props.tweet.id_str}`} target={"_blank"}> <Button variant={"contained"} size="small" color={props.palette}> View on Twitter </Button> </a> </Grid> </Grid> </Grid> </Grid> </Grid> </Paper> ) }; Tweet.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(Tweet);
//// [constantOverloadFunctionNoSubtypeError.ts] class Base { foo() { } } class Derived1 extends Base { bar() { } } class Derived2 extends Base { baz() { } } class Derived3 extends Base { biz() { } } function foo(tagName: 'canvas'): Derived3; function foo(tagName: 'div'): Derived2; function foo(tagName: 'span'): Derived1; function foo(tagName: number): Base; function foo(tagName: any): Base { return null; } //// [constantOverloadFunctionNoSubtypeError.js] var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Base = /** @class */ (function () { function Base() { } Base.prototype.foo = function () { }; return Base; }()); var Derived1 = /** @class */ (function (_super) { __extends(Derived1, _super); function Derived1() { return _super !== null && _super.apply(this, arguments) || this; } Derived1.prototype.bar = function () { }; return Derived1; }(Base)); var Derived2 = /** @class */ (function (_super) { __extends(Derived2, _super); function Derived2() { return _super !== null && _super.apply(this, arguments) || this; } Derived2.prototype.baz = function () { }; return Derived2; }(Base)); var Derived3 = /** @class */ (function (_super) { __extends(Derived3, _super); function Derived3() { return _super !== null && _super.apply(this, arguments) || this; } Derived3.prototype.biz = function () { }; return Derived3; }(Base)); function foo(tagName) { return null; }
module.exports = { env: { browser: true, es6: true, }, extends: ['airbnb', 'prettier', 'prettier/react'], parser: 'babel-eslint', parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 2018, sourceType: 'module', }, plugins: ['react', 'prettier'], rules: { 'import/no-extraneous-dependencies': 'off', 'import/prefer-default-export': 'off', 'react/jsx-filename-extension': 'off', }, settings: { 'import/resolver': { node: { extensions: ['.js'], moduleDirectory: ['node_modules', '.'], }, }, }, };
// Dependencies const express = require("express"); const router = express.Router(); const fs = require("fs"); const path = require("path"); /****************** ***INDEX ROUTES*** ******************/ router.get("/", (req, res) => { res.type("html"); fs.readFile("../client/build/index.html", (err, data) => { res.send(data); }); }); router.get("/static/:folder/:filename", (req, res) => { const { folder, filename } = req.params; fs.readFile(`../client/build/static/${folder}/${filename}`, (err, data) => { if (folder === "media") { } else { res.type(folder); } res.send(data); }); }); router.get("/:file", (req, res) => { const { file } = req.params; const extension = path.extname(file); if (extension) { res.type(extension); fs.readFile(`../client/build/${file}`, (err, data) => { res.send(data); }); } else { res.type("html"); fs.readFile("../client/build/index.html", (err, data) => { res.send(data); }); } }); module.exports = router;
export const GETSTRATEGY_REQUESTING ='GETSTRATEGY_REQUESTING'; export const GETSTRATEGY_REQUESTED = 'GETSTRATEGY_REQUESTED'; export const GETSTRATEGY_ERROR = 'GETSTRATEGY_ERROR'; export const GETPAGE_REQUESTING = 'GETPAGE_REQUESTING'; export const GETPAGE_REQUESTED = 'GETPAGE_REQUESTED'; export const GETPAGE_ERROR = 'GETPAGE_ERROR';
/* jshint -W097 */ /* jshint -W030 */ /* jshint strict:true */ /* jslint node: true */ /* jslint esversion: 6 */ 'use strict'; const shellyHelper = require('../shelly-helper'); /** * Shelly Switch 2.5 / SHSW-25 / shellyswitch25 * CoAP: * {"blk":[{"I":0,"D":"Relay0"},{"I":1,"D":"Relay1"},{"I":2,"D":"Device"}],"sen":[{"I":112,"T":"S","D":"State","R":"0/1","L":0},{"I":122,"T":"S","D":"State","R":"0/1","L":1},{"I":111,"T":"W","D":"Power","R":"0/2300","L":0},{"I":121,"T":"W","D":"Power","R":"0/2300","L":1},{"I":113,"T":"S","D":"Position","R":"0/100","L":2},{"I":118,"T":"S","D":"Input","R":"0/1/2","L":2},{"I":128,"T":"S","D":"Input","R":"0/1/2","L":2},{"I":115,"T":"tC","R":"-40/300","L":2},{"I":116,"T":"tF","R":"-40/300","L":2},{"I":117,"T":"Overtemp","R":"0/1","L":2}]} */ let shellyswitch25 = { 'Relay0.Switch': { coap: { coap_publish: '112', coap_publish_funct: (value) => { return value == 1 ? true : false; }, http_cmd: '/relay/0', http_cmd_funct: async (value, self) => { return value === true ? { turn: 'on', timer: await shellyHelper.getSetDuration(self, 'Relay0.Timer') } : { turn: 'off', timer: await shellyHelper.getSetDuration(self, 'Relay0.Timer') }; } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/relay/0', mqtt_cmd: 'shellies/shellyswitch25-<deviceid>/relay/0/command', mqtt_cmd_funct: (value) => { return value === true ? 'on' : 'off'; }, mqtt_publish_funct: (value) => { return value === 'on'; } }, common: { 'name': 'Switch', 'type': 'boolean', 'role': 'switch', 'read': true, 'write': true, 'def': false } }, 'Relay0.AutoTimerOff': { coap: { http_publish: '/settings', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[0].auto_off : undefined; }, http_cmd: '/settings/relay/0', http_cmd_funct: (value) => { return { auto_off: value }; } }, mqtt: { http_publish: '/settings', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[0].auto_off : undefined; }, http_cmd: '/settings/relay/0', http_cmd_funct: (value) => { return { auto_off: value }; } }, common: { 'name': 'Auto Timer Off', 'type': 'number', 'role': 'level.timer', 'def': 0, 'unit': 's', 'read': true, 'write': true } }, 'Relay0.AutoTimerOn': { coap: { http_publish: '/settings', http_cmd: '/settings/relay/0', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[0].auto_on : undefined; }, http_cmd_funct: (value) => { return { auto_on: value }; } }, mqtt: { http_publish: '/settings', http_cmd: '/settings/relay/0', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[0].auto_on : undefined; }, http_cmd_funct: (value) => { return { auto_on: value }; } }, common: { 'name': 'Auto Timer Off', 'type': 'number', 'role': 'level.timer', 'def': 0, 'unit': 's', 'read': true, 'write': true } }, 'Relay0.ButtonType': { coap: { http_publish: '/settings', http_cmd: '/settings/relay/0', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[0].btn_type : undefined; }, http_cmd_funct: (value) => { return { btn_type: value }; } }, mqtt: { http_publish: '/settings', http_cmd: '/settings/relay/0', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[0].btn_type : undefined; }, http_cmd_funct: (value) => { return { btn_type: value }; } }, common: { 'name': 'Button Type', 'type': 'string', 'role': 'state', 'read': true, 'write': true, 'states': 'momentary:momentary;toggle:toggle;edge:edge;detached:detached;action:action;cycle:cycle;momentary_on_release:momentary_on_release' } }, 'Relay0.ButtonReverse': { coap: { http_publish: '/settings', http_cmd: '/settings/relay/0', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[0].btn_reverse : undefined; }, http_cmd_funct: (value) => { return { btn_reverse: value }; } }, mqtt: { http_publish: '/settings', http_cmd: '/settings/relay/0', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[0].btn_reverse : undefined; }, http_cmd_funct: (value) => { return { btn_reverse: value }; } }, common: { 'name': 'Button Type', 'type': 'number', 'role': 'state', 'read': true, 'write': true, 'states': '0:normal;1:inverted' } }, 'Relay0.Timer': { coap: { http_publish: '/settings', http_publish_funct: async (value, self) => { return await shellyHelper.getSetDuration(self, 'Relay0.Timer'); } }, mqtt: { no_display: true }, common: { 'name': 'Duration', 'type': 'number', 'role': 'level.timer', 'read': true, 'write': true, 'def': 0, 'unit': 's' } }, 'Relay0.Power': { coap: { coap_publish: '111', coap_publish_funct: (value) => { return (Math.round(value* 100) / 100); } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/relay/0/power', mqtt_publish_funct: (value) => { return (Math.round(value * 100) / 100); } }, common: { 'name': 'Power', 'type': 'number', 'role': 'value.power', 'read': true, 'write': false, 'def': 0, 'unit': 'W' } }, 'Relay0.Energy': { coap: { http_publish: '/settings', http_publish_funct: (value) => { return value ? (Math.round((JSON.parse(value).meters[0].total / 60) * 100) / 100) : undefined; } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/relay/0/energy', mqtt_publish_funct: (value) => { return Math.round((value / 60) * 100) / 100; } }, common: { 'name': 'Energy', 'type': 'number', 'role': 'value.power', 'read': true, 'write': false, 'def': 0, 'unit': 'Wh' } }, 'Relay0.Input': { coap: { no_display: true }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/input/0', mqtt_publish_funct: (value) => { return value == 1 ? true : false; } }, common: { 'name': 'Input / Detach', 'type': 'boolean', 'role': 'state', 'read': true, 'write': false, 'def': false } }, 'Relay0.longpush': { coap: { no_display: true }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/longpush/0', mqtt_publish_funct: (value) => { return value == 1 ? true : false; } }, common: { 'name': 'Longpush', 'type': 'boolean', 'role': 'state', 'read': true, 'write': false, 'def': false } }, 'Relay1.Switch': { coap: { coap_publish: '122', coap_publish_funct: (value) => { return value == 1 ? true : false; }, http_cmd: '/relay/1', http_cmd_funct: async (value, self) => { return value === true ? { turn: 'on', timer: await shellyHelper.getSetDuration(self, 'Relay1.Timer') } : { turn: 'off', timer: await shellyHelper.getSetDuration(self, 'Relay1.Timer') }; } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/relay/1', mqtt_cmd: 'shellies/shellyswitch25-<deviceid>/relay/1/command', mqtt_cmd_funct: (value) => { return value === true ? 'on' : 'off'; }, mqtt_publish_funct: (value) => { return value === 'on'; } }, common: { 'name': 'Switch', 'type': 'boolean', 'role': 'switch', 'read': true, 'write': true, 'def': false } }, 'Relay1.AutoTimerOff': { coap: { http_publish: '/settings', http_cmd: '/settings/relay/1', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[1].auto_off : undefined; }, http_cmd_funct: (value) => { return { auto_off: value }; } }, mqtt: { http_publish: '/settings', http_cmd: '/settings/relay/1', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[1].auto_off : undefined; }, http_cmd_funct: (value) => { return { auto_off: value }; } }, common: { 'name': 'Auto Timer Off', 'type': 'number', 'role': 'level.timer', 'def': 0, 'unit': 's', 'read': true, 'write': true } }, 'Relay1.AutoTimerOn': { coap: { http_publish: '/settings', http_cmd: '/settings/relay/1', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[1].auto_on : undefined; }, http_cmd_funct: (value) => { return { auto_on: value }; } }, mqtt: { http_publish: '/settings', http_cmd: '/settings/relay/1', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[1].auto_on : undefined; }, http_cmd_funct: (value) => { return { auto_on: value }; } }, common: { 'name': 'Auto Timer Off', 'type': 'number', 'role': 'level.timer', 'def': 0, 'unit': 's', 'read': true, 'write': true } }, 'Relay1.ButtonType': { coap: { http_publish: '/settings', http_cmd: '/settings/relay/1', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[1].btn_type : undefined; }, http_cmd_funct: (value) => { return { btn_type: value }; } }, mqtt: { http_publish: '/settings', http_cmd: '/settings/relay/1', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[1].btn_type : undefined; }, http_cmd_funct: (value) => { return { btn_type: value }; } }, common: { 'name': 'Button Type', 'type': 'string', 'role': 'state', 'read': true, 'write': true, 'states': 'momentary:momentary;toggle:toggle;edge:edge;detached:detached;action:action;cycle:cycle;momentary_on_release:momentary_on_release' } }, 'Relay1.ButtonReverse': { coap: { http_publish: '/settings', http_cmd: '/settings/relay/1', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[1].btn_reverse : undefined; }, http_cmd_funct: (value) => { return { btn_reverse: value }; } }, mqtt: { http_publish: '/settings', http_cmd: '/settings/relay/1', http_publish_funct: (value) => { return value ? JSON.parse(value).relays[1].btn_reverse : undefined; }, http_cmd_funct: (value) => { return { btn_reverse: value }; } }, common: { 'name': 'Button Type', 'type': 'number', 'role': 'state', 'read': true, 'write': true, 'states': '0:normal;1:inverted' } }, 'Relay1.Timer': { coap: { http_publish: '/settings', http_publish_funct: async (value, self) => { return await shellyHelper.getSetDuration(self, 'Relay1.Timer'); } }, mqtt: { no_display: true }, common: { 'name': 'Duration', 'type': 'number', 'role': 'level.timer', 'read': true, 'write': true, 'def': 0, 'unit': 's' } }, 'Relay1.Power': { coap: { coap_publish: '121', coap_publish_funct: (value) => { return (Math.round(value* 100) / 100); } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/relay/1/power', mqtt_publish_funct: (value) => { return (Math.round(value * 100) / 100); } }, common: { 'name': 'Power', 'type': 'number', 'role': 'value.power', 'read': true, 'write': false, 'def': 0, 'unit': 'W' } }, 'Relay1.Energy': { coap: { http_publish: '/settings', http_publish_funct: (value) => { return value ? (Math.round((JSON.parse(value).meters[1].total / 60) * 100) / 100) : undefined; } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/relay/1/energy', mqtt_publish_funct: (value) => { return Math.round((value / 60) * 100) / 100; } }, common: { 'name': 'Energy', 'type': 'number', 'role': 'value.power', 'read': true, 'write': false, 'def': 0, 'unit': 'Wh' } }, 'Relay1.Input': { coap: { no_display: true }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/input/1', mqtt_publish_funct: (value) => { return value == 1 ? true : false; }, }, common: { 'name': 'Input / Detach', 'type': 'boolean', 'role': 'state', 'read': true, 'write': false, 'def': false } }, 'Relay1.longpush': { coap: { no_display: true }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/longpush/1', mqtt_publish_funct: (value) => { return value == 1 ? true : false; }, }, common: { 'name': 'Longpush', 'type': 'boolean', 'role': 'state', 'read': true, 'write': false, 'def': false } }, 'Shutter.state': { coap: { coap_publish: ['112','122'], coap_publish_funct: (value) => { return value[0] === 1 ? 'open' : value[1] === 1 ? 'close' : 'stop'; }, http_cmd: '/roller/0', http_cmd_funct: (value) => { return { go: value }; }, }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/roller/0', mqtt_cmd: 'shellies/shellyswitch25-<deviceid>/roller/0/command' }, common: { 'name': 'Roller state', 'type': 'string', 'role': 'state', 'read': true, 'write': true, 'states': 'close:close;open:open;stop:stop' } }, 'Shutter.Close': { coap: { // http_cmd: '/roller/0', // http_cmd_funct: () => { return { go: 'close' }; }, http_cmd: '/roller/0', http_cmd_funct: async (value, self) => { return { go: 'close', duration: await shellyHelper.getSetDuration(self, 'Shutter.Duration', 0) }; }, // http_publish: '/settings', // http_publish_funct: (value) => { return JSON.parse(value) ? JSON.parse(value).rollers.maxtime : undefined; }, }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/roller/0', mqtt_cmd_funct: () => { return 'close'; }, mqtt_cmd: 'shellies/shellyswitch25-<deviceid>/roller/0/command', mqtt_publish_funct: (value) => { return value == 'close' ? true : false; } // http_publish: '/settings', // http_publish_funct: (value) => { return JSON.parse(value) ? JSON.parse(value).rollers.maxtime : undefined; }, // http_cmd: '/roller/0', // http_cmd_funct: () => async (value,self) => { return { go: 'close', duration: await getSetDuration(self, 'Shutter.Duration') }; } }, common: { 'name': 'Close', 'type': 'boolean', 'role': 'button', 'read': false, 'write': true } }, 'Shutter.Open': { coap: { // http_cmd: '/roller/0', // http_cmd_funct: () => { return { go: 'open' }; }, http_cmd: '/roller/0', http_cmd_funct: async (value, self) => { return { go: 'open', duration: await shellyHelper.getSetDuration(self, 'Shutter.Duration', 0) }; } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/roller/0', mqtt_cmd_funct: () => { return 'open'; }, mqtt_cmd: 'shellies/shellyswitch25-<deviceid>/roller/0/command', mqtt_publish_funct: (value) => { return value == 'open' ? true : false; } }, common: { 'name': 'Open', 'type': 'boolean', 'role': 'button', 'read': false, 'write': true } }, 'Shutter.Pause': { coap: { // http_cmd: '/roller/0', // http_cmd_funct: () => { return { go: 'stop' }; }, http_cmd: '/roller/0', http_cmd_funct: async (value, self) => { return { go: 'stop', duration: await shellyHelper.getSetDuration(self, 'Shutter.Duration', 0) }; } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/roller/0', mqtt_publish_funct: (value) => { return value == 'stop' ? true : false; }, mqtt_cmd: 'shellies/shellyswitch25-<deviceid>/roller/0/command', mqtt_cmd_funct: () => { return 'stop'; } }, common: { 'name': 'Pause', 'type': 'boolean', 'role': 'button', 'read': false, 'write': true } }, 'Shutter.Duration': { coap: { http_publish: '/settings', http_publish_funct: async (value, self) => { return await shellyHelper.getSetDuration(self, 'Shutter.Duration'); } // http_publish_funct: (value) => { return value ? JSON.parse(value).rollers[0].maxtime : undefined; }, }, mqtt: { // http_publish : '/settings', // http:publish_funct: (value) => { return value ? JSON.parse(value).rollers[0].maxtime : undefined; } no_display: true }, common: { 'name': 'Duration', 'type': 'number', 'role': 'level.timer', 'read': true, 'write': true, 'def': 0, 'unit': 's' } }, 'Shutter.Position': { coap: { coap_publish: '113', coap_publish_funct: (value) => { return value == -1 ? 101 : value; }, http_cmd: '/roller/0', http_cmd_funct: async (value, self) => { return { 'go': 'to_pos', 'roller_pos': value, 'duration': await shellyHelper.getSetDuration(self, 'Shutter.Duration', 0) }; } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/roller/0/pos', mqtt_cmd: 'shellies/shellyswitch25-<deviceid>/roller/0/command/pos', mqtt_cmd_funct: (value) => { return value.toString(); }, mqtt_publish_funct: (value) => { return value == -1 ? 101 : value; } }, common: { 'name': 'Position', 'type': 'number', 'role': 'level.blind', 'read': true, 'write': true, 'unit': '%', 'min': 0, 'max': 100 } }, 'Shutter.ButtonType': { coap: { http_publish: '/settings', http_cmd: '/settings/roller/0', http_publish_funct: (value) => { return value ? JSON.parse(value).rollers[0].button_type : undefined; }, http_cmd_funct: (value) => { return { btn_type: value }; } }, mqtt: { http_publish: '/settings', http_cmd: '/settings/roller/0', http_publish_funct: (value) => { return value ? JSON.parse(value).rollers[0].button_type : undefined; }, http_cmd_funct: (value) => { return { btn_type: value }; } }, common: { 'name': 'Button Type', 'type': 'string', 'role': 'state', 'read': true, 'write': true, 'states': 'momentary:momentary;toggle:toggle;detached:detached' } }, 'Shutter.ButtonReverse': { coap: { http_publish: '/settings', http_cmd: '/settings/roller/0', http_publish_funct: (value) => { return value ? JSON.parse(value).rollers[0].btn_reverse : undefined; }, http_cmd_funct: (value) => { return { btn_reverse: value }; } }, mqtt: { http_publish: '/settings', http_cmd: '/settings/roller/0', http_publish_funct: (value) => { return value ? JSON.parse(value).rollers[0].btn_reverse : undefined; }, http_cmd_funct: (value) => { return { btn_reverse: value }; } }, common: { 'name': 'Button Type', 'type': 'number', 'role': 'state', 'read': true, 'write': true, 'states': '0:normal;1:inverted' } }, 'temperature': { coap: { // no_display: true http_publish: '/status', http_publish_funct: (value) => { return value ? JSON.parse(value).temperature : undefined; } }, mqtt: { mqtt_publish: 'shellies/shellyswitch25-<deviceid>/temperature', }, common: { 'name': 'Temperature', 'type': 'number', 'role': 'value.temperature', 'read': true, 'write': false, 'unit': '°C', 'min': -100, 'max': 100 } }, 'overtemperature': { coap: { http_publish: '/status', http_publish_funct: (value) => { return value ? JSON.parse(value).overtemperature : undefined; } }, mqtt: { mqtt_publish: 'shellies/shellyplug-s-<deviceid>/overtemperature', mqtt_publish_funct: (value) => { return value == 1 ? true : false; }, }, common: { 'name': 'Temperature', 'type': 'boolean', 'role': 'state', 'read': true, 'write': false } }, 'mode': { coap: { http_publish: '/settings', http_publish_funct: (value) => { return value ? JSON.parse(value).mode : undefined; }, http_cmd: '/settings', http_cmd_funct: (value) => { return { mode: value }; } }, mqtt: { http_publish: '/settings', http_publish_funct: (value) => { return value ? JSON.parse(value).mode : undefined; }, http_cmd: '/settings', http_cmd_funct: (value) => { return { mode: value }; } }, common: { 'name': 'Modus', 'type': 'string', 'role': 'state', 'read': true, 'write': true, 'states': 'relay:relay;roller:shutter' } }, 'ext.temperatureC1': { coap: { http_publish: '/status', http_publish_funct: (value) => { return value ? shellyHelper.getExtTemp(JSON.parse(value), '0', 'C') : undefined; } }, mqtt: { mqtt_publish: 'shellies/shelly1pm-<deviceid>/ext_temperature/0', mqtt_publish_funct: (value) => { return String(value).replace(/[^0-9\.]/g, ''); } }, common: { 'name': 'External Temperature', 'type': 'number', 'role': 'value.temperature', 'unit': '°C', 'read': true, 'write': false } }, 'ext.temperatureC2': { coap: { http_publish: '/status', http_publish_funct: (value) => { return value ? shellyHelper.getExtTemp(JSON.parse(value), '1', 'C') : undefined; } }, mqtt: { mqtt_publish: 'shellies/shelly1pm-<deviceid>/ext_temperature/1', mqtt_publish_funct: (value) => { return String(value).replace(/[^0-9\.]/g, ''); } }, common: { 'name': 'External Temperature', 'type': 'number', 'role': 'value.temperature', 'unit': '°C', 'read': true, 'write': false } }, 'ext.temperatureC3': { coap: { http_publish: '/status', http_publish_funct: (value) => { return value ? shellyHelper.getExtTemp(JSON.parse(value), '2', 'C') : undefined; } }, mqtt: { mqtt_publish: 'shellies/shelly1pm-<deviceid>/ext_temperature/2', mqtt_publish_funct: (value) => { return String(value).replace(/[^0-9\.]/g, ''); } }, common: { 'name': 'External Temperature', 'type': 'number', 'role': 'value.temperature', 'unit': '°C', 'read': true, 'write': false } }, 'ext.temperatureC4': { coap: { http_publish: '/status', http_publish_funct: (value) => { return value ? shellyHelper.getExtTemp(JSON.parse(value), '3', 'C') : undefined; } }, mqtt: { mqtt_publish: 'shellies/shelly1pm-<deviceid>/ext_temperature/3', mqtt_publish_funct: (value) => { return String(value).replace(/[^0-9\.]/g, ''); } }, common: { 'name': 'External Temperature', 'type': 'number', 'role': 'value.temperature', 'unit': '°C', 'read': true, 'write': false } }, 'ext.temperatureF1': { coap: { http_publish: '/status', http_publish_funct: (value) => { return value ? shellyHelper.getExtTemp(JSON.parse(value), '0', 'F') : undefined; } }, mqtt: { mqtt_publish: 'shellies/shelly1pm-<deviceid>/ext_temperature_f/0', mqtt_publish_funct: (value) => { return String(value).replace(/[^0-9\.]/g, ''); } }, common: { 'name': 'External Temperature', 'type': 'number', 'role': 'value.temperature', 'unit': '°F', 'read': true, 'write': false } }, 'ext.temperatureF2': { coap: { http_publish: '/status', http_publish_funct: (value) => { return value ? shellyHelper.getExtTemp(JSON.parse(value), '1', 'F') : undefined; } }, mqtt: { mqtt_publish: 'shellies/shelly1pm-<deviceid>/ext_temperature_f/1', mqtt_publish_funct: (value) => { return String(value).replace(/[^0-9\.]/g, ''); } }, common: { 'name': 'External Temperature', 'type': 'number', 'role': 'value.temperature', 'unit': '°F', 'read': true, 'write': false } }, 'ext.temperatureF3': { coap: { http_publish: '/status', http_publish_funct: (value) => { return value ? shellyHelper.getExtTemp(JSON.parse(value), '2', 'F') : undefined; } }, mqtt: { mqtt_publish: 'shellies/shelly1pm-<deviceid>/ext_temperature_f/2', mqtt_publish_funct: (value) => { return String(value).replace(/[^0-9\.]/g, ''); } }, common: { 'name': 'External Temperature', 'type': 'number', 'role': 'value.temperature', 'unit': '°F', 'read': true, 'write': false } }, 'ext.temperatureF4': { coap: { http_publish: '/status', http_publish_funct: (value) => { return value ? shellyHelper.getExtTemp(JSON.parse(value), '3', 'F') : undefined; } }, mqtt: { mqtt_publish: 'shellies/shelly1pm-<deviceid>/ext_temperature_f/3', mqtt_publish_funct: (value) => { return String(value).replace(/[^0-9\.]/g, ''); } }, common: { 'name': 'External Temperature', 'type': 'number', 'role': 'value.temperature', 'unit': '°F', 'read': true, 'write': false } } }; module.exports = { shellyswitch25: shellyswitch25 };
import CalendarData from "../../../storage/data/CalendarData.json"; import WorkDetailsData from "../../../storage/data/WorkDetailsData.json"; import WorkOverviewPersonDaysData from "../../../storage/data/WorkOverviewPersonDaysData.json"; import WorkOverviewPercentageData from "../../../storage/data/WorkOverviewPercentageData.json"; import FeedbackData from "../../../storage/data/FeedbackList.json"; function WorkDetailsAvailableBandwidthPersonDays(state, payload) { payload.item[payload.month + " Available Bandwidth (PD)"] = state.BusinessDaysList[payload.month] - (payload.item[payload.month + " Project Work"] + payload.item[payload.month + " Departmental Internal Work"] + payload.item[payload.month + " Vacation"]); } function WorkDetailsAvailableBandwidthPercentage(state, payload) { if (payload.businessDays && payload.businessDays != 0) { payload.item[payload.month + " Available Bandwidth (%)"] = Math.round(payload.item[payload.month + " Available Bandwidth (PD)"] * 100 / payload.businessDays) } } function WorkOverviewAvailableBandwidthPersonDays(state, payload) { let filteredItems = state.WorkOverviewPersonDaysItems.filter(e => e.Department === payload.item["Department"]) let filteredItem = filteredItems.find(e => e.Team === payload.item["Team"]) filteredItem[payload.month] -= (payload.newValue - payload.currentValue) } function WorkOverviewAvailableBandwidthPercentage(state, payload) { let filteredItems = state.WorkDetailsItems.filter(e => e.Department === payload.item["Department"]) let filteredItem = filteredItems.filter(e => e.Team === payload.item["Team"]) let sum = 0 let length = filteredItem.length !== 0 ? filteredItem.length : 1 filteredItem.forEach(e => { sum += e[payload.month + " Available Bandwidth (%)"] }) let items = state.WorkOverviewPercentageItems.filter(e => e.Department === payload.item["Department"]) let item = items.find(e => e.Team === payload.item["Team"]) item[payload.month] = Math.round(sum / length) } function UpdatedWorkDetailsItems(state, payload) { let currentItem = null let modifiedItem = null; if (state.UpdatedWorkDetailsItems.has(payload.item["rowid"])) { currentItem = state.UpdatedWorkDetailsItems.get(payload.item["rowid"]).currentItem modifiedItem = state.UpdatedWorkDetailsItems.get(payload.item["rowid"]).modifiedItem } else { currentItem = new Map() currentItem["Department"] = payload.item["Department"] currentItem["Team"] = payload.item["Team"] currentItem["Employee Name"] = payload.item["Employee Name"] modifiedItem = new Map() modifiedItem["Department"] = payload.item["Department"] modifiedItem["Team"] = payload.item["Team"] modifiedItem["Employee Name"] = payload.item["Employee Name"] } currentItem[payload.col] = payload.currentValue modifiedItem[payload.col] = payload.newValue modifiedItem[payload.month + " Available Bandwidth (PD)"] = payload.item[payload.month + " Available Bandwidth (PD)"] modifiedItem[payload.month + " Available Bandwidth (%)"] = payload.item[payload.month + " Available Bandwidth (%)"] state.UpdatedWorkDetailsItems.set(payload.item["rowid"], { "currentItem": currentItem, "modifiedItem": modifiedItem }) } function computeBandwidth(state, payload) { WorkDetailsAvailableBandwidthPersonDays(state, payload) WorkDetailsAvailableBandwidthPercentage(state, payload) WorkOverviewAvailableBandwidthPersonDays(state, payload) WorkOverviewAvailableBandwidthPercentage(state, payload) UpdatedWorkDetailsItems(state, payload) } function loadCalendarData(state) { if (CalendarData && CalendarData.length > 0) { let Months = [] let BusinessDays = [] let BusinessDaysList = [] CalendarData.forEach(e => { Months.push(e.Months) BusinessDays.push(e.BusinessDays) BusinessDaysList[e.Months] = e.BusinessDays }) state.Months = Months state.BusinessDays = BusinessDays state.BusinessDaysList = BusinessDaysList } } function loadWorkDetailsData(state) { if (WorkDetailsData && WorkDetailsData.length > 0) { let WorkDetailsHeaders = [] let k = Object.keys(WorkDetailsData[0]) if (k) { k.forEach(e => { if (e != "rowid" && e != "Department" && e != "Team") { WorkDetailsHeaders.push({ "text": e, "value": e }) } }) } state.WorkDetailsHeaders = WorkDetailsHeaders state.WorkDetailsItems = WorkDetailsData } } function loadWorkOverviewPersonDaysData(state) { if (WorkOverviewPersonDaysData && WorkOverviewPersonDaysData.length > 0) { let WorkOverviewHeaders = [] let k = Object.keys(WorkOverviewPersonDaysData[0]) if (k) { k.forEach(e => { WorkOverviewHeaders.push({ "text": e, "value": e }) }) } state.WorkOverviewHeaders = WorkOverviewHeaders state.WorkOverviewPersonDaysItems = WorkOverviewPersonDaysData } } function loadWorkOverviewPercentageData(state) { if (WorkOverviewPercentageData && WorkOverviewPercentageData.length > 0) { state.WorkOverviewPercentageItems = WorkOverviewPercentageData } } function loadOrganizationData(state) { let OrganizationData = new Map(); let WorkDetailsItems = state.WorkDetailsItems; WorkDetailsItems.filter(function (elements) { let Teams = OrganizationData.has(elements.Department) ? OrganizationData.get(elements.Department) : new Set(); Teams.add(elements.Team); OrganizationData.set(elements.Department, Teams); }); state.OrganizationData = OrganizationData; } function loadFeedbackData(state) { state.FeedbackList = FeedbackData } function load(state) { state.isFetching = true loadCalendarData(state) loadWorkDetailsData(state) loadWorkOverviewPersonDaysData(state) loadWorkOverviewPercentageData(state) loadOrganizationData(state) loadFeedbackData(state) state.isFetching = false } export default { load, computeBandwidth }
let express = require("express"); let router = express.Router(); const mu = require("../db/MongoUtils.js"); /* GET home page. */ router.get("/", function(req, res) { mu.databases.findAll().then(databases => { let dbSearched = databases.databases; return res.render("main", {dbSearched}) }); }); router.get("/dbSearched", function(req, res) { console.log("LLEGA"); const dbName = req.query.dbName; console.log(dbName); let dbSearched = []; mu.databases.findAll().then(databases => { let m = databases.databases; for (let i = 0; i < m.length; i++) { if(m[i].name === dbName){ dbSearched.push(m[i]) } } console.log(dbSearched); return res.send({dbSearched}) }); }); router.get("/dbSearched/db", (req, res)=>{ const dbName = req.query.dbName; res.render('database', {dbName}) }) router.get("/dbSearched/db", function(req, res) { console.log("LLEGA"); const dbName = req.query.dbName; console.log(dbName); let y = ""; mu.databases.findAll().then(databases => { let m = databases.databases; for (let i = 0; i < m.length; i++) { if(m[i].name === dbName){ y = m[i]; break; } } console.log(y); return res.send(y); }); }); router.get("/dbSearched/db/collections", function(req, res){ const dbName = req.query.dbName; console.log(dbName); console.log("/----------------------------"); mu.collections.findAll(dbName).then(collections => { console.log(collections); return res.send(collections); }) }) router.get("/dbSearched/db/col", function(req, res){ const dbName = req.query.dbName; const colName = req.query.colName; console.log(dbName); console.log("/----------------------------"); console.log(colName); mu.collections.findAllRecords(dbName, colName).then(records =>{ console.log(records); return res.send(records); }) }) module.exports = router;
(window.webpackJsonp=window.webpackJsonp||[]).push([[6],{214:function(t,e,n){"use strict";n.r(e);var s=n(0),l=Object(s.a)({},(function(){var t=this.$createElement;return(this._self._c||t)("ContentSlotsDistributor",{attrs:{"slot-key":this.$parent.slotKey}})}),[],!1,null,null,null);e.default=l.exports}}]);
angular.module("angularValidator",[]),angular.module("angularValidator").directive("angularValidator",["$injector",function(a){return{restrict:"A",link:function(b,c,d,e){function f(b){return b&&"invalid-message"in b.attributes?a.get(b.attributes["invalid-message"].value):!1}function g(a){for(var b=f(a),c=0;c<a.length;c++)c in a&&h(a[c],b)}function h(a,c){"validate-on"in a.attributes&&"blur"===a.attributes["validate-on"].value&&angular.element(a).on("blur",function(){l(a,c),o(a)});var d=b.$watch(function(){return a.value+a.required+s.submitted+k(a)+i(s[a.name])+j(s[a.name])},function(){if(s.submitted)l(a,c),o(a);else{var b="validate-on"in a.attributes&&"dirty"===a.attributes["validate-on"].value;b?(l(a,c),o(a)):s[a.name]&&s[a.name].$pristine&&(l(a,c),o(a))}});q.push(d)}function i(a){return a&&"$dirty"in a?a.$dirty:void 0}function j(a){return a&&"$valid"in a?a.$valid:void 0}function k(a){if("validator"in a.attributes){var c=b.$eval(a.attributes.validator.value);return s[a.name].$setValidity("angularValidator",c),c}}function l(a,c){var d=function(){return"<i class='fa fa-times'></i> Required"},e=function(){return"<i class='fa fa-times'></i> Invalid"};if(a.name in s){var f=s[a.name],g=n(a);g&&g.remove(),(f.$dirty||b[a.form.name]&&b[a.form.name].submitted)&&(f.$error.required?"required-message"in a.attributes?angular.element(a).after(m(a.attributes["required-message"].value)):angular.element(a).after(m(d)):f.$valid||("invalid-message"in a.attributes?angular.element(a).after(m(a.attributes["invalid-message"].value)):c?angular.element(a).after(m(c.message(f,a))):angular.element(a).after(m(e))))}}function m(a){return"<label class='control-label has-error validationMessage'>"+b.$eval(a)+"</label>"}function n(a){for(var b=angular.element(a).parent().children(),c=0;c<b.length;c++)if(angular.element(b[c]).hasClass("validationMessage"))return angular.element(b[c]);return!1}function o(a){if(a.name in s){var c=s[a.name];angular.element(a).removeClass("has-error"),angular.element(a.parentNode).removeClass("has-error"),(c.$dirty||b[a.form.name]&&b[a.form.name].submitted)&&c.$invalid&&(angular.element(a.parentNode).addClass("has-error"),angular.element(a).addClass("has-error"))}}var p=angular.element(c)[0],q=[],r=p.attributes.name.value,s=b[r];s.submitted=!1,b.$watch(function(){return Object.keys(s).length},function(){angular.forEach(q,function(a){a()}),g(p)}),c.on("submit",function(a){a.preventDefault(),b.$apply(function(){s.submitted=!0}),s.$valid&&b.$apply(function(){b.$eval(p.attributes["angular-validator-submit"].value)})}),s.reset=function(){for(var a=0;a<p.length;a++)p[a].name&&(s[p[a].name].$setViewValue(""),s[p[a].name].$render());s.submitted=!1,s.$setPristine()},g(p)}}}]);
/* eslint-disable camelcase */ const { getFilter } = require('../../filters'); module.exports = { type: 'object', properties: { title: { $ref: 'GenericNestedString', }, field_intro_text: { $ref: 'GenericNestedString', }, field_description: { $ref: 'GenericNestedString', }, field_featured_content: { $ref: 'EntityReferenceArray', }, field_content_block: { $ref: 'EntityReferenceArray', }, field_alert: { type: 'array', items: { // Sometimes what should be entity references are empty arrays oneOf: [{ $ref: 'EntityReference' }, { type: 'array', maxItems: 0 }], }, maxItems: 1, }, field_related_links: { $ref: 'EntityReferenceArray', }, field_administration: { $ref: 'EntityReferenceArray', }, field_page_last_built: { type: 'array', items: { type: 'object', properties: { value: { type: 'string', format: 'custom-date-time' }, }, }, }, metatag: { type: 'object', }, path: { type: 'array', maxItems: 1, items: { type: 'object', properties: { alias: { type: 'string' }, }, required: ['alias'], }, }, }, required: getFilter('node-page'), };
/** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: Apache-2.0 */ suite('ASTNode', function() { setup(function() { Blockly.defineBlocksWithJsonArray([{ "type": "input_statement", "message0": "%1 %2 %3 %4", "args0": [ { "type": "field_input", "name": "NAME", "text": "default" }, { "type": "field_input", "name": "NAME", "text": "default" }, { "type": "input_value", "name": "NAME" }, { "type": "input_statement", "name": "NAME" } ], "previousStatement": null, "nextStatement": null, "colour": 230, "tooltip": "", "helpUrl": "" }, { "type": "value_input", "message0": "%1", "args0": [ { "type": "input_value", "name": "NAME" } ], "colour": 230, "tooltip": "", "helpUrl": "" }, { "type": "field_input", "message0": "%1", "args0": [ { "type": "field_input", "name": "NAME", "text": "default" } ], "output": null, "colour": 230, "tooltip": "", "helpUrl": "" } ]); this.workspace = new Blockly.Workspace(); this.cursor = this.workspace.cursor; var statementInput1 = this.workspace.newBlock('input_statement'); var statementInput2 = this.workspace.newBlock('input_statement'); var statementInput3 = this.workspace.newBlock('input_statement'); var statementInput4 = this.workspace.newBlock('input_statement'); var fieldWithOutput = this.workspace.newBlock('field_input'); var valueInput = this.workspace.newBlock('value_input'); statementInput1.nextConnection.connect(statementInput2.previousConnection); statementInput1.inputList[0].connection .connect(fieldWithOutput.outputConnection); statementInput2.inputList[1].connection .connect(statementInput3.previousConnection); this.blocks = { statementInput1: statementInput1, statementInput2: statementInput2, statementInput3: statementInput3, statementInput4: statementInput4, fieldWithOutput: fieldWithOutput, valueInput: valueInput }; sinon.stub(Blockly, "getMainWorkspace").returns(new Blockly.Workspace()); }); teardown(function() { delete Blockly.Blocks['input_statement']; delete Blockly.Blocks['field_input']; delete Blockly.Blocks['value_input']; this.workspace.dispose(); sinon.restore(); }); suite('HelperFunctions', function() { test('findNextForInput_', function() { var input = this.blocks.statementInput1.inputList[0]; var input2 = this.blocks.statementInput1.inputList[1]; var connection = input.connection; var node = Blockly.ASTNode.createConnectionNode(connection); var newASTNode = node.findNextForInput_(input); chai.assert.equal(newASTNode.getLocation(), input2.connection); }); test('findPrevForInput_', function() { var input = this.blocks.statementInput1.inputList[0]; var input2 = this.blocks.statementInput1.inputList[1]; var connection = input2.connection; var node = Blockly.ASTNode.createConnectionNode(connection); var newASTNode = node.findPrevForInput_(input2); chai.assert.equal(newASTNode.getLocation(), input.connection); }); test('findNextForField_', function() { var field = this.blocks.statementInput1.inputList[0].fieldRow[0]; var field2 = this.blocks.statementInput1.inputList[0].fieldRow[1]; var node = Blockly.ASTNode.createFieldNode(field); var newASTNode = node.findNextForField_(field); chai.assert.equal(newASTNode.getLocation(), field2); }); test('findPrevForField_', function() { var field = this.blocks.statementInput1.inputList[0].fieldRow[0]; var field2 = this.blocks.statementInput1.inputList[0].fieldRow[1]; var node = Blockly.ASTNode.createFieldNode(field2); var newASTNode = node.findPrevForField_(field2); chai.assert.equal(newASTNode.getLocation(), field); }); test('navigateBetweenStacks_Forward', function() { var node = new Blockly.ASTNode( Blockly.ASTNode.types.NEXT, this.blocks.statementInput1.nextConnection); var newASTNode = node.navigateBetweenStacks_(true); chai.assert.equal(newASTNode.getLocation(), this.blocks.statementInput4); }); test('navigateBetweenStacks_Backward', function() { var node = new Blockly.ASTNode( Blockly.ASTNode.types.BLOCK, this.blocks.statementInput4); var newASTNode = node.navigateBetweenStacks_(false); chai.assert.equal(newASTNode.getLocation(), this.blocks.statementInput1); }); test('getOutAstNodeForBlock_', function() { var node = new Blockly.ASTNode( Blockly.ASTNode.types.BLOCK, this.blocks.statementInput2); var newASTNode = node.getOutAstNodeForBlock_(this.blocks.statementInput2); chai.assert.equal(newASTNode.getLocation(), this.blocks.statementInput1); }); test('getOutAstNodeForBlock_OneBlock', function() { var node = new Blockly.ASTNode( Blockly.ASTNode.types.BLOCK, this.blocks.statementInput4); var newASTNode = node.getOutAstNodeForBlock_(this.blocks.statementInput4); chai.assert.equal(newASTNode.getLocation(), this.blocks.statementInput4); }); test('findFirstFieldOrInput_', function() { var node = new Blockly.ASTNode( Blockly.ASTNode.types.BLOCK, this.blocks.statementInput4); var field = this.blocks.statementInput4.inputList[0].fieldRow[0]; var newASTNode = node.findFirstFieldOrInput_(this.blocks.statementInput4); chai.assert.equal(newASTNode.getLocation(), field); }); }); suite('NavigationFunctions', function() { setup(function() { Blockly.defineBlocksWithJsonArray([{ "type": "top_connection", "message0": "", "previousStatement": null, "colour": 230, "tooltip": "", "helpUrl": "" }, { "type": "start_block", "message0": "", "nextStatement": null, "colour": 230, "tooltip": "", "helpUrl": "" }, { "type": "fields_and_input", "message0": "%1 hi %2 %3 %4", "args0": [ { "type": "field_input", "name": "NAME", "text": "default" }, { "type": "input_dummy" }, { "type": "field_input", "name": "NAME", "text": "default" }, { "type": "input_value", "name": "NAME" } ], "previousStatement": null, "nextStatement": null, "colour": 230, "tooltip": "", "helpUrl": "" }, { "type": "two_fields", "message0": "%1 hi", "args0": [ { "type": "field_input", "name": "NAME", "text": "default" } ], "colour": 230, "tooltip": "", "helpUrl": "" }, { "type": "fields_and_input2", "message0": "%1 %2 %3 hi %4 bye", "args0": [ { "type": "input_value", "name": "NAME" }, { "type": "field_input", "name": "NAME", "text": "default" }, { "type": "input_value", "name": "NAME" }, { "type": "input_statement", "name": "NAME" } ], "colour": 230, "tooltip": "", "helpUrl": "" }, { "type": "dummy_input", "message0": "Hello", "colour": 230, "tooltip": "", "helpUrl": "" }, { "type": "dummy_inputValue", "message0": "Hello %1 %2", "args0": [ { "type": "input_dummy" }, { "type": "input_value", "name": "NAME" } ], "colour": 230, "tooltip": "", "helpUrl": "" }, { "type": "output_next", "message0": "", "output": null, "colour": 230, "tooltip": "", "helpUrl": "", "nextStatement": null }]); var noNextConnection = this.workspace.newBlock('top_connection'); var fieldAndInputs = this.workspace.newBlock('fields_and_input'); var twoFields = this.workspace.newBlock('two_fields'); var fieldAndInputs2 = this.workspace.newBlock('fields_and_input2'); var noPrevConnection = this.workspace.newBlock('start_block'); this.blocks.noNextConnection = noNextConnection; this.blocks.fieldAndInputs = fieldAndInputs; this.blocks.twoFields = twoFields; this.blocks.fieldAndInputs2 = fieldAndInputs2; this.blocks.noPrevConnection = noPrevConnection; var dummyInput = this.workspace.newBlock('dummy_input'); var dummyInputValue = this.workspace.newBlock('dummy_inputValue'); var fieldWithOutput2 = this.workspace.newBlock('field_input'); this.blocks.dummyInput = dummyInput; this.blocks.dummyInputValue = dummyInputValue; this.blocks.fieldWithOutput2 = fieldWithOutput2; var secondBlock = this.workspace.newBlock('input_statement'); var outputNextBlock = this.workspace.newBlock('output_next'); this.blocks.secondBlock = secondBlock; this.blocks.outputNextBlock = outputNextBlock; }); teardown(function() { delete this.blocks.noNextConnection; delete this.blocks.fieldAndInputs; delete this.blocks.twoFields; delete this.blocks.fieldAndInputs2; delete this.blocks.noPrevConnection; delete this.blocks.dummyInput; delete this.blocks.dummyInputValue; delete this.blocks.fieldWithOutput2; delete Blockly.Blocks['output_next']; delete Blockly.Blocks['fields_and_input2']; delete Blockly.Blocks['two_fields']; delete Blockly.Blocks['fields_and_input']; delete Blockly.Blocks['top_connection']; delete Blockly.Blocks['start_block']; delete Blockly.Blocks['dummy_input']; delete Blockly.Blocks['dummy_inputValue']; }); suite('Next', function() { setup(function() { this.singleBlockWorkspace = new Blockly.Workspace(); var singleBlock = this.singleBlockWorkspace.newBlock('two_fields'); this.blocks.singleBlock = singleBlock; }); teardown(function() { delete this.blocks.singleBlock; }); test('fromPreviousToBlock', function() { var prevConnection = this.blocks.statementInput1.previousConnection; var node = Blockly.ASTNode.createConnectionNode(prevConnection); var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), this.blocks.statementInput1); }); test('fromBlockToNext', function() { var nextConnection = this.blocks.statementInput1.nextConnection; var node = Blockly.ASTNode.createBlockNode(this.blocks.statementInput1); var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), nextConnection); }); test('fromBlockToNull', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.noNextConnection); var nextNode = node.next(); chai.assert.isNull(nextNode); }); test('fromNextToPrevious', function() { var nextConnection = this.blocks.statementInput1.nextConnection; var prevConnection = this.blocks.statementInput2.previousConnection; var node = Blockly.ASTNode.createConnectionNode(nextConnection); var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), prevConnection); }); test('fromNextToNull', function() { var nextConnection = this.blocks.statementInput2.nextConnection; var node = Blockly.ASTNode.createConnectionNode(nextConnection); var nextNode = node.next(); chai.assert.isNull(nextNode); }); test('fromInputToInput', function() { var input = this.blocks.statementInput1.inputList[0]; var inputConnection = this.blocks.statementInput1.inputList[1].connection; var node = Blockly.ASTNode.createInputNode(input); var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), inputConnection); }); test('fromInputToStatementInput', function() { var input = this.blocks.fieldAndInputs2.inputList[1]; var inputConnection = this.blocks.fieldAndInputs2.inputList[2].connection; var node = Blockly.ASTNode.createInputNode(input); var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), inputConnection); }); test('fromInputToField', function() { var input = this.blocks.fieldAndInputs2.inputList[0]; var field = this.blocks.fieldAndInputs2.inputList[1].fieldRow[0]; var node = Blockly.ASTNode.createInputNode(input); var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), field); }); test('fromInputToNull', function() { var input = this.blocks.fieldAndInputs2.inputList[2]; var node = Blockly.ASTNode.createInputNode(input); var nextNode = node.next(); chai.assert.isNull(nextNode); }); test('fromOutputToBlock', function() { var output = this.blocks.fieldWithOutput.outputConnection; var node = Blockly.ASTNode.createConnectionNode(output); var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), this.blocks.fieldWithOutput); }); test('fromFieldToInput', function() { var field = this.blocks.statementInput1.inputList[0].fieldRow[1]; var inputConnection = this.blocks.statementInput1.inputList[0].connection; var node = Blockly.ASTNode.createFieldNode(field); var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), inputConnection); }); test('fromFieldToField', function() { var field = this.blocks.fieldAndInputs.inputList[0].fieldRow[0]; var node = Blockly.ASTNode.createFieldNode(field); var field2 = this.blocks.fieldAndInputs.inputList[1].fieldRow[0]; var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), field2); }); test('fromFieldToNull', function() { var field = this.blocks.twoFields.inputList[0].fieldRow[0]; var node = Blockly.ASTNode.createFieldNode(field); var nextNode = node.next(); chai.assert.isNull(nextNode); }); test('fromStackToStack', function() { var node = Blockly.ASTNode.createStackNode(this.blocks.statementInput1); var nextNode = node.next(); chai.assert.equal(nextNode.getLocation(), this.blocks.statementInput4); chai.assert.equal(nextNode.getType(), Blockly.ASTNode.types.STACK); }); test('fromStackToNull', function() { var node = Blockly.ASTNode.createStackNode(this.blocks.singleBlock); var nextNode = node.next(); chai.assert.isNull(nextNode); }); }); suite('Previous', function() { test('fromPreviousToNull', function() { var prevConnection = this.blocks.statementInput1.previousConnection; var node = Blockly.ASTNode.createConnectionNode(prevConnection); var prevNode = node.prev(); chai.assert.isNull(prevNode); }); test('fromPreviousToNext', function() { var prevConnection = this.blocks.statementInput2.previousConnection; var node = Blockly.ASTNode.createConnectionNode(prevConnection); var prevNode = node.prev(); var nextConnection = this.blocks.statementInput1.nextConnection; chai.assert.equal(prevNode.getLocation(), nextConnection); }); test('fromPreviousToInput', function() { var prevConnection = this.blocks.statementInput3.previousConnection; var node = Blockly.ASTNode.createConnectionNode(prevConnection); var prevNode = node.prev(); chai.assert.isNull(prevNode); }); test('fromBlockToPrevious', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.statementInput1); var prevNode = node.prev(); var prevConnection = this.blocks.statementInput1.previousConnection; chai.assert.equal(prevNode.getLocation(), prevConnection); }); test('fromBlockToNull', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.noPrevConnection); var prevNode = node.prev(); chai.assert.isNull(prevNode); }); test('fromBlockToOutput', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.fieldWithOutput); var prevNode = node.prev(); var outputConnection = this.blocks.fieldWithOutput.outputConnection; chai.assert.equal(prevNode.getLocation(), outputConnection); }); test('fromNextToBlock', function() { var nextConnection = this.blocks.statementInput1.nextConnection; var node = Blockly.ASTNode.createConnectionNode(nextConnection); var prevNode = node.prev(); chai.assert.equal(prevNode.getLocation(), this.blocks.statementInput1); }); test('fromInputToField', function() { var input = this.blocks.statementInput1.inputList[0]; var node = Blockly.ASTNode.createInputNode(input); var prevNode = node.prev(); chai.assert.equal(prevNode.getLocation(), input.fieldRow[1]); }); test('fromInputToNull', function() { var input = this.blocks.fieldAndInputs2.inputList[0]; var node = Blockly.ASTNode.createInputNode(input); var prevNode = node.prev(); chai.assert.isNull(prevNode); }); test('fromInputToInput', function() { var input = this.blocks.fieldAndInputs2.inputList[2]; var inputConnection = this.blocks.fieldAndInputs2.inputList[1].connection; var node = Blockly.ASTNode.createInputNode(input); var prevNode = node.prev(); chai.assert.equal(prevNode.getLocation(), inputConnection); }); test('fromOutputToNull', function() { var output = this.blocks.fieldWithOutput.outputConnection; var node = Blockly.ASTNode.createConnectionNode(output); var prevNode = node.prev(); chai.assert.isNull(prevNode); }); test('fromFieldToNull', function() { var field = this.blocks.statementInput1.inputList[0].fieldRow[0]; var node = Blockly.ASTNode.createFieldNode(field); var prevNode = node.prev(); chai.assert.isNull(prevNode); }); test('fromFieldToInput', function() { var field = this.blocks.fieldAndInputs2.inputList[1].fieldRow[0]; var inputConnection = this.blocks.fieldAndInputs2.inputList[0].connection; var node = Blockly.ASTNode.createFieldNode(field); var prevNode = node.prev(); chai.assert.equal(prevNode.getLocation(), inputConnection); }); test('fromFieldToField', function() { var field = this.blocks.fieldAndInputs.inputList[1].fieldRow[0]; var field2 = this.blocks.fieldAndInputs.inputList[0].fieldRow[0]; var node = Blockly.ASTNode.createFieldNode(field); var prevNode = node.prev(); chai.assert.equal(prevNode.getLocation(), field2); }); test('fromStackToStack', function() { var node = Blockly.ASTNode.createStackNode(this.blocks.statementInput4); var prevNode = node.prev(); chai.assert.equal(prevNode.getLocation(), this.blocks.statementInput1); chai.assert.equal(prevNode.getType(), Blockly.ASTNode.types.STACK); }); }); suite('In', function() { setup(function() { this.emptyWorkspace = new Blockly.Workspace(); }); teardown(function() { delete this.emptyWorkspace; }); test('fromInputToOutput', function() { var input = this.blocks.statementInput1.inputList[0]; var node = Blockly.ASTNode.createInputNode(input); var inNode = node.in(); var outputConnection = this.blocks.fieldWithOutput.outputConnection; chai.assert.equal(inNode.getLocation(), outputConnection); }); test('fromInputToNull', function() { var input = this.blocks.statementInput2.inputList[0]; var node = Blockly.ASTNode.createInputNode(input); var inNode = node.in(); chai.assert.isNull(inNode); }); test('fromInputToPrevious', function() { var input = this.blocks.statementInput2.inputList[1]; var previousConnection = this.blocks.statementInput3.previousConnection; var node = Blockly.ASTNode.createInputNode(input); var inNode = node.in(); chai.assert.equal(inNode.getLocation(), previousConnection); }); test('fromBlockToInput', function() { var input = this.blocks.valueInput.inputList[0]; var node = Blockly.ASTNode.createBlockNode(this.blocks.valueInput); var inNode = node.in(); chai.assert.equal(inNode.getLocation(), input.connection); }); test('fromBlockToField', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.statementInput1); var inNode = node.in(); var field = this.blocks.statementInput1.inputList[0].fieldRow[0]; chai.assert.equal(inNode.getLocation(), field); }); test('fromBlockToPrevious', function() { var prevConnection = this.blocks.statementInput4.previousConnection; var node = Blockly.ASTNode.createStackNode(this.blocks.statementInput4); var inNode = node.in(); chai.assert.equal(inNode.getLocation(), prevConnection); chai.assert.equal(inNode.getType(), Blockly.ASTNode.types.PREVIOUS); }); test('fromBlockToNull_DummyInput', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.dummyInput); var inNode = node.in(); chai.assert.isNull(inNode); }); test('fromBlockToInput_DummyInputValue', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.dummyInputValue); var inputConnection = this.blocks.dummyInputValue.inputList[1].connection; var inNode = node.in(); chai.assert.equal(inNode.getLocation(), inputConnection); }); test('fromOuputToNull', function() { var output = this.blocks.fieldWithOutput.outputConnection; var node = Blockly.ASTNode.createConnectionNode(output); var inNode = node.in(); chai.assert.isNull(inNode); }); test('fromFieldToNull', function() { var field = this.blocks.statementInput1.inputList[0].fieldRow[0]; var node = Blockly.ASTNode.createFieldNode(field); var inNode = node.in(); chai.assert.isNull(inNode); }); test('fromWorkspaceToStack', function() { var coordinate = new Blockly.utils.Coordinate(100, 100); var node = Blockly.ASTNode.createWorkspaceNode(this.workspace, coordinate); var inNode = node.in(); chai.assert.equal(inNode.getLocation(), this.workspace.getTopBlocks()[0]); chai.assert.equal(inNode.getType(), Blockly.ASTNode.types.STACK); }); test('fromWorkspaceToNull', function() { var coordinate = new Blockly.utils.Coordinate(100, 100); var node = Blockly.ASTNode.createWorkspaceNode( this.emptyWorkspace, coordinate); var inNode = node.in(); chai.assert.isNull(inNode); }); test('fromStackToPrevious', function() { var node = Blockly.ASTNode.createStackNode(this.blocks.statementInput1); var previous = this.blocks.statementInput1.previousConnection; var inNode = node.in(); chai.assert.equal(inNode.getLocation(), previous); chai.assert.equal(inNode.getType(), Blockly.ASTNode.types.PREVIOUS); }); test('fromStackToOutput', function() { var node = Blockly.ASTNode.createStackNode(this.blocks.fieldWithOutput2); var output = this.blocks.fieldWithOutput2.outputConnection; var inNode = node.in(); chai.assert.equal(inNode.getLocation(), output); chai.assert.equal(inNode.getType(), Blockly.ASTNode.types.OUTPUT); }); test('fromStackToBlock', function() { var node = Blockly.ASTNode.createStackNode(this.blocks.dummyInput); var inNode = node.in(); chai.assert.equal(inNode.getLocation(), this.blocks.dummyInput); chai.assert.equal(inNode.getType(), Blockly.ASTNode.types.BLOCK); }); }); suite('Out', function() { setup(function() { var secondBlock = this.blocks.secondBlock; var outputNextBlock = this.blocks.outputNextBlock; this.blocks.noPrevConnection.nextConnection.connect(secondBlock.previousConnection); secondBlock.inputList[0].connection .connect(outputNextBlock.outputConnection); }); test('fromInputToBlock', function() { var input = this.blocks.statementInput1.inputList[0]; var node = Blockly.ASTNode.createInputNode(input); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.BLOCK); chai.assert.equal(outNode.getLocation(), this.blocks.statementInput1); }); test('fromOutputToInput', function() { var output = this.blocks.fieldWithOutput.outputConnection; var node = Blockly.ASTNode.createConnectionNode(output); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.INPUT); chai.assert.equal(outNode.getLocation(), this.blocks.statementInput1.inputList[0].connection); }); test('fromOutputToStack', function() { var output = this.blocks.fieldWithOutput2.outputConnection; var node = Blockly.ASTNode.createConnectionNode(output); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.STACK); chai.assert.equal(outNode.getLocation(), this.blocks.fieldWithOutput2); }); test('fromFieldToBlock', function() { var field = this.blocks.statementInput1.inputList[0].fieldRow[0]; var node = Blockly.ASTNode.createFieldNode(field); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.BLOCK); chai.assert.equal(outNode.getLocation(), this.blocks.statementInput1); }); test('fromStackToWorkspace', function() { var stub = sinon.stub(this.blocks.statementInput4, "getRelativeToSurfaceXY").returns({x: 10, y:10}); var node = Blockly.ASTNode.createStackNode(this.blocks.statementInput4); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.WORKSPACE); chai.assert.equal(outNode.wsCoordinate_.x, 10); chai.assert.equal(outNode.wsCoordinate_.y, -10); stub.restore(); }); test('fromPreviousToInput', function() { var previous = this.blocks.statementInput3.previousConnection; var inputConnection = this.blocks.statementInput2.inputList[1].connection; var node = Blockly.ASTNode.createConnectionNode(previous); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.INPUT); chai.assert.equal(outNode.getLocation(), inputConnection); }); test('fromPreviousToStack', function() { var previous = this.blocks.statementInput2.previousConnection; var node = Blockly.ASTNode.createConnectionNode(previous); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.STACK); chai.assert.equal(outNode.getLocation(), this.blocks.statementInput1); }); test('fromNextToInput', function() { var next = this.blocks.statementInput3.nextConnection; var inputConnection = this.blocks.statementInput2.inputList[1].connection; var node = Blockly.ASTNode.createConnectionNode(next); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.INPUT); chai.assert.equal(outNode.getLocation(), inputConnection); }); test('fromNextToStack', function() { var next = this.blocks.statementInput2.nextConnection; var node = Blockly.ASTNode.createConnectionNode(next); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.STACK); chai.assert.equal(outNode.getLocation(), this.blocks.statementInput1); }); test('fromNextToStack_NoPreviousConnection', function() { var next = this.blocks.secondBlock.nextConnection; var node = Blockly.ASTNode.createConnectionNode(next); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.STACK); chai.assert.equal(outNode.getLocation(), this.blocks.noPrevConnection); }); /** * This is where there is a block with both an output connection and a * next connection attached to an input. */ test('fromNextToInput_OutputAndPreviousConnection', function() { var next = this.blocks.outputNextBlock.nextConnection; var node = Blockly.ASTNode.createConnectionNode(next); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.INPUT); chai.assert.equal(outNode.getLocation(), this.blocks.secondBlock.inputList[0].connection); }); test('fromBlockToStack', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.statementInput2); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.STACK); chai.assert.equal(outNode.getLocation(), this.blocks.statementInput1); }); test('fromBlockToInput', function() { var input = this.blocks.statementInput2.inputList[1].connection; var node = Blockly.ASTNode.createBlockNode(this.blocks.statementInput3); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.INPUT); chai.assert.equal(outNode.getLocation(), input); }); test('fromTopBlockToStack', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.statementInput1); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.STACK); chai.assert.equal(outNode.getLocation(), this.blocks.statementInput1); }); test('fromBlockToStack_OutputConnection', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.fieldWithOutput2); var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.STACK); chai.assert.equal(outNode.getLocation(), this.blocks.fieldWithOutput2); }); test('fromBlockToInput_OutputConnection', function() { var node = Blockly.ASTNode.createBlockNode(this.blocks.outputNextBlock); var inputConnection = this.blocks.secondBlock.inputList[0].connection; var outNode = node.out(); chai.assert.equal(outNode.getType(), Blockly.ASTNode.types.INPUT); chai.assert.equal(outNode.getLocation(), inputConnection); }); }); suite('createFunctions', function() { test('createFieldNode', function() { var field = this.blocks.statementInput1.inputList[0].fieldRow[0]; var node = Blockly.ASTNode.createFieldNode(field); chai.assert.equal(node.getLocation(), field); chai.assert.equal(node.getType(), Blockly.ASTNode.types.FIELD); chai.assert.isFalse(node.isConnection()); }); test('createConnectionNode', function() { var prevConnection = this.blocks.statementInput4.previousConnection; var node = Blockly.ASTNode.createConnectionNode(prevConnection); chai.assert.equal(node.getLocation(), prevConnection); chai.assert.equal(node.getType(), Blockly.ASTNode.types.PREVIOUS); chai.assert.isTrue(node.isConnection()); }); test('createInputNode', function() { var input = this.blocks.statementInput1.inputList[0]; var node = Blockly.ASTNode.createInputNode(input); chai.assert.equal(node.getLocation(), input.connection); chai.assert.equal(node.getType(), Blockly.ASTNode.types.INPUT); chai.assert.isTrue(node.isConnection()); }); test('createWorkspaceNode', function() { var coordinate = new Blockly.utils.Coordinate(100, 100); var node = Blockly.ASTNode .createWorkspaceNode(this.workspace, coordinate); chai.assert.equal(node.getLocation(), this.workspace); chai.assert.equal(node.getType(), Blockly.ASTNode.types.WORKSPACE); chai.assert.equal(node.getWsCoordinate(), coordinate); chai.assert.isFalse(node.isConnection()); }); test('createStatementConnectionNode', function() { var nextConnection = this.blocks.statementInput1.inputList[1].connection; var inputConnection = this.blocks.statementInput1.inputList[1].connection; var node = Blockly.ASTNode.createConnectionNode(nextConnection); chai.assert.equal(node.getLocation(), inputConnection); chai.assert.equal(node.getType(), Blockly.ASTNode.types.INPUT); chai.assert.isTrue(node.isConnection()); }); test('createTopNode-previous', function() { var block = this.blocks.statementInput1; var topNode = Blockly.ASTNode.createTopNode(block); chai.assert.equal(topNode.getLocation(), block.previousConnection); }); test('createTopNode-block', function() { var block = this.blocks.noPrevConnection; var topNode = Blockly.ASTNode.createTopNode(block); chai.assert.equal(topNode.getLocation(), block); }); test('createTopNode-output', function() { var block = this.blocks.outputNextBlock; var topNode = Blockly.ASTNode.createTopNode(block); chai.assert.equal(topNode.getLocation(), block.outputConnection); }); }); }); });
var ShareView = function(){ /*var previewArea = myWorkArea;*/ var settings = settings_tryon; var loadimg=''; var mainArea=''; ShareView.prototype.initPlugin = function() { EventListener.addEventListener("SHARE_PREVIEW_SCREEN", setupLayout); }; function setupLayout(evt) { // body... //this will open a transparent black panel in which we will have sharing icons// }; ShareView.prototype.savetheImage=function (option) { var previewArea=jsDom.nodeById(settings_tryon.activeTryon); mainArea=jsDom.nodeById("mainArea"); loadimg= jsDom.createNode("img", {"src":"assets/vtoplus/assets/images/loader.gif"}, "", "parent", previewArea, true); jsDom.css(loadimg, {"position":"absolute", "display":"block", "opacity":"1","left":"45%","top":"45%"}); jsDom.css(mainArea, {"opacity":"0.5"}); var data=''; var areatoshare=jsDom.nodeById("mainArea"); var mainimage=jsDom.nodeById("previewImage"); var canvaswidth=mainimage.width; var canvasheight=mainimage.height; var canvas =document.createElement('canvas'); canvas.width=canvaswidth; canvas.height=canvasheight; var scalefactor=mainimage.naturalHeight/mainimage.height; var ctx=canvas.getContext("2d"); Tools.getTransformData(mainimage,function(scale,fRotation){ ctx.save(); ctx.translate(mainimage.width/2,mainimage.height/2); ctx.rotate(fRotation*Math.PI/180); ctx.scale(scale,scale); ctx.drawImage(mainimage,-mainimage.width/2,-mainimage.height/2,mainimage.width,mainimage.height); getFilterData(mainimage,ctx,canvas); data=canvas.toDataURL('image/png'); }) frame=jsDom.nodeById("frame"); if(frame){ Tools.getTransformData(frame,function(scale,fRotation){ var x=parseFloat(frame.style.left)+frame.width/2-parseFloat(mainimage.style.left); var y=parseFloat(frame.style.top)+frame.height/2-parseFloat(mainimage.style.top); ctx.restore(); ctx.translate(x,y); ctx.rotate(fRotation*Math.PI/180); ctx.scale(scale,scale); ctx.globalAlpha = 0.85; ctx.drawImage(frame,-1*frame.width/2,-1*frame.height/2,frame.width,frame.height); data=canvas.toDataURL('image/png'); sendRequest(option,data); }); } else{ sendRequest(option,data); } }; function sendRequest(option,data){ try{ var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 ) { if(xmlhttp.status == 200){ jsDom.remove(loadimg); jsDom.css(mainArea, {"opacity":"1"}); switch(option){ case 'tw': shareToTwitter(xmlhttp.responseText); break; case 'fb': shareToFB(xmlhttp.responseText); break; case 'saveonly': var a = document.createElement('a'); a.setAttribute('download', settings.saveImageTitle); a.href = xmlhttp.responseText; a.setAttribute('target', '_blank'); a.innerHTML = 'testing'; a.style.display = 'none'; document.body.appendChild(a); a.click(); break; } } else if(xmlhttp.status == 400) { console.log('There was an error 400') } else { console.log('something else other than 200 was returned') } } } xmlhttp.open("POST", settings.saveFileUrl, true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send('img='+data); }catch(e){console.log(e);} }; function getFilterData(container,context,canvas){ var st = window.getComputedStyle(container, null); var tr = st.getPropertyValue("-webkit-filter") || st.getPropertyValue("filter"); if(tr!='none'){ var imageData = context.getImageData(0, 0, canvas.width, canvas.height); var pixels = imageData.data,delta=50; for (var i = 0, il = pixels.length; i < il; i += 4) { pixels[i] +=delta ; pixels[i + 1] +=delta; pixels[i + 2] +=delta; } var contrast=65; var factor = (259 * (contrast + 255)) / (255 * (259 - contrast)); for(var i=0;i<pixels.length;i+=4) { pixels[i] = factor * (pixels[i] - 128) + 128; pixels[i+1] = factor * (pixels[i+1] - 128) + 128; pixels[i+2] = factor * (pixels[i+2] - 128) + 128; } context.putImageData(imageData, 0, 0); } }; function shareToFB(imgurl) { var encodedurl=encodeURIComponent(settings.shareURL+"?title="+settings.shareTitle+"& desc="+settings.shareDescription+" & image="+imgurl); var fbUrl="http://www.facebook.com/sharer/sharer.php?u="+encodedurl; window.open(fbUrl, "_blank"); }; function shareToTwitter(imgurl) { var encodedurl=encodeURIComponent(settings.shareURL+"?title="+settings.shareTitle+"& desc="+settings.shareDescription+" & image="+imgurl); var twUrl='https://twitter.com/intent/tweet?text='+settings.shareTitle+'&url=http://demo.thesoftsol.com/tryon.html&hashtags='+settings.twitterHashtag; window.open(twUrl, "_blank"); }; // auto intiate // this.initPlugin(); };
import dayjs from 'dayjs-with-plugins'; import omit from 'lodash/omit'; import MonthCalendar from '../vc-calendar/src/MonthCalendar'; import VcDatePicker from '../vc-calendar/src/Picker'; import classNames from 'classnames'; import Icon from '../icon'; import { ConfigConsumerProps } from '../config-provider'; import interopDefault from '../_util/interopDefault'; import BaseMixin from '../_util/BaseMixin'; import { hasProp, getOptionProps, initDefaultProps, mergeProps, getComponentFromProp, isValidElement, getListeners, } from '../_util/props-util'; import { cloneElement } from '../_util/vnode'; // export const PickerProps = { // value?: dayjs.Dayjs; // prefixCls: string; // } function noop() { } export default function createPicker(TheCalendar, props) { return { props: initDefaultProps(props, { allowClear: true, showToday: true, }), mixins: [BaseMixin], model: { prop: 'value', event: 'change', }, inject: { configProvider: { default: () => ConfigConsumerProps }, }, data() { const value = this.value || this.defaultValue; if (value && !interopDefault(dayjs).isMoment(value)) { throw new Error( 'The value/defaultValue of DatePicker or MonthPicker must be ' + 'a dayjs object', ); } return { sValue: value, showDate: value, _open: !!this.open, }; }, watch: { open(val) { const props = getOptionProps(this); const state = {}; state._open = val; if ('value' in props && !val && props.value !== this.showDate) { state.showDate = props.value; } this.setState(state); }, value(val) { const state = {}; state.sValue = val; if (val !== this.sValue) { state.showDate = val; } this.setState(state); }, _open(val, oldVal) { this.$nextTick(() => { if (!hasProp(this, 'open') && oldVal && !val) { this.focus(); } }); }, }, methods: { renderFooter(...args) { const { $scopedSlots, $slots, _prefixCls: prefixCls } = this; const renderExtraFooter = this.renderExtraFooter || $scopedSlots.renderExtraFooter || $slots.renderExtraFooter; return renderExtraFooter ? ( <div class={`${prefixCls}-footer-extra`}> {typeof renderExtraFooter === 'function' ? renderExtraFooter(...args) : renderExtraFooter} </div> ) : null; }, clearSelection(e) { e.preventDefault(); e.stopPropagation(); this.handleChange(null); }, handleChange(value) { if (!hasProp(this, 'value')) { this.setState({ sValue: value, showDate: value, }); } this.$emit('change', value, (value && value.format(this.format)) || ''); }, handleCalendarChange(value) { this.setState({ showDate: value }); }, handleOpenChange(open) { const props = getOptionProps(this); if (!('open' in props)) { this.setState({ _open: open }); } this.$emit('openChange', open); }, focus() { this.$refs.input.focus(); }, blur() { this.$refs.input.blur(); }, onMouseEnter(e) { this.$emit('mouseenter', e); }, onMouseLeave(e) { this.$emit('mouseleave', e); }, }, render() { const { $scopedSlots } = this; const { sValue: value, showDate, _open: open } = this.$data; let suffixIcon = getComponentFromProp(this, 'suffixIcon'); suffixIcon = Array.isArray(suffixIcon) ? suffixIcon[0] : suffixIcon; const listeners = getListeners(this); const { panelChange = noop, focus = noop, blur = noop, ok = noop } = listeners; const props = getOptionProps(this); const { prefixCls: customizePrefixCls, locale, localeCode } = props; const getPrefixCls = this.configProvider.getPrefixCls; const prefixCls = getPrefixCls('calendar', customizePrefixCls); this._prefixCls = prefixCls; const dateRender = props.dateRender || $scopedSlots.dateRender; const monthCellContentRender = props.monthCellContentRender || $scopedSlots.monthCellContentRender; const placeholder = 'placeholder' in props ? props.placeholder : locale.lang.placeholder; const disabledTime = props.showTime ? props.disabledTime : null; const calendarClassName = classNames({ [`${prefixCls}-time`]: props.showTime, [`${prefixCls}-month`]: MonthCalendar === TheCalendar, }); if (value && localeCode) { value.locale(localeCode); } const pickerProps = { props: {}, on: {} }; const calendarProps = { props: {}, on: {} }; const pickerStyle = {}; if (props.showTime) { // fix https://github.com/ant-design/ant-design/issues/1902 calendarProps.on.select = this.handleChange; pickerStyle.width = '195px'; } else { pickerProps.on.change = this.handleChange; } if ('mode' in props) { calendarProps.props.mode = props.mode; } const theCalendarProps = mergeProps(calendarProps, { props: { disabledDate: props.disabledDate, disabledTime, locale: locale.lang, timePicker: props.timePicker, defaultValue: props.defaultPickerValue || interopDefault(dayjs)(), dateInputPlaceholder: placeholder, prefixCls, dateRender, format: props.format, showToday: props.showToday, monthCellContentRender, renderFooter: this.renderFooter, value: showDate, }, on: { ok: ok, panelChange, change: this.handleCalendarChange, }, class: calendarClassName, scopedSlots: $scopedSlots, }); const calendar = <TheCalendar {...theCalendarProps} />; const clearIcon = !props.disabled && props.allowClear && value ? ( <Icon type="close-circle" class={`${prefixCls}-picker-clear`} onClick={this.clearSelection} theme="filled" /> ) : null; const inputIcon = (suffixIcon && (isValidElement(suffixIcon) ? ( cloneElement(suffixIcon, { class: `${prefixCls}-picker-icon`, }) ) : ( <span class={`${prefixCls}-picker-icon`}>{suffixIcon}</span> ))) || <Icon type="calendar" class={`${prefixCls}-picker-icon`} />; const input = ({ value: inputValue }) => ( <div> <input ref="input" disabled={props.disabled} onFocus={focus} onBlur={blur} readOnly value={(inputValue && inputValue.format(props.format)) || ''} placeholder={placeholder} class={props.pickerInputClass} tabIndex={props.tabIndex} /> {clearIcon} {inputIcon} </div> ); const vcDatePickerProps = { props: { ...props, ...pickerProps.props, calendar, value, prefixCls: `${prefixCls}-picker-container`, }, on: { ...omit(listeners, 'change'), ...pickerProps.on, open, onOpenChange: this.handleOpenChange, }, style: props.popupStyle, scopedSlots: { default: input, ...$scopedSlots }, }; return ( <span class={props.pickerClass} style={pickerStyle} // tabIndex={props.disabled ? -1 : 0} // onFocus={focus} // onBlur={blur} onMouseenter={this.onMouseEnter} onMouseleave={this.onMouseLeave} > <VcDatePicker {...vcDatePickerProps} /> </span> ); }, }; }
import { createStore, applyMiddleware } from 'redux'; import { persistStore } from 'redux-persist'; import logger from 'redux-logger'; import rootReducer from './root-reducer'; // Middleware const middlewares = [logger]; export const store = createStore(rootReducer, applyMiddleware(...middlewares)); export const persistor = persistStore(store)
#!/usr/bin/env node 'use strict'; // 内置包 const fs = require('fs'); const path = require('path'); // 二方包 const logo = require('./lib/logo'); const log = require('./lib/log'); const rmrf = require('./lib/rmrf'); const move = require('./lib/move'); const pkg = require('../package.json'); log.info(`${logo} 版本: ${pkg.version} 作者: https://github.com/Lucien-X 用途: 将Lottie动画的JSON格式转换成PNG序列帧 依赖:请提前安装好Google Chrome `); // 三方包 const readlineSync = require('readline-sync'); const open = require('open'); const renderLottie = require('./lib/puppeteer-lottie'); try { let [fileFullPath] = process.argv.slice(2); if (!fileFullPath) { fileFullPath = readlineSync.question(`========================================== [使用方法] 请将JSON文件拖拽至此,点击窗口,按下回车。 直接输入完整文件路径,按下回车也可; 按下 Ctrl+C 组合键可强行终止程序。 ========================================== `); } const filePathObj = path.parse(fileFullPath); const { name: fileName, dir: fileDir, ext: fileExt } = filePathObj; if (fileExt !== '.json') { throw new Error('仅支持json拓展名的文件输入'); } // 定义常量 const TEMP = './temp'; const DEST = `${path.resolve(fileDir)}/${fileName}_${new Date().getTime()}/`; const executor = async done => { // 清理临时文件夹 if (fs.existsSync(TEMP)) { rmrf(TEMP); } fs.mkdirSync(TEMP); // Render each frame of the animation as PNG images await renderLottie({ path: `${fileFullPath}`, output: `${TEMP}/frame-%d.png`, // sprintf format }); // // Render the first frame of the animation as a JPEG image // await renderLottie({ // path: 'bodymovin.json', // output: `${TEMP}/preview.jpg`, // }); // // Create a GIF with width 640px from a lottie animation // // gifski needed // await renderLottie({ // path: 'bodymovin.json', // output: `${TEMP}/example.gif`, // }); // // Create an MP4 from a lottie animation // // ffmpeg needed // await renderLottie({ // path: 'bodymovin.json', // output: `${TEMP}/example.mp4`, // }); // 将临时文件夹中的文件,移动到目标路径 move(TEMP, DEST, () => { log.warn(`转换成功!文件已输出至:\n ${DEST}`); log.warn('2秒后将自动打开文件夹...'); setTimeout(() => { open(DEST); }, 2000); }); }; executor(); } catch (err) { log.error('好像有哪里不对,以下是错误日志:\n'); log.error(err); process.exit(1); }
import React from 'react'; import { Tabs, Tab } from 'material-ui/Tabs'; import { Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import TextField from 'material-ui/TextField'; import Toggle from 'material-ui/Toggle'; import { GridList, GridTile } from 'material-ui/GridList'; import IconButton from 'material-ui/IconButton'; import StarBorder from 'material-ui/svg-icons/toggle/star-border'; const styles = { root: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', }, gridList: { width: 500, height: 450, overflowY: 'auto', }, propContainer: { width: 200, overflow: 'hidden', margin: '20px auto 0', }, propToggleHeader: { margin: '20px auto 10px', }, }; const tableData = [ { name: 'John Smith', status: 'Employed', selected: true, }, { name: 'Randal White', status: 'Unemployed', }, { name: 'Stephanie Sanders', status: 'Employed', selected: true, }, { name: 'Steve Brown', status: 'Employed', }, { name: 'Joyce Whitten', status: 'Employed', }, { name: 'Samuel Roberts', status: 'Employed', }, { name: 'Adam Moore', status: 'Employed', }, ]; class TableExampleComplex extends React.Component { state = { fixedHeader: true, fixedFooter: true, stripedRows: false, showRowHover: false, selectable: true, multiSelectable: false, enableSelectAll: false, deselectOnClickaway: true, showCheckboxes: true, height: '300px', }; handleToggle = (event, toggled) => { this.setState({ [event.target.name]: toggled, }); }; handleChange = event => { this.setState({ height: event.target.value, }); }; render() { return ( <div> <Table height={this.state.height} fixedHeader={this.state.fixedHeader} fixedFooter={this.state.fixedFooter} selectable={this.state.selectable} multiSelectable={this.state.multiSelectable} > <TableHeader displaySelectAll={this.state.showCheckboxes} adjustForCheckbox={this.state.showCheckboxes} enableSelectAll={this.state.enableSelectAll} > <TableRow> <TableHeaderColumn colSpan="3" tooltip="Super Header" style={{ textAlign: 'center' }}> Super Header </TableHeaderColumn> </TableRow> <TableRow> <TableHeaderColumn tooltip="The ID">ID</TableHeaderColumn> <TableHeaderColumn tooltip="The Name">Name</TableHeaderColumn> <TableHeaderColumn tooltip="The Status">Status</TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={this.state.showCheckboxes} deselectOnClickaway={this.state.deselectOnClickaway} showRowHover={this.state.showRowHover} stripedRows={this.state.stripedRows} > {tableData.map((row, index) => (<TableRow key={row.name} selected={row.selected}> <TableRowColumn> {index} </TableRowColumn> <TableRowColumn> {row.name} </TableRowColumn> <TableRowColumn> {row.status} </TableRowColumn> </TableRow>), )} </TableBody> <TableFooter adjustForCheckbox={this.state.showCheckboxes}> <TableRow> <TableRowColumn>ID</TableRowColumn> <TableRowColumn>Name</TableRowColumn> <TableRowColumn>Status</TableRowColumn> </TableRow> <TableRow> <TableRowColumn colSpan="3" style={{ textAlign: 'center' }}> Super Footer </TableRowColumn> </TableRow> </TableFooter> </Table> <div style={styles.propContainer}> <h3>Table Properties</h3> <TextField floatingLabelText="Table Body Height" defaultValue={this.state.height} onChange={this.handleChange} /> <Toggle name="fixedHeader" label="Fixed Header" onToggle={this.handleToggle} defaultToggled={this.state.fixedHeader} /> <Toggle name="fixedFooter" label="Fixed Footer" onToggle={this.handleToggle} defaultToggled={this.state.fixedFooter} /> <Toggle name="selectable" label="Selectable" onToggle={this.handleToggle} defaultToggled={this.state.selectable} /> <Toggle name="multiSelectable" label="Multi-Selectable" onToggle={this.handleToggle} defaultToggled={this.state.multiSelectable} /> <Toggle name="enableSelectAll" label="Enable Select All" onToggle={this.handleToggle} defaultToggled={this.state.enableSelectAll} /> <h3 style={styles.propToggleHeader}>TableBody Properties</h3> <Toggle name="deselectOnClickaway" label="Deselect On Clickaway" onToggle={this.handleToggle} defaultToggled={this.state.deselectOnClickaway} /> <Toggle name="stripedRows" label="Stripe Rows" onToggle={this.handleToggle} defaultToggled={this.state.stripedRows} /> <Toggle name="showRowHover" label="Show Row Hover" onToggle={this.handleToggle} defaultToggled={this.state.showRowHover} /> <h3 style={styles.propToggleHeader}>Multiple Properties</h3> <Toggle name="showCheckboxes" label="Show Checkboxes" onToggle={this.handleToggle} defaultToggled={this.state.showCheckboxes} /> </div> </div> ); } } const tilesData = [ { img: '/images/home/cutecate1.jpg', title: 'Cute Cat, Mr. Tom', author: 'jill111', featured: true, }, { img: '/images/home/cutecate2.jpg', title: 'Cute Cat, Miss. Jerry', author: 'pashminu', }, { img: '/images/home/cutecate3.jpg', title: 'Cute Cat, Mr. Gerry', author: 'Danson67', }, { img: '/images/home/cutecate4.jpg', title: 'Cute Cat, Mr. James', author: 'fancycrave1', featured: true, }, { img: '/images/home/cutecate5.jpg', title: 'Cute Cat, Miss. Rose', author: 'Hans', }, { img: '/images/home/cutecate6.jpg', title: 'Cute Cat, Mr. Jack', author: 'fancycravel', }, { img: '/images/home/horse1.jpg', title: 'Cute Animal', author: 'jill111', }, { img: '/images/home/horse2.jpg', title: 'Cute Animal2', author: 'BkrmadtyaKarki', }, ]; const GridListExampleComplex = () => (<div> <h2>Complex Grid List</h2> <GridList cols={2} cellHeight={200} padding={1} style={styles.gridList}> {tilesData.map(tile => (<GridTile key={tile.img} title={tile.title} actionIcon={ <IconButton> <StarBorder color="white" /> </IconButton> } actionPosition="left" titlePosition="top" titleBackground="linear-gradient(to bottom, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)" cols={tile.featured ? 2 : 1} rows={tile.featured ? 2 : 1} > <img src={tile.img} alt={tile.title} /> </GridTile>), )} </GridList> </div>); const GridListExampleSingleLine = () => (<div> <h2>Simple Grid List</h2> <GridList style={{ display: 'flex', flexWrap: 'nowrap', overflowX: 'auto' }} cols={2.2}> {tilesData.map(tile => (<GridTile key={tile.img} title={tile.title} actionIcon={ <IconButton> <StarBorder color="rgb(0, 188, 212)" /> </IconButton> } titleStyle={styles.titleStyle} titleBackground="linear-gradient(to top, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)" > <img src={tile.img} alt={tile.title} /> </GridTile>), )} </GridList> </div>); function TableList() { return ( <div> <Tabs className="components-secondary-navbar"> <Tab label="Grid List"> <GridListExampleSingleLine /> <GridListExampleComplex /> </Tab> <Tab label="Table"> <TableExampleComplex /> </Tab> </Tabs> </div> ); } export default TableList;
import React from "react"; import { connect } from "react-redux"; import { Text, View } from "react-native"; import { styles } from "../home-page/styles"; class Component extends React.Component { constructor(props) { super(props); } render() { return ( <React.Fragment> <View style={styles.container}> <Text style={styles.welcome}> {this.props.LocaleReducer.strings["welcome"]} </Text> </View> </React.Fragment> ); } } const Redux = connect((store) => { return { LocaleReducer: { strings: store.LocaleReducer.strings } }; })(Component); export const MainPage = Redux;
import React from 'react'; import { NavLink } from 'react-router-dom'; import CopyLinkButton from './CopyLinkButton'; import LoginLogoutButton from './LoginLogoutButton'; function PictureNavbar(props) { const { className, item, parent, title } = props; return ( <div className={className}> <nav className="navbar navbar-light bg-light"> <NavLink to={parent}> <div className="container"> <div className="column"> <span className="row oi oi-chevron-top" title="chevron top" aria-hidden="true"></span> <div className="row">Up</div> </div> </div> </NavLink> <h1>{title}</h1> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarNavDropdown"> <div className="navbar-nav"> <CopyLinkButton className="nav-item" /> <LoginLogoutButton className="nav-item" item={item}/> </div> </div> </nav> </div> ); } export default PictureNavbar;
/** * Block pour le TestCd * @author Moi */ 'use strict'; goog.provide('Blockly.Blocks.keypad'); goog.require('Blockly.Blocks'); goog.require('Blockly.Types'); //@CD 20170311 Blockly.Blocks.keypad_touche_appuyee = { init: function() { this.setColour(Blockly.Blocks.keypad.HUE); this.setHelpUrl(Blockly.Msg.KEYPAD_TOUCHE_HELPURL); this.appendDummyInput("") .appendField(Blockly.Msg.KEYPAD_TOUCHE_TEXT); this.appendDummyInput("") .setAlign(Blockly.ALIGN_CENTRE) .appendField(new Blockly.FieldImage(Blockly.pathToBlockly + 'blocks/KEYPAD/Clavier12.jpg', Blockly.Arduino.imageSize, Blockly.Arduino.imageSize)); this.appendValueInput("L1") .setCheck(Blockly.Types.NUMBER.checkList) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.KEYPAD_TOUCHE_LIGNE1); this.appendValueInput("L2") .setCheck(Blockly.Types.NUMBER.checkList) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.KEYPAD_TOUCHE_LIGNE2); this.appendValueInput("L3") .setCheck(Blockly.Types.NUMBER.checkList) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.KEYPAD_TOUCHE_LIGNE3); this.appendValueInput("L4") .setCheck(Blockly.Types.NUMBER.checkList) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.KEYPAD_TOUCHE_LIGNE4); this.appendValueInput("C1") .setCheck(Blockly.Types.NUMBER.checkList) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.KEYPAD_TOUCHE_COLONNE1); this.appendValueInput("C2") .setCheck(Blockly.Types.NUMBER.checkList) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.KEYPAD_TOUCHE_COLONNE2); this.appendValueInput("C3") .setCheck(Blockly.Types.NUMBER.checkList) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.KEYPAD_TOUCHE_COLONNE3); this.setOutput(true, Blockly.Types.TEXT.checkList); this.setPreviousStatement(false, null); this.setNextStatement(false, null); this.setTooltip(Blockly.Msg.KEYPAD_TOUCHE_TOOLTIP); } };
#!/usr/bin/env node const spawn = require("cross-spawn"); const script = process.argv[2]; const args = process.argv.slice(3); switch (script) { case "build": case "test": const result = spawn.sync("node", [require.resolve("../scripts/" + script)].concat(args), { stdio: "inherit" }); process.exit(result.status); break; default: console.log('Unknown script "' + script + '".'); console.log("Perhaps you need to update secretlint-scripts?"); break; }
import React, { forwardRef } from 'react'; import { TooltipProvider } from './TooltipProvider' import { TooltipContext } from './TooltipContext'; export const TooltipProviderWrapper = forwardRef((props, ref) => ( <TooltipContext.Consumer> {(providerValue) => ( <TooltipProvider providerValue={providerValue} forwardedRef={ref} {...props}/> )} </TooltipContext.Consumer> ))
import { Card, Col, message, Row } from "antd" import { useEffect, useState } from "react" import { connect } from 'dva' import t from '@/utils/t' import Title from "./components/boxTitle" import { AddtaskIcon, MydatasetIcon } from '@/components/common/icons' import { cardHead, cardBody } from "./components/styles" import styles from './index.less' import { Lists } from '@/components/project/list' import { Link } from "umi" const MyProject = ({ count = 6, ...func }) => { const [projects, setProjects] = useState([]) useEffect(() => { getData() }, []) async function getData() { const result = await func.getProjects(count) if (result) { setProjects(result.items) } } const addExample = async () => { const result = await func.addExampleProject() if (result) { message.success(t('project.create.success')) getData() } } return ( <Card id='mydataset' className={`${styles.box} ${styles.myProject}`} bordered={false} headStyle={cardHead} bodyStyle={cardBody} title={<Title title={<><MydatasetIcon className={styles.headIcon} /><span className={styles.headTitle}>{t('portal.project.my.title')}</span></>} link='/home/project'> </Title>} > <div className={`${styles.rowContainer} scrollbar`}> <div className={styles.addBtn}> <Link className={styles.emptyBoxAction} to={'/home/project/add'}> <AddtaskIcon style={{ fontSize: 20, color: '#36cbcb' }} /> <span style={{ color: '#36cbcb', fontSize: 16, marginLeft: 10 }}>{t('portal.action.new.project')}</span> </Link> </div> {projects.length ? <Lists projects={projects} /> : <div className={styles.addBtn} style={{ marginTop: 20 }}> <Link className={styles.emptyBoxAction} to={''} onClick={() => addExample()}> <AddtaskIcon style={{ fontSize: 20, color: '#36cbcb' }} /> <span style={{ color: '#36cbcb', fontSize: 16, marginLeft: 10 }}>{t('project.new.example.label')}</span> </Link> </div> } </div> </Card> ) } const actions = (dispatch) => { return { getProjects: (limit) => { return dispatch({ type: 'project/getProjects', payload: { limit }, }) }, addExampleProject() { return dispatch({ type: 'project/addExampleProject', }) }, } } export default connect(null, actions)(MyProject)
require = require('esm')(module) // eslint-disable-line const arc = require('@architect/functions') const data = require('@begin/data') const Notes = require('@architect/views/pages/notes.js').default const HTML = require('@architect/views/document/html.js').default exports.handler = arc.http.async(notes) async function notes(req) { let session = req.session || {} let account = session.account || {} let accountId = account.id if (accountId) { let table = `notes-${accountId}` let pages = await data.get({ table, limit: 25 }) let notes = [] for await (let note of pages) { notes.push(note) } // Return oldest notes first notes.sort((a, b) => { if (a.created < b.created) return -1 if (a.created > b.created) return 1 return 0 }) return { statusCode: 200, headers: { 'cache-control': 'no-cache, no-store, must-revalidate, max-age=0, s-maxage=0', 'content-type': 'text/html; charset=utf8' }, body: HTML({ title: 'Notes Demo', children: Notes({ account: { avatar: account.avatar, name: account.name, url: `https://github.com/${account.login}` }, notes }) }) } } else { return { statusCode: 302, location: '/' } } }
var classnlohmann_1_1detail_1_1other__error = [ [ "other_error", "d5/d1b/classnlohmann_1_1detail_1_1other__error.html#adf9227d6ca5161508f6a598a0dc6e7cd", null ], [ "create", "d5/d1b/classnlohmann_1_1detail_1_1other__error.html#a3a25fa67a0ec36b5d36cbc4424eb901d", null ] ];
import Snap from 'imports-loader?this=>window,fix=>module.exports=0!snapsvg/dist/snap.svg.js' import EventsEmitter from 'EventsEmitter' import './Legend.scss' class Legend extends EventsEmitter { ///////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////// constructor (container, data, options = {}) { super() this.svgId = this.guid() this.options = Object.assign({}, options, { textStrokeColor: '#727272', textFillColor: '#727272', textHorizontalSpacing: 32, textVerticalAlign: 13, verticalSpacing: 20, textStrokeWidth: 0.1, textMaxLength: 25, circleRadius: 6, fontSize: 13, fontName: 'ArtifaktElementRegular', strokeWidth: 3 }) $(container).append(` <svg class="legend" id="${this.svgId}"> </svg> ` ) this.snap = Snap($(`#${this.svgId}`)[0]) data.forEach((entry, idx) => { this.drawElement(entry, idx) }) } ///////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////// drawElement(element, idx) { var circle = this.snap.paper.circle( 2 * this.options.circleRadius, this.options.strokeWidth + this.options.circleRadius + idx * this.options.verticalSpacing, this.options.circleRadius) circle.attr({ fill: element.color, fillOpacity: 0.5, stroke: element.color, strokeWidth: this.options.strokeWidth }) circle.click(() => { this.emit('legend.click', { item: element.item, index: idx }) }) circle.addClass('clickable') element.legendLabel.forEach((label) => { var txt = this.snap.paper.text( this.options.textHorizontalSpacing + label.spacing, this.options.textVerticalAlign + idx * this.options.verticalSpacing, this.getFormattedText(label.text)) txt.attr({ font: `${this.options.fontSize}px ${this.options.fontName}`, fill: this.options.textStrokeColor, stroke: this.options.textFillColor, strokeWidth: this.options.textStrokeWidth }) txt.click(() => { this.emit('legend.click', { item: element.item, index: idx }) }) txt.addClass('clickable') }) } ///////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////// getFormattedText(label) { return label.length > this.options.textMaxLength ? label.substring(0, this.options.textMaxLength) + ' ...' : label } } export default Legend
const dashboard = require('../../../../index.js') module.exports = { get: async (req) => { if (!req.query || !req.query.sessionid) { throw new Error('invalid-sessionid') } let session if (req.cacheData && req.cacheData[req.query.sessionid]) { session = req.cacheData[req.query.sessionid] } else { session = await dashboard.Storage.read(`${req.appid}/session/${req.query.sessionid}`) } if (!session) { throw new Error('invalid-sessionid') } try { session = JSON.parse(session) } catch (error) { } if (!session || session.object !== 'session') { throw new Error('invalid-sessionid') } delete (session.tokenHash) if (!session.ended) { const query = req.query req.query.accountid = session.accountid const account = await global.api.administrator.Account.get(req) req.query = query if (session.sessionKeyNumber < account.sessionKeyNumber) { session.ended = account.sessionKeyLastReset } else if (session.expires <= dashboard.Timestamp.now) { session.ended = session.expires } } return session } }
import * as React from "react"; import Svg, { Rect, Path } from "react-native-svg"; function SvgCalendarClearOutline(props) { return <Svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="1em" height="1em" {...props}><Rect fill="none" stroke={props.fill} strokeLinejoin="round" strokeWidth={32} x={48} y={80} width={416} height={384} rx={48} /><Path fill="none" stroke={props.fill} strokeLinejoin="round" strokeWidth={32} strokeLinecap="round" d="M128 48v32M384 48v32M464 160H48" /></Svg>; } export default SvgCalendarClearOutline;
var packager = require('electron-packager'), path = require('path'); var options = { dir: __dirname, out: 'out', arch: 'all', download: { cache: path.join(__dirname, '..') }, icon: './icons/Checkmark', overwrite: true, ignore: [ /\/token.json/, /\/ApplicationState.json/, /\/thumb.*/ ] }; // Dynamic album images only work with the beta now on windows if (process.platform === "win32") { options.download = { cache: path.join(__dirname, '..') }; options.electronVersion = '1.8.2-beta.2' } packager(options, (err, paths) => { if (err) console.log("Error creating package", err); else console.log('Success creating package', paths); });
(function($) { var EA = {}; /** * Single location */ EA.Location = Backbone.Model.extend({ defaults : { name:"", address: "", location: "", cord: null }, url: function() { return ajaxurl+'?action=ea_location&id=' + encodeURIComponent(this.id) }, toJSON : function() { var attrs = _.clone( this.attributes ); return attrs; } }); /** * Service model */ EA.Service = Backbone.Model.extend({ defaults : { name:"", duration: 60, slot_step: 60, price: 10 }, url : function() { return ajaxurl+'?action=ea_service&id=' + this.id; }, toJSON : function() { var attrs = _.clone( this.attributes ); return attrs; } }); /** * Service model */ EA.Worker = Backbone.Model.extend({ defaults : { name:"", description : "", email: "", phone: "" }, url : function() { return ajaxurl+'?action=ea_worker&id=' + this.id; }, toJSON : function() { var attrs = _.clone( this.attributes ); return attrs; } }); /** * Single connection */ EA.Connection = Backbone.Model.extend({ defaults : { group_id : null, location : null, service : null, worker : null, day_of_week : [], time_from : null, time_to : null, day_from : '2018-01-01', day_to : '2020-01-01', is_working : 0 }, url: function() { return ajaxurl+'?action=ea_connection&id=' + encodeURIComponent(this.id) }, toJSON: function() { var attrs = _.clone( this.attributes ); return attrs; }, parse: function(data, options) { if(typeof data.day_of_week !== "undefined" && data.day_of_week != null) { data.day_of_week = data.day_of_week.split(','); } else { // console.log(this.get('day_of_week').split(',')); this.set('day_of_week', this.get('day_of_week')); } if(typeof data.time_from !== "undefined" && typeof data.time_to !== "undefined") { if(data.time_from.length === 8) { data.time_from = data.time_from.substring(0, 5); } if(data.time_to.length === 8) { data.time_to = data.time_to.substring(0, 5); } } return data; }, save: function(attrs, options) { options || (options = {}); attrs || (attrs = _.clone(this.attributes)); attrs.day_of_week = attrs.day_of_week.join(','); return Backbone.Model.prototype.save.call(this, attrs, options); } }); /** * Service model */ EA.Setting = Backbone.Model.extend({ defaults : { ea_key:"", ea_value : "", type: "" }, url : function() { return ajaxurl+'?action=ea_setting&id=' + this.id; }, toJSON : function() { var attrs = _.clone( this.attributes ); return attrs; }, parse: function(data, options) { // console.log(data); return data; } }); /** * Single field */ EA.Field = Backbone.Model.extend({ defaults : { type: 'INPUT', slug: '', label: '', default_value: '', validation: false, mixed: '', visible: true, required: false, position: 10, }, url: function() { return ajaxurl+'?action=ea_field&id=' + encodeURIComponent(this.id); }, toJSON: function() { var attrs = _.clone( this.attributes ); //console.log(attrs); return attrs; } }); /** * Single error */ EA.Error = Backbone.Model.extend({ defaults : { error_type: '', errors: '', errors_data: '', }, url: function() { return ajaxurl+'?action=ea_error&id=' + encodeURIComponent(this.id); }, }); /** * Connections collection */ EA.Fields = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_fields', model: EA.Field }); /** * Locations collection */ EA.Locations = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_locations', model: EA.Location, cacheData: function() { if(typeof eaData !== 'undefined') { eaData.Locations = this.toJSON(); } } }); /** * Services collection */ EA.Services = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_services', model: EA.Service, parse: function(response) { // console.log(response); return response; }, cacheData: function() { if(typeof eaData !== 'undefined') { eaData.Services = this.toJSON(); } } }); /** * Workers collection */ EA.Workers = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_workers', model: EA.Worker, cacheData: function() { if(typeof eaData !== 'undefined') { eaData.Workers = this.toJSON(); } } }); /** * Connections collection */ EA.Connections = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_connections', model: EA.Connection }); /** * Settings collection */ EA.Settings = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_settings', model: EA.Setting }); /** * Wrapper around settings data */ EA.SettingsWrapper = Backbone.Model.extend({ url : ajaxurl+'?action=ea_settings', /*toJSON : function() { return this.model.toJSON(); }*/ }); /** * Connections collection */ EA.Errors = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_errors', model: EA.Error }); /** * Locations main view */ EA.LocationView = Backbone.View.extend({ tagName: "tr", // show template template_show : _.template( jQuery("#ea-tpl-locations-row").html() ), // edit template template_edit : _.template( jQuery("#ea-tpl-locations-row-edit").html() ), template : null, edit_mode : false, events: { "click .btn-edit" : "edit", "dblclick" : "edit", "click .btn-del" : "removeItem", "click .btn-save" : "save", "click .btn-cancel" : "cancel", "keydown input" : "keydownEvent" }, initialize: function (options) { this.template = this.template_show; this.render(); this.parent = options.parent; }, render: function () { var renderedContent = this.template( { row : this.model.toJSON() } ); jQuery(this.el).html( renderedContent ); this.$el.addClass('ea-row'); return this; }, edit: function() { if(this.edit_mode) { return; } // Edit class this.$el.addClass('ea-editing'); this.template = this.template_edit; this.render(); this.$el.find('input:first').focus(); this.edit_mode = true; }, save: function() { var location = this.model; var view = this; jQuery.each(this.$el.find('input'), function(index, elem){ location.set(jQuery(elem).data('prop'), jQuery(elem).val()); }); this.parent.showMessage('Saving...'); // Saves location location.save(null, { success: function(model, response) { view.render(); model.collection.cacheData(); view.parent.showMessage('Saved...'); } }); this.$el.removeClass('ea-editing'); this.template = this.template_show; this.render(); this.edit_mode = false; }, cancel: function() { // If is new remove model/view if(this.model.isNew()) { this.parent.showMessage('New canceled'); this.model.destroy(); this.remove(); } else { this.parent.showMessage('Edit canceled'); this.$el.removeClass('ea-editing'); this.template = this.template_show; this.render(); } this.edit_mode = false; }, // Delets model and view removeItem: function() { var view = this; if(confirm('Are you sure?')) { view.parent.showMessage('Deleting...'); this.model.destroy({ success: function(model, response) { view.remove(); view.parent.showMessage('Done...'); }, error: function(model, response) { view.parent.showMessage('Error...'); } }); } }, // keydownEvent: function(e) { switch (e.which) { // esc case 27 : this.cancel(); break; } } }); // Main tamplate EA.LocationsView = Backbone.View.extend({ //el: jQuery("#wpbody-content"), template : _.template( jQuery("#ea-tpl-locations-table").html() ), rowsView : null, events : { "click .add-new" : "addNew", "click .refresh-list" : "refreshList", "change #sort-locations-by": "sortChange", "change #order-locations-by": "sortChange" }, initialize: function () { // Get pre chache data if(typeof eaData !== 'undefined'){ this.collection = new EA.Locations(eaData.Locations); } else { this.collection = new EA.Locations(); } // Table draw this.render(); // Bind the reset event this.collection.bind("reset", this.render, this); // if there is no data in cache if( this.collection.length === 0 ) { // Get data from server this.collection.fetch( {reset:true} ); } }, render: function () { this.$el.empty(); // clear the element to make sure you don't double your contact view this.$el.html( this.template ); var self = this; // so you can use this inside the each function this.collection.each(function(location) { // iterate through the collection var locationView = new EA.LocationView({ model: location, parent: self }); self.$el.find("#ea-locations").append(locationView.$el); }); this.$el.find('#sort-locations-by').val(ea_settings['sort.locations-by']); this.$el.find('#order-locations-by').val(ea_settings['order.locations-by']); return this; }, addNew: function(e) { e.preventDefault(); var location = new EA.Location(); var self = this; this.collection.add(location, {at: 0}); var locationView = new EA.LocationView({ model: location, parent: self }); this.$el.find("#ea-locations").prepend(locationView.$el); locationView.edit(); }, refreshList: function(e) { e.preventDefault(); var that = this; this.showMessage('Loading table...', true); this.collection.fetch( {reset:true}, { error: function(response){ that.showMessage(''); alert('Error, try refresh again.'); }, success: function(){ that.showMessage(''); } }); }, destroy_view: function() { // COMPLETELY UNBIND THE VIEW this.undelegateEvents(); this.$el.removeData().unbind(); // Remove view from DOM this.remove(); Backbone.View.prototype.remove.call(this); }, showMessage: function(text, hold) { var onHold = hold || false; if(onHold) { this.$el.find('#status-msg').text(text).show(); } else { this.$el.find('#status-msg').text(text).show().delay(2000).fadeOut(); } }, sortChange: function (event) { var plugin = this; var column = this.$el.find('#sort-locations-by').val(); var type = this.$el.find('#order-locations-by').val(); var columnSettings = new EA.Setting(); columnSettings.set('ea_key', 'sort.locations-by'); columnSettings.set('ea_value', column); columnSettings.set('type', 'default'); var d1 = columnSettings.save(); var orderSettings = new EA.Setting(); orderSettings.set('ea_key', 'order.locations-by'); orderSettings.set('ea_value', type); orderSettings.set('type', 'default'); var d2 = orderSettings.save(); jQuery.when(d1, d2).done(function () { ea_settings['sort.locations-by'] = column; ea_settings['order.locations-by'] = type; plugin.refreshList(jQuery.Event( "click" )); }); } }); /** * Services main view */ EA.ServiceView = Backbone.View.extend({ tagName: "tr", // show template template_show : _.template( jQuery("#ea-tpl-services-row").html() ), // edit template template_edit : _.template( jQuery("#ea-tpl-services-row-edit").html() ), template : null, edit_mode : false, events: { "click .btn-edit" : "edit", "dblclick" : "edit", "click .btn-del" : "removeItem", "click .btn-save" : "save", "click .btn-cancel" : "cancel", "keydown input" : "keydownEvent" }, initialize: function (options) { this.template = this.template_show; this.parent = options.parent; this.render(); }, render: function () { var renderedContent = this.template( { row : this.model.toJSON() } ); jQuery(this.el).html( renderedContent ); this.$el.addClass('ea-row'); return this; }, edit: function() { if(this.edit_mode) { return; } // Edit class this.$el.addClass('ea-editing'); this.template = this.template_edit; this.render(); this.$el.find('input:first').focus(); this.edit_mode = true; }, save: function() { var service = this.model; var view = this; jQuery.each(this.$el.find('input'), function(index, elem){ service.set(jQuery(elem).data('prop'), jQuery(elem).val()); }); this.parent.showMessage('Saving...'); var message = '(duration / slot_step) must be round number.'; if (service.get('duration') % service.get('slot_step') !== 0) { alert(message); return; } // Saves Service service.save(null, { success: function(model, response) { view.render(); model.collection.cacheData(); view.parent.showMessage('Saved...'); } }); this.$el.removeClass('ea-editing'); this.template = this.template_show; this.render(); this.edit_mode = false; }, cancel: function() { // If is new remove model/view if(this.model.isNew()) { this.model.destroy(); this.remove(); this.parent.showMessage('New canceled'); } else { this.$el.removeClass('ea-editing'); this.template = this.template_show; this.render(); this.parent.showMessage('Edit canceled'); } this.edit_mode = false; }, // Delets model and view removeItem: function() { var view = this; if(confirm('Are you sure?')) { view.parent.showMessage('Deleting...'); this.model.destroy({ success: function(model, response) { view.remove(); view.parent.showMessage('Done...'); }, error: function(model, response) { view.parent.showMessage('Error...'); } }); } }, // keydownEvent: function(e) { switch (e.which) { // esc case 27 : this.cancel(); break; } } }); // Main tamplate EA.ServicesView = Backbone.View.extend({ //el: jQuery("#wpbody-content"), template : _.template( jQuery("#ea-tpl-services-table").html() ), rowsView : null, events : { "click .add-new" : "addNew", "click .refresh-list" : "refreshList", "change #sort-services-by": "sortChange", "change #order-services-by": "sortChange" }, initialize: function () { // Get pre chache data if(typeof eaData !== 'undefined'){ this.collection = new EA.Services(eaData.Services); } else { this.collection = new EA.Services(); } // Table draw this.render(); // Bind the reset event this.collection.bind("reset", this.render, this); // if there is no data in cache if( this.collection.length == 0 ) { // Get data from server this.collection.fetch( {reset:true} ); } }, render: function () { this.$el.empty(); // clear the element to make sure you don't double your contact view this.$el.html( this.template ); var self = this; // so you can use this inside the each function this.collection.each(function(service) { // iterate through the collection var serviceView = new EA.ServiceView({ model: service, parent: self }); self.$el.find("#ea-services").append(serviceView.$el); }); if(typeof eaData !== 'undefined') { eaData.Services = this.collection.toJSON(); } this.$el.find('#sort-services-by').val(ea_settings['sort.services-by']); this.$el.find('#order-services-by').val(ea_settings['order.services-by']); return this; }, addNew: function(e) { e.preventDefault(); var service = new EA.Service(); var self = this; this.collection.add(service, {at: 0}); var serviceView = new EA.ServiceView({ model: service, parent: self }); this.$el.find("#ea-services").prepend(serviceView.$el); serviceView.edit(); }, refreshList: function(e) { e.preventDefault(); var that = this; this.showMessage('Loading table...', true); this.collection.fetch( {reset:true}, { error: function(response) { that.showMessage(''); alert('Error, try refresh again.'); }, success: function() { that.showMessage(''); } }); }, destroy_view: function() { // COMPLETELY UNBIND THE VIEW this.undelegateEvents(); this.$el.removeData().unbind(); // Remove view from DOM this.remove(); Backbone.View.prototype.remove.call(this); }, showMessage: function(text, hold) { var onHold = hold || false; if(onHold) { this.$el.find('#status-msg').text(text).show(); } else { this.$el.find('#status-msg').text(text).show().delay(2000).fadeOut(); } }, sortChange: function (event) { var plugin = this; var column = this.$el.find('#sort-services-by').val(); var type = this.$el.find('#order-services-by').val(); var columnSettings = new EA.Setting(); columnSettings.set('ea_key', 'sort.services-by'); columnSettings.set('ea_value', column); columnSettings.set('type', 'default'); var d1 = columnSettings.save(); var orderSettings = new EA.Setting(); orderSettings.set('ea_key', 'order.services-by'); orderSettings.set('ea_value', type); orderSettings.set('type', 'default'); var d2 = orderSettings.save(); jQuery.when(d1, d2).done(function () { ea_settings['sort.services-by'] = column; ea_settings['order.services-by'] = type; plugin.refreshList(jQuery.Event( "click" )); }); } }); /** * Worker main view */ EA.WorkerView = Backbone.View.extend({ tagName: "tr", // show template template_show : _.template( jQuery("#ea-tpl-worker-row").html() ), // edit template template_edit : _.template( jQuery("#ea-tpl-worker-row-edit").html() ), template : null, edit_mode : false, events: { "click .btn-edit" : "edit", "dblclick" : "edit", "click .btn-del" : "removeItem", "click .btn-save" : "save", "click .btn-cancel" : "cancel", "keydown input" : "keydownEvent" }, initialize: function (options) { this.template = this.template_show; this.parent = options.parent; this.render(); }, render: function () { var renderedContent = this.template( { row : this.model.toJSON() } ); jQuery(this.el).html( renderedContent ); this.$el.addClass('ea-row'); return this; }, edit: function() { if(this.edit_mode) { return; } // Edit class this.$el.addClass('ea-editing'); this.template = this.template_edit; this.render(); this.$el.find('input:first').focus(); this.edit_mode = true; }, save: function() { var worker = this.model; var view = this; jQuery.each(this.$el.find('input'), function(index, elem){ worker.set(jQuery(elem).data('prop'), jQuery(elem).val()); }); if (!this.checkEmailAddress(worker.get('email'))) { return; } this.parent.showMessage('Saving...'); // Saves Worker worker.save(null, { success: function(model, response) { view.render(); model.collection.cacheData(); view.parent.showMessage('Saved...'); } }); this.$el.removeClass('ea-editing'); this.template = this.template_show; this.render(); this.edit_mode = false; }, /** * Validate email address for Worker * * @param email * @returns {boolean} */ checkEmailAddress: function(email) { var re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; var valid = re.test(email); if (!valid) { var emailField = this.$el.find('[data-prop="email"]'); emailField.css({border: '2px solid #ff0000'}).animate({ backgroundColor: 'white' }, 2000, function() { emailField.css({border: '1px solid #ccc'}); }); } return valid; }, cancel: function() { // If is new remove model/view if (this.model.isNew()) { this.parent.showMessage('New canceled'); this.model.destroy(); this.remove(); } else { this.parent.showMessage('Edit canceled'); this.$el.removeClass('ea-editing'); this.template = this.template_show; this.render(); } this.edit_mode = false; }, // Delets model and view removeItem: function() { var view = this; if(confirm('Are you sure?')) { view.parent.showMessage('Deleting...'); view.model.destroy({ success: function(model, response) { view.remove(); view.parent.showMessage('Done...'); }, error: function(model, response) { view.parent.showMessage('Error...'); } }); } }, // keydownEvent: function(e) { switch (e.which) { // esc case 27 : this.cancel(); break; } } }); // Main Template for Workers EA.StaffView = Backbone.View.extend({ template: _.template(jQuery("#ea-tpl-staff-table").html()), rowsView: null, events: { "click .add-new": "addNew", "click .refresh-list": "refreshList", "change #sort-workers-by": "sortChange", "change #order-workers-by": "sortChange" }, initialize: function () { // Get pre chache data if (typeof eaData !== 'undefined') { this.collection = new EA.Workers(eaData.Workers); } else { this.collection = new EA.Workers(); } // Table draw this.render(); // Bind the reset event this.collection.bind("reset", this.render, this); // if there is no data in cache if (this.collection.length == 0) { // Get data from server this.collection.fetch({reset: true}); } }, render: function () { this.$el.empty(); // clear the element to make sure you don't double your contact view this.$el.html(this.template); var self = this; // so you can use this inside the each function this.collection.each(function (worker) { // iterate through the collection var workerView = new EA.WorkerView({ model: worker, parent: self }); self.$el.find("#ea-staff").append(workerView.$el); }); this.$el.find('#sort-workers-by').val(ea_settings['sort.workers-by']); this.$el.find('#order-workers-by').val(ea_settings['order.workers-by']); return this; }, addNew: function (e) { e.preventDefault(); var worker = new EA.Worker(); var self = this; this.collection.add(worker, {at: 0}); var workerView = new EA.WorkerView({ model: worker, parent: self }); this.$el.find("#ea-staff").prepend(workerView.$el); workerView.edit(); }, refreshList: function (e) { e.preventDefault(); this.showMessage('Loading table...', true); this.collection.fetch({reset: true}, { error: function (response) { that.showMessage(''); alert('Error, try refresh again.'); }, success: function () { that.showMessage(''); } }); }, destroy_view: function () { // COMPLETELY UNBIND THE VIEW this.undelegateEvents(); this.$el.removeData().unbind(); // Remove view from DOM this.remove(); Backbone.View.prototype.remove.call(this); }, showMessage: function (text, hold) { var onHold = hold || false; if (onHold) { this.$el.find('#status-msg').text(text).show(); } else { this.$el.find('#status-msg').text(text).show().delay(2000).fadeOut(); } }, sortChange: function (event) { var plugin = this; var column = this.$el.find('#sort-workers-by').val(); var type = this.$el.find('#order-workers-by').val(); var columnSettings = new EA.Setting(); columnSettings.set('ea_key', 'sort.workers-by'); columnSettings.set('ea_value', column); columnSettings.set('type', 'default'); var d1 = columnSettings.save(); var orderSettings = new EA.Setting(); orderSettings.set('ea_key', 'order.workers-by'); orderSettings.set('ea_value', type); orderSettings.set('type', 'default'); var d2 = orderSettings.save(); jQuery.when(d1, d2).done(function () { ea_settings['sort.workers-by'] = column; ea_settings['order.workers-by'] = type; plugin.refreshList(jQuery.Event( "click" )); }); } }); /** * */ EA.ConnectionView = Backbone.View.extend({ tagName: "tr", // show template template_show : _.template( jQuery("#ea-tpl-connection-row").html() ), // edit template template_edit : _.template( jQuery("#ea-tpl-connection-row-edit").html() ), template : null, locations : null, services : null, workers : null, /** * Is edit mode active */ edit_mode: false, events: { "click .btn-edit" : "edit", "dblclick" : "edit", "click .btn-del" : "removeItem", "click .btn-save" : "save", "click .btn-clone" : "clone", "click .btn-cancel" : "cancel", "keydown input" : "keydownEvent", "keydown select" : "keydownEvent" }, initialize: function (options) { this.template = this.template_show; this.parent = options.parent; }, render: function () { var self = this; //after save split days of week if(!jQuery.isArray(this.model.get('day_of_week'))) { this.model.set('day_of_week', this.model.get('day_of_week').split(',')); } var renderedContent = this.template( { row : this.model.toJSON(), locations : self.locations.toJSON(), services : self.services.toJSON(), workers : self.workers.toJSON() } ); jQuery(this.el).html( renderedContent ); this.$el.addClass('ea-row'); return this; }, edit: function() { if(this.edit_mode) { return; } // Edit class this.$el.addClass('ea-editing'); this.template = this.template_edit; this.render(); this.$el.find(".day-from").datepicker({ dateFormat: "yy-mm-dd", firstDay: 1 }); this.$el.find(".time-from").timepicker(); this.$el.find(".day-to").datepicker({ dateFormat: "yy-mm-dd", firstDay: 1 }); this.$el.find(".time-to").timepicker(); this.$el.find('select, input').first().focus(); this.edit_mode = true; }, save: function() { var connection = this.model; var view = this; jQuery.each(this.$el.find('input, select'), function(index, elem){ connection.set(jQuery(elem).data('prop'), jQuery(elem).val()); }); if (!this.validateConnection(connection)) { return; } this.parent.showMessage('Saving...'); // Saves connection connection.save(null, { success: function(model, response) { view.render(); view.parent.showMessage('Saved...'); } }); this.$el.removeClass('ea-editing'); this.template = this.template_show; this.render(); this.edit_mode = false; }, validateConnection: function(connection) { var $el = this.$el; var result = true; var values = ['location', 'service', 'worker', 'day_of_week', 'time_from', 'time_to']; jQuery.each(values, function(index, element) { var current = connection.get(element); if ( current != '' && current != null ) { return; } var elementField = $el.find('[data-prop="' + element + '"]'); elementField.css({border: '2px solid #ff0000'}).animate({ backgroundColor: 'white' }, 2000, function() { elementField.css({border: '1px solid #ccc'}); }); result = false; }); // valide select time of day if (result) { var time_from = parseInt(connection.get('time_from').replace(':', '')); var time_to = parseInt(connection.get('time_to').replace(':', '')); console.log(time_from, time_to); if (time_from > time_to) { var fromField = $el.find('[data-prop="time_from"]'); var toField = $el.find('[data-prop="time_to"]'); fromField.css({border: '2px solid #ff0000'}).animate({ backgroundColor: 'white' }, 2000, function() { fromField.css({border: '1px solid #ccc'}); }); toField.css({border: '2px solid #ff0000'}).animate({ backgroundColor: 'white' }, 2000, function() { toField.css({border: '1px solid #ccc'}); }); result = false; } } return result; }, clone: function () { var connection = this.model; var clone = connection.clone(); // clone.set('id', null); clone.unset('id'); clone.save(null, { success: function(model, response) { connection.collection.fetch( {reset:true} ); } }); }, cancel: function() { // If is new remove model/view if(this.model.isNew()) { this.parent.showMessage('New canceled'); this.model.destroy(); this.remove(); } else { this.parent.showMessage('Edit canceled'); this.$el.removeClass('ea-editing'); this.template = this.template_show; this.render(); } this.edit_mode = false; }, // Delets model and view removeItem: function() { var view = this; if(confirm('Are you sure?')) { view.parent.showMessage('Deleting...'); this.model.destroy({ success: function(model, response) { view.remove(); view.parent.showMessage('Done...'); }, error: function(model, response) { view.parent.showMessage('Error...'); } }); } }, setData: function(locations, services, workers) { this.locations = locations; this.services = services; this.workers = workers; }, // keydownEvent: function(e) { switch (e.which) { // esc case 27 : this.cancel(); break; } } }); /** * Bulk component */ EA.ConnectionBulkView = Backbone.View.extend({ tagName: "div", // edit template template_edit : _.template( jQuery("#ea-tpl-connection-bulk").html() ), template_bulk_connections: _.template( jQuery("#ea-tpl-single-bulk-connection").html() ), locations : null, services : null, workers : null, connections: [], events: { 'click #bulk-next': 'bulkNext', 'click #bulk-save': 'save', 'click #bulk-connection-remove': 'removeConnection' }, initialize: function (options) { this.parent = options.parent; }, render: function () { var self = this; //after save split days of week if(!jQuery.isArray(this.model.get('day_of_week'))) { this.model.set('day_of_week', this.model.get('day_of_week').split(',')); } var renderedContent = this.template( { row : this.model.toJSON(), locations : self.locations.toJSON(), services : self.services.toJSON(), workers : self.workers.toJSON() } ); jQuery(this.el).html( renderedContent ); return this; }, /** * Calculate number of combinations * * @returns {number} */ connectionsCount: function() { var values = ['location', 'service', 'worker']; var locations = this.$el.find('[data-prop="location"]').val(); var services = this.$el.find('[data-prop="service"]').val(); var workers = this.$el.find('[data-prop="worker"]').val(); if (locations === null || services === null || workers === null) { return 0; } return locations.length * services.length * workers.length; }, /** * */ processConnections: function() { var locations = this.$el.find('[data-prop="location"]').val(); var services = this.$el.find('[data-prop="service"]').val(); var workers = this.$el.find('[data-prop="worker"]').val(); var day_of_week = this.$el.find('[data-prop="day_of_week"]').val(); var time_from = this.$el.find('[data-prop="time_from"]').val(); var time_to = this.$el.find('[data-prop="time_to"]').val(); var day_from = this.$el.find('[data-prop="day_from"]').val(); var day_to = this.$el.find('[data-prop="day_to"]').val(); var is_working = this.$el.find('[data-prop="is_working"]').val(); var nextId = this.parent.getMax() + 1; var connections = []; jQuery.each(locations, function(i, location) { jQuery.each(services, function(j, service) { jQuery.each(workers, function(k, worker) { var model = new EA.Connection({ group_id : nextId, location : location, service : service, worker : worker, day_of_week : day_of_week, time_from : time_from, time_to : time_to, day_from : day_from, day_to : day_to, is_working : is_working }); connections.push(model); }); }); }); return connections; }, removeButtonClick: function(e) { var element = jQuery(e.target); var connection = element.data('model'); this.removeConnection(connection); element.closest('li').remove(); }, removeConnection: function(connection) { var self = this; jQuery.each(this.connections, function(i, current) { if (current == connection) { self.connections.splice(i, 1); } }); this.updateConnectionsCount(this.connections.length); }, /** * Update html element */ updateConnectionsCount: function(number) { this.$el.find('#bulk-connection-count').text(number); }, /** * Edit state */ edit: function() { if(this.edit_mode) { return; } var plugin = this; // Edit class this.$el.addClass('ea-editing'); this.template = this.template_edit; this.render(); this.$el.find(".day-from").datepicker({ dateFormat: "yy-mm-dd", firstDay: 1 }); this.$el.find(".time-from").timepicker(); this.$el.find(".day-to").datepicker({ dateFormat: "yy-mm-dd", firstDay: 1 }); this.$el.find(".time-to").timepicker(); this.$el.find('select, input').first().focus(); this.$el.find('.chosen-select').chosen({ placeholder_text_multiple: ' ', width: '100%' }).change(function() { var num = plugin.connectionsCount(); plugin.updateConnectionsCount(num); }); }, bulkNext: function(e) { e.preventDefault(); var self = this; if (!this.validateConnection()) { return; } this.connections = this.processConnections(); var list = this.$el.find('#bulk-connections'); jQuery.each(this.connections, function(i, model) { var renderedContent = self.template_bulk_connections( { row : model.toJSON(), locations : self.locations.toJSON(), services : self.services.toJSON(), workers : self.workers.toJSON() }); var content = jQuery(renderedContent); list.append(content); content .find('.bulk-connection-remove') .on('click', jQuery.proxy(self.removeButtonClick, self)) .data('model', model); }); this.$el.find('.step-1').hide(); this.$el.find('#bulk-next').hide(); this.$el.find('.step-2').show(); this.$el.find('#bulk-save').prop('disabled', false); }, save: function(e) { jQuery(e.target).prop('disabled', true); var self = this; if (this.connections.length == 0) { tb_remove(); this.parent.refreshList(e); } var connection = this.connections.shift(); if (typeof connection == 'undefined') { return; } connection.save().then(function() { self.removeConnection(connection); self.$el.find('#bulk-connections').children().first().remove(); self.updateConnectionsCount(self.connections.length); self.save(e); }); }, validateConnection: function(connection) { var $el = this.$el; var result = true; var values = ['location', 'service', 'worker', 'day_of_week', 'time_from', 'time_to']; jQuery.each(values, function(index, element) { var elementField = $el.find('[data-prop="' + element + '"]'); if (elementField.hasClass('chosen-select')) { var selection = elementField.val(); if (selection !== null && selection.length > 0) { return; } elementField = elementField.next().children(); } else { if (elementField.val() != '' && elementField.val() != null) { return; } } elementField.css({border: '1px solid #ff0000'}).animate({ backgroundColor: 'white' }, 2000, function() { elementField.css({border: '1px solid #aaa'}); }); result = false; }); // valide select time of day if (result) { var time_from = parseInt($el.find('[data-prop="time_from"]').val().replace(':', '')); var time_to = parseInt($el.find('[data-prop="time_to"]').val().replace(':', '')); if (time_from > time_to) { var fromField = $el.find('[data-prop="time_from"]'); var toField = $el.find('[data-prop="time_to"]'); fromField.css({border: '1px solid #ff0000'}).animate({ backgroundColor: 'white' }, 2000, function() { fromField.css({border: '1px solid #aaa'}); }); toField.css({border: '1px solid #ff0000'}).animate({ backgroundColor: 'white' }, 2000, function() { toField.css({border: '1px solid #aaa'}); }); result = false; } } return result; }, setData: function(locations, services, workers) { this.locations = locations; this.services = services; this.workers = workers; } }); // Main tamplate EA.ConnectionsView = Backbone.View.extend({ template : _.template( jQuery("#ea-tpl-connections-table").html() ), rowsView : null, events : { "click .add-new" : "addNew", "click .add-new-bulk": "addBulk", "click .refresh-list" : "refreshList" }, locations : null, services : null, workers : null, initialize: function () { // bug fix for missing regional settings // jQuery.datepicker.setDefaults( jQuery.datepicker.regional[ea_settings.datepicker] ); if (typeof jQuery.timepicker.regional[ea_settings.datepicker] !== 'undefined') { jQuery.timepicker.setDefaults( jQuery.timepicker.regional[ea_settings.datepicker] ); } // Empty array of connections this.collection = new EA.Connections(); if(typeof eaData !== 'undefined'){ // In page cache this.locations = new EA.Locations(eaData.Locations); this.services = new EA.Services(eaData.Services); this.workers = new EA.Workers(eaData.Workers); } else { // Get from server this.locations = new EA.Locations(); this.services = new EA.Services(); this.workers = new EA.Workers(); this.locations.fetch(); this.services.fetch(); this.workers.fetch(); } // Table draw this.render(); // Bind the reset event this.collection.bind("reset", this.render, this); this.showMessage('Table loading...', true); // Get data from server this.collection.fetch( {reset:true}, { success : function () { this.showMessage('Loading table...'); } } ); }, render: function () { this.$el.empty(); // clear the element to make sure you don't double your contact view this.$el.html( this.template ); var self = this; // so you can use this inside the each function this.collection.each(function(connection) { // iterate through the collection var connectionView = new EA.ConnectionView({ model: connection, parent: self }); connectionView.setData( self.locations, self.services, self.workers ); connectionView.render(); self.$el.find("#ea-connections").append(connectionView.$el); }); return this; }, addNew: function(e) { e.preventDefault(); var connection = new EA.Connection(); var self = this; this.collection.add(connection, {at: 0}); var connectionView = new EA.ConnectionView({ model: connection, parent: self }); connectionView.setData( this.locations, this.services, this.workers ); this.$el.find("#ea-connections").prepend(connectionView.$el); connectionView.edit(); }, getMax: function() { if (this.collection.length === 0) { return 0; } var maxModel = _.max(this.collection.toJSON(), function(model) { return model.id; }); return parseInt(maxModel.id); }, addBulk: function(e) { e.preventDefault(); var self = this; var connection = new EA.Connection(); var connectionBulkView = new EA.ConnectionBulkView({ model: connection, parent: self }); connectionBulkView.setData( this.locations, this.services, this.workers ); this.$el.find("#bulk-connections-builder-content").html(connectionBulkView.$el); connectionBulkView.edit(); tb_show('Bulk Connections builder', '#TB_inline?height=420&width=900&inlineId=bulk-connections-builder'); }, refreshList: function(e) { e.preventDefault(); this.showMessage('Loading table...', true); this.collection.fetch( {reset:true}, { error: function(response){ that.showMessage(''); alert('Error, try refresh again.'); }, success: function(){ that.showMessage(''); } }); }, destroy_view: function() { // COMPLETELY UNBIND THE VIEW this.undelegateEvents(); this.$el.removeData().unbind(); // Remove view from DOM this.remove(); Backbone.View.prototype.remove.call(this); }, showMessage: function(text, hold) { var onHold = hold || false; if(onHold) { this.$el.find('#status-msg').text(text).show(); } else { this.$el.find('#status-msg').text(text).show().delay(2000).fadeOut(); } } }); /** * Safe validation * * @param collection * @param id * @param returnedParamName * @returns {*} */ function findWhereSafe(collection, id, returnedParamName) { var result = _.findWhere(collection, {id:id}); if (_.isUndefined(result)) { return '-- DELETED --'; } return result[returnedParamName]; } _.mixin({ findWhereSafe:findWhereSafe }); // Main tamplate EA.CustumizeView = Backbone.View.extend({ template : _.template( jQuery("#ea-tpl-custumize").html() ), template_fields : _.template(jQuery("#ea-tpl-custom-forms").html()), template_options : _.template(jQuery("#ea-tpl-custom-form-options").html()), tinymceOn : true, events: { "click .btn-save-settings" : "saveSettings", "click .btn-add-field" : "addCustomFiled", "click .single-field-options" : "fieldOptions", "click .add-select-option" : "addSelectOption", "click .item-save" : "apply", "click .item-delete": "deleteOption", "click .remove-select-option": "removeSelectedOption", "click .mail-tab": "selectMailNotification" }, initialize: function () { var plugin = this; this.collection = new EA.Settings(); this.fields = new EA.Fields(); this.fields.comparator = 'position'; // Table draw // this.render(); var defOptions = jQuery.Deferred(); var defFields = jQuery.Deferred(); // plugin.collection.bind("reset", this.render, this); // plugin.fields.bind("reset", this.renderFields, this); jQuery.when(defOptions, defFields).done(function (d1, d2) { plugin.render(); }); // if there is no data in cache this.collection.fetch( { reset:true, success: function(collection, response, options) { defOptions.resolve(); } }); this.fields.fetch( { reset:true, success: function(collection, response, options) { defFields.resolve(); } } ); }, render: function () { var obj = this; this.$el.empty(); // clear the element to make sure you don't double your contact view var content = this.template( { settings : this.collection.toJSON() } ); this.$el.html( content ); this.renderFields(); this.$el.find('#custom-fields').sortable({ placeholder: 'sortable-placeholder', update : function(event, ui) { obj.reorder(); } }); //this.$el.find('#custom-fields').disableSelection(); // init tiny mce this.initTinyMCE(); return this; }, /** * */ initTinyMCE: function() { if (typeof tinymce === 'undefined') { this.tinymceOn = false; return; } tinymce.init( { mode : "exact", elements : 'mail-template', theme: "modern", skin: "lightgray", menubar : false, statusbar : false, relative_urls : false, remove_script_host : false, toolbar: [ "bold,italic,alignleft,aligncenter,alignright,bullist,numlist,outdent,indent,undo,redo,link,unlink,code" ], plugins : "wordpress,wplink,paste,-code", paste_auto_cleanup_on_paste : true, paste_postprocess : function( pl, o ) { o.node.innerHTML = o.node.innerHTML.replace( /&nbsp;+/ig, " " ); } } ); }, selectMailNotification: function(event) { // save previous content from tinyMCE this.updateMailTemplate(); // process new content var $newTemplate = jQuery(event.target); var newContent = this.$el.find($newTemplate.data('textarea')).val(); if (this.tinymceOn) { tinymce.get('mail-template').setContent(newContent); // clear the stack of undo tinymce.activeEditor.undoManager.clear(); } else { this.$el.find('#mail-template').val(newContent); } this.$el.find('.mail-tab').filter('.selected').removeClass('selected'); $newTemplate.addClass('selected'); }, updateMailTemplate: function() { var prevContent = ''; var $prevTemplate = this.$el.find('.mail-tab').filter('.selected'); if (this.tinymceOn) { prevContent = tinymce.get('mail-template').getContent(); } else { prevContent = this.$el.find('#mail-template').val(); } this.$el.find($prevTemplate.data('textarea')).val(prevContent); }, saveSettings: function() { this.updateMailTemplate(); var fields = this.$el.find('.field'); var that = this; // list of options that are processed var processed = []; // update the collection this.collection.each(function(model, index) { var key = model.get('ea_key'); // mark for removing model.set('for_delete', true); if (processed.indexOf(key) !== -1) { return; } var input = fields.filter('[data-key="' + key + '"]'); if(input.is('[type="checkbox"]')) { if(input.is(':checked')) { model.set('ea_value', 1); } else { model.set('ea_value', 0); } model.unset('for_delete', {silent:true}); } else { model.set('ea_value', input.val()); model.unset('for_delete', {silent:true}); } // mark as processed processed.push(key); }); var collectionToBeDeleted = []; // clear down the section this.collection.each(function(model, index) { if (model.get('for_delete')) { collectionToBeDeleted.push(model); } }); this.collection.remove(collectionToBeDeleted, {silent:true}); var wrapper = new EA.SettingsWrapper({options: this.collection, fields: this.fields}); wrapper.save( null, { error: function(response){ alert('There has been some error. Please try later.'); }, success: function(){ alert('Settings saved!'); } }); }, addCustomFiled: function(e) { var obj = this; var $btn = jQuery(e.currentTarget); var $row = $btn.closest('th'); var name = $row.find('input').val(); var type = $row.find('select').val(); var field = new EA.Field({ label:name, type:type, position: obj.fields.length + 1 }); this.fields.add(field); var $html = this.template_fields({item : field.toJSON()}); $ul = this.$el.find('#custom-fields'); $ul.append($html); $row.find('input').val(''); $ul.find('.single-field-options:last').click(); }, renderFields: function() { var obj = this, $ul, tags = []; $ul = this.$el.find('#custom-fields'); $ul.empty(); this.fields.sort(); this.fields.each(function(model, index) { var o = model.toJSON(); var $html = obj.template_fields({item : o}); $ul.append($html); tags.push('#' + o.slug + '#'); }); this.$el.find('#custom-tags').html(tags.join(', ')); }, fieldOptions: function(e) { e.preventDefault(); var $btn = jQuery(e.currentTarget); var $li = $btn.closest('li'); var name = $li.data('name'); var element = this.fields.findWhere({label: name}); if ($btn.find('i').hasClass('fa-chevron-down')) { // open $btn.find('i').removeClass('fa-chevron-down'); $btn.find('i').addClass('fa-chevron-up'); var o = element.toJSON(); if (o.type === 'SELECT') { if (o.mixed !== '' ) { o.options = o.mixed.split(','); } else { o.options = ['-']; } } $html = this.template_options({item:o}); $li.append($html); this.$el.find('#custom-fields').sortable('disable'); $li.find('.select-options').sortable(); } else { // close $btn.find('i').removeClass('fa-chevron-up'); $btn.find('i').addClass('fa-chevron-down'); $li.find('.field-settings').remove(); this.$el.find('#custom-fields').sortable('enable'); } return false; }, addSelectOption: function(e) { e.preventDefault(); var $btn = jQuery(e.currentTarget); var value = $btn.prevAll('input').val(); var cont = $btn.closest('.field-settings'); cont.find('.select-options').append('<li data-element="'+ value + '">'+ value + '<a href="#" class="remove-select-option"><i class="fa fa-trash-o"></i></a></li>'); // delete option $btn.prevAll('input').val(''); }, apply: function(e) { e.preventDefault(); var $btn = jQuery(e.currentTarget); var $li = $btn.closest('li'); var name = $li.data('name'); var element = this.fields.findWhere({label:name}); var options = []; $li.find('.select-options > li').each(function(index, el) { options.push(jQuery(el).text().trim()); }); element.set('label', $li.find('.field-label').val()); element.set('required', $li.find('.required').is(":checked")); element.set('visible', $li.find('.visible').is(":checked")); if ($li.find('.field-mixed').length > 0) { element.set('mixed', $li.find('.field-mixed').val()); } if (options.length > 0) { element.set('mixed', options.join(',')); } $li.closest('ul').sortable('enable'); element.save( null, { error: function(response){ alert('There has been some error.'); } }); this.renderFields(); }, deleteOption: function(e) { e.preventDefault(); var obj = this; var $btn = jQuery(e.currentTarget); var $li = $btn.closest('li'); var name = $li.data('name'); var element = this.fields.findWhere({label:name}); this.fields.remove(element); element.destroy({ success: function(model, response) { obj.renderFields(); }, error: function() { alert('Error on delete!'); } }); }, removeSelectedOption: function(e) { e.preventDefault(); var $btn = jQuery(e.currentTarget); $btn.closest('li').remove(); }, reorder: function() { var obj = this; var $ul = this.$el.find('#custom-fields'); var $lis = $ul.children(); var count = 1; $lis.each(function(index, el) { var name = jQuery(el).data('name'); var element = obj.fields.findWhere({label:name}); element.set('position', count++); }); }, destroy_view: function() { tinymce.remove('#mail-template'); // COMPLETELY UNBIND THE VIEW this.undelegateEvents(); this.$el.removeData().unbind(); // Remove view from DOM this.remove(); Backbone.View.prototype.remove.call(this); }, }); // Main tamplate EA.ToolsView = Backbone.View.extend({ template : _.template( jQuery("#ea-tpl-tools").html() ), template_error_log : _.template( jQuery("#ea-tpl-tools-log").text() ), events: { "click #test-wp-mail" : "testWPMail", "click #test-mail" : "testMail" }, initialize: function () { this.render(); this.errors = new EA.Errors(); this.errors.bind("reset", this.renderLog, this); this.errors.fetch({reset:true}); }, render: function () { var obj = this; this.$el.empty(); // clear the element to make sure you don't double your contact view var content = this.template( {} ); this.$el.html( content ); return this; }, testWPMail: function() { var data = { action: 'ea_test_wp_mail', address: jQuery('#test-email-address').val(), native: 0 }; jQuery.post(ajaxurl, data, function(response) { alert(response); }); }, testMail: function() { var data = { action: 'ea_test_wp_mail', address: jQuery('#test-email-address').val(), native: 1 }; jQuery.post(ajaxurl, data, function(response) { alert(response); }); }, /** * Renders error log textarea */ renderLog: function () { var obj = this, content = ''; this.errors.each(function(model, index) { var o = model.toJSON(); content += obj.template_error_log({item : o}); }); this.$el.find('#ea-error-log').val(content); }, destroy_view: function() { // COMPLETELY UNBIND THE VIEW this.undelegateEvents(); this.$el.removeData().unbind(); // Remove view from DOM this.remove(); Backbone.View.prototype.remove.call(this); } }); /** * Main Admin View * Renders Admin tab panel * **/ EA.MainView = Backbone.View.extend({ el : jQuery('#wpbody-content'), template : _.template( jQuery("#ea-settings-main").html() ), events : { "click #tab-header li a" : "select" }, initialize: function () { this.render(); }, render: function () { this.$el.empty(); this.$el.html( this.template ); return this; }, addContainer: function () { if( this.$el.find('#tab-content').length > 0 ) { return; } this.$el.children('.wrap').append( jQuery( document.createElement('div') ) .attr( 'id', 'tab-content' ) ); }, select: function(e) { // console.log(e); var element = jQuery(e.target); this.$el.find('#tab-header li').removeClass('tab-selected'); element.parents('li:first').addClass('tab-selected'); }, selectHash: function(hash) { if(hash === '') { hash = '#locations/'; } this.$el.find('[href="' + hash + '"]').click(); } }); var mainView = new EA.MainView(); EA.AppRouter = Backbone.Router.extend({ current: null, routes: { "custumize":"custumize", "staff/": "staff", "services/": "services", "connection/": "connections", "locations/": "location", "custumize/": "custumize", "tools/": "tools", "": 'location' }, initialize: function () { var currentHash = window.location.hash; mainView.selectHash(currentHash); }, clearState : function() { if(this.current != null) { this.current.destroy_view(); // FIX mainView.addContainer(); } }, setState: function(newState) { this.current = newState; // FIX back/forward navigation var hash = window.location.hash; if(hash === '') { hash = '#locations/'; } var tab = mainView.$el.find('[href="' + hash + '"]')[0]; mainView.select({ target : tab}); } }); // Instantiate the router var app_router = new EA.AppRouter; // Services app_router.on('route:services', function () { this.clearState(); var services = new EA.ServicesView({ el: '#tab-content' }); this.setState(services); }); // Locations app_router.on('route:location', function () { this.clearState(); var locations = new EA.LocationsView({ el: '#tab-content' }); this.setState(locations); }); // Staff app_router.on('route:staff', function () { this.clearState(); var staff = new EA.StaffView({ el: '#tab-content' }); this.setState(staff); }); // Connections app_router.on('route:connections', function () { this.clearState(); var connections = new EA.ConnectionsView({ el: '#tab-content' }); this.setState(connections); }); // Customize app_router.on('route:custumize', function () { this.clearState(); var custumize = new EA.CustumizeView({ el: '#tab-content' }); this.setState(custumize); }); app_router.on('route:tools', function () { this.clearState(); var custumize = new EA.ToolsView({ el: '#tab-content' }); this.setState(custumize); }); // Start Backbone history a necessary step for bookmarkable URL's Backbone.history.start(); }(jQuery));
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.History=t():e.History=t()}(this,function(){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}}t.__esModule=!0;var a=n(17),o=r(a);t.createHistory=o["default"];var i=n(18),u=r(i);t.createHashHistory=u["default"];var s=n(19),f=r(s);t.createMemoryHistory=f["default"];var c=n(12),l=r(c);t.createLocation=l["default"];var d=n(22),p=r(d);t.useBasename=p["default"];var h=n(13),g=r(h);t.useBeforeUnload=g["default"];var y=n(14),v=r(y);t.useQueries=v["default"];var m=n(1),b=r(m);t.Actions=b["default"];var O=n(20),w=r(O);t.enableBeforeUnload=w["default"];var x=n(21),P=r(x);t.enableQueries=P["default"]},function(e,t){"use strict";t.__esModule=!0;var n="PUSH";t.PUSH=n;var r="REPLACE";t.REPLACE=r;var a="POP";t.POP=a,t["default"]={PUSH:n,REPLACE:r,POP:a}},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t){"use strict";t.__esModule=!0;var n=!("undefined"==typeof window||!window.document||!window.document.createElement);t.canUseDOM=n},function(e,t){"use strict";function n(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent("on"+t,n)}function r(e,t,n){e.removeEventListener?e.removeEventListener(t,n,!1):e.detachEvent("on"+t,n)}function a(){return window.location.href.split("#")[1]||""}function o(e){window.location.replace(window.location.pathname+window.location.search+"#"+e)}function i(){return window.location.pathname+window.location.search+window.location.hash}function u(e){e&&window.history.go(e)}function s(e,t){t(window.confirm(e))}function f(){var e=navigator.userAgent;return-1===e.indexOf("Android 2.")&&-1===e.indexOf("Android 4.0")||-1===e.indexOf("Mobile Safari")||-1!==e.indexOf("Chrome")||-1!==e.indexOf("Windows Phone")?window.history&&"pushState"in window.history:!1}function c(){var e=navigator.userAgent;return-1===e.indexOf("Firefox")}t.__esModule=!0,t.addEventListener=n,t.removeEventListener=r,t.getHashPath=a,t.replaceHashPath=o,t.getWindowPath=i,t.go=u,t.getUserConfirmation=s,t.supportsHistory=f,t.supportsGoWithoutReloadUsingHash=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(e,t){return function(){return i["default"](!1,"[history] "+t),e.apply(this,arguments)}}t.__esModule=!0;var o=n(2),i=r(o);t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";var r=function(e,t,n,r,a,o,i,u){if(!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var f=[n,r,a,o,i,u],c=0;s=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return f[c++]}))}throw s.framesToPop=1,s}};e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(e){var t=e.match(/^https?:\/\/[^\/]*/);return null==t?e:(u["default"](!1,'A path must be pathname + search + hash only, not a fully qualified URL like "%s"',e),e.substring(t[0].length))}function o(e){var t=a(e),n="",r="",o=t.indexOf("#");-1!==o&&(r=t.substring(o),t=t.substring(0,o));var i=t.indexOf("?");return-1!==i&&(n=t.substring(i),t=t.substring(0,i)),""===t&&(t="/"),{pathname:t,search:n,hash:r}}t.__esModule=!0;var i=n(2),u=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(e,t,n){var r=e(t,n);e.length<2?n(r):i["default"](void 0===r,'You should not "return" in a transition hook with a callback argument; call the callback instead')}t.__esModule=!0;var o=n(2),i=r(o);t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(e){return f+e}function o(e,t){try{window.sessionStorage.setItem(a(e),JSON.stringify(t))}catch(n){if(n.name===c||0===window.sessionStorage.length)return void s["default"](!1,"[history] Unable to save state; sessionStorage is not available in Safari private mode");throw n}}function i(e){var t=window.sessionStorage.getItem(a(e));if(t)try{return JSON.parse(t)}catch(n){}return null}t.__esModule=!0,t.saveState=o,t.readState=i;var u=n(2),s=r(u),f="@@History/",c="QuotaExceededError"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(e){function t(e){return u["default"](s.canUseDOM,"DOM history needs a DOM"),n.listen(e)}var n=l["default"](o({getUserConfirmation:f.getUserConfirmation},e,{go:f.go}));return o({},n,{listen:t})}t.__esModule=!0;var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(6),u=r(i),s=n(3),f=n(4),c=n(11),l=r(c);t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(e){return Math.random().toString(36).substr(2,e)}function o(e,t){return e.pathname===t.pathname&&e.search===t.search&&e.key===t.key&&f["default"](e.state,t.state)}function i(){function e(e){return U.push(e),function(){U=U.filter(function(t){return t!==e})}}function t(){return R&&R.action===l.POP?B.indexOf(R.key):D?B.indexOf(D.key):-1}function n(e){var n=t();D=e,D.action===l.PUSH?B=[].concat(B.slice(0,n+1),[D.key]):D.action===l.REPLACE&&(B[n]=D.key),C.forEach(function(e){e(D)})}function r(e){if(C.push(e),D)e(D);else{var t=S();B=[t.key],n(t)}return function(){C=C.filter(function(t){return t!==e})}}function i(e,t){c.loopAsync(U.length,function(t,n,r){g["default"](U[t],e,function(e){null!=e?r(e):n()})},function(e){T&&"string"==typeof e?T(e,function(e){t(e!==!1)}):t(e!==!1)})}function s(e){D&&o(D,e)||(R=e,i(e,function(t){if(R===e)if(t)M(e)!==!1&&n(e);else if(D&&e.action===l.POP){var r=B.indexOf(D.key),a=B.indexOf(e.key);-1!==r&&-1!==a&&A(r-a)}}))}function f(e,t){s(x(t,e,l.PUSH,b()))}function d(e,t){s(x(t,e,l.REPLACE,b()))}function h(){A(-1)}function y(){A(1)}function b(){return a(E)}function O(e){if(null==e||"string"==typeof e)return e;var t=e.pathname,n=e.search,r=e.hash,a=t;return n&&(a+=n),r&&(a+=r),a}function w(e){return O(e)}function x(e,t,n){var r=arguments.length<=3||void 0===arguments[3]?b():arguments[3];return p["default"](e,t,n,r)}function P(e){D?(j(D,e),n(D)):j(S(),e)}function j(e,t){e.state=u({},e.state,t),L(e.key,e.state)}function _(e){-1===U.indexOf(e)&&U.push(e)}function H(e){U=U.filter(function(t){return t!==e})}var k=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],S=k.getCurrentLocation,M=k.finishTransition,L=k.saveState,A=k.go,E=k.keyLength,T=k.getUserConfirmation;"number"!=typeof E&&(E=m);var U=[],B=[],C=[],D=void 0,R=void 0;return{listenBefore:e,listen:r,transitionTo:s,pushState:f,replaceState:d,go:A,goBack:h,goForward:y,createKey:b,createPath:O,createHref:w,createLocation:x,setState:v["default"](P,"setState is deprecated; use location.key to save state instead"),registerTransitionHook:v["default"](_,"registerTransitionHook is deprecated; use listenBefore instead"),unregisterTransitionHook:v["default"](H,"unregisterTransitionHook is deprecated; use the callback returned from listenBefore instead")}}t.__esModule=!0;var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(23),f=r(s),c=n(16),l=n(1),d=n(12),p=r(d),h=n(8),g=r(h),y=n(5),v=r(y),m=6;t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(){var e=arguments.length<=0||void 0===arguments[0]?"/":arguments[0],t=arguments.length<=1||void 0===arguments[1]?null:arguments[1],n=arguments.length<=2||void 0===arguments[2]?o.POP:arguments[2],r=arguments.length<=3||void 0===arguments[3]?null:arguments[3];"string"==typeof e&&(e=u["default"](e));var a=e.pathname||"/",i=e.search||"",s=e.hash||"";return{pathname:a,search:i,hash:s,state:t,action:n,key:r}}t.__esModule=!0;var o=n(1),i=n(7),u=r(i);t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(e){function t(t){var n=e();return"string"==typeof n?((t||window.event).returnValue=n,n):void 0}return c.addEventListener(window,"beforeunload",t),function(){c.removeEventListener(window,"beforeunload",t)}}function o(e){return function(t){function n(){for(var e=void 0,t=0,n=p.length;null==e&&n>t;++t)e=p[t].call();return e}function r(e){return p.push(e),1===p.length&&(f.canUseDOM?l=a(n):s["default"](!1,"listenBeforeUnload only works in DOM environments")),function(){p=p.filter(function(t){return t!==e}),0===p.length&&l&&(l(),l=null)}}function o(e){f.canUseDOM&&-1===p.indexOf(e)&&(p.push(e),1===p.length&&(l=a(n)))}function u(e){p.length>0&&(p=p.filter(function(t){return t!==e}),0===p.length&&l())}var c=e(t),l=void 0,p=[];return i({},c,{listenBeforeUnload:r,registerBeforeUnloadHook:d["default"](o,"registerBeforeUnloadHook is deprecated; use listenBeforeUnload instead"),unregisterBeforeUnloadHook:d["default"](u,"unregisterBeforeUnloadHook is deprecated; use the callback returned from listenBeforeUnload instead")})}}t.__esModule=!0;var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),f=n(3),c=n(4),l=n(5),d=r(l);t["default"]=o,e.exports=t["default"]},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){return c["default"].stringify(e,{arrayFormat:"brackets"})}function i(e){return c["default"].parse(e)}function u(e){return function(){function t(e){return null==e.query&&(e.query=m(e.search.substring(1))),e}function n(e,t){var n=void 0;if(!t||""===(n=v(t)))return e;"string"==typeof e&&(e=h["default"](e));var r=e.search+(e.search?"&":"?")+n;return s({},e,{search:r})}function r(e){return O.listenBefore(function(n,r){d["default"](e,t(n),r)})}function u(e){return O.listen(function(n){e(t(n))})}function f(e,t,r){return O.pushState(e,n(t,r))}function c(e,t,r){return O.replaceState(e,n(t,r))}function l(e,t){return O.createPath(n(e,t))}function p(e,t){return O.createHref(n(e,t))}function g(){return t(O.createLocation.apply(O,arguments))}var y=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],v=y.stringifyQuery,m=y.parseQueryString,b=a(y,["stringifyQuery","parseQueryString"]),O=e(b);return"function"!=typeof v&&(v=o),"function"!=typeof m&&(m=i),s({},O,{listenBefore:r,listen:u,pushState:f,replaceState:c,createPath:l,createHref:p,createLocation:g})}}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(26),c=r(f),l=n(8),d=r(l),p=n(7),h=r(p);t["default"]=u,e.exports=t["default"]},function(e,t){var n={};n.hexTable=new Array(256);for(var r=0;256>r;++r)n.hexTable[r]="%"+((16>r?"0":"")+r.toString(16)).toUpperCase();t.arrayToObject=function(e,t){for(var n=t.plainObjects?Object.create(null):{},r=0,a=e.length;a>r;++r)"undefined"!=typeof e[r]&&(n[r]=e[r]);return n},t.merge=function(e,n,r){if(!n)return e;if("object"!=typeof n)return Array.isArray(e)?e.push(n):"object"==typeof e?e[n]=!0:e=[e,n],e;if("object"!=typeof e)return e=[e].concat(n);Array.isArray(e)&&!Array.isArray(n)&&(e=t.arrayToObject(e,r));for(var a=Object.keys(n),o=0,i=a.length;i>o;++o){var u=a[o],s=n[u];Object.prototype.hasOwnProperty.call(e,u)?e[u]=t.merge(e[u],s,r):e[u]=s}return e},t.decode=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},t.encode=function(e){if(0===e.length)return e;"string"!=typeof e&&(e=""+e);for(var t="",r=0,a=e.length;a>r;++r){var o=e.charCodeAt(r);45===o||46===o||95===o||126===o||o>=48&&57>=o||o>=65&&90>=o||o>=97&&122>=o?t+=e[r]:128>o?t+=n.hexTable[o]:2048>o?t+=n.hexTable[192|o>>6]+n.hexTable[128|63&o]:55296>o||o>=57344?t+=n.hexTable[224|o>>12]+n.hexTable[128|o>>6&63]+n.hexTable[128|63&o]:(++r,o=65536+((1023&o)<<10|1023&e.charCodeAt(r)),t+=n.hexTable[240|o>>18]+n.hexTable[128|o>>12&63]+n.hexTable[128|o>>6&63]+n.hexTable[128|63&o])}return t},t.compact=function(e,n){if("object"!=typeof e||null===e)return e;n=n||[];var r=n.indexOf(e);if(-1!==r)return n[r];if(n.push(e),Array.isArray(e)){for(var a=[],o=0,i=e.length;i>o;++o)"undefined"!=typeof e[o]&&a.push(e[o]);return a}var u=Object.keys(e);for(o=0,i=u.length;i>o;++o){var s=u[o];e[s]=t.compact(e[s],n)}return e},t.isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},t.isBuffer=function(e){return null===e||"undefined"==typeof e?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}},function(e,t){"use strict";function n(e,t,n){function r(){i=!0,n.apply(this,arguments)}function a(){i||(e>o?t.call(this,o++,a,r):r.apply(this,arguments))}var o=0,i=!1;a()}t.__esModule=!0,t.loopAsync=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(){function e(e){e=e||window.history.state||{};var t=c.getWindowPath(),n=e,r=n.key,a=void 0;return r?a=l.readState(r):(a=null,r=m.createKey(),y&&window.history.replaceState(o({},e,{key:r}),null,t)),m.createLocation(t,a,void 0,r)}function t(t){function n(t){void 0!==t.state&&r(e(t.state))}var r=t.transitionTo;return c.addEventListener(window,"popstate",n),function(){c.removeEventListener(window,"popstate",n)}}function n(e){var t=e.basename,n=e.pathname,r=e.search,a=e.hash,o=e.state,i=e.action,u=e.key;if(i!==s.POP){l.saveState(u,o);var f=(t||"")+n+r+a,c={key:u};if(i===s.PUSH){if(v)return window.location.href=f,!1;window.history.pushState(c,null,f)}else{if(v)return window.location.replace(f),!1;window.history.replaceState(c,null,f)}}}function r(e){1===++b&&(O=t(m));var n=m.listenBefore(e);return function(){n(),0===--b&&O()}}function a(e){1===++b&&(O=t(m));var n=m.listen(e);return function(){n(),0===--b&&O()}}function i(e){1===++b&&(O=t(m)),m.registerTransitionHook(e)}function d(e){m.unregisterTransitionHook(e),0===--b&&O()}var h=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];u["default"](f.canUseDOM,"Browser history needs a DOM");var g=h.forceRefresh,y=c.supportsHistory(),v=!y||g,m=p["default"](o({},h,{getCurrentLocation:e,finishTransition:n,saveState:l.saveState})),b=0,O=void 0;return o({},m,{listenBefore:r,listen:a,registerTransitionHook:i,unregisterTransitionHook:d})}t.__esModule=!0;var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(6),u=r(i),s=n(1),f=n(3),c=n(4),l=n(9),d=n(10),p=r(d);t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(e){return"string"==typeof e&&"/"===e.charAt(0)}function o(){var e=v.getHashPath();return a(e)?!0:(v.replaceHashPath("/"+e),!1)}function i(e,t,n){return e+(-1===e.indexOf("?")?"?":"&")+(t+"="+n)}function u(e,t){return e.replace(new RegExp("[?&]?"+t+"=[a-zA-Z0-9]+"),"")}function s(e,t){var n=e.match(new RegExp("\\?.*?\\b"+t+"=(.+?)\\b"));return n&&n[1]}function f(){function e(){var e=v.getHashPath(),t=void 0,n=void 0;return _?(t=s(e,_),e=u(e,_),t?n=m.readState(t):(n=null,t=H.createKey(),v.replaceHashPath(i(e,_,t)))):t=n=null,H.createLocation(e,n,void 0,t)}function t(t){function n(){o()&&r(e())}var r=t.transitionTo;return o(),v.addEventListener(window,"hashchange",n),function(){v.removeEventListener(window,"hashchange",n)}}function n(e){var t=e.basename,n=e.pathname,r=e.search,a=e.state,o=e.action,u=e.key;if(o!==g.POP){var s=(t||"")+n+r;_&&(s=i(s,_,u)),s===v.getHashPath()?d["default"](!1,"You cannot %s the same path using hash history",o):(_?m.saveState(u,a):e.key=e.state=null,o===g.PUSH?window.location.hash=s:v.replaceHashPath(s))}}function r(e){1===++k&&(S=t(H));var n=H.listenBefore(e);return function(){n(),0===--k&&S()}}function a(e){1===++k&&(S=t(H));var n=H.listen(e);return function(){n(),0===--k&&S()}}function f(e,t){d["default"](_||null==e,"You cannot use state without a queryKey it will be dropped"),H.pushState(e,t)}function l(e,t){d["default"](_||null==e,"You cannot use state without a queryKey it will be dropped"),H.replaceState(e,t)}function p(e){d["default"](M,"Hash history go(n) causes a full page reload in this browser"),H.go(e)}function b(e){return"#"+H.createHref(e)}function x(e){1===++k&&(S=t(H)),H.registerTransitionHook(e)}function P(e){H.unregisterTransitionHook(e),0===--k&&S()}var j=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];h["default"](y.canUseDOM,"Hash history needs a DOM");var _=j.queryKey;(void 0===_||_)&&(_="string"==typeof _?_:w);var H=O["default"](c({},j,{getCurrentLocation:e,finishTransition:n,saveState:m.saveState})),k=0,S=void 0,M=v.supportsGoWithoutReloadUsingHash();return c({},H,{listenBefore:r,listen:a,pushState:f,replaceState:l,go:p,createHref:b,registerTransitionHook:x,unregisterTransitionHook:P})}t.__esModule=!0;var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(2),d=r(l),p=n(6),h=r(p),g=n(1),y=n(3),v=n(4),m=n(9),b=n(10),O=r(b),w="_k";t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function a(e){return e.filter(function(e){return e.state}).reduce(function(e,t){return e[t.key]=t.state,e},{})}function o(){function e(e,t){y[e]=t}function t(e){return y[e]}function n(){var e=h[g],n=e.key,r=e.basename,a=e.pathname,o=e.search,i=(r||"")+a+(o||""),u=void 0;return n?u=t(n):(u=null,n=d.createKey(),e.key=n),d.createLocation(i,u,void 0,n)}function r(e){var t=g+e;return t>=0&&t<h.length}function o(e){if(e){s["default"](r(e),"Cannot go(%s) there is not enough history",e),g+=e;var t=n();d.transitionTo(i({},t,{action:f.POP}))}}function u(t){switch(t.action){case f.PUSH:g+=1,g<h.length&&h.splice(g),h.push(t),e(t.key,t.state);break;case f.REPLACE:h[g]=t,e(t.key,t.state)}}var c=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];Array.isArray(c)?c={entries:c}:"string"==typeof c&&(c={entries:[c]});var d=l["default"](i({},c,{getCurrentLocation:n,finishTransition:u,saveState:e,go:o})),p=c,h=p.entries,g=p.current;"string"==typeof h?h=[h]:Array.isArray(h)||(h=["/"]),h=h.map(function(e){var t=d.createKey();return"string"==typeof e?{pathname:e,key:t}:"object"==typeof e&&e?i({},e,{key:t}):void s["default"](!1,"Unable to create history entry from %s",e)}),null==g?g=h.length-1:s["default"](g>=0&&g<h.length,"Current index must be >= 0 and < %s, was %s",h.length,g);var y=a(h);return d}t.__esModule=!0;var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(6),s=r(u),f=n(1),c=n(11),l=r(c);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var a=n(5),o=r(a),i=n(13),u=r(i);t["default"]=o["default"](u["default"],"enableBeforeUnload is deprecated, use useBeforeUnload instead"),e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var a=n(5),o=r(a),i=n(14),u=r(i);t["default"]=o["default"](u["default"],"enableQueries is deprecated, use useQueries instead"),e.exports=t["default"]},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){return function(){function t(e){return y&&null==e.basename&&(0===e.pathname.indexOf(y)?(e.pathname=e.pathname.substring(y.length),e.basename=y,""===e.pathname&&(e.pathname="/")):e.basename=""),e}function n(e){if(!y)return e;"string"==typeof e&&(e=l["default"](e));var t=e.pathname,n="/"===y.slice(-1)?y:y+"/",r="/"===t.charAt(0)?t.slice(1):t,a=n+r;return i({},e,{pathname:a})}function r(e){return m.listenBefore(function(n,r){f["default"](e,t(n),r)})}function o(e){return m.listen(function(n){e(t(n))})}function s(e,t){m.pushState(e,n(t))}function c(e,t){m.replaceState(e,n(t))}function d(e){return m.createPath(n(e))}function p(e){return m.createHref(n(e))}function h(){return t(m.createLocation.apply(m,arguments))}var g=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],y=g.basename,v=a(g,["basename"]),m=e(v);if(null==y&&u.canUseDOM){var b=document.getElementsByTagName("base")[0];b&&(y=b.href)}return i({},m,{listenBefore:r,listen:o,pushState:s,replaceState:c,createPath:d,createHref:p,createLocation:h})}}t.__esModule=!0;var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(3),s=n(8),f=r(s),c=n(7),l=r(c);t["default"]=o,e.exports=t["default"]},function(e,t,n){function r(e){return null===e||void 0===e}function a(e){return e&&"object"==typeof e&&"number"==typeof e.length?"function"!=typeof e.copy||"function"!=typeof e.slice?!1:e.length>0&&"number"!=typeof e[0]?!1:!0:!1}function o(e,t,n){var o,c;if(r(e)||r(t))return!1;if(e.prototype!==t.prototype)return!1;if(s(e))return s(t)?(e=i.call(e),t=i.call(t),f(e,t,n)):!1;if(a(e)){if(!a(t))return!1;if(e.length!==t.length)return!1;for(o=0;o<e.length;o++)if(e[o]!==t[o])return!1;return!0}try{var l=u(e),d=u(t)}catch(p){return!1}if(l.length!=d.length)return!1;for(l.sort(),d.sort(),o=l.length-1;o>=0;o--)if(l[o]!=d[o])return!1;for(o=l.length-1;o>=0;o--)if(c=l[o],!f(e[c],t[c],n))return!1;return typeof e==typeof t}var i=Array.prototype.slice,u=n(25),s=n(24),f=e.exports=function(e,t,n){return n||(n={}),e===t?!0:e instanceof Date&&t instanceof Date?e.getTime()===t.getTime():!e||!t||"object"!=typeof e&&"object"!=typeof t?n.strict?e===t:e==t:o(e,t,n)}},function(e,t){function n(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function r(e){return e&&"object"==typeof e&&"number"==typeof e.length&&Object.prototype.hasOwnProperty.call(e,"callee")&&!Object.prototype.propertyIsEnumerable.call(e,"callee")||!1}var a="[object Arguments]"==function(){return Object.prototype.toString.call(arguments)}();t=e.exports=a?n:r,t.supported=n,t.unsupported=r},function(e,t){function n(e){var t=[];for(var n in e)t.push(n);return t}t=e.exports="function"==typeof Object.keys?Object.keys:n,t.shim=n},function(e,t,n){var r=n(28),a=n(27);e.exports={stringify:r,parse:a}},function(e,t,n){var r=n(15),a={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:!1,plainObjects:!1,allowPrototypes:!1};a.parseValues=function(e,t){for(var n={},a=e.split(t.delimiter,t.parameterLimit===1/0?void 0:t.parameterLimit),o=0,i=a.length;i>o;++o){var u=a[o],s=-1===u.indexOf("]=")?u.indexOf("="):u.indexOf("]=")+1;if(-1===s)n[r.decode(u)]="",t.strictNullHandling&&(n[r.decode(u)]=null);else{var f=r.decode(u.slice(0,s)),c=r.decode(u.slice(s+1));Object.prototype.hasOwnProperty.call(n,f)?n[f]=[].concat(n[f]).concat(c):n[f]=c}}return n},a.parseObject=function(e,t,n){if(!e.length)return t;var r,o=e.shift();if("[]"===o)r=[],r=r.concat(a.parseObject(e,t,n));else{r=n.plainObjects?Object.create(null):{};var i="["===o[0]&&"]"===o[o.length-1]?o.slice(1,o.length-1):o,u=parseInt(i,10),s=""+u;!isNaN(u)&&o!==i&&s===i&&u>=0&&n.parseArrays&&u<=n.arrayLimit?(r=[],r[u]=a.parseObject(e,t,n)):r[i]=a.parseObject(e,t,n)}return r},a.parseKeys=function(e,t,n){if(e){n.allowDots&&(e=e.replace(/\.([^\.\[]+)/g,"[$1]"));var r=/^([^\[\]]*)/,o=/(\[[^\[\]]*\])/g,i=r.exec(e),u=[];if(i[1]){if(!n.plainObjects&&Object.prototype.hasOwnProperty(i[1])&&!n.allowPrototypes)return;u.push(i[1])}for(var s=0;null!==(i=o.exec(e))&&s<n.depth;)++s,(n.plainObjects||!Object.prototype.hasOwnProperty(i[1].replace(/\[|\]/g,""))||n.allowPrototypes)&&u.push(i[1]);return i&&u.push("["+e.slice(i.index)+"]"),a.parseObject(u,t,n)}},e.exports=function(e,t){if(t=t||{},t.delimiter="string"==typeof t.delimiter||r.isRegExp(t.delimiter)?t.delimiter:a.delimiter,t.depth="number"==typeof t.depth?t.depth:a.depth,t.arrayLimit="number"==typeof t.arrayLimit?t.arrayLimit:a.arrayLimit,t.parseArrays=t.parseArrays!==!1,t.allowDots=t.allowDots!==!1,t.plainObjects="boolean"==typeof t.plainObjects?t.plainObjects:a.plainObjects,t.allowPrototypes="boolean"==typeof t.allowPrototypes?t.allowPrototypes:a.allowPrototypes,t.parameterLimit="number"==typeof t.parameterLimit?t.parameterLimit:a.parameterLimit,t.strictNullHandling="boolean"==typeof t.strictNullHandling?t.strictNullHandling:a.strictNullHandling,""===e||null===e||"undefined"==typeof e)return t.plainObjects?Object.create(null):{};for(var n="string"==typeof e?a.parseValues(e,t):e,o=t.plainObjects?Object.create(null):{},i=Object.keys(n),u=0,s=i.length;s>u;++u){var f=i[u],c=a.parseKeys(f,n[f],t);o=r.merge(o,c,t)}return r.compact(o)}},function(e,t,n){var r=n(15),a={delimiter:"&",arrayPrefixGenerators:{brackets:function(e,t){return e+"[]"},indices:function(e,t){return e+"["+t+"]"},repeat:function(e,t){return e}},strictNullHandling:!1};a.stringify=function(e,t,n,o,i){if("function"==typeof i)e=i(t,e);else if(r.isBuffer(e))e=e.toString();else if(e instanceof Date)e=e.toISOString();else if(null===e){if(o)return r.encode(t);e=""}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return[r.encode(t)+"="+r.encode(e)];var u=[];if("undefined"==typeof e)return u;for(var s=Array.isArray(i)?i:Object.keys(e),f=0,c=s.length;c>f;++f){var l=s[f];u=Array.isArray(e)?u.concat(a.stringify(e[l],n(t,l),n,o,i)):u.concat(a.stringify(e[l],t+"["+l+"]",n,o,i))}return u},e.exports=function(e,t){t=t||{};var n,r,o="undefined"==typeof t.delimiter?a.delimiter:t.delimiter,i="boolean"==typeof t.strictNullHandling?t.strictNullHandling:a.strictNullHandling;"function"==typeof t.filter?(r=t.filter,e=r("",e)):Array.isArray(t.filter)&&(n=r=t.filter);var u=[];if("object"!=typeof e||null===e)return"";var s;s=t.arrayFormat in a.arrayPrefixGenerators?t.arrayFormat:"indices"in t?t.indices?"indices":"repeat":"indices";var f=a.arrayPrefixGenerators[s];n||(n=Object.keys(e));for(var c=0,l=n.length;l>c;++c){var d=n[c];u=u.concat(a.stringify(e[d],d,f,i,r))}return u.join(o)}}])});
/** * @license * (c) 2009-2016 Michael Leibman * michael{dot}leibman{at}gmail{dot}com * http://github.com/mleibman/slickgrid * * Distributed under MIT license. * All rights reserved. * * SlickGrid v2.4 * * NOTES: * Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods. * This increases the speed dramatically, but can only be done safely because there are no event handlers * or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy() * and do proper cleanup. */ // make sure required JavaScript modules are loaded if (typeof jQuery === "undefined") { throw new Error("SlickGrid requires jquery module to be loaded"); } if (!jQuery.fn.drag) { throw new Error("SlickGrid requires jquery.event.drag module to be loaded"); } if (typeof Slick === "undefined") { throw new Error("slick.core.js not loaded"); } (function ($) { // Slick.Grid $.extend(true, window, { Slick: { Grid: SlickGrid } }); // shared across all grids on the page var scrollbarDimensions; var maxSupportedCssHeight; // browser's breaking point ////////////////////////////////////////////////////////////////////////////////////////////// // SlickGrid class implementation (available as Slick.Grid) /** * Creates a new instance of the grid. * @class SlickGrid * @constructor * @param {Node} container Container node to create the grid in. * @param {Array,Object} data An array of objects for databinding. * @param {Array} columns An array of column definitions. * @param {Object} options Grid options. **/ function SlickGrid(container, data, columns, options) { // settings var defaults = { alwaysShowVerticalScroll: false, alwaysAllowHorizontalScroll: false, explicitInitialization: false, rowHeight: 25, defaultColumnWidth: 80, enableAddRow: false, leaveSpaceForNewRows: false, editable: false, autoEdit: true, suppressActiveCellChangeOnEdit: false, enableCellNavigation: true, enableColumnReorder: true, asyncEditorLoading: false, asyncEditorLoadDelay: 100, forceFitColumns: false, enableAsyncPostRender: false, asyncPostRenderDelay: 50, enableAsyncPostRenderCleanup: false, asyncPostRenderCleanupDelay: 40, autoHeight: false, editorLock: Slick.GlobalEditorLock, showHeaderRow: false, headerRowHeight: 25, createFooterRow: false, showFooterRow: false, footerRowHeight: 25, createPreHeaderPanel: false, showPreHeaderPanel: false, preHeaderPanelHeight: 25, showTopPanel: false, topPanelHeight: 25, formatterFactory: null, editorFactory: null, cellFlashingCssClass: "flashing", selectedCellCssClass: "selected", multiSelect: true, enableTextSelectionOnCells: false, dataItemColumnValueExtractor: null, frozenBottom: false, frozenColumn: -1, frozenRow: -1, fullWidthRows: false, multiColumnSort: false, numberedMultiColumnSort: false, tristateMultiColumnSort: false, sortColNumberInSeparateSpan: false, defaultFormatter: defaultFormatter, forceSyncScrolling: false, addNewRowCssClass: "new-row", preserveCopiedSelectionOnPaste: false, showCellSelection: true, viewportClass: null, minRowBuffer: 3, emulatePagingWhenScrolling: true, // when scrolling off bottom of viewport, place new row at top of viewport editorCellNavOnLRKeys: false, doPaging: true }; var columnDefaults = { name: "", resizable: true, sortable: false, minWidth: 30, rerenderOnResize: false, headerCssClass: null, defaultSortAsc: true, focusable: true, selectable: true }; // scroller var th; // virtual height var h; // real scrollable height var ph; // page height var n; // number of pages var cj; // "jumpiness" coefficient var page = 0; // current page var offset = 0; // current page offset var vScrollDir = 1; // private var initialized = false; var $container; var uid = "slickgrid_" + Math.round(1000000 * Math.random()); var self = this; var $focusSink, $focusSink2; var $groupHeaders = $(); var $headerScroller; var $headers; var $headerRow, $headerRowScroller, $headerRowSpacerL, $headerRowSpacerR; var $footerRow, $footerRowScroller, $footerRowSpacerL, $footerRowSpacerR; var $preHeaderPanel, $preHeaderPanelScroller, $preHeaderPanelSpacer; var $topPanelScroller; var $topPanel; var $viewport; var $canvas; var $style; var $boundAncestors; var treeColumns; var stylesheet, columnCssRulesL, columnCssRulesR; var viewportH, viewportW; var canvasWidth, canvasWidthL, canvasWidthR; var headersWidth, headersWidthL, headersWidthR; var viewportHasHScroll, viewportHasVScroll; var headerColumnWidthDiff = 0, headerColumnHeightDiff = 0, // border+padding cellWidthDiff = 0, cellHeightDiff = 0, jQueryNewWidthBehaviour = false; var absoluteColumnMinWidth; var hasFrozenRows = false; var frozenRowsHeight = 0; var actualFrozenRow = -1; var paneTopH = 0; var paneBottomH = 0; var viewportTopH = 0; var viewportBottomH = 0; var topPanelH = 0; var headerRowH = 0; var footerRowH = 0; var tabbingDirection = 1; var $activeCanvasNode; var $activeViewportNode; var activePosX; var activeRow, activeCell; var activeCellNode = null; var currentEditor = null; var serializedEditorValue; var editController; var rowsCache = {}; var renderedRows = 0; var numVisibleRows = 0; var prevScrollTop = 0; var scrollTop = 0; var lastRenderedScrollTop = 0; var lastRenderedScrollLeft = 0; var prevScrollLeft = 0; var scrollLeft = 0; var selectionModel; var selectedRows = []; var plugins = []; var cellCssClasses = {}; var columnsById = {}; var sortColumns = []; var columnPosLeft = []; var columnPosRight = []; var pagingActive = false; var pagingIsLastPage = false; var scrollThrottle = ActionThrottle(render, 50); // async call handles var h_editorLoader = null; var h_render = null; var h_postrender = null; var h_postrenderCleanup = null; var postProcessedRows = {}; var postProcessToRow = null; var postProcessFromRow = null; var postProcessedCleanupQueue = []; var postProcessgroupId = 0; // perf counters var counter_rows_rendered = 0; var counter_rows_removed = 0; // These two variables work around a bug with inertial scrolling in Webkit/Blink on Mac. // See http://crbug.com/312427. var rowNodeFromLastMouseWheelEvent; // this node must not be deleted while inertial scrolling var zombieRowNodeFromLastMouseWheelEvent; // node that was hidden instead of getting deleted var zombieRowCacheFromLastMouseWheelEvent; // row cache for above node var zombieRowPostProcessedFromLastMouseWheelEvent; // post processing references for above node var $paneHeaderL; var $paneHeaderR; var $paneTopL; var $paneTopR; var $paneBottomL; var $paneBottomR; var $headerScrollerL; var $headerScrollerR; var $headerL; var $headerR; var $groupHeadersL; var $groupHeadersR; var $headerRowScrollerL; var $headerRowScrollerR; var $footerRowScrollerL; var $footerRowScrollerR; var $headerRowL; var $headerRowR; var $footerRowL; var $footerRowR; var $topPanelScrollerL; var $topPanelScrollerR; var $topPanelL; var $topPanelR; var $viewportTopL; var $viewportTopR; var $viewportBottomL; var $viewportBottomR; var $canvasTopL; var $canvasTopR; var $canvasBottomL; var $canvasBottomR; var $viewportScrollContainerX; var $viewportScrollContainerY; var $headerScrollContainer; var $headerRowScrollContainer; var $footerRowScrollContainer; // store css attributes if display:none is active in container or parent var cssShow = { position: 'absolute', visibility: 'hidden', display: 'block' }; var $hiddenParents; var oldProps = []; var columnResizeDragging = false; ////////////////////////////////////////////////////////////////////////////////////////////// // Initialization function init() { if (container instanceof jQuery) { $container = container; } else { $container = $(container); } if ($container.length < 1) { throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM."); } cacheCssForHiddenInit(); // calculate these only once and share between grid instances maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight(); options = $.extend({}, defaults, options); validateAndEnforceOptions(); columnDefaults.width = options.defaultColumnWidth; treeColumns = new Slick.TreeColumns(columns); columns = treeColumns.extractColumns(); updateColumnProps(); // validate loaded JavaScript modules against requested options if (options.enableColumnReorder && !$.fn.sortable) { throw new Error("SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded"); } editController = { "commitCurrentEdit": commitCurrentEdit, "cancelCurrentEdit": cancelCurrentEdit }; $container .empty() .css("overflow", "hidden") .css("outline", 0) .addClass(uid) .addClass("ui-widget"); // set up a positioning container if needed if (!/relative|absolute|fixed/.test($container.css("position"))) { $container.css("position", "relative"); } $focusSink = $("<div tabIndex='0' hideFocus style='position:fixed;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container); // Containers used for scrolling frozen columns and rows $paneHeaderL = $("<div class='slick-pane slick-pane-header slick-pane-left' tabIndex='0' />").appendTo($container); $paneHeaderR = $("<div class='slick-pane slick-pane-header slick-pane-right' tabIndex='0' />").appendTo($container); $paneTopL = $("<div class='slick-pane slick-pane-top slick-pane-left' tabIndex='0' />").appendTo($container); $paneTopR = $("<div class='slick-pane slick-pane-top slick-pane-right' tabIndex='0' />").appendTo($container); $paneBottomL = $("<div class='slick-pane slick-pane-bottom slick-pane-left' tabIndex='0' />").appendTo($container); $paneBottomR = $("<div class='slick-pane slick-pane-bottom slick-pane-right' tabIndex='0' />").appendTo($container); if (options.createPreHeaderPanel) { $preHeaderPanelScroller = $("<div class='slick-preheader-panel ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($paneHeaderL); $preHeaderPanel = $("<div />").appendTo($preHeaderPanelScroller); $preHeaderPanelSpacer = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($preHeaderPanelScroller); if (!options.showPreHeaderPanel) { $preHeaderPanelScroller.hide(); } } // Append the header scroller containers $headerScrollerL = $("<div class='slick-header ui-state-default slick-header-left' />").appendTo($paneHeaderL); $headerScrollerR = $("<div class='slick-header ui-state-default slick-header-right' />").appendTo($paneHeaderR); // Cache the header scroller containers $headerScroller = $().add($headerScrollerL).add($headerScrollerR); if (treeColumns.hasDepth()) { $groupHeadersL = [], $groupHeadersR = []; for (var index = 0; index < treeColumns.getDepth() - 1; index++) { $groupHeadersL[index] = $("<div class='slick-group-header-columns slick-group-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL); $groupHeadersR[index] = $("<div class='slick-group-header-columns slick-group-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR); } $groupHeaders = $().add($groupHeadersL).add($groupHeadersR); } // Append the columnn containers to the headers $headerL = $("<div class='slick-header-columns slick-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL); $headerR = $("<div class='slick-header-columns slick-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR); // Cache the header columns $headers = $().add($headerL).add($headerR); $headerRowScrollerL = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopL); $headerRowScrollerR = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopR); $headerRowScroller = $().add($headerRowScrollerL).add($headerRowScrollerR); $headerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($headerRowScrollerL); $headerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($headerRowScrollerR); $headerRowL = $("<div class='slick-headerrow-columns slick-headerrow-columns-left' />").appendTo($headerRowScrollerL); $headerRowR = $("<div class='slick-headerrow-columns slick-headerrow-columns-right' />").appendTo($headerRowScrollerR); $headerRow = $().add($headerRowL).add($headerRowR); // Append the top panel scroller $topPanelScrollerL = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopL); $topPanelScrollerR = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopR); $topPanelScroller = $().add($topPanelScrollerL).add($topPanelScrollerR); // Append the top panel $topPanelL = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerL); $topPanelR = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerR); $topPanel = $().add($topPanelL).add($topPanelR); if (!options.showTopPanel) { $topPanelScroller.hide(); } if (!options.showHeaderRow) { $headerRowScroller.hide(); } // Append the viewport containers $viewportTopL = $("<div class='slick-viewport slick-viewport-top slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneTopL); $viewportTopR = $("<div class='slick-viewport slick-viewport-top slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneTopR); $viewportBottomL = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneBottomL); $viewportBottomR = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneBottomR); // Cache the viewports $viewport = $().add($viewportTopL).add($viewportTopR).add($viewportBottomL).add($viewportBottomR); // Default the active viewport to the top left $activeViewportNode = $viewportTopL; // Append the canvas containers $canvasTopL = $("<div class='grid-canvas grid-canvas-top grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportTopL); $canvasTopR = $("<div class='grid-canvas grid-canvas-top grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportTopR); $canvasBottomL = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportBottomL); $canvasBottomR = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportBottomR); if (options.viewportClass) $viewport.toggleClass(options.viewportClass, true); // Cache the canvases $canvas = $().add($canvasTopL).add($canvasTopR).add($canvasBottomL).add($canvasBottomR); scrollbarDimensions = scrollbarDimensions || measureScrollbar(); // Default the active canvas to the top left $activeCanvasNode = $canvasTopL; // pre-header if ($preHeaderPanelSpacer) $preHeaderPanelSpacer.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); $headers.width(getHeadersWidth()); $headerRowSpacerL.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); $headerRowSpacerR.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); // footer Row if (options.createFooterRow) { $footerRowScrollerR = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopR); $footerRowScrollerL = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopL); $footerRowScroller = $().add($footerRowScrollerL).add($footerRowScrollerR); $footerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($footerRowScrollerL); $footerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($footerRowScrollerR); $footerRowL = $("<div class='slick-footerrow-columns slick-footerrow-columns-left' />").appendTo($footerRowScrollerL); $footerRowR = $("<div class='slick-footerrow-columns slick-footerrow-columns-right' />").appendTo($footerRowScrollerR); $footerRow = $().add($footerRowL).add($footerRowR); if (!options.showFooterRow) { $footerRowScroller.hide(); } } $focusSink2 = $focusSink.clone().appendTo($container); if (!options.explicitInitialization) { finishInitialization(); } } function finishInitialization() { if (!initialized) { initialized = true; getViewportWidth(); getViewportHeight(); // header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?) // calculate the diff so we can set consistent sizes measureCellPaddingAndBorder(); // for usability reasons, all text selection in SlickGrid is disabled // with the exception of input and textarea elements (selection must // be enabled there so that editors work as expected); note that // selection in grid cells (grid body) is already unavailable in // all browsers except IE disableSelection($headers); // disable all text selection in header (including input and textarea) if (!options.enableTextSelectionOnCells) { // disable text selection in grid cells except in input and textarea elements // (this is IE-specific, because selectstart event will only fire in IE) $viewport.on("selectstart.ui", function (event) { return $(event.target).is("input,textarea"); }); } setFrozenOptions(); setPaneVisibility(); setScroller(); setOverflow(); updateColumnCaches(); createColumnHeaders(); createColumnGroupHeaders(); createColumnFooter(); setupColumnSort(); createCssRules(); resizeCanvas(); bindAncestorScrollEvents(); $container .on("resize.slickgrid", resizeCanvas); $viewport .on("scroll", handleScroll); if (jQuery.fn.mousewheel) { $viewport.on("mousewheel", handleMouseWheel); } $headerScroller //.on("scroll", handleHeaderScroll) .on("contextmenu", handleHeaderContextMenu) .on("click", handleHeaderClick) .on("mouseenter", ".slick-header-column", handleHeaderMouseEnter) .on("mouseleave", ".slick-header-column", handleHeaderMouseLeave); $headerRowScroller .on("scroll", handleHeaderRowScroll); if (options.createFooterRow) { $footerRowScroller .on("scroll", handleFooterRowScroll); } if (options.createPreHeaderPanel) { $preHeaderPanelScroller .on("scroll", handlePreHeaderPanelScroll); } $focusSink.add($focusSink2) .on("keydown", handleKeyDown); $canvas .on("keydown", handleKeyDown) .on("click", handleClick) .on("dblclick", handleDblClick) .on("contextmenu", handleContextMenu) .on("draginit", handleDragInit) .on("dragstart", {distance: 3}, handleDragStart) .on("drag", handleDrag) .on("dragend", handleDragEnd) .on("mouseenter", ".slick-cell", handleMouseEnter) .on("mouseleave", ".slick-cell", handleMouseLeave); restoreCssFromHiddenInit(); } } function cacheCssForHiddenInit() { // handle display:none on container or container parents $hiddenParents = $container.parents().addBack().not(':visible'); $hiddenParents.each(function() { var old = {}; for ( var name in cssShow ) { old[ name ] = this.style[ name ]; this.style[ name ] = cssShow[ name ]; } oldProps.push(old); }); } function restoreCssFromHiddenInit() { // finish handle display:none on container or container parents // - put values back the way they were $hiddenParents.each(function(i) { var old = oldProps[i]; for ( var name in cssShow ) { this.style[ name ] = old[ name ]; } }); } function hasFrozenColumns() { return options.frozenColumn > -1; } function registerPlugin(plugin) { plugins.unshift(plugin); plugin.init(self); } function unregisterPlugin(plugin) { for (var i = plugins.length; i >= 0; i--) { if (plugins[i] === plugin) { if (plugins[i].destroy) { plugins[i].destroy(); } plugins.splice(i, 1); break; } } } function getPluginByName(name) { for (var i = plugins.length; i >= 0; i--) { if (plugins[i].pluginName === name) { return plugins[i]; } } return undefined; } function setSelectionModel(model) { if (selectionModel) { selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged); if (selectionModel.destroy) { selectionModel.destroy(); } } selectionModel = model; if (selectionModel) { selectionModel.init(self); selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged); } } function getSelectionModel() { return selectionModel; } function getCanvasNode(columnIdOrIdx, rowIndex) { if (!columnIdOrIdx) { columnIdOrIdx = 0; } if (!rowIndex) { rowIndex = 0; } var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); return (hasFrozenRows && rowIndex >= actualFrozenRow + (options.frozenBottom ? 0 : 1) ) ? ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasBottomR[0] : $canvasBottomL[0]) : ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasTopR[0] : $canvasTopL[0]) ; } function getActiveCanvasNode(element) { setActiveCanvasNode(element); return $activeCanvasNode[0]; } function getCanvases() { return $canvas; } function setActiveCanvasNode(element) { if (element) { $activeCanvasNode = $(element.target).closest('.grid-canvas'); } } function getViewportNode() { return $viewport[0]; } function getActiveViewportNode(element) { setActiveViewPortNode(element); return $activeViewportNode[0]; } function setActiveViewportNode(element) { if (element) { $activeViewportNode = $(element.target).closest('.slick-viewport'); } } function measureScrollbar() { var $outerdiv = $('<div class="' + $viewport.className + '" style="position:absolute; top:-10000px; left:-10000px; overflow:auto; width:100px; height:100px;"></div>').appendTo($viewport); var $innerdiv = $('<div style="width:200px; height:200px; overflow:auto;"></div>').appendTo($outerdiv); var dim = { width: $outerdiv[0].offsetWidth - $outerdiv[0].clientWidth, height: $outerdiv[0].offsetHeight - $outerdiv[0].clientHeight }; $innerdiv.remove(); $outerdiv.remove(); return dim; } function getHeadersWidth() { headersWidth = headersWidthL = headersWidthR = 0; var includeScrollbar = !options.autoHeight; for (var i = 0, ii = columns.length; i < ii; i++) { var width = columns[ i ].width; if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) { headersWidthR += width; } else { headersWidthL += width; } } if (includeScrollbar) { if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) { headersWidthR += scrollbarDimensions.width; } else { headersWidthL += scrollbarDimensions.width; } } if (hasFrozenColumns()) { headersWidthL = headersWidthL + 1000; headersWidthR = Math.max(headersWidthR, viewportW) + headersWidthL; headersWidthR += scrollbarDimensions.width; } else { headersWidthL += scrollbarDimensions.width; headersWidthL = Math.max(headersWidthL, viewportW) + 1000; } headersWidth = headersWidthL + headersWidthR; return Math.max(headersWidth, viewportW) + 1000; } function getHeadersWidthL() { headersWidthL =0; columns.forEach(function(column, i) { if (!(( options.frozenColumn ) > -1 && ( i > options.frozenColumn ))) headersWidthL += column.width; }); if (hasFrozenColumns()) { headersWidthL += 1000; } else { headersWidthL += scrollbarDimensions.width; headersWidthL = Math.max(headersWidthL, viewportW) + 1000; } return headersWidthL; } function getHeadersWidthR() { headersWidthR =0; columns.forEach(function(column, i) { if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) headersWidthR += column.width; }); if (hasFrozenColumns()) { headersWidthR = Math.max(headersWidthR, viewportW) + getHeadersWidthL(); headersWidthR += scrollbarDimensions.width; } return headersWidthR; } function getCanvasWidth() { var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; var i = columns.length; canvasWidthL = canvasWidthR = 0; while (i--) { if (hasFrozenColumns() && (i > options.frozenColumn)) { canvasWidthR += columns[i].width; } else { canvasWidthL += columns[i].width; } } var totalRowWidth = canvasWidthL + canvasWidthR; return options.fullWidthRows ? Math.max(totalRowWidth, availableWidth) : totalRowWidth; } function updateCanvasWidth(forceColumnWidthsUpdate) { var oldCanvasWidth = canvasWidth; var oldCanvasWidthL = canvasWidthL; var oldCanvasWidthR = canvasWidthR; var widthChanged; canvasWidth = getCanvasWidth(); widthChanged = canvasWidth !== oldCanvasWidth || canvasWidthL !== oldCanvasWidthL || canvasWidthR !== oldCanvasWidthR; if (widthChanged || hasFrozenColumns() || hasFrozenRows) { $canvasTopL.width(canvasWidthL); getHeadersWidth(); $headerL.width(headersWidthL); $headerR.width(headersWidthR); if (hasFrozenColumns()) { $canvasTopR.width(canvasWidthR); $paneHeaderL.width(canvasWidthL); $paneHeaderR.css('left', canvasWidthL); $paneHeaderR.css('width', viewportW - canvasWidthL); $paneTopL.width(canvasWidthL); $paneTopR.css('left', canvasWidthL); $paneTopR.css('width', viewportW - canvasWidthL); $headerRowScrollerL.width(canvasWidthL); $headerRowScrollerR.width(viewportW - canvasWidthL); $headerRowL.width(canvasWidthL); $headerRowR.width(canvasWidthR); if (options.createFooterRow) { $footerRowScrollerL.width(canvasWidthL); $footerRowScrollerR.width(viewportW - canvasWidthL); $footerRowL.width(canvasWidthL); $footerRowR.width(canvasWidthR); } if (options.createPreHeaderPanel) { $preHeaderPanel.width(canvasWidth); } $viewportTopL.width(canvasWidthL); $viewportTopR.width(viewportW - canvasWidthL); if (hasFrozenRows) { $paneBottomL.width(canvasWidthL); $paneBottomR.css('left', canvasWidthL); $viewportBottomL.width(canvasWidthL); $viewportBottomR.width(viewportW - canvasWidthL); $canvasBottomL.width(canvasWidthL); $canvasBottomR.width(canvasWidthR); } } else { $paneHeaderL.width('100%'); $paneTopL.width('100%'); $headerRowScrollerL.width('100%'); $headerRowL.width(canvasWidth); if (options.createFooterRow) { $footerRowScrollerL.width('100%'); $footerRowL.width(canvasWidth); } if (options.createPreHeaderPanel) { $preHeaderPanel.width('100%'); $preHeaderPanel.width(canvasWidth); } $viewportTopL.width('100%'); if (hasFrozenRows) { $viewportBottomL.width('100%'); $canvasBottomL.width(canvasWidthL); } } viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width); } $headerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); $headerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); if (options.createFooterRow) { $footerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); $footerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); } if (widthChanged || forceColumnWidthsUpdate) { applyColumnWidths(); } } function disableSelection($target) { if ($target && $target.jquery) { $target .attr("unselectable", "on") .css("MozUserSelect", "none") .on("selectstart.ui", function () { return false; }); // from jquery:ui.core.js 1.7.2 } } function getMaxSupportedCssHeight() { var supportedHeight = 1000000; // FF reports the height back but still renders blank after ~6M px var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000; var div = $("<div style='display:none' />").appendTo(document.body); while (true) { var test = supportedHeight * 2; div.css("height", test); if (test > testUpTo || div.height() !== test) { break; } else { supportedHeight = test; } } div.remove(); return supportedHeight; } function getUID() { return uid; } function getHeaderColumnWidthDiff() { return headerColumnWidthDiff; } function getScrollbarDimensions() { return scrollbarDimensions; } // TODO: this is static. need to handle page mutation. function bindAncestorScrollEvents() { var elem = (hasFrozenRows && !options.frozenBottom) ? $canvasBottomL[0] : $canvasTopL[0]; while ((elem = elem.parentNode) != document.body && elem != null) { // bind to scroll containers only if (elem == $viewportTopL[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) { var $elem = $(elem); if (!$boundAncestors) { $boundAncestors = $elem; } else { $boundAncestors = $boundAncestors.add($elem); } $elem.on("scroll." + uid, handleActiveCellPositionChange); } } } function unbindAncestorScrollEvents() { if (!$boundAncestors) { return; } $boundAncestors.off("scroll." + uid); $boundAncestors = null; } function updateColumnHeader(columnId, title, toolTip) { if (!initialized) { return; } var idx = getColumnIndex(columnId); if (idx == null) { return; } var columnDef = columns[idx]; var $header = $headers.children().eq(idx); if ($header) { if (title !== undefined) { columns[idx].name = title; } if (toolTip !== undefined) { columns[idx].toolTip = toolTip; } trigger(self.onBeforeHeaderCellDestroy, { "node": $header[0], "column": columnDef, "grid": self }); $header .attr("title", toolTip || "") .children().eq(0).html(title); trigger(self.onHeaderCellRendered, { "node": $header[0], "column": columnDef, "grid": self }); } } function getHeader(columnDef) { if (!columnDef) { return hasFrozenColumns() ? $headers : $headerL; } var idx = getColumnIndex(columnDef.id); return hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL; } function getHeaderColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var targetHeader = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL; var targetIndex = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? idx : idx - options.frozenColumn - 1) : idx; var $rtn = targetHeader.children().eq(targetIndex); return $rtn && $rtn[0]; } function getHeaderRow() { return hasFrozenColumns() ? $headerRow : $headerRow[0]; } function getFooterRow() { return hasFrozenColumns() ? $footerRow : $footerRow[0]; } function getPreHeaderPanel() { return $preHeaderPanel[0]; } function getHeaderRowColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var $headerRowTarget; if (hasFrozenColumns()) { if (idx <= options.frozenColumn) { $headerRowTarget = $headerRowL; } else { $headerRowTarget = $headerRowR; idx -= options.frozenColumn + 1; } } else { $headerRowTarget = $headerRowL; } var $header = $headerRowTarget.children().eq(idx); return $header && $header[0]; } function getFooterRowColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var $footerRowTarget; if (hasFrozenColumns()) { if (idx <= options.frozenColumn) { $footerRowTarget = $footerRowL; } else { $footerRowTarget = $footerRowR; idx -= options.frozenColumn + 1; } } else { $footerRowTarget = $footerRowL; } var $footer = $footerRowTarget.children().eq(idx); return $footer && $footer[0]; } function createColumnFooter() { if (options.createFooterRow) { $footerRow.find(".slick-footerrow-column") .each(function () { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowL.empty(); $footerRowR.empty(); for (var i = 0; i < columns.length; i++) { var m = columns[i]; var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo(hasFrozenColumns() && (i > options.frozenColumn)? $footerRowR: $footerRowL); trigger(self.onFooterRowCellRendered, { "node": footerRowCell[0], "column": m, "grid": self }); } } } function createColumnGroupHeaders() { var columnsLength = 0; var frozenColumnsValid = false; if (!treeColumns.hasDepth()) return; for (var index = 0; index < $groupHeadersL.length; index++) { $groupHeadersL[index].empty(); $groupHeadersR[index].empty(); var groupColumns = treeColumns.getColumnsInDepth(index); for (var indexGroup in groupColumns) { var m = groupColumns[indexGroup]; columnsLength += m.extractColumns().length; if (hasFrozenColumns() && index == 0 && (columnsLength-1) === options.frozenColumn) frozenColumnsValid = true; $("<div class='ui-state-default slick-group-header-column' />") .html("<span class='slick-column-name'>" + m.name + "</span>") .attr("id", "" + uid + m.id) .attr("title", m.toolTip || "") .data("column", m) .addClass(m.headerCssClass || "") .addClass(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? 'frozen': '') .appendTo(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? $groupHeadersR[index]: $groupHeadersL[index]); } if (hasFrozenColumns() && index == 0 && !frozenColumnsValid) { $groupHeadersL[index].empty(); $groupHeadersR[index].empty(); alert("All columns of group should to be grouped!"); break; } } applyColumnGroupHeaderWidths(); } function createColumnHeaders() { function onMouseEnter() { $(this).addClass("ui-state-hover"); } function onMouseLeave() { $(this).removeClass("ui-state-hover"); } $headers.find(".slick-header-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headerL.empty(); $headerR.empty(); getHeadersWidth(); $headerL.width(headersWidthL); $headerR.width(headersWidthR); $headerRow.find(".slick-headerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headerRowL.empty(); $headerRowR.empty(); if (options.createFooterRow) { $footerRowL.find(".slick-footerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowL.empty(); if (hasFrozenColumns()) { $footerRowR.find(".slick-footerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowR.empty(); } } for (var i = 0; i < columns.length; i++) { var m = columns[i]; var $headerTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerL : $headerR) : $headerL; var $headerRowTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerRowL : $headerRowR) : $headerRowL; var header = $("<div class='ui-state-default slick-header-column' />") .html("<span class='slick-column-name'>" + m.name + "</span>") .width(m.width - headerColumnWidthDiff) .attr("id", "" + uid + m.id) .attr("title", m.toolTip || "") .data("column", m) .addClass(m.headerCssClass || "") .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo($headerTarget); if (options.enableColumnReorder || m.sortable) { header .on('mouseenter', onMouseEnter) .on('mouseleave', onMouseLeave); } if (m.sortable) { header.addClass("slick-header-sortable"); header.append("<span class='slick-sort-indicator" + (options.numberedMultiColumnSort && !options.sortColNumberInSeparateSpan ? " slick-sort-indicator-numbered" : "" ) + "' />"); if (options.numberedMultiColumnSort && options.sortColNumberInSeparateSpan) { header.append("<span class='slick-sort-indicator-numbered' />"); } } trigger(self.onHeaderCellRendered, { "node": header[0], "column": m, "grid": self }); if (options.showHeaderRow) { var headerRowCell = $("<div class='ui-state-default slick-headerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo($headerRowTarget); trigger(self.onHeaderRowCellRendered, { "node": headerRowCell[0], "column": m, "grid": self }); } if (options.createFooterRow && options.showFooterRow) { var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .appendTo($footerRow); trigger(self.onFooterRowCellRendered, { "node": footerRowCell[0], "column": m, "grid": self }); } } setSortColumns(sortColumns); setupColumnResize(); if (options.enableColumnReorder) { if (typeof options.enableColumnReorder == 'function') { options.enableColumnReorder(self, $headers, headerColumnWidthDiff, setColumns, setupColumnResize, columns, getColumnIndex, uid, trigger); } else { setupColumnReorder(); } } } function setupColumnSort() { $headers.click(function (e) { if (columnResizeDragging) return; // temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328) e.metaKey = e.metaKey || e.ctrlKey; if ($(e.target).hasClass("slick-resizable-handle")) { return; } var $col = $(e.target).closest(".slick-header-column"); if (!$col.length) { return; } var column = $col.data("column"); if (column.sortable) { if (!getEditorLock().commitCurrentEdit()) { return; } var sortColumn = null; var i = 0; for (; i < sortColumns.length; i++) { if (sortColumns[i].columnId == column.id) { sortColumn = sortColumns[i]; sortColumn.sortAsc = !sortColumn.sortAsc; break; } } var hadSortCol = !!sortColumn; if (options.tristateMultiColumnSort) { if (!sortColumn) { sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc }; } if (hadSortCol && sortColumn.sortAsc) { // three state: remove sort rather than go back to ASC sortColumns.splice(i, 1); sortColumn = null; } if (!options.multiColumnSort) { sortColumns = []; } if (sortColumn && (!hadSortCol || !options.multiColumnSort)) { sortColumns.push(sortColumn); } } else { // legacy behaviour if (e.metaKey && options.multiColumnSort) { if (sortColumn) { sortColumns.splice(i, 1); } } else { if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) { sortColumns = []; } if (!sortColumn) { sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc }; sortColumns.push(sortColumn); } else if (sortColumns.length == 0) { sortColumns.push(sortColumn); } } } setSortColumns(sortColumns); if (!options.multiColumnSort) { trigger(self.onSort, { multiColumnSort: false, columnId: (sortColumns.length > 0 ? column.id : null), sortCol: (sortColumns.length > 0 ? column : null), sortAsc: (sortColumns.length > 0 ? sortColumns[0].sortAsc : true) }, e); } else { trigger(self.onSort, { multiColumnSort: true, sortCols: $.map(sortColumns, function(col) { return {columnId: columns[getColumnIndex(col.columnId)].id, sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc }; }) }, e); } } }); } function currentPositionInHeader(id) { var currentPosition = 0; $headers.find('.slick-header-column').each(function (i) { if (this.id == id) { currentPosition = i; return false; } }); return currentPosition; } function limitPositionInGroup(idColumn) { var groupColumnOfPreviousPosition, startLimit = 0, endLimit = 0; treeColumns .getColumnsInDepth($groupHeadersL.length - 1) .some(function (groupColumn) { startLimit = endLimit; endLimit += groupColumn.columns.length; groupColumn.columns.some(function (column) { if (column.id === idColumn) groupColumnOfPreviousPosition = groupColumn; return groupColumnOfPreviousPosition; }); return groupColumnOfPreviousPosition; }); endLimit--; return { start: startLimit, end: endLimit, group: groupColumnOfPreviousPosition } } function remove(arr, elem) { var index = arr.lastIndexOf(elem); if(index > -1) { arr.splice(index, 1); remove(arr, elem); } } function columnPositionValidInGroup($item) { var currentPosition = currentPositionInHeader($item[0].id); var limit = limitPositionInGroup($item.data('column').id); var positionValid = limit.start <= currentPosition && currentPosition <= limit.end; return { limit: limit, valid: positionValid, message: positionValid? '': 'Column "'.concat($item.text(), '" can be reordered only within the "', limit.group.name, '" group!') }; } function setupColumnReorder() { $headers.filter(":ui-sortable").sortable("destroy"); var columnScrollTimer = null; function scrollColumnsRight() { $viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft + 10; } function scrollColumnsLeft() { $viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft - 10; } var canDragScroll; $headers.sortable({ containment: "parent", distance: 3, axis: "x", cursor: "default", tolerance: "intersection", helper: "clone", placeholder: "slick-sortable-placeholder ui-state-default slick-header-column", start: function (e, ui) { ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff); canDragScroll = !hasFrozenColumns() || (ui.placeholder.offset().left + ui.placeholder.width()) > $viewportScrollContainerX.offset().left; $(ui.helper).addClass("slick-header-column-active"); }, beforeStop: function (e, ui) { $(ui.helper).removeClass("slick-header-column-active"); }, sort: function (e, ui) { if (canDragScroll && e.originalEvent.pageX > $container[0].clientWidth) { if (!(columnScrollTimer)) { columnScrollTimer = setInterval( scrollColumnsRight, 100); } } else if (canDragScroll && e.originalEvent.pageX < $viewportScrollContainerX.offset().left) { if (!(columnScrollTimer)) { columnScrollTimer = setInterval( scrollColumnsLeft, 100); } } else { clearInterval(columnScrollTimer); columnScrollTimer = null; } }, stop: function (e, ui) { var cancel = false; clearInterval(columnScrollTimer); columnScrollTimer = null; var limit = null; if (treeColumns.hasDepth()) { var validPositionInGroup = columnPositionValidInGroup(ui.item); limit = validPositionInGroup.limit; cancel = !validPositionInGroup.valid; if (cancel) alert(validPositionInGroup.message); } if (cancel || !getEditorLock().commitCurrentEdit()) { $(this).sortable("cancel"); return; } var reorderedIds = $headerL.sortable("toArray"); reorderedIds = reorderedIds.concat($headerR.sortable("toArray")); var reorderedColumns = []; for (var i = 0; i < reorderedIds.length; i++) { reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]); } setColumns(reorderedColumns); trigger(self.onColumnsReordered, { impactedColumns : getImpactedColumns( limit ) }); e.stopPropagation(); setupColumnResize(); } }); } function getImpactedColumns( limit ) { var impactedColumns = []; if( limit != undefined ) { for( var i = limit.start; i <= limit.end; i++ ) { impactedColumns.push( columns[i] ); } } else { impactedColumns = columns; } return impactedColumns; } function setupColumnResize() { var $col, j, k, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable; columnElements = $headers.children(); columnElements.find(".slick-resizable-handle").remove(); columnElements.each(function (i, e) { if (i >= columns.length) { return; } if (columns[i].resizable) { if (firstResizable === undefined) { firstResizable = i; } lastResizable = i; } }); if (firstResizable === undefined) { return; } columnElements.each(function (i, e) { if (i >= columns.length) { return; } if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) { return; } $col = $(e); $("<div class='slick-resizable-handle' />") .appendTo(e) .on("dragstart", function (e, dd) { if (!getEditorLock().commitCurrentEdit()) { return false; } pageX = e.pageX; $(this).parent().addClass("slick-header-column-active"); var shrinkLeewayOnRight = null, stretchLeewayOnRight = null; // lock each column's width option to current width columnElements.each(function (i, e) { if (i >= columns.length) { return; } columns[i].previousWidth = $(e).outerWidth(); }); if (options.forceFitColumns) { shrinkLeewayOnRight = 0; stretchLeewayOnRight = 0; // colums on right affect maxPageX/minPageX for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (stretchLeewayOnRight !== null) { if (c.maxWidth) { stretchLeewayOnRight += c.maxWidth - c.previousWidth; } else { stretchLeewayOnRight = null; } } shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } } var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0; for (j = 0; j <= i; j++) { // columns on left only affect minPageX c = columns[j]; if (c.resizable) { if (stretchLeewayOnLeft !== null) { if (c.maxWidth) { stretchLeewayOnLeft += c.maxWidth - c.previousWidth; } else { stretchLeewayOnLeft = null; } } shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } if (shrinkLeewayOnRight === null) { shrinkLeewayOnRight = 100000; } if (shrinkLeewayOnLeft === null) { shrinkLeewayOnLeft = 100000; } if (stretchLeewayOnRight === null) { stretchLeewayOnRight = 100000; } if (stretchLeewayOnLeft === null) { stretchLeewayOnLeft = 100000; } maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft); minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight); }) .on("drag", function (e, dd) { columnResizeDragging = true; var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x; if (d < 0) { // shrink column x = d; var newCanvasWidthL = 0, newCanvasWidthR = 0; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } } } for (k = 0; k <= i; k++) { c = columns[k]; if (hasFrozenColumns() && (k > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } else { for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } } } else { // stretch column x = d; var newCanvasWidthL = 0, newCanvasWidthR = 0; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } for (k = 0; k <= i; k++) { c = columns[k]; if (hasFrozenColumns() && (k > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } else { for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } if (hasFrozenColumns() && newCanvasWidthL != canvasWidthL) { $headerL.width(newCanvasWidthL + 1000); $paneHeaderR.css('left', newCanvasWidthL); } applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); if (options.syncColumnCellResize) { applyColumnWidths(); } }) .on("dragend", function (e, dd) { var newWidth; $(this).parent().removeClass("slick-header-column-active"); for (j = 0; j < columns.length; j++) { c = columns[j]; newWidth = $(columnElements[j]).outerWidth(); if (c.previousWidth !== newWidth && c.rerenderOnResize) { invalidateAllRows(); } } updateCanvasWidth(true); render(); trigger(self.onColumnsResized, {}); setTimeout(function () { columnResizeDragging = false; }, 300); }); }); } function getVBoxDelta($el) { var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; var delta = 0; $.each(p, function (n, val) { delta += parseFloat($el.css(val)) || 0; }); return delta; } function setFrozenOptions() { options.frozenColumn = (options.frozenColumn >= 0 && options.frozenColumn < columns.length) ? parseInt(options.frozenColumn) : -1; if (options.frozenRow > -1) { hasFrozenRows = true; frozenRowsHeight = ( options.frozenRow ) * options.rowHeight; var dataLength = getDataLength(); actualFrozenRow = ( options.frozenBottom ) ? ( dataLength - options.frozenRow ) : options.frozenRow; } else { hasFrozenRows = false; } } function setPaneVisibility() { if (hasFrozenColumns()) { $paneHeaderR.show(); $paneTopR.show(); if (hasFrozenRows) { $paneBottomL.show(); $paneBottomR.show(); } else { $paneBottomR.hide(); $paneBottomL.hide(); } } else { $paneHeaderR.hide(); $paneTopR.hide(); $paneBottomR.hide(); if (hasFrozenRows) { $paneBottomL.show(); } else { $paneBottomR.hide(); $paneBottomL.hide(); } } } function setOverflow() { $viewportTopL.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ) : ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportTopR.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'scroll' : 'auto' ) : ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportBottomL.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ): ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ): ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportBottomR.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'auto' : 'auto' ) : ( hasFrozenRows ? 'auto' : 'auto' )) }); if (options.viewportClass) { $viewportTopL.toggleClass(options.viewportClass, true); $viewportTopR.toggleClass(options.viewportClass, true); $viewportBottomL.toggleClass(options.viewportClass, true); $viewportBottomR.toggleClass(options.viewportClass, true); } } function setScroller() { if (hasFrozenColumns()) { $headerScrollContainer = $headerScrollerR; $headerRowScrollContainer = $headerRowScrollerR; $footerRowScrollContainer = $footerRowScrollerR; if (hasFrozenRows) { if (options.frozenBottom) { $viewportScrollContainerX = $viewportBottomR; $viewportScrollContainerY = $viewportTopR; } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomR; } } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportTopR; } } else { $headerScrollContainer = $headerScrollerL; $headerRowScrollContainer = $headerRowScrollerL; $footerRowScrollContainer = $footerRowScrollerL; if (hasFrozenRows) { if (options.frozenBottom) { $viewportScrollContainerX = $viewportBottomL; $viewportScrollContainerY = $viewportTopL; } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomL; } } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportTopL; } } } function measureCellPaddingAndBorder() { var el; var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"]; var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; // jquery prior to version 1.8 handles .width setter/getter as a direct css write/read // jquery 1.8 changed .width to read the true inner element width if box-sizing is set to border-box, and introduced a setter for .outerWidth // so for equivalent functionality, prior to 1.8 use .width, and after use .outerWidth var verArray = $.fn.jquery.split('.'); jQueryNewWidthBehaviour = (verArray[0]==1 && verArray[1]>=8) || verArray[0] >=2; el = $("<div class='ui-state-default slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers); headerColumnWidthDiff = headerColumnHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { headerColumnWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { headerColumnHeightDiff += parseFloat(el.css(val)) || 0; }); } el.remove(); var r = $("<div class='slick-row' />").appendTo($canvas); el = $("<div class='slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r); cellWidthDiff = cellHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { cellWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { cellHeightDiff += parseFloat(el.css(val)) || 0; }); } r.remove(); absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff); } function createCssRules() { $style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head")); var rowHeight = (options.rowHeight - cellHeightDiff); var rules = [ "." + uid + " .slick-group-header-column { left: 1000px; }", "." + uid + " .slick-header-column { left: 1000px; }", "." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }", "." + uid + " .slick-preheader-panel { height:" + options.preHeaderPanelHeight + "px; }", "." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }", "." + uid + " .slick-footerrow-columns { height:" + options.footerRowHeight + "px; }", "." + uid + " .slick-cell { height:" + rowHeight + "px; }", "." + uid + " .slick-row { height:" + options.rowHeight + "px; }" ]; for (var i = 0; i < columns.length; i++) { rules.push("." + uid + " .l" + i + " { }"); rules.push("." + uid + " .r" + i + " { }"); } if ($style[0].styleSheet) { // IE $style[0].styleSheet.cssText = rules.join(" "); } else { $style[0].appendChild(document.createTextNode(rules.join(" "))); } } function getColumnCssRules(idx) { var i; if (!stylesheet) { var sheets = document.styleSheets; for (i = 0; i < sheets.length; i++) { if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) { stylesheet = sheets[i]; break; } } if (!stylesheet) { throw new Error("Cannot find stylesheet."); } // find and cache column CSS rules columnCssRulesL = []; columnCssRulesR = []; var cssRules = (stylesheet.cssRules || stylesheet.rules); var matches, columnIdx; for (i = 0; i < cssRules.length; i++) { var selector = cssRules[i].selectorText; if (matches = /\.l\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesL[columnIdx] = cssRules[i]; } else if (matches = /\.r\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesR[columnIdx] = cssRules[i]; } } } return { "left": columnCssRulesL[idx], "right": columnCssRulesR[idx] }; } function removeCssRules() { $style.remove(); stylesheet = null; } function destroy() { getEditorLock().cancelCurrentEdit(); trigger(self.onBeforeDestroy, {}); var i = plugins.length; while(i--) { unregisterPlugin(plugins[i]); } if (options.enableColumnReorder) { $headers.filter(":ui-sortable").sortable("destroy"); } unbindAncestorScrollEvents(); $container.off(".slickgrid"); removeCssRules(); $canvas.off("draginit dragstart dragend drag"); $container.empty().removeClass(uid); } ////////////////////////////////////////////////////////////////////////////////////////////// // General function trigger(evt, args, e) { e = e || new Slick.EventData(); args = args || {}; args.grid = self; return evt.notify(args, e, self); } function getEditorLock() { return options.editorLock; } function getEditController() { return editController; } function getColumnIndex(id) { return columnsById[id]; } function autosizeColumns() { var i, c, widths = [], shrinkLeeway = 0, total = 0, prevTotal, availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; for (i = 0; i < columns.length; i++) { c = columns[i]; widths.push(c.width); total += c.width; if (c.resizable) { shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth); } } // shrink prevTotal = total; while (total > availWidth && shrinkLeeway) { var shrinkProportion = (total - availWidth) / shrinkLeeway; for (i = 0; i < columns.length && total > availWidth; i++) { c = columns[i]; var width = widths[i]; if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) { continue; } var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth); var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1; shrinkSize = Math.min(shrinkSize, width - absMinWidth); total -= shrinkSize; shrinkLeeway -= shrinkSize; widths[i] -= shrinkSize; } if (prevTotal <= total) { // avoid infinite loop break; } prevTotal = total; } // grow prevTotal = total; while (total < availWidth) { var growProportion = availWidth / total; for (i = 0; i < columns.length && total < availWidth; i++) { c = columns[i]; var currentWidth = widths[i]; var growSize; if (!c.resizable || c.maxWidth <= currentWidth) { growSize = 0; } else { growSize = Math.min(Math.floor(growProportion * currentWidth) - currentWidth, (c.maxWidth - currentWidth) || 1000000) || 1; } total += growSize; widths[i] += (total <= availWidth ? growSize : 0); } if (prevTotal >= total) { // avoid infinite loop break; } prevTotal = total; } var reRender = false; for (i = 0; i < columns.length; i++) { if (columns[i].rerenderOnResize && columns[i].width != widths[i]) { reRender = true; } columns[i].width = widths[i]; } applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); updateCanvasWidth(true); trigger(self.onAutosizeColumns, { "columns": columns}); if (reRender) { invalidateAllRows(); render(); } } function applyColumnGroupHeaderWidths() { if (!treeColumns.hasDepth()) return; for (var depth = $groupHeadersL.length - 1; depth >= 0; depth--) { var groupColumns = treeColumns.getColumnsInDepth(depth); $().add($groupHeadersL[depth]).add($groupHeadersR[depth]).each(function(i) { var $groupHeader = $(this), currentColumnIndex = 0; $groupHeader.width(i == 0? getHeadersWidthL(): getHeadersWidthR()); $groupHeader.children().each(function() { var $groupHeaderColumn = $(this); var m = $(this).data('column'); m.width = 0; m.columns.forEach(function() { var $headerColumn = $groupHeader.next().children(':eq(' + (currentColumnIndex++) + ')'); m.width += $headerColumn.outerWidth(); }) $groupHeaderColumn.width(m.width - headerColumnWidthDiff); }); }) } } function applyColumnHeaderWidths() { if (!initialized) { return; } var h; for (var i = 0, headers = $headers.children(), ii = columns.length; i < ii; i++) { h = $(headers[i]); if (jQueryNewWidthBehaviour) { if (h.outerWidth() !== columns[i].width) { h.outerWidth(columns[i].width); } } else { if (h.width() !== columns[i].width - headerColumnWidthDiff) { h.width(columns[i].width - headerColumnWidthDiff); } } } updateColumnCaches(); } function applyColumnWidths() { var x = 0, w, rule; for (var i = 0; i < columns.length; i++) { w = columns[i].width; rule = getColumnCssRules(i); rule.left.style.left = x + "px"; rule.right.style.right = (((options.frozenColumn != -1 && i > options.frozenColumn) ? canvasWidthR : canvasWidthL) - x - w) + "px"; // If this column is frozen, reset the css left value since the // column starts in a new viewport. if (options.frozenColumn == i) { x = 0; } else { x += columns[i].width; } } } function setSortColumn(columnId, ascending) { setSortColumns([{ columnId: columnId, sortAsc: ascending}]); } function setSortColumns(cols) { sortColumns = cols; var numberCols = options.numberedMultiColumnSort && sortColumns.length > 1; var headerColumnEls = $headers.children(); headerColumnEls .removeClass("slick-header-column-sorted") .find(".slick-sort-indicator") .removeClass("slick-sort-indicator-asc slick-sort-indicator-desc"); headerColumnEls .find(".slick-sort-indicator-numbered") .text(''); $.each(sortColumns, function(i, col) { if (col.sortAsc == null) { col.sortAsc = true; } var columnIndex = getColumnIndex(col.columnId); if (columnIndex != null) { headerColumnEls.eq(columnIndex) .addClass("slick-header-column-sorted") .find(".slick-sort-indicator") .addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc"); if (numberCols) { headerColumnEls.eq(columnIndex) .find(".slick-sort-indicator-numbered") .text(i+1); } } }); } function getSortColumns() { return sortColumns; } function handleSelectedRangesChanged(e, ranges) { var previousSelectedRows = selectedRows.slice(0); // shallow copy previously selected rows for later comparison selectedRows = []; var hash = {}; for (var i = 0; i < ranges.length; i++) { for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) { if (!hash[j]) { // prevent duplicates selectedRows.push(j); hash[j] = {}; } for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) { if (canCellBeSelected(j, k)) { hash[j][columns[k].id] = options.selectedCellCssClass; } } } } setCellCssStyles(options.selectedCellCssClass, hash); if (simpleArrayEquals(previousSelectedRows, selectedRows)) { trigger(self.onSelectedRowsChanged, {rows: getSelectedRows()}, e); } } // compare 2 simple arrays (integers or strings only, do not use to compare object arrays) function simpleArrayEquals(arr1, arr2) { return Array.isArray(arr1) && Array.isArray(arr2) && arr2.sort().toString() !== arr1.sort().toString(); } function getColumns() { return columns; } function updateColumnCaches() { // Pre-calculate cell boundaries. columnPosLeft = []; columnPosRight = []; var x = 0; for (var i = 0, ii = columns.length; i < ii; i++) { columnPosLeft[i] = x; columnPosRight[i] = x + columns[i].width; if (options.frozenColumn == i) { x = 0; } else { x += columns[i].width; } } } function updateColumnProps() { columnsById = {}; for (var i = 0; i < columns.length; i++) { if (columns[i].width) { columns[i].widthRequest = columns[i].width; } var m = columns[i] = $.extend({}, columnDefaults, columns[i]); columnsById[m.id] = i; if (m.minWidth && m.width < m.minWidth) { m.width = m.minWidth; } if (m.maxWidth && m.width > m.maxWidth) { m.width = m.maxWidth; } } } function setColumns(columnDefinitions) { var _treeColumns = new Slick.TreeColumns(columnDefinitions); if (_treeColumns.hasDepth()) { treeColumns = _treeColumns; columns = treeColumns.extractColumns(); } else { columns = columnDefinitions; } updateColumnProps(); updateColumnCaches(); if (initialized) { setPaneVisibility(); setOverflow(); invalidateAllRows(); createColumnHeaders(); createColumnGroupHeaders(); createColumnFooter(); removeCssRules(); createCssRules(); resizeCanvas(); updateCanvasWidth(); applyColumnWidths(); handleScroll(); } } function getOptions() { return options; } function setOptions(args, suppressRender) { if (!getEditorLock().commitCurrentEdit()) { return; } makeActiveCellNormal(); if (options.enableAddRow !== args.enableAddRow) { invalidateRow(getDataLength()); } options = $.extend(options, args); validateAndEnforceOptions(); $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto"); if (!suppressRender) { render(); } setFrozenOptions(); setScroller(); zombieRowNodeFromLastMouseWheelEvent = null; setColumns(treeColumns.extractColumns()); } function validateAndEnforceOptions() { if (options.autoHeight) { options.leaveSpaceForNewRows = false; } } function setData(newData, scrollToTop) { data = newData; invalidateAllRows(); updateRowCount(); if (scrollToTop) { scrollTo(0); } } function getData() { return data; } function getDataLength() { if (data.getLength) { return data.getLength(); } else { return data && data.length || 0; } } function getDataLengthIncludingAddNew() { return getDataLength() + (!options.enableAddRow ? 0 : (!pagingActive || pagingIsLastPage ? 1 : 0) ); } function getDataItem(i) { if (data.getItem) { return data.getItem(i); } else { return data[i]; } } function getTopPanel() { return $topPanel[0]; } function setTopPanelVisibility(visible) { if (options.showTopPanel != visible) { options.showTopPanel = visible; if (visible) { $topPanelScroller.slideDown("fast", resizeCanvas); } else { $topPanelScroller.slideUp("fast", resizeCanvas); } } } function setHeaderRowVisibility(visible) { if (options.showHeaderRow != visible) { options.showHeaderRow = visible; if (visible) { $headerRowScroller.slideDown("fast", resizeCanvas); } else { $headerRowScroller.slideUp("fast", resizeCanvas); } } } function setFooterRowVisibility(visible) { if (options.showFooterRow != visible) { options.showFooterRow = visible; if (visible) { $footerRowScroller.slideDown("fast", resizeCanvas); } else { $footerRowScroller.slideUp("fast", resizeCanvas); } } } function setPreHeaderPanelVisibility(visible) { if (options.showPreHeaderPanel != visible) { options.showPreHeaderPanel = visible; if (visible) { $preHeaderPanelScroller.slideDown("fast", resizeCanvas); } else { $preHeaderPanelScroller.slideUp("fast", resizeCanvas); } } } function getContainerNode() { return $container.get(0); } ////////////////////////////////////////////////////////////////////////////////////////////// // Rendering / Scrolling function getRowTop(row) { return options.rowHeight * row - offset; } function getRowFromPosition(y) { return Math.floor((y + offset) / options.rowHeight); } function scrollTo(y) { y = Math.max(y, 0); y = Math.min(y, th - $viewportScrollContainerY.height() + ((viewportHasHScroll || hasFrozenColumns()) ? scrollbarDimensions.height : 0)); var oldOffset = offset; page = Math.min(n - 1, Math.floor(y / ph)); offset = Math.round(page * cj); var newScrollTop = y - offset; if (offset != oldOffset) { var range = getVisibleRange(newScrollTop); cleanupRows(range); updateRowPositions(); } if (prevScrollTop != newScrollTop) { vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1; lastRenderedScrollTop = ( scrollTop = prevScrollTop = newScrollTop ); if (hasFrozenColumns()) { $viewportTopL[0].scrollTop = newScrollTop; } if (hasFrozenRows) { $viewportBottomL[0].scrollTop = $viewportBottomR[0].scrollTop = newScrollTop; } $viewportScrollContainerY[0].scrollTop = newScrollTop; trigger(self.onViewportChanged, {}); } } function defaultFormatter(row, cell, value, columnDef, dataContext, grid) { if (value == null) { return ""; } else { return (value + "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); } } function getFormatter(row, column) { var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); // look up by id, then index var columnOverrides = rowMetadata && rowMetadata.columns && (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]); return (columnOverrides && columnOverrides.formatter) || (rowMetadata && rowMetadata.formatter) || column.formatter || (options.formatterFactory && options.formatterFactory.getFormatter(column)) || options.defaultFormatter; } function callFormatter( row, cell, value, m, item, grid ) { var result; // pass metadata to formatter var metadata = data.getItemMetadata && data.getItemMetadata(row); metadata = metadata && metadata.columns; if( metadata ) { var columnData = metadata[m.id] || metadata[cell]; result = getFormatter(row, m)(row, cell, value, m, item, columnData ); } else { result = getFormatter(row, m)(row, cell, value, m, item); } return result; } function getEditor(row, cell) { var column = columns[cell]; var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) { return columnMetadata[column.id].editor; } if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) { return columnMetadata[cell].editor; } return column.editor || (options.editorFactory && options.editorFactory.getEditor(column)); } function getDataItemValueForColumn(item, columnDef) { if (options.dataItemColumnValueExtractor) { return options.dataItemColumnValueExtractor(item, columnDef); } return item[columnDef.field]; } function appendRowHtml(stringArrayL, stringArrayR, row, range, dataLength) { var d = getDataItem(row); var dataLoading = row < dataLength && !d; var rowCss = "slick-row" + (hasFrozenRows && row <= options.frozenRow? ' frozen': '') + (dataLoading ? " loading" : "") + (row === activeRow && options.showCellSelection ? " active" : "") + (row % 2 == 1 ? " odd" : " even"); if (!d) { rowCss += " " + options.addNewRowCssClass; } var metadata = data.getItemMetadata && data.getItemMetadata(row); if (metadata && metadata.cssClasses) { rowCss += " " + metadata.cssClasses; } var frozenRowOffset = getFrozenRowOffset(row); var rowHtml = "<div class='ui-widget-content " + rowCss + "' style='top:" + (getRowTop(row) - frozenRowOffset ) + "px'>"; stringArrayL.push(rowHtml); if (hasFrozenColumns()) { stringArrayR.push(rowHtml); } var colspan, m; for (var i = 0, ii = columns.length; i < ii; i++) { m = columns[i]; colspan = 1; if (metadata && metadata.columns) { var columnData = metadata.columns[m.id] || metadata.columns[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } // Do not render cells outside of the viewport. if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { if (!m.alwaysRenderColumn && columnPosLeft[i] > range.rightPx) { // All columns to the right are outside the range. break; } if (hasFrozenColumns() && ( i > options.frozenColumn )) { appendCellHtml(stringArrayR, row, i, colspan, d); } else { appendCellHtml(stringArrayL, row, i, colspan, d); } } else if (m.alwaysRenderColumn || (hasFrozenColumns() && i <= options.frozenColumn)) { appendCellHtml(stringArrayL, row, i, colspan, d); } if (colspan > 1) { i += (colspan - 1); } } stringArrayL.push("</div>"); if (hasFrozenColumns()) { stringArrayR.push("</div>"); } } function appendCellHtml(stringArray, row, cell, colspan, item) { // stringArray: stringBuilder containing the HTML parts // row, cell: row and column index // colspan: HTML colspan // item: grid data for row var m = columns[cell]; var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1) + (m.cssClass ? " " + m.cssClass : ""); if (hasFrozenColumns() && cell <= options.frozenColumn) { cellCss += (" frozen"); } if (row === activeRow && cell === activeCell && options.showCellSelection) { cellCss += (" active"); } // TODO: merge them together in the setter for (var key in cellCssClasses) { if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) { cellCss += (" " + cellCssClasses[key][row][m.id]); } } var value = null, formatterResult = ''; if (item) { value = getDataItemValueForColumn(item, m); formatterResult = getFormatter(row, m)(row, cell, value, m, item, self); if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; } } // get addl css class names from object type formatter return and from string type return of onBeforeAppendCell var addlCssClasses = trigger(self.onBeforeAppendCell, { row: row, cell: cell, value: value, dataContext: item }) || ''; addlCssClasses += (formatterResult && formatterResult.addClasses ? (addlCssClasses ? ' ' : '') + formatterResult.addClasses : ''); var toolTip = formatterResult && formatterResult.toolTip ? "title='" + formatterResult.toolTip + "'" : ''; stringArray.push("<div class='" + cellCss + (addlCssClasses ? ' ' + addlCssClasses : '') + "' " + toolTip + ">"); // if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet) if (item) { stringArray.push(formatterResult); } stringArray.push("</div>"); rowsCache[row].cellRenderQueue.push(cell); rowsCache[row].cellColSpans[cell] = colspan; } function cleanupRows(rangeToKeep) { for (var i in rowsCache) { var removeFrozenRow = true; if (hasFrozenRows && ( ( options.frozenBottom && i >= actualFrozenRow ) // Frozen bottom rows || ( !options.frozenBottom && i <= actualFrozenRow ) // Frozen top rows ) ) { removeFrozenRow = false; } if (( ( i = parseInt(i, 10)) !== activeRow ) && ( i < rangeToKeep.top || i > rangeToKeep.bottom ) && ( removeFrozenRow ) ) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidate() { updateRowCount(); invalidateAllRows(); render(); } function invalidateAllRows() { if (currentEditor) { makeActiveCellNormal(); } for (var row in rowsCache) { removeRowFromCache(row); } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function queuePostProcessedRowForCleanup(cacheEntry, postProcessedRow, rowIdx) { postProcessgroupId++; // store and detach node for later async cleanup for (var columnIdx in postProcessedRow) { if (postProcessedRow.hasOwnProperty(columnIdx)) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cacheEntry.cellNodesByColumnIdx[ columnIdx | 0], columnIdx: columnIdx | 0, rowIdx: rowIdx }); } } postProcessedCleanupQueue.push({ actionType: 'R', groupId: postProcessgroupId, node: cacheEntry.rowNode }); $(cacheEntry.rowNode).detach(); } function queuePostProcessedCellForCleanup(cellnode, columnIdx, rowIdx) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cellnode, columnIdx: columnIdx, rowIdx: rowIdx }); $(cellnode).detach(); } function removeRowFromCache(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } if (rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[0] || (hasFrozenColumns() && rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[1])) { cacheEntry.rowNode.hide(); zombieRowNodeFromLastMouseWheelEvent = cacheEntry.rowNode; } else { cacheEntry.rowNode.each(function() { this.parentElement.removeChild(this); }); } delete rowsCache[row]; delete postProcessedRows[row]; renderedRows--; counter_rows_removed++; } function invalidateRows(rows) { var i, rl; if (!rows || !rows.length) { return; } vScrollDir = 0; rl = rows.length; for (i = 0; i < rl; i++) { if (currentEditor && activeRow === rows[i]) { makeActiveCellNormal(); } if (rowsCache[rows[i]]) { removeRowFromCache(rows[i]); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidateRow(row) { if (!row && row !== 0) { return; } invalidateRows([row]); } function applyFormatResultToCellNode(formatterResult, cellNode, suppressRemove) { if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; } if (Object.prototype.toString.call(formatterResult) !== '[object Object]') { cellNode.innerHTML = formatterResult; return; } cellNode.innerHTML = formatterResult.text; if (formatterResult.removeClasses && !suppressRemove) { $(cellNode).removeClass(formatterResult.removeClasses); } if (formatterResult.addClasses) { $(cellNode).addClass(formatterResult.addClasses); } if (formatterResult.toolTip) { $(cellNode).attr("title", formatterResult.toolTip); } } function updateCell(row, cell) { var cellNode = getCellNode(row, cell); if (!cellNode) { return; } var m = columns[cell], d = getDataItem(row); if (currentEditor && activeRow === row && activeCell === cell) { currentEditor.loadValue(d); } else { var formatterResult = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d, self) : ""; applyFormatResultToCellNode(formatterResult, cellNode); invalidatePostProcessingResults(row); } } function updateRow(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } ensureCellNodesInRowsCache(row); var formatterResult, d = getDataItem(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx], node = cacheEntry.cellNodesByColumnIdx[columnIdx][0]; if (row === activeRow && columnIdx === activeCell && currentEditor) { currentEditor.loadValue(d); } else if (d) { formatterResult = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d, self); applyFormatResultToCellNode(formatterResult, node); } else { node.innerHTML = ""; } } invalidatePostProcessingResults(row); } function getViewportHeight() { if (options.autoHeight) { var fullHeight = $paneHeaderL.outerHeight(); fullHeight += ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0; fullHeight += ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0; fullHeight += (getCanvasWidth() > viewportW) ? scrollbarDimensions.height : 0; viewportH = options.rowHeight * getDataLengthIncludingAddNew() + ( ( options.frozenColumn == -1 ) ? fullHeight : 0 ); } else { topPanelH = ( options.showTopPanel ) ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0; headerRowH = ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0; footerRowH = ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0; preHeaderH = (options.createPreHeaderPanel && options.showPreHeaderPanel) ? options.preHeaderPanelHeight + getVBoxDelta($preHeaderPanelScroller) : 0; viewportH = parseFloat($.css($container[0], "height", true)) - parseFloat($.css($container[0], "paddingTop", true)) - parseFloat($.css($container[0], "paddingBottom", true)) - parseFloat($.css($headerScroller[0], "height")) - getVBoxDelta($headerScroller) - topPanelH - headerRowH - footerRowH - preHeaderH; } numVisibleRows = Math.ceil(viewportH / options.rowHeight); return viewportH; } function getViewportWidth() { viewportW = parseFloat($container.width()); } function resizeCanvas() { if (!initialized) { return; } paneTopH = 0 paneBottomH = 0 viewportTopH = 0 viewportBottomH = 0; getViewportWidth(); getViewportHeight(); // Account for Frozen Rows if (hasFrozenRows) { if (options.frozenBottom) { paneTopH = viewportH - frozenRowsHeight - scrollbarDimensions.height; paneBottomH = frozenRowsHeight + scrollbarDimensions.height; } else { paneTopH = frozenRowsHeight; paneBottomH = viewportH - frozenRowsHeight; } } else { paneTopH = viewportH; } // The top pane includes the top panel and the header row paneTopH += topPanelH + headerRowH + footerRowH; if (hasFrozenColumns() && options.autoHeight) { paneTopH += scrollbarDimensions.height; } // The top viewport does not contain the top panel or header row viewportTopH = paneTopH - topPanelH - headerRowH - footerRowH; if (options.autoHeight) { if (hasFrozenColumns()) { $container.height( paneTopH + parseFloat($.css($headerScrollerL[0], "height")) ); } $paneTopL.css('position', 'relative'); } $paneTopL.css({ 'top': $paneHeaderL.height(), 'height': paneTopH }); var paneBottomTop = $paneTopL.position().top + paneTopH; if (!options.autoHeight) { $viewportTopL.height(viewportTopH); } if (hasFrozenColumns()) { $paneTopR.css({ 'top': $paneHeaderL.height(), 'height': paneTopH }); $viewportTopR.height(viewportTopH); if (hasFrozenRows) { $paneBottomL.css({ 'top': paneBottomTop, 'height': paneBottomH }); $paneBottomR.css({ 'top': paneBottomTop, 'height': paneBottomH }); $viewportBottomR.height(paneBottomH); } } else { if (hasFrozenRows) { $paneBottomL.css({ 'width': '100%', 'height': paneBottomH }); $paneBottomL.css('top', paneBottomTop); } } if (hasFrozenRows) { $viewportBottomL.height(paneBottomH); if (options.frozenBottom) { $canvasBottomL.height(frozenRowsHeight); if (hasFrozenColumns()) { $canvasBottomR.height(frozenRowsHeight); } } else { $canvasTopL.height(frozenRowsHeight); if (hasFrozenColumns()) { $canvasTopR.height(frozenRowsHeight); } } } else { $viewportTopR.height(viewportTopH); } if (!scrollbarDimensions || !scrollbarDimensions.width) { scrollbarDimensions = measureScrollbar(); } if (options.forceFitColumns) { autosizeColumns(); } updateRowCount(); handleScroll(); // Since the width has changed, force the render() to reevaluate virtually rendered cells. lastRenderedScrollLeft = -1; render(); } function updatePagingStatusFromView( pagingInfo ) { pagingActive = (pagingInfo.pageSize !== 0); pagingIsLastPage = (pagingInfo.pageNum == pagingInfo.totalPages - 1); } function updateRowCount() { if (!initialized) { return; } var dataLength = getDataLength(); var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); var numberOfRows = 0; var oldH = ( hasFrozenRows && !options.frozenBottom ) ? $canvasBottomL.height() : $canvasTopL.height(); if (hasFrozenRows ) { var numberOfRows = getDataLength() - options.frozenRow; } else { var numberOfRows = dataLengthIncludingAddNew + (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0); } var tempViewportH = $viewportScrollContainerY.height(); var oldViewportHasVScroll = viewportHasVScroll; // with autoHeight, we do not need to accommodate the vertical scroll bar viewportHasVScroll = options.alwaysShowVerticalScroll || !options.autoHeight && (numberOfRows * options.rowHeight > tempViewportH); makeActiveCellNormal(); // remove the rows that are now outside of the data range // this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows var r1 = dataLength - 1; for (var i in rowsCache) { if (i > r1) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } if (activeCellNode && activeRow > r1) { resetActiveCell(); } th = Math.max(options.rowHeight * numberOfRows, tempViewportH - scrollbarDimensions.height); if (th < maxSupportedCssHeight) { // just one page h = ph = th; n = 1; cj = 0; } else { // break into pages h = maxSupportedCssHeight; ph = h / 100; n = Math.floor(th / ph); cj = (th - h) / (n - 1); } if (h !== oldH) { if (hasFrozenRows && !options.frozenBottom) { $canvasBottomL.css("height", h); if (hasFrozenColumns()) { $canvasBottomR.css("height", h); } } else { $canvasTopL.css("height", h); $canvasTopR.css("height", h); } scrollTop = $viewportScrollContainerY[0].scrollTop; } var oldScrollTopInRange = (scrollTop + offset <= th - tempViewportH); if (th == 0 || scrollTop == 0) { page = offset = 0; } else if (oldScrollTopInRange) { // maintain virtual position scrollTo(scrollTop + offset); } else { // scroll to bottom scrollTo(th - tempViewportH); } if (Math.abs(h - oldH) > 0.1 && options.autoHeight) { resizeCanvas(); } if (options.forceFitColumns && oldViewportHasVScroll != viewportHasVScroll) { autosizeColumns(); } updateCanvasWidth(false); } function getVisibleRange(viewportTop, viewportLeft) { if (viewportTop == null) { viewportTop = scrollTop; } if (viewportLeft == null) { viewportLeft = scrollLeft; } return { top: getRowFromPosition(viewportTop), bottom: getRowFromPosition(viewportTop + viewportH) + 1, leftPx: viewportLeft, rightPx: viewportLeft + viewportW }; } function getRenderedRange(viewportTop, viewportLeft) { var range = getVisibleRange(viewportTop, viewportLeft); var buffer = Math.round(viewportH / options.rowHeight); var minBuffer = options.minRowBuffer; if (vScrollDir == -1) { range.top -= buffer; range.bottom += minBuffer; } else if (vScrollDir == 1) { range.top -= minBuffer; range.bottom += buffer; } else { range.top -= minBuffer; range.bottom += minBuffer; } range.top = Math.max(0, range.top); range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom); range.leftPx -= viewportW; range.rightPx += viewportW; range.leftPx = Math.max(0, range.leftPx); range.rightPx = Math.min(canvasWidth, range.rightPx); return range; } function ensureCellNodesInRowsCache(row) { var cacheEntry = rowsCache[row]; if (cacheEntry) { if (cacheEntry.cellRenderQueue.length) { var $lastNode = cacheEntry.rowNode.children().last(); while (cacheEntry.cellRenderQueue.length) { var columnIdx = cacheEntry.cellRenderQueue.pop(); cacheEntry.cellNodesByColumnIdx[columnIdx] = $lastNode; $lastNode = $lastNode.prev(); // Hack to retrieve the frozen columns because if ($lastNode.length == 0) { $lastNode = $(cacheEntry.rowNode[0]).children().last(); } } } } } function cleanUpCells(range, row) { // Ignore frozen rows if (hasFrozenRows && ( ( options.frozenBottom && row > actualFrozenRow ) // Frozen bottom rows || ( row <= actualFrozenRow ) // Frozen top rows ) ) { return; } var totalCellsRemoved = 0; var cacheEntry = rowsCache[row]; // Remove cells outside the range. var cellsToRemove = []; for (var i in cacheEntry.cellNodesByColumnIdx) { // I really hate it when people mess with Array.prototype. if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) { continue; } // This is a string, so it needs to be cast back to a number. i = i | 0; // Ignore frozen columns if (i <= options.frozenColumn) { continue; } // Ignore alwaysRenderedColumns if (Array.isArray(columns) && columns[i] && columns[i].alwaysRenderColumn){ continue; } var colspan = cacheEntry.cellColSpans[i]; if (columnPosLeft[i] > range.rightPx || columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) { if (!(row == activeRow && i == activeCell)) { cellsToRemove.push(i); } } } var cellToRemove; while ((cellToRemove = cellsToRemove.pop()) != null) { cacheEntry.cellNodesByColumnIdx[cellToRemove][0].parentElement.removeChild(cacheEntry.cellNodesByColumnIdx[cellToRemove][0]); delete cacheEntry.cellColSpans[cellToRemove]; delete cacheEntry.cellNodesByColumnIdx[cellToRemove]; if (postProcessedRows[row]) { delete postProcessedRows[row][cellToRemove]; } totalCellsRemoved++; } } function cleanUpAndRenderCells(range) { var cacheEntry; var stringArray = []; var processedRows = []; var cellsAdded; var totalCellsAdded = 0; var colspan; for (var row = range.top, btm = range.bottom; row <= btm; row++) { cacheEntry = rowsCache[row]; if (!cacheEntry) { continue; } // cellRenderQueue populated in renderRows() needs to be cleared first ensureCellNodesInRowsCache(row); cleanUpCells(range, row); // Render missing cells. cellsAdded = 0; var metadata = data.getItemMetadata && data.getItemMetadata(row); metadata = metadata && metadata.columns; var d = getDataItem(row); // TODO: shorten this loop (index? heuristics? binary search?) for (var i = 0, ii = columns.length; i < ii; i++) { // Cells to the right are outside the range. if (columnPosLeft[i] > range.rightPx) { break; } // Already rendered. if ((colspan = cacheEntry.cellColSpans[i]) != null) { i += (colspan > 1 ? colspan - 1 : 0); continue; } colspan = 1; if (metadata) { var columnData = metadata[columns[i].id] || metadata[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { appendCellHtml(stringArray, row, i, colspan, d); cellsAdded++; } i += (colspan > 1 ? colspan - 1 : 0); } if (cellsAdded) { totalCellsAdded += cellsAdded; processedRows.push(row); } } if (!stringArray.length) { return; } var x = document.createElement("div"); x.innerHTML = stringArray.join(""); var processedRow; var $node; while ((processedRow = processedRows.pop()) != null) { cacheEntry = rowsCache[processedRow]; var columnIdx; while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) { $node = $(x).children().last(); if (hasFrozenColumns() && ( columnIdx > options.frozenColumn )) { $(cacheEntry.rowNode[1]).append($node); } else { $(cacheEntry.rowNode[0]).append($node); } cacheEntry.cellNodesByColumnIdx[columnIdx] = $node; } } } function renderRows(range) { var stringArrayL = [], stringArrayR = [], rows = [], needToReselectCell = false, dataLength = getDataLength(); for (var i = range.top, ii = range.bottom; i <= ii; i++) { if (rowsCache[i] || ( hasFrozenRows && options.frozenBottom && i == getDataLength() )) { continue; } renderedRows++; rows.push(i); // Create an entry right away so that appendRowHtml() can // start populatating it. rowsCache[i] = { "rowNode": null, // ColSpans of rendered cells (by column idx). // Can also be used for checking whether a cell has been rendered. "cellColSpans": [], // Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache(). "cellNodesByColumnIdx": [], // Column indices of cell nodes that have been rendered, but not yet indexed in // cellNodesByColumnIdx. These are in the same order as cell nodes added at the // end of the row. "cellRenderQueue": [] }; appendRowHtml(stringArrayL, stringArrayR, i, range, dataLength); if (activeCellNode && activeRow === i) { needToReselectCell = true; } counter_rows_rendered++; } if (!rows.length) { return; } var x = document.createElement("div"), xRight = document.createElement("div"); //insert objects into left side var objectListL = []; for (var i = 0; i < stringArrayL.length; i++) { if (typeof stringArrayL[i] !== "string") { objectListL.push(stringArrayL[i]); stringArrayL[i] = "<div class='slick-object-container'></div>"; } } x.innerHTML = stringArrayL.join(""); var containersHtml = x.getElementsByClassName('slick-object-container'); for (var i = 0; i < objectListL.length; i++) { containersHtml[i].parentElement.append(objectListL[i]); } for (var i = 0; i < objectListL.length; i++) { containersHtml[0].remove(); } //insert objects into right side var objectListR = []; for (var i = 0; i < stringArrayR.length; i++) { if (typeof stringArrayR[i] !== "string") { objectListR.push(stringArrayR[i]); stringArrayR[i] = "<div class='slick-object-container'></div>"; } } xRight.innerHTML = stringArrayR.join(""); containersHtml = xRight.getElementsByClassName('slick-object-container'); for (var i = 0; i < objectListR.length; i++) { containersHtml[i].parentElement.append(objectListR[i]); } for (var i = 0; i < objectListR.length; i++) { containersHtml[0].remove(); } for (var i = 0, ii = rows.length; i < ii; i++) { if (( hasFrozenRows ) && ( rows[i] >= actualFrozenRow )) { if (hasFrozenColumns()) { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasBottomL)) .add($(xRight.firstChild).appendTo($canvasBottomR)); } else { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasBottomL)); } } else if (hasFrozenColumns()) { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasTopL)) .add($(xRight.firstChild).appendTo($canvasTopR)); } else { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasTopL)); } } if (needToReselectCell) { activeCellNode = getCellNode(activeRow, activeCell); } } function startPostProcessing() { if (!options.enableAsyncPostRender) { return; } clearTimeout(h_postrender); h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); } function startPostProcessingCleanup() { if (!options.enableAsyncPostRenderCleanup) { return; } clearTimeout(h_postrenderCleanup); h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } function invalidatePostProcessingResults(row) { // change status of columns to be re-rendered for (var columnIdx in postProcessedRows[row]) { if (postProcessedRows[row].hasOwnProperty(columnIdx)) { postProcessedRows[row][columnIdx] = 'C'; } } postProcessFromRow = Math.min(postProcessFromRow, row); postProcessToRow = Math.max(postProcessToRow, row); startPostProcessing(); } function updateRowPositions() { for (var row in rowsCache) { rowsCache[row].rowNode.style.top = getRowTop(row) + "px"; } } function render() { if (!initialized) { return; } scrollThrottle.dequeue(); var visible = getVisibleRange(); var rendered = getRenderedRange(); // remove rows no longer in the viewport cleanupRows(rendered); // add new rows & missing cells in existing rows if (lastRenderedScrollLeft != scrollLeft) { if ( hasFrozenRows ) { var renderedFrozenRows = jQuery.extend(true, {}, rendered); if (options.frozenBottom) { renderedFrozenRows.top=actualFrozenRow; renderedFrozenRows.bottom=getDataLength(); } else { renderedFrozenRows.top=0; renderedFrozenRows.bottom=options.frozenRow; } cleanUpAndRenderCells(renderedFrozenRows); } cleanUpAndRenderCells(rendered); } // render missing rows renderRows(rendered); // Render frozen rows if (hasFrozenRows) { if (options.frozenBottom) { renderRows({ top: actualFrozenRow, bottom: getDataLength() - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx }); } else { renderRows({ top: 0, bottom: options.frozenRow - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx }); } } postProcessFromRow = visible.top; postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom); startPostProcessing(); lastRenderedScrollTop = scrollTop; lastRenderedScrollLeft = scrollLeft; h_render = null; trigger(self.onRendered, { startRow: visible.top, endRow: visible.bottom, grid: self }); } function handleHeaderScroll() { handleElementScroll($headerScrollContainer[0]); } function handleHeaderRowScroll() { var scrollLeft = $headerRowScrollContainer[0].scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handleFooterRowScroll() { var scrollLeft = $footerRowScrollContainer[0].scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handlePreHeaderPanelScroll() { handleElementScroll($preHeaderPanelScroller[0]); } function handleElementScroll(element) { var scrollLeft = element.scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handleScroll() { scrollTop = $viewportScrollContainerY[0].scrollTop; scrollLeft = $viewportScrollContainerX[0].scrollLeft; return _handleScroll(false); } function _handleScroll(isMouseWheel) { var maxScrollDistanceY = $viewportScrollContainerY[0].scrollHeight - $viewportScrollContainerY[0].clientHeight; var maxScrollDistanceX = $viewportScrollContainerY[0].scrollWidth - $viewportScrollContainerY[0].clientWidth; // Ceiling the max scroll values if (scrollTop > maxScrollDistanceY) { scrollTop = maxScrollDistanceY; } if (scrollLeft > maxScrollDistanceX) { scrollLeft = maxScrollDistanceX; } var vScrollDist = Math.abs(scrollTop - prevScrollTop); var hScrollDist = Math.abs(scrollLeft - prevScrollLeft); if (hScrollDist) { prevScrollLeft = scrollLeft; $viewportScrollContainerX[0].scrollLeft = scrollLeft; $headerScrollContainer[0].scrollLeft = scrollLeft; $topPanelScroller[0].scrollLeft = scrollLeft; $headerRowScrollContainer[0].scrollLeft = scrollLeft; if (options.createFooterRow) { $footerRowScrollContainer[0].scrollLeft = scrollLeft; } if (options.createPreHeaderPanel) { $preHeaderPanelScroller[0].scrollLeft = scrollLeft; } if (hasFrozenColumns()) { if (hasFrozenRows) { $viewportTopR[0].scrollLeft = scrollLeft; } } else { if (hasFrozenRows) { $viewportTopL[0].scrollLeft = scrollLeft; } } } if (vScrollDist) { vScrollDir = prevScrollTop < scrollTop ? 1 : -1; prevScrollTop = scrollTop; if (isMouseWheel) { $viewportScrollContainerY[0].scrollTop = scrollTop; } if (hasFrozenColumns()) { if (hasFrozenRows && !options.frozenBottom) { $viewportBottomL[0].scrollTop = scrollTop; } else { $viewportTopL[0].scrollTop = scrollTop; } } // switch virtual pages if needed if (vScrollDist < viewportH) { scrollTo(scrollTop + offset); } else { var oldOffset = offset; if (h == viewportH) { page = 0; } else { page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph))); } offset = Math.round(page * cj); if (oldOffset != offset) { invalidateAllRows(); } } } if (hScrollDist || vScrollDist) { var dx = Math.abs(lastRenderedScrollLeft - scrollLeft); var dy = Math.abs(lastRenderedScrollTop - scrollTop); if (dx > 20 || dy > 20) { // if rendering is forced or scrolling is small enough to be "easy", just render if (options.forceSyncScrolling || (dy < viewportH && dx < viewportW)) { render(); } else { // otherwise, perform "difficult" renders at a capped frequency scrollThrottle.enqueue(); } trigger(self.onViewportChanged, {}); } } trigger(self.onScroll, {scrollLeft: scrollLeft, scrollTop: scrollTop}); if (hScrollDist || vScrollDist) return true; return false; } /* limits the frequency at which the provided action is executed. call enqueue to execute the action - it will execute either immediately or, if it was executed less than minPeriod_ms in the past, as soon as minPeriod_ms has expired. call dequeue to cancel any pending action. */ function ActionThrottle(action, minPeriod_ms) { var blocked = false; var queued = false; function enqueue() { if (!blocked) { blockAndExecute(); } else { queued = true; } } function dequeue() { queued = false; } function blockAndExecute() { blocked = true; setTimeout(unblock, minPeriod_ms); action(); } function unblock() { if (queued) { dequeue(); blockAndExecute(); } else { blocked = false; } } return { enqueue: enqueue, dequeue: dequeue } } function asyncPostProcessRows() { var dataLength = getDataLength(); while (postProcessFromRow <= postProcessToRow) { var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--; var cacheEntry = rowsCache[row]; if (!cacheEntry || row >= dataLength) { continue; } if (!postProcessedRows[row]) { postProcessedRows[row] = {}; } ensureCellNodesInRowsCache(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx]; var processedStatus = postProcessedRows[row][columnIdx]; // C=cleanup and re-render, R=rendered if (m.asyncPostRender && processedStatus !== 'R') { var node = cacheEntry.cellNodesByColumnIdx[columnIdx]; if (node) { m.asyncPostRender(node, row, getDataItem(row), m, (processedStatus === 'C')); } postProcessedRows[row][columnIdx] = 'R'; } } h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); return; } } function asyncPostProcessCleanupRows() { if (postProcessedCleanupQueue.length > 0) { var groupId = postProcessedCleanupQueue[0].groupId; // loop through all queue members with this groupID while (postProcessedCleanupQueue.length > 0 && postProcessedCleanupQueue[0].groupId == groupId) { var entry = postProcessedCleanupQueue.shift(); if (entry.actionType == 'R') { $(entry.node).remove(); } if (entry.actionType == 'C') { var column = columns[entry.columnIdx]; if (column.asyncPostRenderCleanup && entry.node) { // cleanup must also remove element column.asyncPostRenderCleanup(entry.node, entry.rowIdx, column); } } } // call this function again after the specified delay h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } } function updateCellCssStylesOnRenderedRows(addedHash, removedHash) { var node, columnId, addedRowHash, removedRowHash; for (var row in rowsCache) { removedRowHash = removedHash && removedHash[row]; addedRowHash = addedHash && addedHash[row]; if (removedRowHash) { for (columnId in removedRowHash) { if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).removeClass(removedRowHash[columnId]); } } } } if (addedRowHash) { for (columnId in addedRowHash) { if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).addClass(addedRowHash[columnId]); } } } } } } function addCellCssStyles(key, hash) { if (cellCssClasses[key]) { throw new Error("addCellCssStyles: cell CSS hash with key '" + key + "' already exists."); } cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, null); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function removeCellCssStyles(key) { if (!cellCssClasses[key]) { return; } updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]); delete cellCssClasses[key]; trigger(self.onCellCssStylesChanged, { "key": key, "hash": null, "grid": self }); } function setCellCssStyles(key, hash) { var prevHash = cellCssClasses[key]; cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, prevHash); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function getCellCssStyles(key) { return cellCssClasses[key]; } function flashCell(row, cell, speed) { speed = speed || 100; if (rowsCache[row]) { var $cell = $(getCellNode(row, cell)); function toggleCellClass(times) { if (!times) { return; } setTimeout(function () { $cell.queue(function () { $cell.toggleClass(options.cellFlashingCssClass).dequeue(); toggleCellClass(times - 1); }); }, speed); } toggleCellClass(4); } } ////////////////////////////////////////////////////////////////////////////////////////////// // Interactivity function handleMouseWheel(e, delta, deltaX, deltaY) { var $rowNode = $(e.target).closest(".slick-row"); var rowNode = $rowNode[0]; if (rowNode != rowNodeFromLastMouseWheelEvent) { var $gridCanvas = $rowNode.parents('.grid-canvas'); var left = $gridCanvas.hasClass('grid-canvas-left'); if (zombieRowNodeFromLastMouseWheelEvent && zombieRowNodeFromLastMouseWheelEvent[left? 0:1] != rowNode) { var zombieRow = zombieRowNodeFromLastMouseWheelEvent[left || zombieRowNodeFromLastMouseWheelEvent.length == 1? 0:1]; zombieRow.parentElement.removeChild(zombieRow); zombieRowNodeFromLastMouseWheelEvent = null; } rowNodeFromLastMouseWheelEvent = rowNode; } scrollTop = Math.max(0, $viewportScrollContainerY[0].scrollTop - (deltaY * options.rowHeight)); scrollLeft = $viewportScrollContainerX[0].scrollLeft + (deltaX * 10); var handled = _handleScroll(true); if (handled) e.preventDefault(); } function handleDragInit(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragInit, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } // if nobody claims to be handling drag'n'drop by stopping immediate propagation, // cancel out of it return false; } function handleDragStart(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragStart, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } return false; } function handleDrag(e, dd) { return trigger(self.onDrag, dd, e); } function handleDragEnd(e, dd) { trigger(self.onDragEnd, dd, e); } function handleKeyDown(e) { trigger(self.onKeyDown, {row: activeRow, cell: activeCell}, e); var handled = e.isImmediatePropagationStopped(); var keyCode = Slick.keyCode; if (!handled) { if (!e.shiftKey && !e.altKey) { if (options.editable && currentEditor && currentEditor.keyCaptureList) { if (currentEditor.keyCaptureList.indexOf(e.which) > -1) { return; } } if (e.which == keyCode.HOME) { handled = (e.ctrlKey) ? navigateTop() : navigateRowStart(); } else if (e.which == keyCode.END) { handled = (e.ctrlKey) ? navigateBottom() : navigateRowEnd(); } } } if (!handled) { if (!e.shiftKey && !e.altKey && !e.ctrlKey) { // editor may specify an array of keys to bubble if (options.editable && currentEditor && currentEditor.keyCaptureList) { if (currentEditor.keyCaptureList.indexOf( e.which ) > -1) { return; } } if (e.which == keyCode.ESCAPE) { if (!getEditorLock().isActive()) { return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event) } cancelEditAndSetFocus(); } else if (e.which == keyCode.PAGE_DOWN) { navigatePageDown(); handled = true; } else if (e.which == keyCode.PAGE_UP) { navigatePageUp(); handled = true; } else if (e.which == keyCode.LEFT) { handled = navigateLeft(); } else if (e.which == keyCode.RIGHT) { handled = navigateRight(); } else if (e.which == keyCode.UP) { handled = navigateUp(); } else if (e.which == keyCode.DOWN) { handled = navigateDown(); } else if (e.which == keyCode.TAB) { handled = navigateNext(); } else if (e.which == keyCode.ENTER) { if (options.editable) { if (currentEditor) { // adding new row if (activeRow === getDataLength()) { navigateDown(); } else { commitEditAndSetFocus(); } } else { if (getEditorLock().commitCurrentEdit()) { makeActiveCellEditable(undefined, undefined, e); } } } handled = true; } } else if (e.which == keyCode.TAB && e.shiftKey && !e.ctrlKey && !e.altKey) { handled = navigatePrev(); } } if (handled) { // the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it e.stopPropagation(); e.preventDefault(); try { e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.) } // ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl" // (hitting control key only, nothing else), "Shift" (maybe others) catch (error) { } } } function handleClick(e) { if (!currentEditor) { // if this click resulted in some cell child node getting focus, // don't steal it back - keyboard events will still bubble up // IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly. if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) { setFocus(); } } var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onClick, {row: cell.row, cell: cell.cell}, e); if (e.isImmediatePropagationStopped()) { return; } // this optimisation causes trouble - MLeibman #329 //if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) { if (canCellBeActive(cell.row, cell.cell)) { if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) { scrollRowIntoView(cell.row, false); var preClickModeOn = (e.target && e.target.className === Slick.preClickClassName); var column = columns[cell.cell]; var suppressActiveCellChangedEvent = (options.editable && column && column.editor && options.suppressActiveCellChangeOnEdit) ? true : false; setActiveCellInternal(getCellNode(cell.row, cell.cell), null, preClickModeOn, suppressActiveCellChangedEvent, e); } } } function handleContextMenu(e) { var $cell = $(e.target).closest(".slick-cell", $canvas); if ($cell.length === 0) { return; } // are we editing this cell? if (activeCellNode === $cell[0] && currentEditor !== null) { return; } trigger(self.onContextMenu, {}, e); } function handleDblClick(e) { var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onDblClick, {row: cell.row, cell: cell.cell}, e); if (e.isImmediatePropagationStopped()) { return; } if (options.editable) { gotoCell(cell.row, cell.cell, true, e); } } function handleHeaderMouseEnter(e) { trigger(self.onHeaderMouseEnter, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderMouseLeave(e) { trigger(self.onHeaderMouseLeave, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderContextMenu(e) { var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); trigger(self.onHeaderContextMenu, {column: column}, e); } function handleHeaderClick(e) { if (columnResizeDragging) return; var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); if (column) { trigger(self.onHeaderClick, {column: column}, e); } } function handleMouseEnter(e) { trigger(self.onMouseEnter, {}, e); } function handleMouseLeave(e) { trigger(self.onMouseLeave, {}, e); } function cellExists(row, cell) { return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length); } function getCellFromPoint(x, y) { var row = getRowFromPosition(y); var cell = 0; var w = 0; for (var i = 0; i < columns.length && w < x; i++) { w += columns[i].width; cell++; } if (cell < 0) { cell = 0; } return {row: row, cell: cell - 1}; } function getCellFromNode(cellNode) { // read column number from .l<columnNumber> CSS class var cls = /l\d+/.exec(cellNode.className); if (!cls) { throw new Error("getCellFromNode: cannot get cell - " + cellNode.className); } return parseInt(cls[0].substr(1, cls[0].length - 1), 10); } function getRowFromNode(rowNode) { for (var row in rowsCache) { for (var i in rowsCache[row].rowNode) { if (rowsCache[row].rowNode[i] === rowNode) return row | 0; } } return null; } function getFrozenRowOffset(row) { var offset = ( hasFrozenRows ) ? ( options.frozenBottom ) ? ( row >= actualFrozenRow ) ? ( h < viewportTopH ) ? ( actualFrozenRow * options.rowHeight ) : h : 0 : ( row >= actualFrozenRow ) ? frozenRowsHeight : 0 : 0; return offset; } function getCellFromEvent(e) { var row, cell; var $cell = $(e.target).closest(".slick-cell", $canvas); if (!$cell.length) { return null; } row = getRowFromNode($cell[0].parentNode); if (hasFrozenRows) { var c = $cell.parents('.grid-canvas').offset(); var rowOffset = 0; var isBottom = $cell.parents('.grid-canvas-bottom').length; if (isBottom) { rowOffset = ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight; } row = getCellFromPoint(e.clientX - c.left, e.clientY - c.top + rowOffset + $(document).scrollTop()).row; } cell = getCellFromNode($cell[0]); if (row == null || cell == null) { return null; } else { return { "row": row, "cell": cell }; } } function getCellNodeBox(row, cell) { if (!cellExists(row, cell)) { return null; } var frozenRowOffset = getFrozenRowOffset(row); var y1 = getRowTop(row) - frozenRowOffset; var y2 = y1 + options.rowHeight - 1; var x1 = 0; for (var i = 0; i < cell; i++) { x1 += columns[i].width; if (options.frozenColumn == i) { x1 = 0; } } var x2 = x1 + columns[cell].width; return { top: y1, left: x1, bottom: y2, right: x2 }; } ////////////////////////////////////////////////////////////////////////////////////////////// // Cell switching function resetActiveCell() { setActiveCellInternal(null, false); } function setFocus() { if (tabbingDirection == -1) { $focusSink[0].focus(); } else { $focusSink2[0].focus(); } } function scrollCellIntoView(row, cell, doPaging) { scrollRowIntoView(row, doPaging); if (cell <= options.frozenColumn) { return; } var colspan = getColspan(row, cell); internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)]); } function internalScrollColumnIntoView(left, right) { var scrollRight = scrollLeft + $viewportScrollContainerX.width(); if (left < scrollLeft) { $viewportScrollContainerX.scrollLeft(left); handleScroll(); render(); } else if (right > scrollRight) { $viewportScrollContainerX.scrollLeft(Math.min(left, right - $viewportScrollContainerX[0].clientWidth)); handleScroll(); render(); } } function scrollColumnIntoView(cell) { internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell]); } function setActiveCellInternal(newCell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent, e) { if (activeCellNode !== null) { makeActiveCellNormal(); $(activeCellNode).removeClass("active"); if (rowsCache[activeRow]) { $(rowsCache[activeRow].rowNode).removeClass("active"); } } var activeCellChanged = (activeCellNode !== newCell); activeCellNode = newCell; if (activeCellNode != null) { var $activeCellNode = $(activeCellNode); var $activeCellOffset = $activeCellNode.offset(); var rowOffset = Math.floor($activeCellNode.parents('.grid-canvas').offset().top); var isBottom = $activeCellNode.parents('.grid-canvas-bottom').length; if (hasFrozenRows && isBottom) { rowOffset -= ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight; } cell = getCellFromPoint($activeCellOffset.left, Math.ceil($activeCellOffset.top) - rowOffset); activeRow = cell.row; activeCell = activePosX = activeCell = activePosX = getCellFromNode(activeCellNode); $activeCellNode.addClass("active"); if (rowsCache[activeRow]) { $(rowsCache[activeRow].rowNode).addClass('active'); } if (opt_editMode == null) { opt_editMode = (activeRow == getDataLength()) || options.autoEdit; } if (options.showCellSelection) { $(activeCellNode).addClass("active"); $(rowsCache[activeRow].rowNode).addClass("active"); } if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) { clearTimeout(h_editorLoader); if (options.asyncEditorLoading) { h_editorLoader = setTimeout(function () { makeActiveCellEditable(undefined, preClickModeOn, e); }, options.asyncEditorLoadDelay); } else { makeActiveCellEditable(undefined, preClickModeOn, e); } } } else { activeRow = activeCell = null; } // this optimisation causes trouble - MLeibman #329 //if (activeCellChanged) { if (!suppressActiveCellChangedEvent) { trigger(self.onActiveCellChanged, getActiveCell()); } //} } function clearTextSelection() { if (document.selection && document.selection.empty) { try { //IE fails here if selected element is not in dom document.selection.empty(); } catch (e) { } } else if (window.getSelection) { var sel = window.getSelection(); if (sel && sel.removeAllRanges) { sel.removeAllRanges(); } } } function isCellPotentiallyEditable(row, cell) { var dataLength = getDataLength(); // is the data for this row loaded? if (row < dataLength && !getDataItem(row)) { return false; } // are we in the Add New row? can we create new from this cell? if (columns[cell].cannotTriggerInsert && row >= dataLength) { return false; } // does this cell have an editor? if (!getEditor(row, cell)) { return false; } return true; } function makeActiveCellNormal() { if (!currentEditor) { return; } trigger(self.onBeforeCellEditorDestroy, {editor: currentEditor}); currentEditor.destroy(); currentEditor = null; if (activeCellNode) { var d = getDataItem(activeRow); $(activeCellNode).removeClass("editable invalid"); if (d) { var column = columns[activeCell]; var formatter = getFormatter(activeRow, column); var formatterResult = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d, self); applyFormatResultToCellNode(formatterResult, activeCellNode); invalidatePostProcessingResults(activeRow); } } // if there previously was text selected on a page (such as selected text in the edit cell just removed), // IE can't set focus to anything else correctly if (navigator.userAgent.toLowerCase().match(/msie/)) { clearTextSelection(); } getEditorLock().deactivate(editController); } function makeActiveCellEditable(editor, preClickModeOn, e) { if (!activeCellNode) { return; } if (!options.editable) { throw new Error("Grid : makeActiveCellEditable : should never get called when options.editable is false"); } // cancel pending async call if there is one clearTimeout(h_editorLoader); if (!isCellPotentiallyEditable(activeRow, activeCell)) { return; } var columnDef = columns[activeCell]; var item = getDataItem(activeRow); if (trigger(self.onBeforeEditCell, {row: activeRow, cell: activeCell, item: item, column: columnDef}) === false) { setFocus(); return; } getEditorLock().activate(editController); $(activeCellNode).addClass("editable"); var useEditor = editor || getEditor(activeRow, activeCell); // don't clear the cell if a custom editor is passed through if (!editor && !useEditor.suppressClearOnEdit) { activeCellNode.innerHTML = ""; } var metadata = data.getItemMetadata && data.getItemMetadata(activeRow); metadata = metadata && metadata.columns; var columnMetaData = metadata && ( metadata[columnDef.id] || metadata[activeCell] ); currentEditor = new useEditor({ grid: self, gridPosition: absBox($container[0]), position: absBox(activeCellNode), container: activeCellNode, column: columnDef, columnMetaData: columnMetaData, item: item || {}, event: e, commitChanges: commitEditAndSetFocus, cancelChanges: cancelEditAndSetFocus }); if (item) { currentEditor.loadValue(item); if (preClickModeOn && currentEditor.preClick) { currentEditor.preClick(); } } serializedEditorValue = currentEditor.serializeValue(); if (currentEditor.position) { handleActiveCellPositionChange(); } } function commitEditAndSetFocus() { // if the commit fails, it would do so due to a validation error // if so, do not steal the focus from the editor if (getEditorLock().commitCurrentEdit()) { setFocus(); if (options.autoEdit) { navigateDown(); } } } function cancelEditAndSetFocus() { if (getEditorLock().cancelCurrentEdit()) { setFocus(); } } function absBox(elem) { var box = { top: elem.offsetTop, left: elem.offsetLeft, bottom: 0, right: 0, width: $(elem).outerWidth(), height: $(elem).outerHeight(), visible: true}; box.bottom = box.top + box.height; box.right = box.left + box.width; // walk up the tree var offsetParent = elem.offsetParent; while ((elem = elem.parentNode) != document.body) { if (elem == null) break; if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") { box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight; } if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") { box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth; } box.left -= elem.scrollLeft; box.top -= elem.scrollTop; if (elem === offsetParent) { box.left += elem.offsetLeft; box.top += elem.offsetTop; offsetParent = elem.offsetParent; } box.bottom = box.top + box.height; box.right = box.left + box.width; } return box; } function getActiveCellPosition() { return absBox(activeCellNode); } function getGridPosition() { return absBox($container[0]) } function handleActiveCellPositionChange() { if (!activeCellNode) { return; } trigger(self.onActiveCellPositionChanged, {}); if (currentEditor) { var cellBox = getActiveCellPosition(); if (currentEditor.show && currentEditor.hide) { if (!cellBox.visible) { currentEditor.hide(); } else { currentEditor.show(); } } if (currentEditor.position) { currentEditor.position(cellBox); } } } function getCellEditor() { return currentEditor; } function getActiveCell() { if (!activeCellNode) { return null; } else { return {row: activeRow, cell: activeCell}; } } function getActiveCellNode() { return activeCellNode; } function scrollRowIntoView(row, doPaging) { if (!hasFrozenRows || ( !options.frozenBottom && row > actualFrozenRow - 1 ) || ( options.frozenBottom && row < actualFrozenRow - 1 ) ) { var viewportScrollH = $viewportScrollContainerY.height(); // if frozen row on top // subtract number of frozen row var rowNumber = ( hasFrozenRows && !options.frozenBottom ? row - options.frozenRow : row ); var rowAtTop = rowNumber * options.rowHeight; var rowAtBottom = (rowNumber + 1) * options.rowHeight - viewportScrollH + (viewportHasHScroll ? scrollbarDimensions.height : 0); // need to page down? if ((rowNumber + 1) * options.rowHeight > scrollTop + viewportScrollH + offset) { scrollTo(doPaging ? rowAtTop : rowAtBottom); render(); } // or page up? else if (rowNumber * options.rowHeight < scrollTop + offset) { scrollTo(doPaging ? rowAtBottom : rowAtTop); render(); } } } function scrollRowToTop(row) { scrollTo(row * options.rowHeight); render(); } function scrollPage(dir) { var deltaRows = dir * numVisibleRows; /// First fully visible row crosses the line with /// y == bottomOfTopmostFullyVisibleRow var bottomOfTopmostFullyVisibleRow = scrollTop + options.rowHeight - 1; scrollTo((getRowFromPosition(bottomOfTopmostFullyVisibleRow) + deltaRows) * options.rowHeight); render(); if (options.enableCellNavigation && activeRow != null) { var row = activeRow + deltaRows; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); if (row >= dataLengthIncludingAddNew) { row = dataLengthIncludingAddNew - 1; } if (row < 0) { row = 0; } var cell = 0, prevCell = null; var prevActivePosX = activePosX; while (cell <= activePosX) { if (canCellBeActive(row, cell)) { prevCell = cell; } cell += getColspan(row, cell); } if (prevCell !== null) { setActiveCellInternal(getCellNode(row, prevCell)); activePosX = prevActivePosX; } else { resetActiveCell(); } } } function navigatePageDown() { scrollPage(1); } function navigatePageUp() { scrollPage(-1); } function navigateTop() { navigateToRow(0); } function navigateBottom() { navigateToRow(getDataLength()-1); } function navigateToRow(row) { var num_rows = getDataLength(); if (!num_rows) return true; if (row < 0) row = 0; else if (row >= num_rows) row = num_rows - 1; scrollCellIntoView(row, 0, true); if (options.enableCellNavigation && activeRow != null) { var cell = 0, prevCell = null; var prevActivePosX = activePosX; while (cell <= activePosX) { if (canCellBeActive(row, cell)) { prevCell = cell; } cell += getColspan(row, cell); } if (prevCell !== null) { setActiveCellInternal(getCellNode(row, prevCell)); activePosX = prevActivePosX; } else { resetActiveCell(); } } return true; } function getColspan(row, cell) { var metadata = data.getItemMetadata && data.getItemMetadata(row); if (!metadata || !metadata.columns) { return 1; } var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell]; var colspan = (columnData && columnData.colspan); if (colspan === "*") { colspan = columns.length - cell; } else { colspan = colspan || 1; } return colspan; } function findFirstFocusableCell(row) { var cell = 0; while (cell < columns.length) { if (canCellBeActive(row, cell)) { return cell; } cell += getColspan(row, cell); } return null; } function findLastFocusableCell(row) { var cell = 0; var lastFocusableCell = null; while (cell < columns.length) { if (canCellBeActive(row, cell)) { lastFocusableCell = cell; } cell += getColspan(row, cell); } return lastFocusableCell; } function gotoRight(row, cell, posX) { if (cell >= columns.length) { return null; } do { cell += getColspan(row, cell); } while (cell < columns.length && !canCellBeActive(row, cell)); if (cell < columns.length) { return { "row": row, "cell": cell, "posX": cell }; } return null; } function gotoLeft(row, cell, posX) { if (cell <= 0) { return null; } var firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell === null || firstFocusableCell >= cell) { return null; } var prev = { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; var pos; while (true) { pos = gotoRight(prev.row, prev.cell, prev.posX); if (!pos) { return null; } if (pos.cell >= cell) { return prev; } prev = pos; } } function gotoDown(row, cell, posX) { var prevCell; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); while (true) { if (++row >= dataLengthIncludingAddNew) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoUp(row, cell, posX) { var prevCell; while (true) { if (--row < 0) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoNext(row, cell, posX) { if (row == null && cell == null) { row = cell = posX = 0; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos = gotoRight(row, cell, posX); if (pos) { return pos; } var firstFocusableCell = null; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); // if at last row, cycle through columns rather than get stuck in the last one if (row === dataLengthIncludingAddNew - 1) { row--; } while (++row < dataLengthIncludingAddNew) { firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell !== null) { return { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; } } return null; } function gotoPrev(row, cell, posX) { if (row == null && cell == null) { row = getDataLengthIncludingAddNew() - 1; cell = posX = columns.length - 1; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos; var lastSelectableCell; while (!pos) { pos = gotoLeft(row, cell, posX); if (pos) { break; } if (--row < 0) { return null; } cell = 0; lastSelectableCell = findLastFocusableCell(row); if (lastSelectableCell !== null) { pos = { "row": row, "cell": lastSelectableCell, "posX": lastSelectableCell }; } } return pos; } function gotoRowStart(row, cell, posX) { var newCell = findFirstFocusableCell(row); if (newCell === null) return null; return { "row": row, "cell": newCell, "posX": newCell }; } function gotoRowEnd(row, cell, posX) { var newCell = findLastFocusableCell(row); if (newCell === null) return null; return { "row": row, "cell": newCell, "posX": newCell }; } function navigateRight() { return navigate("right"); } function navigateLeft() { return navigate("left"); } function navigateDown() { return navigate("down"); } function navigateUp() { return navigate("up"); } function navigateNext() { return navigate("next"); } function navigatePrev() { return navigate("prev"); } function navigateRowStart() { return navigate("home"); } function navigateRowEnd() { return navigate("end"); } /** * @param {string} dir Navigation direction. * @return {boolean} Whether navigation resulted in a change of active cell. */ function navigate(dir) { if (!options.enableCellNavigation) { return false; } if (!activeCellNode && dir != "prev" && dir != "next") { return false; } if (!getEditorLock().commitCurrentEdit()) { return true; } setFocus(); var tabbingDirections = { "up": -1, "down": 1, "left": -1, "right": 1, "prev": -1, "next": 1, "home": -1, "end": 1 }; tabbingDirection = tabbingDirections[dir]; var stepFunctions = { "up": gotoUp, "down": gotoDown, "left": gotoLeft, "right": gotoRight, "prev": gotoPrev, "next": gotoNext, "home": gotoRowStart, "end": gotoRowEnd }; var stepFn = stepFunctions[dir]; var pos = stepFn(activeRow, activeCell, activePosX); if (pos) { if (hasFrozenRows && options.frozenBottom & pos.row == getDataLength()) { return; } var isAddNewRow = (pos.row == getDataLength()); if (( !options.frozenBottom && pos.row >= actualFrozenRow ) || ( options.frozenBottom && pos.row < actualFrozenRow ) ) { scrollCellIntoView(pos.row, pos.cell, !isAddNewRow && options.emulatePagingWhenScrolling); } setActiveCellInternal(getCellNode(pos.row, pos.cell)); activePosX = pos.posX; return true; } else { setActiveCellInternal(getCellNode(activeRow, activeCell)); return false; } } function getCellNode(row, cell) { if (rowsCache[row]) { ensureCellNodesInRowsCache(row); try { return rowsCache[row].cellNodesByColumnIdx[cell][0]; } catch (e) { return rowsCache[row].cellNodesByColumnIdx[cell]; } } return null; } function setActiveCell(row, cell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent) { if (!initialized) { return; } if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return; } if (!options.enableCellNavigation) { return; } scrollCellIntoView(row, cell, false); setActiveCellInternal(getCellNode(row, cell), opt_editMode, preClickModeOn, suppressActiveCellChangedEvent); } function canCellBeActive(row, cell) { if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.focusable !== "undefined") { return !!rowMetadata.focusable; } var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable !== "undefined") { return !!columnMetadata[columns[cell].id].focusable; } if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable !== "undefined") { return !!columnMetadata[cell].focusable; } return !!columns[cell].focusable; } function canCellBeSelected(row, cell) { if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.selectable !== "undefined") { return !!rowMetadata.selectable; } var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]); if (columnMetadata && typeof columnMetadata.selectable !== "undefined") { return !!columnMetadata.selectable; } return !!columns[cell].selectable; } function gotoCell(row, cell, forceEdit, e) { if (!initialized) { return; } if (!canCellBeActive(row, cell)) { return; } if (!getEditorLock().commitCurrentEdit()) { return; } scrollCellIntoView(row, cell, false); var newCell = getCellNode(row, cell); // if selecting the 'add new' row, start editing right away setActiveCellInternal(newCell, (forceEdit || (row === getDataLength()) || options.autoEdit), null, options.editable, e); // if no editor was created, set the focus back on the grid if (!currentEditor) { setFocus(); } } ////////////////////////////////////////////////////////////////////////////////////////////// // IEditor implementation for the editor lock function commitCurrentEdit() { var item = getDataItem(activeRow); var column = columns[activeCell]; if (currentEditor) { if (currentEditor.isValueChanged()) { var validationResults = currentEditor.validate(); if (validationResults.valid) { if (activeRow < getDataLength()) { var editCommand = { row: activeRow, cell: activeCell, editor: currentEditor, serializedValue: currentEditor.serializeValue(), prevSerializedValue: serializedEditorValue, execute: function () { this.editor.applyValue(item, this.serializedValue); updateRow(this.row); trigger(self.onCellChange, { row: this.row, cell: this.cell, item: item }); }, undo: function () { this.editor.applyValue(item, this.prevSerializedValue); updateRow(this.row); trigger(self.onCellChange, { row: this.row, cell: this.cell, item: item }); } }; if (options.editCommandHandler) { makeActiveCellNormal(); options.editCommandHandler(item, column, editCommand); } else { editCommand.execute(); makeActiveCellNormal(); } } else { var newItem = {}; currentEditor.applyValue(newItem, currentEditor.serializeValue()); makeActiveCellNormal(); trigger(self.onAddNewRow, {item: newItem, column: column}); } // check whether the lock has been re-acquired by event handlers return !getEditorLock().isActive(); } else { // Re-add the CSS class to trigger transitions, if any. $(activeCellNode).removeClass("invalid"); $(activeCellNode).width(); // force layout $(activeCellNode).addClass("invalid"); trigger(self.onValidationError, { editor: currentEditor, cellNode: activeCellNode, validationResults: validationResults, row: activeRow, cell: activeCell, column: column }); currentEditor.focus(); return false; } } makeActiveCellNormal(); } return true; } function cancelCurrentEdit() { makeActiveCellNormal(); return true; } function rowsToRanges(rows) { var ranges = []; var lastCell = columns.length - 1; for (var i = 0; i < rows.length; i++) { ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell)); } return ranges; } function getSelectedRows() { if (!selectionModel) { throw new Error("Selection model is not set"); } return selectedRows; } function setSelectedRows(rows) { if (!selectionModel) { throw new Error("Selection model is not set"); } if (self && self.getEditorLock && !self.getEditorLock().isActive()) { selectionModel.setSelectedRanges(rowsToRanges(rows)); } } ////////////////////////////////////////////////////////////////////////////////////////////// // Debug this.debug = function () { var s = ""; s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered); s += ("\n" + "counter_rows_removed: " + counter_rows_removed); s += ("\n" + "renderedRows: " + renderedRows); s += ("\n" + "numVisibleRows: " + numVisibleRows); s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight); s += ("\n" + "n(umber of pages): " + n); s += ("\n" + "(current) page: " + page); s += ("\n" + "page height (ph): " + ph); s += ("\n" + "vScrollDir: " + vScrollDir); alert(s); }; // a debug helper to be able to access private members this.eval = function (expr) { return eval(expr); }; ////////////////////////////////////////////////////////////////////////////////////////////// // Public API $.extend(this, { "slickGridVersion": "2.4.5", // Events "onScroll": new Slick.Event(), "onSort": new Slick.Event(), "onHeaderMouseEnter": new Slick.Event(), "onHeaderMouseLeave": new Slick.Event(), "onHeaderContextMenu": new Slick.Event(), "onHeaderClick": new Slick.Event(), "onHeaderCellRendered": new Slick.Event(), "onBeforeHeaderCellDestroy": new Slick.Event(), "onHeaderRowCellRendered": new Slick.Event(), "onFooterRowCellRendered": new Slick.Event(), "onBeforeHeaderRowCellDestroy": new Slick.Event(), "onBeforeFooterRowCellDestroy": new Slick.Event(), "onMouseEnter": new Slick.Event(), "onMouseLeave": new Slick.Event(), "onClick": new Slick.Event(), "onDblClick": new Slick.Event(), "onContextMenu": new Slick.Event(), "onKeyDown": new Slick.Event(), "onAddNewRow": new Slick.Event(), "onBeforeAppendCell": new Slick.Event(), "onValidationError": new Slick.Event(), "onViewportChanged": new Slick.Event(), "onColumnsReordered": new Slick.Event(), "onColumnsResized": new Slick.Event(), "onCellChange": new Slick.Event(), "onBeforeEditCell": new Slick.Event(), "onBeforeCellEditorDestroy": new Slick.Event(), "onBeforeDestroy": new Slick.Event(), "onActiveCellChanged": new Slick.Event(), "onActiveCellPositionChanged": new Slick.Event(), "onDragInit": new Slick.Event(), "onDragStart": new Slick.Event(), "onDrag": new Slick.Event(), "onDragEnd": new Slick.Event(), "onSelectedRowsChanged": new Slick.Event(), "onCellCssStylesChanged": new Slick.Event(), "onAutosizeColumns": new Slick.Event(), "onRendered": new Slick.Event(), // Methods "registerPlugin": registerPlugin, "unregisterPlugin": unregisterPlugin, "getPluginByName": getPluginByName, "getColumns": getColumns, "setColumns": setColumns, "getColumnIndex": getColumnIndex, "updateColumnHeader": updateColumnHeader, "setSortColumn": setSortColumn, "setSortColumns": setSortColumns, "getSortColumns": getSortColumns, "autosizeColumns": autosizeColumns, "getOptions": getOptions, "setOptions": setOptions, "getData": getData, "getDataLength": getDataLength, "getDataItem": getDataItem, "setData": setData, "getSelectionModel": getSelectionModel, "setSelectionModel": setSelectionModel, "getSelectedRows": getSelectedRows, "setSelectedRows": setSelectedRows, "getContainerNode": getContainerNode, "updatePagingStatusFromView": updatePagingStatusFromView, "applyFormatResultToCellNode": applyFormatResultToCellNode, "render": render, "invalidate": invalidate, "invalidateRow": invalidateRow, "invalidateRows": invalidateRows, "invalidateAllRows": invalidateAllRows, "updateCell": updateCell, "updateRow": updateRow, "getViewport": getVisibleRange, "getRenderedRange": getRenderedRange, "resizeCanvas": resizeCanvas, "updateRowCount": updateRowCount, "scrollRowIntoView": scrollRowIntoView, "scrollRowToTop": scrollRowToTop, "scrollCellIntoView": scrollCellIntoView, "scrollColumnIntoView": scrollColumnIntoView, "getCanvasNode": getCanvasNode, "getUID": getUID, "getHeaderColumnWidthDiff": getHeaderColumnWidthDiff, "getScrollbarDimensions": getScrollbarDimensions, "getHeadersWidth": getHeadersWidth, "getCanvasWidth": getCanvasWidth, "getCanvases": getCanvases, "getActiveCanvasNode": getActiveCanvasNode, "setActiveCanvasNode": setActiveCanvasNode, "getViewportNode": getViewportNode, "getActiveViewportNode": getActiveViewportNode, "setActiveViewportNode": setActiveViewportNode, "focus": setFocus, "scrollTo": scrollTo, "getCellFromPoint": getCellFromPoint, "getCellFromEvent": getCellFromEvent, "getActiveCell": getActiveCell, "setActiveCell": setActiveCell, "getActiveCellNode": getActiveCellNode, "getActiveCellPosition": getActiveCellPosition, "resetActiveCell": resetActiveCell, "editActiveCell": makeActiveCellEditable, "getCellEditor": getCellEditor, "getCellNode": getCellNode, "getCellNodeBox": getCellNodeBox, "canCellBeSelected": canCellBeSelected, "canCellBeActive": canCellBeActive, "navigatePrev": navigatePrev, "navigateNext": navigateNext, "navigateUp": navigateUp, "navigateDown": navigateDown, "navigateLeft": navigateLeft, "navigateRight": navigateRight, "navigatePageUp": navigatePageUp, "navigatePageDown": navigatePageDown, "navigateTop": navigateTop, "navigateBottom": navigateBottom, "navigateRowStart": navigateRowStart, "navigateRowEnd": navigateRowEnd, "gotoCell": gotoCell, "getTopPanel": getTopPanel, "setTopPanelVisibility": setTopPanelVisibility, "getPreHeaderPanel": getPreHeaderPanel, "setPreHeaderPanelVisibility": setPreHeaderPanelVisibility, "getHeader": getHeader, "getHeaderColumn": getHeaderColumn, "setHeaderRowVisibility": setHeaderRowVisibility, "getHeaderRow": getHeaderRow, "getHeaderRowColumn": getHeaderRowColumn, "setFooterRowVisibility": setFooterRowVisibility, "getFooterRow": getFooterRow, "getFooterRowColumn": getFooterRowColumn, "getGridPosition": getGridPosition, "flashCell": flashCell, "addCellCssStyles": addCellCssStyles, "setCellCssStyles": setCellCssStyles, "removeCellCssStyles": removeCellCssStyles, "getCellCssStyles": getCellCssStyles, "getFrozenRowOffset": getFrozenRowOffset, "init": finishInitialization, "destroy": destroy, // IEditor implementation "getEditorLock": getEditorLock, "getEditController": getEditController }); init(); } }(jQuery));
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Post from './post' import * as actions from '../actions' class RecentPosts extends Component { componentDidMount() { this.props.fetchRecentPosts(); } renderPosts = function() { const posts = this.props.recentPosts.map((post, index) => { if(index < 3) { return ( <Post type='recent' key={index} {...post} /> )} }) return posts } render() { return ( <div className="recent-posts-wrapper"> <div className="recent-posts-heading">Recent Posts</div> <ul className="recent-posts-posts"> {this.renderPosts()} </ul> </div> ); } } function mapStateToProps(state) { return { recentPosts: state.posts.recentPosts } } export default connect(mapStateToProps, actions)(RecentPosts);
var class_tempest_1_1_color = [ [ "Color", "class_tempest_1_1_color.html#a9a742cbe9f9f4037f5d9f4e81a9b2428", null ], [ "Color", "class_tempest_1_1_color.html#a4570f17f449c0302fd4c2964989ff65d", null ], [ "Color", "class_tempest_1_1_color.html#a1ff48fafaffb35cdbf0d8384fc48e7e9", null ], [ "a", "class_tempest_1_1_color.html#a1ea9703c89cd7534c33e73cd2c5d1c19", null ], [ "b", "class_tempest_1_1_color.html#a1d70a9e2386aa5d25cac60c9201b6269", null ], [ "data", "class_tempest_1_1_color.html#a4f3e9640877ef9e09319bdce18ef70dc", null ], [ "g", "class_tempest_1_1_color.html#a09a7c4d10a387bf59823d52eb0bc0173", null ], [ "operator!=", "class_tempest_1_1_color.html#aa15294900b566e774375f66c9d2a5371", null ], [ "operator+", "class_tempest_1_1_color.html#ad2da29b884581b6601b9cf524228cb7d", null ], [ "operator+=", "class_tempest_1_1_color.html#ac283f565588e93af17866d357827fa87", null ], [ "operator-", "class_tempest_1_1_color.html#aa00513416acac8489d70fd27b78b81af", null ], [ "operator-=", "class_tempest_1_1_color.html#aa058fd5b4366eaaf053d0cda3837c9a5", null ], [ "operator=", "class_tempest_1_1_color.html#a5ec3c2546dae446433c59fbdf400ef65", null ], [ "operator==", "class_tempest_1_1_color.html#aa6f2f7ba5990e7daa42d1e2d1b1a948d", null ], [ "operator[]", "class_tempest_1_1_color.html#a530574bfdce44ddb000245e06eb8788a", null ], [ "operator[]", "class_tempest_1_1_color.html#a46fef2af67b7ffbd777e8fd622ee3e47", null ], [ "r", "class_tempest_1_1_color.html#acf37af858b317db5b9295b0fb4d6cc51", null ], [ "set", "class_tempest_1_1_color.html#ac527f9b3cd41835585b31767b44cf6a9", null ], [ "set", "class_tempest_1_1_color.html#a8d94f6e9cabde79faeb5b8a7391c3101", null ] ];
var Layout = function () { var isMobileDevice = function() { return (( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i) ) ? true : false); } var WindowWidth = $(window).width(); var WindowHeight = $(window).height(); var handleParallax = function () { $(window).load(function(){ if (isMobileDevice() === false) { $("#message-block").parallax("50%",0.4); $("#facts-block").parallax("50%",0.4); } }); } var handleScrolling = function () { $(".scroll").on("click", function(event) { event.preventDefault();//the default action of the event will not be triggered $("html, body").animate({scrollTop:($("#"+this.href.split("#")[1]).offset().top)}, 600); }); } /* Smooth scrolling and smart navigation when user scrolls on one-page sites */ var handleNavItemCurrent = function () { $(".header-navigation").onePageNav({ currentClass: "current", scrollThreshold: 0 }); } var handleHeaderPosition = function () { var CurrentHeaderPosition = $(".header").offset().top;// current header's vertical position var headerFix = function(){ var CurrentWindowPosition = $(window).scrollTop();// current vertical position if (CurrentWindowPosition > CurrentHeaderPosition) { $(".header").addClass("fixNav"); } else { $(".header").removeClass("fixNav"); } }; headerFix();// call headerFix() when the page was loaded if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) { $(window).bind("touchend touchcancel touchleave", function(e){ headerFix(); }); } else { $(window).scroll(function() { headerFix(); }); } } var handleGo2Top = function () { var Go2TopOperation = function(){ var CurrentWindowPosition = $(window).scrollTop();// current vertical position if (CurrentWindowPosition > 300) { $(".go2top").show(); } else { $(".go2top").hide(); } }; Go2TopOperation();// call headerFix() when the page was loaded if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) { $(window).bind("touchend touchcancel touchleave", function(e){ Go2TopOperation(); }); } else { $(window).scroll(function() { Go2TopOperation(); }); } } function handleBootstrap() { $(".carousel").carousel({ interval: 15000, pause: "hover" }); $(".tooltips").tooltip(); $(".popovers").popover(); } function handleCounter() { /*$('.counter').counterUp({ delay: 10, time: 1000 });*/ } var handlePortfolioSorting = function () { /*$(".sorting-grid").mixitup();*/ } var handleFancybox = function () { if (!jQuery.fancybox) { return; } $(".zoom").fancybox(); } var handleMobiToggler = function () { $(".mobi-toggler").on("click", function(event) { event.preventDefault();//the default action of the event will not be triggered $(".header").toggleClass("menuOpened"); $(".header").find(".header-navigation").toggle(300); }); function SlideUpMenu () { $(".header-navigation a").on("click", function(event) { if ($(window).width()<1024) { event.preventDefault();//the default action of the event will not be triggered $(".header-navigation").slideUp(100); $(".header").removeClass("menuOpened"); } }); $(window).scroll(function() { if (($(window).width()>480)&&($(window).width()<1024)) { $(".header-navigation").slideUp(100); $(".header").removeClass("menuOpened"); } }); } SlideUpMenu(); $(window).resize(function() { SlideUpMenu(); }); } var handleTwitter = function () { !function(d,s,id){ var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);} }(document,"script","twitter-wjs"); } function valignCenterMessageFunction () { MessageCurrentElemHeight = $(".message-block .valign-center-elem").height(); $(".message-block .valign-center-elem").css("position", "absolute") .css ("top", "50%") .css ("margin-top", "-"+MessageCurrentElemHeight/2+"px") .css ("width", "100%") .css ("height", MessageCurrentElemHeight); } function valignCenterPortfolioFunction () { PortfolioCurrentElemHeight = $(".portfolio-block .valign-center-elem").height(); $(".portfolio-block .valign-center-elem").css("position", "absolute") .css ("top", "50%") .css ("margin-top", "-"+PortfolioCurrentElemHeight/2+"px") .css ("width", "100%") .css ("height", PortfolioCurrentElemHeight); } var valignCenterMessage = function () { valignCenterMessageFunction(); $(window).resize(function() { valignCenterMessageFunction(); }); } var valignCenterPortfolio = function () { valignCenterPortfolioFunction(); $(window).resize(function() { valignCenterPortfolioFunction(); }); } var handleTheme = function () { var panel = $('.color-panel'); // handle theme colors var setColor = function (color) { $('#style-color').attr("href", "../../assets/onepage/css/themes/" + color + ".css"); $('.site-logo img').attr("src", "../../assets/onepage/img/logo/" + color + ".png"); } $('.icon-color', panel).click(function () { $('.color-mode').show(); $('.icon-color-close').show(); }); $('.icon-color-close', panel).click(function () { $('.color-mode').hide(); $('.icon-color-close').hide(); }); $('li', panel).click(function () { var color = $(this).attr("data-style"); setColor(color); $('.inline li', panel).removeClass("current"); $(this).addClass("current"); }); $('.color-panel .menu-pos').change(function(){ if ($(this).val() == "top") { $('body').addClass("menu-always-on-top"); } else { $('body').removeClass("menu-always-on-top"); } }); } return { init: function () { //handlePromoBlock(); handleParallax(); handleScrolling(); handleNavItemCurrent(); handleHeaderPosition(); handleBootstrap(); handleCounter(); handleGo2Top(); handlePortfolioSorting(); handleFancybox(); handleMobiToggler(); handleTwitter(); valignCenterMessage(); valignCenterPortfolio(); handleTheme(); }, }; }();
import React from 'react' import PropTypes from 'prop-types' import DefaultPlugin from './DefaultPlugin' import { MAP } from '../../../../modules/itemTypes' const MapPlugin = ({ applyFilters, ...props }) => { if (props.item.type === MAP) { // apply filters only to thematic and event layers // for maps AO const mapViews = props.visualization.mapViews.map(mapView => { if ( mapView.layer.includes('thematic') || mapView.layer.includes('event') ) { return applyFilters(mapView, props.itemFilters) } return mapView }) props.visualization = { ...props.visualization, mapViews, } } else { // this is the case of a non map AO passed to the maps plugin // due to a visualization type switch in dashboard item // maps plugin takes care of converting the AO to a suitable format props.visualization = applyFilters( props.visualization, props.itemFilters ) } return ( <DefaultPlugin options={{ hideTitle: true, }} {...props} /> ) } MapPlugin.propTypes = { applyFilters: PropTypes.func, item: PropTypes.object, itemFilters: PropTypes.object, visualization: PropTypes.object, } export default MapPlugin
'use strict'; angular.module('app') .controller('signupController', function($scope, $state, $auth, toastr) { $scope.signup = function() { $auth.signup($scope.user) .then(function(response) { $auth.setToken(response); toastr.info('You have successfully created a new account and have been signed-in'); $state.go('home'); }) .catch(function(response) { toastr.error(response.data.message); }); }; });
if(!Control){var Control={}}Control.Slider=Class.create();Control.Slider.prototype={initialize:function(handle,track,options){this.handle=$(handle);this.track=$(track);this.options=options||{};this.axis=this.options.axis||"horizontal";this.increment=this.options.increment||1;this.step=parseInt(this.options.step)||1;this.value=0;var defaultMaximum=Math.round(this.track.offsetWidth/this.increment);if(this.isVertical()){defaultMaximum=Math.round(this.track.offsetHeight/this.increment)}this.maximum=this.options.maximum||defaultMaximum;this.minimum=this.options.minimum||0;this.alignX=parseInt(this.options.alignX)||0;this.alignY=parseInt(this.options.alignY)||0;this.setCurrentLeft(Position.cumulativeOffset(this.track)[0]-Position.cumulativeOffset(this.handle)[0]+this.alignX);this.setCurrentTop(this.trackTop()-Position.cumulativeOffset(this.handle)[1]+this.alignY);this.offsetX=0;this.offsetY=0;this.originalLeft=this.currentLeft();this.originalTop=this.currentTop();this.originalZ=parseInt(this.handle.style.zIndex||"0");this.setSliderValue(parseInt(this.options.sliderValue)||0);this.active=false;this.dragging=false;this.disabled=false;this.handleImage=$(this.options.handleImage)||false;this.handleDisabled=this.options.handleDisabled||false;this.handleEnabled=false;if(this.handleImage){this.handleEnabled=this.handleImage.src||false}if(this.options.disabled){this.setDisabled()}this.values=this.options.values||false;Element.makePositioned(this.handle);this.eventMouseDown=this.startDrag.bindAsEventListener(this);this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.update.bindAsEventListener(this);this.eventKeypress=this.keyPress.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Event.observe(document,"mouseup",this.eventMouseUp);Event.observe(document,"mousemove",this.eventMouseMove);Event.observe(document,"keypress",this.eventKeypress)},dispose:function(){Event.stopObserving(this.handle,"mousedown",this.eventMouseDown);Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);Event.stopObserving(document,"keypress",this.eventKeypress)},setDisabled:function(){this.disabled=true;if(this.handleDisabled){this.handleImage.src=this.handleDisabled}},setEnabled:function(){this.disabled=false;if(this.handleEnabled){this.handleImage.src=this.handleEnabled}},currentLeft:function(){return parseInt(this.handle.style.left||"0")},currentTop:function(){return parseInt(this.handle.style.top||"0")},setCurrentLeft:function(left){this.handle.style.left=left+"px"},setCurrentTop:function(top){this.handle.style.top=top+"px"},trackLeft:function(){return Position.cumulativeOffset(this.track)[0]},trackTop:function(){return Position.cumulativeOffset(this.track)[1]},getNearestValue:function(value){if(this.values){var i=0;var offset=Math.abs(this.values[0]-value);var newValue=this.values[0];for(i=0;i<this.values.length;i++){var currentOffset=Math.abs(this.values[i]-value);if(currentOffset<offset){newValue=this.values[i];offset=currentOffset}}return newValue}return value},setSliderValue:function(sliderValue){sliderValue=this.getNearestValue(sliderValue);if(sliderValue>this.maximum){sliderValue=this.maximum}if(sliderValue<this.minimum){sliderValue=this.minimum}var offsetDiff=(sliderValue-(this.value||this.minimum))*this.increment;if(this.isVertical()){this.setCurrentTop(offsetDiff+this.currentTop())}else{this.setCurrentLeft(offsetDiff+this.currentLeft())}this.value=sliderValue;this.updateFinished()},minimumOffset:function(){return(this.isVertical()?this.trackTop()+this.alignY:this.trackLeft()+this.alignX)},maximumOffset:function(){return(this.isVertical()?this.trackTop()+this.alignY+(this.maximum-this.minimum)*this.increment:this.trackLeft()+this.alignX+(this.maximum-this.minimum)*this.increment)},isVertical:function(){return(this.axis=="vertical")},startDrag:function(event){if(Event.isLeftClick(event)){if(!this.disabled){this.active=true;var pointer=[Event.pointerX(event),Event.pointerY(event)];var offsets=Position.cumulativeOffset(this.handle);this.offsetX=(pointer[0]-offsets[0]);this.offsetY=(pointer[1]-offsets[1]);this.originalLeft=this.currentLeft();this.originalTop=this.currentTop()}Event.stop(event)}},update:function(event){if(this.active){if(!this.dragging){var style=this.handle.style;this.dragging=true;if(style.position==""){style.position="relative"}style.zIndex=this.options.zindex}this.draw(event);if(navigator.appVersion.indexOf("AppleWebKit")>0){window.scrollBy(0,0)}Event.stop(event)}},draw:function(event){var pointer=[Event.pointerX(event),Event.pointerY(event)];var offsets=Position.cumulativeOffset(this.handle);offsets[0]-=this.currentLeft();offsets[1]-=this.currentTop();pointer[0]-=this.offsetX;pointer[1]-=this.offsetY;var style=this.handle.style;if(this.isVertical()){if(pointer[1]>this.maximumOffset()){pointer[1]=this.maximumOffset()}if(pointer[1]<this.minimumOffset()){pointer[1]=this.minimumOffset()}if(this.values){this.value=this.getNearestValue(Math.round((pointer[1]-this.minimumOffset())/this.increment)+this.minimum);pointer[1]=this.trackTop()+this.alignY+(this.value-this.minimum)*this.increment}else{this.value=Math.round((pointer[1]-this.minimumOffset())/this.increment)+this.minimum}style.top=pointer[1]-offsets[1]+"px"}else{if(pointer[0]>this.maximumOffset()){pointer[0]=this.maximumOffset()}if(pointer[0]<this.minimumOffset()){pointer[0]=this.minimumOffset()}if(this.values){this.value=this.getNearestValue(Math.round((pointer[0]-this.minimumOffset())/this.increment)+this.minimum);pointer[0]=this.trackLeft()+this.alignX+(this.value-this.minimum)*this.increment}else{this.value=Math.round((pointer[0]-this.minimumOffset())/this.increment)+this.minimum}style.left=(pointer[0]-offsets[0])+"px"}if(this.options.onSlide){this.options.onSlide(this.value)}},endDrag:function(event){if(this.active&&this.dragging){this.finishDrag(event,true);Event.stop(event)}this.active=false;this.dragging=false},finishDrag:function(event,success){this.active=false;this.dragging=false;this.handle.style.zIndex=this.originalZ;this.originalLeft=this.currentLeft();this.originalTop=this.currentTop();this.updateFinished()},updateFinished:function(){if(this.options.onChange){this.options.onChange(this.value)}},keyPress:function(event){if(this.active&&!this.disabled){switch(event.keyCode){case Event.KEY_ESC:this.finishDrag(event,false);Event.stop(event);break}if(navigator.appVersion.indexOf("AppleWebKit")>0){Event.stop(event)}}}};
// // Vivado(TM) // rundef.js: a Vivado-generated Runs Script for WSH 5.1/5.6 // Copyright 1986-2016 Xilinx, Inc. All Rights Reserved. // var WshShell = new ActiveXObject( "WScript.Shell" ); var ProcEnv = WshShell.Environment( "Process" ); var PathVal = ProcEnv("PATH"); if ( PathVal.length == 0 ) { PathVal = "C:/Xilinx/SDK/2016.3/bin;C:/Xilinx/Vivado/2016.3/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2016.3/ids_lite/ISE/lib/nt64;C:/Xilinx/Vivado/2016.3/bin;"; } else { PathVal = "C:/Xilinx/SDK/2016.3/bin;C:/Xilinx/Vivado/2016.3/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2016.3/ids_lite/ISE/lib/nt64;C:/Xilinx/Vivado/2016.3/bin;" + PathVal; } ProcEnv("PATH") = PathVal; var RDScrFP = WScript.ScriptFullName; var RDScrN = WScript.ScriptName; var RDScrDir = RDScrFP.substr( 0, RDScrFP.length - RDScrN.length - 1 ); var ISEJScriptLib = RDScrDir + "/ISEWrap.js"; eval( EAInclude(ISEJScriptLib) ); // pre-commands: ISETouchFile( "init_design", "begin" ); ISEStep( "vivado", "-log TwinElevatorsTopModule.vdi -applog -m64 -product Vivado -messageDb vivado.pb -mode batch -source TwinElevatorsTopModule.tcl -notrace" ); function EAInclude( EAInclFilename ) { var EAFso = new ActiveXObject( "Scripting.FileSystemObject" ); var EAInclFile = EAFso.OpenTextFile( EAInclFilename ); var EAIFContents = EAInclFile.ReadAll(); EAInclFile.Close(); return EAIFContents; }
import request from '@/router/axios'; export const getList = (current, size, params) => { return request({ url: '/api/blade-develop/code/list', method: 'get', params: { ...params, current, size } }); }; export const build = (ids) => { return request({ url: '/api/blade-develop/code/gen-code', method: 'post', params: { ids, system: 'saber' } }); }; export const remove = (ids) => { return request({ url: '/api/blade-develop/code/remove', method: 'post', params: { ids, } }); }; export const add = (row) => { return request({ url: '/api/blade-develop/code/submit', method: 'post', data: row }); }; export const update = (row) => { return request({ url: '/api/blade-develop/code/submit', method: 'post', data: row }); }; export const copy = (id) => { return request({ url: '/api/blade-develop/code/copy', method: 'post', params: { id, } }); }; export const getCode = (id) => { return request({ url: '/api/blade-develop/code/detail', method: 'get', params: { id, } }); };
import axios from 'axios' const state = { user: null }; const mutations = { }; const actions = { auth({commit}, {email, password }){ axios.post('/api/auth',{ email, password }).then((res) => { console.log(res.data) }).catch((err) => { console.log(err) }) } }; const getters = { }; export default { state, mutations, actions, getters }
/* <copyright> Copyright (c) 2012, Motorola Mobility LLC. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Motorola Mobility LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </copyright> */ /* ///////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// NOTES: For newFile, only the 'uri' is required, if contents is empty, such empty file will be created. 'contents' should be a string to be saved as the file. 'contentType' is the mime type of the file. Core API reference in NINJA: this.application.ninja.coreIoApi //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// */ // var Montage = require("montage/core/core").Montage, Component = require("montage/ui/component").Component; //////////////////////////////////////////////////////////////////////// //Exporting as File I/O exports.FileIo = Montage.create(Component, { //////////////////////////////////////////////////////////////////// //Creating new file newFile: { enumerable: true, value: function(file) { //Checking for API to be available if (!this.application.ninja.coreIoApi.cloudAvailable()) { //API not available, no IO action taken return null; } //Peforming check for file to exist var check = this.application.ninja.coreIoApi.fileExists({uri: file.uri}), status, create; //Upon successful check, handling results if (check.success) { //Handling status of check switch (check.status) { case 204: //Storing status to be returned (for UI handling) status = check.status; break; case 404: //File does not exists, ready to be created create = this.application.ninja.coreIoApi.createFile(file); status = create.status; break; default: //Unknown Error status = 500; break; } } else { //Unknown Error status = 500; } //Returning resulting code return status; // 204: File exists (not created) | 400: File exists | 404: File does not exists // 201: File succesfully created | 500: Unknown } }, //////////////////////////////////////////////////////////////////// //Reading contents from file readFile: { enumerable: true, value: function(file) { //Checking for API to be available if (!this.application.ninja.coreIoApi.cloudAvailable()) { //API not available, no IO action taken return null; } //Peforming check for file to exist var check = this.application.ninja.coreIoApi.fileExists({uri: file.uri}), status, create, result; //Upon successful check, handling results if (check.success) { //Handling status of check switch (check.status) { case 204: //File exists result = {}; result.content = this.application.ninja.coreIoApi.readFile(file).content; result.details = this.infoFile(file); status = check.status; break; case 404: //File does not exists status = check.status; break; default: //Unknown Error status = 500; break; } } else { //Unknown Error status = 500; } //Returning status and result (null if none) return {status: status, file: result}; //Status Codes // 204: File exists | 404: File does not exists | 500: Unknown } }, //////////////////////////////////////////////////////////////////// //Saving file (existing file or creates and saves if none exists) saveFile: { enumerable: true, value: function(file) { //Checking for API to be available if (!this.application.ninja.coreIoApi.cloudAvailable()) { //API not available, no IO action taken return null; } //Peforming check for file to exist var check = this.application.ninja.coreIoApi.fileExists({uri: file.uri}), status, result; //Upon successful check, handling results if (check.success) { //Handling status of check switch (check.status) { case 204: //File exists result = this.application.ninja.coreIoApi.updateFile(file); status = 204; break; case 404: //File does not exists, ready to be created result = this.application.ninja.coreIoApi.createFile(file); status = 404; break; default: //Unknown Error status = 500; break; } } else { //Unknown Error status = 500; } //Returning status and result (null if none) return {status: status, result: result}; //Status Codes // 204: File exists | 404: File does not exists | 500: Unknown } }, //////////////////////////////////////////////////////////////////// //TODO: Add functionality deleteFile: { enumerable: true, value: function() { //Checking for API to be available if (!this.application.ninja.coreIoApi.cloudAvailable()) { //API not available, no IO action taken return null; } // } }, //////////////////////////////////////////////////////////////////// //TODO: Add functionality copyFile: { enumerable: true, value: function() { //Checking for API to be available if (!this.application.ninja.coreIoApi.cloudAvailable()) { //API not available, no IO action taken return null; } // } }, //////////////////////////////////////////////////////////////////// // infoFile: { enumerable: true, value: function(file) { //Checking for API to be available if (!this.application.ninja.coreIoApi.cloudAvailable()) { //API not available, no IO action taken return null; } // var check = this.application.ninja.coreIoApi.fileExists({uri: file.uri}), details; // if (check.success) { //Handling status of check switch (check.status) { case 204: //File exists details = JSON.parse(this.application.ninja.coreIoApi.isFileWritable(file).content); details.uri = file.uri; details.name = this.getFileNameFromPath(file.uri); details.extension = details.name.split('.')[details.name.split('.').length-1]; details.status = 204; break; case 404: //File does not exists, ready to be created details = {status: 404, uri: file.uri, name: this.getFileNameFromPath(file.uri)}; break; default: //Unknown Error details = {status: 500, uri: file.uri, name: this.getFileNameFromPath(file.uri)}; break; } } else { //Unknown Error details = {status: 500, uri: file.uri, name: this.getFileNameFromPath(file.uri)}; } return details; } }, //////////////////////////////////////////////////////////////////// // getFileNameFromPath : { value: function(path) { path = path.replace(/[/\\]$/g,""); path = path.replace(/\\/g,"/"); return path.substr(path.lastIndexOf('/') + 1); } } //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// }); //////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
/* beautiful-react-diagrams version: 0.5.0 */ import { useContext } from 'react'; import DiagramContext from '../../Context/DiagramContext.js'; var useCanvas = function useCanvas() { var _useContext = useContext(DiagramContext), canvas = _useContext.canvas; return canvas; }; export default useCanvas;
import axios from "axios"; import { GET_NOTES, ADD_NOTE, SET_LOADING, DELETE_NOTE, GET_NOTES_IN_TRASH, MOVE_TO_TRASH, UPDATE_NOTE, RESTORE_NOTE, } from "./types"; export const getNotes = () => async (dispatch) => { try { setLoading(); const res = await axios.get(`${process.env.REACT_APP_SERVER_URL}/api/todos`); dispatch({ type: GET_NOTES, payload: res.data, }); } catch (err) { console.log(err); // dispatch({ // type: LOGS_ERROR, // payload: err.response.statusText, // }); } }; export const getNotesInTrash = () => async (dispatch) => { try { setLoading(); const res = await axios.get(`${process.env.REACT_APP_SERVER_URL}/api/todos`); dispatch({ type: GET_NOTES_IN_TRASH, payload: res.data, }); } catch (err) { console.log(err); // dispatch({ // type: LOGS_ERROR, // payload: err.response.statusText, // }); } }; export const addNote = (note) => async (dispatch) => { try { setLoading(); const config = { headers: { "Content-Type": "application/json", }, }; const res = await axios.post( `${process.env.REACT_APP_SERVER_URL}/api/todos`, note, config ); dispatch({ type: ADD_NOTE, payload: res.data, }); } catch (err) { // dispatch({ // type: LOGS_ERROR, // payload: err.response.statusText, // }); } }; export const updateNote = (note) => async (dispatch) => { try { setLoading(); const config = { headers: { "Content-Type": "application/json", }, }; const res = await axios.put( `${process.env.REACT_APP_SERVER_URL}/api/todos/${note._id}`, note, config ); dispatch({ type: UPDATE_NOTE, payload: res.data, }); } catch (err) { // dispatch({ // type: LOGS_ERROR, // payload: err.response.statusText, // }); } }; export const moveToTrash = (note) => async (dispatch) => { try { setLoading(); const config = { headers: { "Content-Type": "application/json", }, }; await axios.put( `${process.env.REACT_APP_SERVER_URL}/api/todos/${note._id}`, note, config ); dispatch({ type: MOVE_TO_TRASH, payload: note._id, }); } catch (err) { // dispatch({ // type: LOGS_ERROR, // payload: err.response.statusText, // }); } }; export const restoreNote = (note) => async (dispatch) => { try { setLoading(); const config = { headers: { "Content-Type": "application/json", }, }; await axios.put( `${process.env.REACT_APP_SERVER_URL}/api/todos/${note._id}`, note, config ); dispatch({ type: RESTORE_NOTE, payload: note._id, }); } catch (err) { // dispatch({ // type: LOGS_ERROR, // payload: err.response.statusText, // }); } }; export const deleteNote = (noteId) => async (dispatch) => { try { setLoading(); await axios.delete(`${process.env.REACT_APP_SERVER_URL}/api/todos/${noteId}`); dispatch({ type: DELETE_NOTE, payload: noteId, }); } catch (err) { // dispatch({ // type: NOTE_ERROR, // payload: err.response.msg, // }); } }; export const setLoading = () => { return { type: SET_LOADING, }; };
//module.exports = require('cqrs-domain').defineContext({ module.exports = require('../../../../../').defineContext({ });
require(`dotenv`).config({ path: `.env`, }); const shouldAnalyseBundle = process.env.ANALYSE_BUNDLE; module.exports = { siteMetadata: { siteTitle: `dehamzah`, siteTitleAlt: `Dede Hamzah`, siteHeadline: `Dede Hamzah - Software Engineer`, siteUrl: `https://dehamzah.com`, siteDescription: `Dede Hamzah - Software Engineer`, siteLanguage: `id`, siteImage: `/owl_emoji.jpg`, author: `@dehamzah`, }, plugins: [ { resolve: `@lekoarts/gatsby-theme-minimal-blog`, // See the theme's README for all available options options: { navigation: [ { title: `Blog`, slug: `/blog`, }, { title: `About`, slug: `/about`, }, ], externalLinks: [ { name: `Twitter`, url: `https://twitter.com/dehamzah`, }, { name: `Github`, url: `https://www.github.com/dehamzah`, }, { name: `LinkedIn`, url: `https://www.linkedin.com/in/dedehamzah`, }, ], }, }, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: process.env.GOOGLE_ANALYTICS_ID, }, }, `gatsby-plugin-sitemap`, { resolve: `gatsby-plugin-manifest`, options: { name: `Dede Hamzah`, short_name: `dede-hamzah`, description: `Software Engineer`, start_url: `/`, background_color: `#fff`, theme_color: `#6B46C1`, display: `standalone`, icon: `static/owl_emoji.png`, icons: [ { src: `/android-chrome-192x192.png`, sizes: `192x192`, type: `image/png`, }, { src: `/android-chrome-512x512.png`, sizes: `512x512`, type: `image/png`, }, ], }, }, `gatsby-plugin-offline`, `gatsby-plugin-netlify`, shouldAnalyseBundle && { resolve: `gatsby-plugin-webpack-bundle-analyser-v2`, options: { analyzerMode: `static`, reportFilename: `_bundle.html`, openAnalyzer: false, }, }, ].filter(Boolean), };
var input1 = []; function GetParaOne() { input1.length; for (var i = 1; i <= 5; i++) { input1.push(document.getElementById("paral_input_box_" + i).value); document.getElementById("showParaOne").innerHTML = input1.join(". "); } console.log(input1); } var input2 = []; function GetParaTwo() { for (var i = 1; i <= 5; i++) { input2.push(document.getElementById("paral2_input_box_" + i).value); document.getElementById("showParaTwo").innerHTML = input2.join(". "); } console.log(input2); }
!function(modules){function webpackJsonpCallback(data){for(var moduleId,chunkId,chunkIds=data[0],moreModules=data[1],executeModules=data[2],i=0,resolves=[];i<chunkIds.length;i++)chunkId=chunkIds[i],Object.prototype.hasOwnProperty.call(installedChunks,chunkId)&&installedChunks[chunkId]&&resolves.push(installedChunks[chunkId][0]),installedChunks[chunkId]=0;for(moduleId in moreModules)Object.prototype.hasOwnProperty.call(moreModules,moduleId)&&(modules[moduleId]=moreModules[moduleId]);for(parentJsonpFunction&&parentJsonpFunction(data);resolves.length;)resolves.shift()();return deferredModules.push.apply(deferredModules,executeModules||[]),checkDeferredModules()}function checkDeferredModules(){for(var result,i=0;i<deferredModules.length;i++){for(var deferredModule=deferredModules[i],fulfilled=!0,j=1;j<deferredModule.length;j++){var depId=deferredModule[j];0!==installedChunks[depId]&&(fulfilled=!1)}fulfilled&&(deferredModules.splice(i--,1),result=__webpack_require__(__webpack_require__.s=deferredModule[0]))}return result}var installedModules={},installedChunks={1:0},deferredModules=[];function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}__webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{enumerable:!0,get:getter})},__webpack_require__.r=function(exports){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(exports,"__esModule",{value:!0})},__webpack_require__.t=function(value,mode){if(1&mode&&(value=__webpack_require__(value)),8&mode)return value;if(4&mode&&"object"==typeof value&&value&&value.__esModule)return value;var ns=Object.create(null);if(__webpack_require__.r(ns),Object.defineProperty(ns,"default",{enumerable:!0,value:value}),2&mode&&"string"!=typeof value)for(var key in value)__webpack_require__.d(ns,key,function(key){return value[key]}.bind(null,key));return ns},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module.default}:function getModuleExports(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="";var jsonpArray=window.webpackJsonp=window.webpackJsonp||[],oldJsonpFunction=jsonpArray.push.bind(jsonpArray);jsonpArray.push=webpackJsonpCallback,jsonpArray=jsonpArray.slice();for(var i=0;i<jsonpArray.length;i++)webpackJsonpCallback(jsonpArray[i]);var parentJsonpFunction=oldJsonpFunction;checkDeferredModules()}([]); //# sourceMappingURL=runtime~main.7de8ddf5bbaa52ab4ef4.bundle.js.map
const path = require('path'); const webpack = require('webpack'); const MemoryFileSystem = require('memory-fs'); const { RetryChunkLoadPlugin } = require('../../../src'); module.exports = function ( pluginOptions = {}, { fixture = 'index.js', extend = {} } = {} ) { const config = { mode: 'development', devtool: false, entry: path.join(__dirname, '..', 'fixtures', fixture), output: { path: path.join(__dirname, '..', 'fixtures', 'dist'), }, plugins: [new RetryChunkLoadPlugin(pluginOptions)], ...extend, }; const fs = new MemoryFileSystem(); const result = new Promise((resolve, reject) => { const compiler = webpack(config); compiler.outputFileSystem = fs; compiler.run((err, stats) => { if (err) { return reject(err); } return resolve(stats); }); }); return { fs, result, }; };
var urllib = require('urllib'); var extend = require('util')._extend; var querystring = require('querystring'); var AccessToken = function (data) { if (!(this instanceof AccessToken)) { return new AccessToken(data); } this.data = data; }; /*! * 检查AccessToken是否有效,检查规则为当前时间和过期时间进行对比 * * Examples: * ``` * token.isValid(); * ``` */ AccessToken.prototype.isValid = function () { return !!this.data.access_token && (new Date().getTime()) < (this.data.create_at + this.data.expires_in * 1000); }; /** * 根据appid和appsecret创建OAuth接口的构造函数 * 如需跨进程跨机器进行操作,access token需要进行全局维护 * 使用使用token的优先级是: * * 1. 使用当前缓存的token对象 * 2. 调用开发传入的获取token的异步方法,获得token之后使用(并缓存它)。 * Examples: * ``` * var OAuth = require('co-qq-oauth'); * var api = new OAuth('appid', 'secret'); * ``` * @param {String} appid 在公众平台上申请得到的appid * @param {String} appsecret 在公众平台上申请得到的app secret * @param {Generator} getToken 用于获取token的方法 * @param {Generator} saveToken 用于保存token的方法 */ var OAuth = function (appid, appsecret, getToken, saveToken) { this.appid = appid; this.appsecret = appsecret; // token的获取和存储 this.store = {}; this.getToken = getToken || function * () { return this.store['qq_token']; }; if (!saveToken && process.env.NODE_ENV === 'production') { console.warn("Please dont save oauth token into memory under production"); } this.saveToken = saveToken || function * (token) { this.store['qq_token'] = token; }; this.defaults = {}; }; /** * 用于设置urllib的默认options * * Examples: * ``` * oauth.setOpts({timeout: 15000}); * ``` * @param {Object} opts 默认选项 */ OAuth.prototype.setOpts = function (opts) { this.defaults = opts; }; /*! * urllib的封装 * * @param {String} url 路径 * @param {Object} opts urllib选项 */ OAuth.prototype.request = function * (url, opts) { var options = {}; extend(options, this.defaults); opts || (opts = {}); for (var key in opts) { if (key !== 'headers') { options[key] = opts[key]; } else { if (opts.headers) { options.headers = options.headers || {}; extend(options.headers, opts.headers); } } } var result; try { result = yield urllib.requestThunk(url, options); } catch (err) { err.name = 'QQAPI ' + err.name; throw err; } var data = result.data; if (data.errcode) { var err = new Error(data.errmsg); err.name = 'QQAPI Error'; err.code = data.errcode; throw err; } return data; }; /** * 获取授权页面的URL地址 * @param {String} redirect 授权后要跳转的地址 * @param {String} state 开发者可提供的数据 */ OAuth.prototype.getAuthorizeURL = function (redirect, state) { var url = 'https://graph.qq.com/oauth2.0/authorize'; this.redirect = redirect var info = { client_id: this.appid, redirect_uri: redirect, response_type: 'code', state: state || 1 }; return url + '?' + querystring.stringify(info) + '#qq_redirect'; }; /*! * 处理token,更新过期时间 */ OAuth.prototype.processToken = function * (data) { data.create_at = new Date().getTime(); // 存储token yield this.saveToken(data); return AccessToken(data); }; /** * 根据授权获取到的code,换取access token * * Return: * ``` * { * data: { * "access_token": "ACCESS_TOKEN", * "expires_in": 7200, * "refresh_token": "REFRESH_TOKEN", * } * } * ``` * @param {String} code 授权获取到的code */ OAuth.prototype.getAccessToken = function * (code) { var url = 'https://graph.qq.com/oauth2.0/token'; var info = { client_id: this.appid, client_secret: this.appsecret, code: code, grant_type: 'authorization_code', redirect_uri: this.redirect || '/' }; var args = { data: info, dataType: 'text' }; var data = yield this.request(url, args), _data = {} for (var i in data.split('&')) { _data[data.split('&')[i].split('=')[0]] = data.split('&')[i].split('=')[1] } return yield this.processToken(_data); }; /** * 根据refresh token,刷新access token,调用getAccessToken后才有效 * Examples: * ``` * api.refreshAccessToken(refreshToken); * ``` * Exception: * * - `err`, 刷新access token出现异常时的异常对象 * * Return: * ``` * { * data: { * "access_token": "ACCESS_TOKEN", * "expires_in": 7200, * "refresh_token": "REFRESH_TOKEN", * } * } * ``` * @param {String} refreshToken refreshToken */ OAuth.prototype.refreshAccessToken = function * (refreshToken) { var url = 'https://graph.qq.com/oauth2.0/token'; var info = { client_id: this.appid, client_secret: this.appsecret, grant_type: 'refresh_token', refresh_token: refreshToken }; var args = { data: info, dataType: 'text' }; var data = yield this.request(url, args), _data for (var i in data.split('&')) { _data[data.split('&')[i].split('=')[0]] = data.split('&')[i].split('=')[1] } return yield this.processToken(data); }; OAuth.prototype._getUser = function * (options, accessToken) { var url = 'https://graph.qq.com/user/get_user_info'; var info = { access_token: accessToken, openid: options.openid, oauth_consumer_key: this.appid }; var args = { data: info, dataType: 'json' }; return yield this.request(url, args); }; /** * 根据openid,获取用户信息。 * 当access token无效时,自动通过refresh token获取新的access token。然后再获取用户信息 * Examples: * ``` * api.getUser(options); * ``` * * Options: * ``` * openId * // 或 * { * "openId": "the open Id", // 必须 * "lang": "the lang code" // zh_CN 简体,zh_TW 繁体,en 英语 * } * ``` * Callback: * * - `err`, 获取用户信息出现异常时的异常对象 * * Result: * ``` * { ret: 0, msg: '', is_lost: 0, nickname: 'nick', gender: '男', province: '浙江', city: '杭州', year: '1990', figureurl: 'http://xxx/30', figureurl_1: 'http://xxx/50', figureurl_2: 'http://xxx/100', figureurl_qq_1: 'http://xxx/40', figureurl_qq_2: 'http://xxx/100', is_yellow_vip: '0', vip: '0', yellow_vip_level: '0', level: '0', is_yellow_year_vip: '0' } * * ``` * @param {Object|String} options 传入openid或者参见Options */ OAuth.prototype.getUser = function * (options) { if (typeof options !== 'object') { options = { openid: options }; } var data = yield this.getToken(); // 没有token数据 if (!data) { var error = new Error('No token for ' + options.openid + ', please authorize first.'); error.name = 'NoOAuthTokenError'; throw error; } var token = AccessToken(data); var accessToken; if (token.isValid()) { accessToken = token.data.access_token; } else { var newToken = yield this.refreshAccessToken(token.data.refresh_token); accessToken = newToken.data.access_token; } return yield this._getUser(options, accessToken); }; /** * 根据token,获取用户openid。 * Examples: * ``` * var userOpenId = yield api.getUserOpenId(token); * ``` * Exception: * * - `err`, 获取用户openid出现异常时的异常对象 * * Result: * ``` * { * "openid": "OPENID", * ... * } * ``` * @param {String} token */ OAuth.prototype.getUserOpenId = function * (token) { var url = 'https://graph.qq.com/oauth2.0/me'; var info = { access_token: token }; var args = { data: info, dataType: 'text' }; var data = yield this.request(url, args); return JSON.parse(data.slice(data.indexOf('{'), data.indexOf('}') + 1)).openid }; module.exports = OAuth;
/** @license * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.util.Iterables'); /** * Recreations of Array-like functions so that they work on any iterable * type. * @final */ shaka.util.Iterables = class { /** * @param {!Iterable.<FROM>} iterable * @param {function(FROM):TO} mapping * @return {!Iterable.<TO>} * @template FROM,TO */ static map(iterable, mapping) { const array = []; for (const x of iterable) { array.push(mapping(x)); } return array; } /** * @param {!Iterable.<T>} iterable * @param {function(T):boolean} test * @return {boolean} * @template T */ static every(iterable, test) { for (const x of iterable) { if (!test(x)) { return false; } } return true; } /** * @param {!Iterable.<T>} iterable * @param {function(T):boolean} test * @return {boolean} * @template T */ static some(iterable, test) { for (const x of iterable) { if (test(x)) { return true; } } return false; } /** * Iterate over an iterable object and return only the items that |filter| * returns true for. * * @param {!Iterable.<T>} iterable * @param {function(T):boolean} filter * @return {!Array.<T>} * @template T */ static filter(iterable, filter) { const out = []; for (const x of iterable) { if (filter(x)) { out.push(x); } } return out; } /** * Returns an iterable that contains numbers in the range [0, end). * * @param {number=} end The exclusive end of the list. * @return {!Iterable.<number>} */ static* range(end) { for (let i = 0; i < end; i++) { yield i; } } /** * Iterates over an iterable object and includes additional info about each * item: * - The zero-based index of the element. * - The next item in the list, if it exists. * - The previous item in the list, if it exists. * * @param {!Iterable.<T>} iterable * @return {!Iterable.< * {i: number, item: T, prev: (T|undefined), next: (T|undefined)}>} * @template T */ static* enumerate(iterable) { // Since we want the "next" item, we need to skip the first item and return // elements one in the past. So as we iterate, we are getting the "next" // element and yielding the one from the previous iteration. let i = -1; let prev = undefined; let item = undefined; for (const next of iterable) { if (i >= 0) { yield {i, item, prev, next}; } i++; prev = item; item = next; } if (i != -1) { // If it's still -1, there were no items. Otherwise we need to yield // the last item. yield {i, prev, item, next: undefined}; } } };
import React from 'react' import classnames from 'classnames' import PropTypes from 'prop-types' import { renderMarkdown } from './renderMarkdown' import styles from './index.styl' export default function ArticleBody({ markdown }) { return ( <div className={classnames('markdown-body', styles.body)}> {renderMarkdown(markdown)} </div> ) } ArticleBody.propTypes = { markdown: PropTypes.string.isRequired, }